Module | Sequel::Postgres::DatabaseMethods |
In: |
lib/sequel/adapters/shared/postgres.rb
|
Methods shared by Database instances that connect to PostgreSQL.
PREPARED_ARG_PLACEHOLDER | = | LiteralString.new('$').freeze | ||
RE_CURRVAL_ERROR | = | /currval of sequence "(.*)" is not yet defined in this session|relation "(.*)" does not exist/.freeze | ||
FOREIGN_KEY_LIST_ON_DELETE_MAP | = | {'a'.freeze=>:no_action, 'r'.freeze=>:restrict, 'c'.freeze=>:cascade, 'n'.freeze=>:set_null, 'd'.freeze=>:set_default}.freeze | ||
POSTGRES_DEFAULT_RE | = | /\A(?:B?('.*')::[^']+|\((-?\d+(?:\.\d+)?)\))\z/ | ||
UNLOGGED | = | 'UNLOGGED '.freeze | ||
ON_COMMIT | = | { :drop => 'DROP', :delete_rows => 'DELETE ROWS', :preserve_rows => 'PRESERVE ROWS', }.freeze | ||
SELECT_CUSTOM_SEQUENCE_SQL | = | (<<-end_sql SELECT name.nspname AS "schema", CASE WHEN split_part(def.adsrc, '''', 2) ~ '.' THEN substr(split_part(def.adsrc, '''', 2), strpos(split_part(def.adsrc, '''', 2), '.')+1) ELSE split_part(def.adsrc, '''', 2) END AS "sequence" FROM pg_class t JOIN pg_namespace name ON (t.relnamespace = name.oid) JOIN pg_attribute attr ON (t.oid = attrelid) JOIN pg_attrdef def ON (adrelid = attrelid AND adnum = attnum) JOIN pg_constraint cons ON (conrelid = adrelid AND adnum = conkey[1]) WHERE cons.contype = 'p' AND def.adsrc ~* 'nextval' end_sql | SQL fragment for custom sequences (ones not created by serial primary key), Returning the schema and literal form of the sequence name, by parsing the column defaults table. | |
SELECT_PK_SQL | = | (<<-end_sql SELECT pg_attribute.attname AS pk FROM pg_class, pg_attribute, pg_index, pg_namespace WHERE pg_class.oid = pg_attribute.attrelid AND pg_class.relnamespace = pg_namespace.oid AND pg_class.oid = pg_index.indrelid AND pg_index.indkey[0] = pg_attribute.attnum AND pg_index.indisprimary = 't' end_sql | SQL fragment for determining primary key column for the given table. Only returns the first primary key if the table has a composite primary key. | |
SELECT_SERIAL_SEQUENCE_SQL | = | (<<-end_sql SELECT name.nspname AS "schema", seq.relname AS "sequence" FROM pg_class seq, pg_attribute attr, pg_depend dep, pg_namespace name, pg_constraint cons, pg_class t WHERE seq.oid = dep.objid AND seq.relnamespace = name.oid AND seq.relkind = 'S' AND attr.attrelid = dep.refobjid AND attr.attnum = dep.refobjsubid AND attr.attrelid = cons.conrelid AND attr.attnum = cons.conkey[1] AND attr.attrelid = t.oid AND cons.contype = 'p' end_sql | SQL fragment for getting sequence associated with table‘s primary key, assuming it was a serial primary key column. | |
VALID_CLIENT_MIN_MESSAGES | = | %w'DEBUG5 DEBUG4 DEBUG3 DEBUG2 DEBUG1 LOG NOTICE WARNING ERROR FATAL PANIC'.freeze | ||
EXCLUSION_CONSTRAINT_SQL_STATE | = | '23P01'.freeze | ||
DEADLOCK_SQL_STATE | = | '40P01'.freeze | ||
DATABASE_ERROR_REGEXPS | = | [ # Add this check first, since otherwise it's possible for users to control # which exception class is generated. [/invalid input syntax/, DatabaseError], [/duplicate key value violates unique constraint/, UniqueConstraintViolation], [/violates foreign key constraint/, ForeignKeyConstraintViolation], [/violates check constraint/, CheckConstraintViolation], [/violates not-null constraint/, NotNullConstraintViolation], [/conflicting key value violates exclusion constraint/, ExclusionConstraintViolation], [/could not serialize access/, SerializationFailure], ].freeze |
conversion_procs | [R] | A hash of conversion procs, keyed by type integer (oid) and having callable values for the conversion proc for that type. |
Add a conversion proc for a named type. This should be used for types without fixed OIDs, which includes all types that are not included in a default PostgreSQL installation. If a block is given, it is used as the conversion proc, otherwise the conversion proc is looked up in the PG_NAMED_TYPES hash.
# File lib/sequel/adapters/shared/postgres.rb, line 187 187: def add_named_conversion_proc(name, &block) 188: add_named_conversion_procs(conversion_procs, name=>(block || PG_NAMED_TYPES[name])) 189: end
Commit an existing prepared transaction with the given transaction identifier string.
# File lib/sequel/adapters/shared/postgres.rb, line 193 193: def commit_prepared_transaction(transaction_id, opts=OPTS) 194: run("COMMIT PREPARED #{literal(transaction_id)}", opts) 195: end
Creates the function in the database. Arguments:
name : | name of the function to create | ||||||||||||||||||||||||||
definition : | string definition of the function, or object file for a dynamically loaded C function. | ||||||||||||||||||||||||||
opts : | options hash:
|
# File lib/sequel/adapters/shared/postgres.rb, line 217 217: def create_function(name, definition, opts=OPTS) 218: self << create_function_sql(name, definition, opts) 219: end
Create the procedural language in the database. Arguments:
name : | Name of the procedural language (e.g. plpgsql) | ||||||||
opts : | options hash:
|
# File lib/sequel/adapters/shared/postgres.rb, line 228 228: def create_language(name, opts=OPTS) 229: self << create_language_sql(name, opts) 230: end
Create a schema in the database. Arguments:
name : | Name of the schema (e.g. admin) | ||||
opts : | options hash:
|
# File lib/sequel/adapters/shared/postgres.rb, line 237 237: def create_schema(name, opts=OPTS) 238: self << create_schema_sql(name, opts) 239: end
Create a trigger in the database. Arguments:
table : | the table on which this trigger operates | ||||||||||
name : | the name of this trigger | ||||||||||
function : | the function to call for this trigger, which should return type trigger. | ||||||||||
opts : | options hash:
|
# File lib/sequel/adapters/shared/postgres.rb, line 252 252: def create_trigger(table, name, function, opts=OPTS) 253: self << create_trigger_sql(table, name, function, opts) 254: end
PostgreSQL uses the :postgres database type.
# File lib/sequel/adapters/shared/postgres.rb, line 257 257: def database_type 258: :postgres 259: end
Use PostgreSQL‘s DO syntax to execute an anonymous code block. The code should be the literal code string to use in the underlying procedural language. Options:
:language : | The procedural language the code is written in. The PostgreSQL default is plpgsql. Can be specified as a string or a symbol. |
# File lib/sequel/adapters/shared/postgres.rb, line 266 266: def do(code, opts=OPTS) 267: language = opts[:language] 268: run "DO #{"LANGUAGE #{literal(language.to_s)} " if language}#{literal(code)}" 269: end
Drops the function from the database. Arguments:
name : | name of the function to drop | ||||||
opts : | options hash:
|
# File lib/sequel/adapters/shared/postgres.rb, line 277 277: def drop_function(name, opts=OPTS) 278: self << drop_function_sql(name, opts) 279: end
Drops a procedural language from the database. Arguments:
name : | name of the procedural language to drop | ||||
opts : | options hash:
|
# File lib/sequel/adapters/shared/postgres.rb, line 286 286: def drop_language(name, opts=OPTS) 287: self << drop_language_sql(name, opts) 288: end
Drops a schema from the database. Arguments:
name : | name of the schema to drop | ||||
opts : | options hash:
|
# File lib/sequel/adapters/shared/postgres.rb, line 295 295: def drop_schema(name, opts=OPTS) 296: self << drop_schema_sql(name, opts) 297: end
Drops a trigger from the database. Arguments:
table : | table from which to drop the trigger | ||||
name : | name of the trigger to drop | ||||
opts : | options hash:
|
# File lib/sequel/adapters/shared/postgres.rb, line 305 305: def drop_trigger(table, name, opts=OPTS) 306: self << drop_trigger_sql(table, name, opts) 307: end
Return full foreign key information using the pg system tables, including :name, :on_delete, :on_update, and :deferrable entries in the hashes.
# File lib/sequel/adapters/shared/postgres.rb, line 311 311: def foreign_key_list(table, opts=OPTS) 312: m = output_identifier_meth 313: schema, _ = opts.fetch(:schema, schema_and_table(table)) 314: range = 0...32 315: 316: base_ds = metadata_dataset. 317: from(:pg_constraint___co). 318: join(:pg_class___cl, :oid=>:conrelid). 319: where(:cl__relkind=>'r', :co__contype=>'f', :cl__oid=>regclass_oid(table)) 320: 321: # We split the parsing into two separate queries, which are merged manually later. 322: # This is because PostgreSQL stores both the referencing and referenced columns in 323: # arrays, and I don't know a simple way to not create a cross product, as PostgreSQL 324: # doesn't appear to have a function that takes an array and element and gives you 325: # the index of that element in the array. 326: 327: ds = base_ds. 328: join(:pg_attribute___att, :attrelid=>:oid, :attnum=>SQL::Function.new(:ANY, :co__conkey)). 329: order(:co__conname, SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(:co__conkey, [x]), x]}, 32, :att__attnum)). 330: select(:co__conname___name, :att__attname___column, :co__confupdtype___on_update, :co__confdeltype___on_delete, 331: SQL::BooleanExpression.new(:AND, :co__condeferrable, :co__condeferred).as(:deferrable)) 332: 333: ref_ds = base_ds. 334: join(:pg_class___cl2, :oid=>:co__confrelid). 335: join(:pg_attribute___att2, :attrelid=>:oid, :attnum=>SQL::Function.new(:ANY, :co__confkey)). 336: order(:co__conname, SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(:co__confkey, [x]), x]}, 32, :att2__attnum)). 337: select(:co__conname___name, :cl2__relname___table, :att2__attname___refcolumn) 338: 339: # If a schema is given, we only search in that schema, and the returned :table 340: # entry is schema qualified as well. 341: if schema 342: ref_ds = ref_ds.join(:pg_namespace___nsp2, :oid=>:cl2__relnamespace). 343: select_more(:nsp2__nspname___schema) 344: end 345: 346: h = {} 347: fklod_map = FOREIGN_KEY_LIST_ON_DELETE_MAP 348: ds.each do |row| 349: if r = h[row[:name]] 350: r[:columns] << m.call(row[:column]) 351: else 352: h[row[:name]] = {:name=>m.call(row[:name]), :columns=>[m.call(row[:column])], :on_update=>fklod_map[row[:on_update]], :on_delete=>fklod_map[row[:on_delete]], :deferrable=>row[:deferrable]} 353: end 354: end 355: ref_ds.each do |row| 356: r = h[row[:name]] 357: r[:table] ||= schema ? SQL::QualifiedIdentifier.new(m.call(row[:schema]), m.call(row[:table])) : m.call(row[:table]) 358: r[:key] ||= [] 359: r[:key] << m.call(row[:refcolumn]) 360: end 361: h.values 362: end
Use the pg_* system tables to determine indexes on a table
# File lib/sequel/adapters/shared/postgres.rb, line 365 365: def indexes(table, opts=OPTS) 366: m = output_identifier_meth 367: range = 0...32 368: attnums = server_version >= 80100 ? SQL::Function.new(:ANY, :ind__indkey) : range.map{|x| SQL::Subscript.new(:ind__indkey, [x])} 369: ds = metadata_dataset. 370: from(:pg_class___tab). 371: join(:pg_index___ind, :indrelid=>:oid). 372: join(:pg_class___indc, :oid=>:indexrelid). 373: join(:pg_attribute___att, :attrelid=>:tab__oid, :attnum=>attnums). 374: left_join(:pg_constraint___con, :conname=>:indc__relname). 375: filter(:indc__relkind=>'i', :ind__indisprimary=>false, :indexprs=>nil, :indpred=>nil, :indisvalid=>true, :tab__oid=>regclass_oid(table, opts)). 376: order(:indc__relname, SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(:ind__indkey, [x]), x]}, 32, :att__attnum)). 377: select(:indc__relname___name, :ind__indisunique___unique, :att__attname___column, :con__condeferrable___deferrable) 378: 379: ds.filter!(:indisready=>true, :indcheckxmin=>false) if server_version >= 80300 380: 381: indexes = {} 382: ds.each do |r| 383: i = indexes[m.call(r[:name])] ||= {:columns=>[], :unique=>r[:unique], :deferrable=>r[:deferrable]} 384: i[:columns] << m.call(r[:column]) 385: end 386: indexes 387: end
Notifies the given channel. See the PostgreSQL NOTIFY documentation. Options:
:payload : | The payload string to use for the NOTIFY statement. Only supported in PostgreSQL 9.0+. |
:server : | The server to which to send the NOTIFY statement, if the sharding support is being used. |
# File lib/sequel/adapters/shared/postgres.rb, line 400 400: def notify(channel, opts=OPTS) 401: sql = String.new 402: sql << "NOTIFY " 403: dataset.send(:identifier_append, sql, channel) 404: if payload = opts[:payload] 405: sql << ", " 406: dataset.literal_append(sql, payload.to_s) 407: end 408: execute_ddl(sql, opts) 409: end
Return primary key for the given table.
# File lib/sequel/adapters/shared/postgres.rb, line 412 412: def primary_key(table, opts=OPTS) 413: quoted_table = quote_schema_table(table) 414: Sequel.synchronize{return @primary_keys[quoted_table] if @primary_keys.has_key?(quoted_table)} 415: sql = "#{SELECT_PK_SQL} AND pg_class.oid = #{literal(regclass_oid(table, opts))}" 416: value = fetch(sql).single_value 417: Sequel.synchronize{@primary_keys[quoted_table] = value} 418: end
Return the sequence providing the default for the primary key for the given table.
# File lib/sequel/adapters/shared/postgres.rb, line 421 421: def primary_key_sequence(table, opts=OPTS) 422: quoted_table = quote_schema_table(table) 423: Sequel.synchronize{return @primary_key_sequences[quoted_table] if @primary_key_sequences.has_key?(quoted_table)} 424: sql = "#{SELECT_SERIAL_SEQUENCE_SQL} AND t.oid = #{literal(regclass_oid(table, opts))}" 425: if pks = fetch(sql).single_record 426: value = literal(SQL::QualifiedIdentifier.new(pks[:schema], pks[:sequence])) 427: Sequel.synchronize{@primary_key_sequences[quoted_table] = value} 428: else 429: sql = "#{SELECT_CUSTOM_SEQUENCE_SQL} AND t.oid = #{literal(regclass_oid(table, opts))}" 430: if pks = fetch(sql).single_record 431: value = literal(SQL::QualifiedIdentifier.new(pks[:schema], LiteralString.new(pks[:sequence]))) 432: Sequel.synchronize{@primary_key_sequences[quoted_table] = value} 433: end 434: end 435: end
Refresh the materialized view with the given name.
DB.refresh_view(:items_view) # REFRESH MATERIALIZED VIEW items_view DB.refresh_view(:items_view, :concurrently=>true) # REFRESH MATERIALIZED VIEW CONCURRENTLY items_view
# File lib/sequel/adapters/shared/postgres.rb, line 443 443: def refresh_view(name, opts=OPTS) 444: run "REFRESH MATERIALIZED VIEW#{' CONCURRENTLY' if opts[:concurrently]} #{quote_schema_table(name)}" 445: end
Reset the database‘s conversion procs, requires a server query if there any named types.
# File lib/sequel/adapters/shared/postgres.rb, line 449 449: def reset_conversion_procs 450: @conversion_procs = get_conversion_procs 451: conversion_procs_updated 452: @conversion_procs 453: end
Reset the primary key sequence for the given table, basing it on the maximum current value of the table‘s primary key.
# File lib/sequel/adapters/shared/postgres.rb, line 457 457: def reset_primary_key_sequence(table) 458: return unless seq = primary_key_sequence(table) 459: pk = SQL::Identifier.new(primary_key(table)) 460: db = self 461: seq_ds = db.from(LiteralString.new(seq)) 462: s, t = schema_and_table(table) 463: table = Sequel.qualify(s, t) if s 464: get{setval(seq, db[table].select{coalesce(max(pk)+seq_ds.select{:increment_by}, seq_ds.select(:min_value))}, false)} 465: end
Rollback an existing prepared transaction with the given transaction identifier string.
# File lib/sequel/adapters/shared/postgres.rb, line 469 469: def rollback_prepared_transaction(transaction_id, opts=OPTS) 470: run("ROLLBACK PREPARED #{literal(transaction_id)}", opts) 471: end
PostgreSQL uses SERIAL psuedo-type instead of AUTOINCREMENT for managing incrementing primary keys.
# File lib/sequel/adapters/shared/postgres.rb, line 475 475: def serial_primary_key_options 476: {:primary_key => true, :serial => true, :type=>Integer} 477: end
The version of the PostgreSQL server, used for determining capability.
# File lib/sequel/adapters/shared/postgres.rb, line 480 480: def server_version(server=nil) 481: return @server_version if @server_version 482: @server_version = synchronize(server) do |conn| 483: (conn.server_version rescue nil) if conn.respond_to?(:server_version) 484: end 485: unless @server_version 486: @server_version = if m = /PostgreSQL (\d+)\.(\d+)(?:(?:rc\d+)|\.(\d+))?/.match(fetch('SELECT version()').single_value) 487: (m[1].to_i * 10000) + (m[2].to_i * 100) + m[3].to_i 488: else 489: 0 490: end 491: end 492: warn 'Sequel no longer supports PostgreSQL <8.2, some things may not work' if @server_version < 80200 493: @server_version 494: end
PostgreSQL supports CREATE TABLE IF NOT EXISTS on 9.1+
# File lib/sequel/adapters/shared/postgres.rb, line 497 497: def supports_create_table_if_not_exists? 498: server_version >= 90100 499: end
PostgreSQL 9.0+ supports some types of deferrable constraints beyond foreign key constraints.
# File lib/sequel/adapters/shared/postgres.rb, line 502 502: def supports_deferrable_constraints? 503: server_version >= 90000 504: end
PostgreSQL supports deferrable foreign key constraints.
# File lib/sequel/adapters/shared/postgres.rb, line 507 507: def supports_deferrable_foreign_key_constraints? 508: true 509: end
PostgreSQL supports DROP TABLE IF EXISTS
# File lib/sequel/adapters/shared/postgres.rb, line 512 512: def supports_drop_table_if_exists? 513: true 514: end
PostgreSQL supports prepared transactions (two-phase commit) if max_prepared_transactions is greater than 0.
# File lib/sequel/adapters/shared/postgres.rb, line 528 528: def supports_prepared_transactions? 529: return @supports_prepared_transactions if defined?(@supports_prepared_transactions) 530: @supports_prepared_transactions = self['SHOW max_prepared_transactions'].get.to_i > 0 531: end
PostgreSQL supports savepoints
# File lib/sequel/adapters/shared/postgres.rb, line 534 534: def supports_savepoints? 535: true 536: end
PostgreSQL supports transaction isolation levels
# File lib/sequel/adapters/shared/postgres.rb, line 539 539: def supports_transaction_isolation_levels? 540: true 541: end
PostgreSQL supports transaction DDL statements.
# File lib/sequel/adapters/shared/postgres.rb, line 544 544: def supports_transactional_ddl? 545: true 546: end
PostgreSQL 9.0+ supports trigger conditions.
# File lib/sequel/adapters/shared/postgres.rb, line 522 522: def supports_trigger_conditions? 523: server_version >= 90000 524: end
Array of symbols specifying table names in the current database. The dataset used is yielded to the block if one is provided, otherwise, an array of symbols of table names is returned.
Options:
:qualify : | Return the tables as Sequel::SQL::QualifiedIdentifier instances, using the schema the table is located in as the qualifier. |
:schema : | The schema to search |
:server : | The server to use |
# File lib/sequel/adapters/shared/postgres.rb, line 557 557: def tables(opts=OPTS, &block) 558: pg_class_relname('r', opts, &block) 559: end
Check whether the given type name string/symbol (e.g. :hstore) is supported by the database.
# File lib/sequel/adapters/shared/postgres.rb, line 563 563: def type_supported?(type) 564: @supported_types ||= {} 565: @supported_types.fetch(type){@supported_types[type] = (from(:pg_type).filter(:typtype=>'b', :typname=>type.to_s).count > 0)} 566: end
Creates a dataset that uses the VALUES clause:
DB.values([[1, 2], [3, 4]]) VALUES ((1, 2), (3, 4)) DB.values([[1, 2], [3, 4]]).order(:column2).limit(1, 1) VALUES ((1, 2), (3, 4)) ORDER BY column2 LIMIT 1 OFFSET 1
# File lib/sequel/adapters/shared/postgres.rb, line 575 575: def values(v) 576: @default_dataset.clone(:values=>v) 577: end
Array of symbols specifying view names in the current database.
Options:
:qualify : | Return the views as Sequel::SQL::QualifiedIdentifier instances, using the schema the view is located in as the qualifier. |
:schema : | The schema to search |
:server : | The server to use |
# File lib/sequel/adapters/shared/postgres.rb, line 586 586: def views(opts=OPTS) 587: pg_class_relname('v', opts) 588: end