Module | Sequel::DatabaseMethods |
In: |
lib/sequel/adapters/shared/postgres.rb
|
PREPARED_ARG_PLACEHOLDER | = | LiteralString.new('$').freeze | ||
FOREIGN_KEY_LIST_ON_DELETE_MAP | = | {'a'=>:no_action, 'r'=>:restrict, 'c'=>:cascade, 'n'=>:set_null, 'd'=>:set_default}.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.each(&: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. |
Set a conversion proc for the given oid. The callable can be passed either as a argument or a block.
# File lib/sequel/adapters/shared/postgres.rb, line 201 201: def add_conversion_proc(oid, callable=Proc.new) 202: conversion_procs[oid] = callable 203: end
Add a conversion proc for a named type, using the given block. This should be used for types without fixed OIDs, which includes all types that are not included in a default PostgreSQL installation.
# File lib/sequel/adapters/shared/postgres.rb, line 208 208: def add_named_conversion_proc(name, &block) 209: name = name.to_s if name.is_a?(Symbol) 210: unless oid = from(:pg_type).where(:typtype=>['b', 'e'], :typname=>name.to_s).get(:oid) 211: raise Error, "No matching type in pg_type for #{name.inspect}" 212: end 213: add_conversion_proc(oid, block) 214: end
# File lib/sequel/adapters/shared/postgres.rb, line 216 216: def commit_prepared_transaction(transaction_id, opts=OPTS) 217: run("COMMIT PREPARED #{literal(transaction_id)}", opts) 218: 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 240 240: def create_function(name, definition, opts=OPTS) 241: self << create_function_sql(name, definition, opts) 242: 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 251 251: def create_language(name, opts=OPTS) 252: self << create_language_sql(name, opts) 253: 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 260 260: def create_schema(name, opts=OPTS) 261: self << create_schema_sql(name, opts) 262: 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 275 275: def create_trigger(table, name, function, opts=OPTS) 276: self << create_trigger_sql(table, name, function, opts) 277: end
# File lib/sequel/adapters/shared/postgres.rb, line 279 279: def database_type 280: :postgres 281: 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 288 288: def do(code, opts=OPTS) 289: language = opts[:language] 290: run "DO #{"LANGUAGE #{literal(language.to_s)} " if language}#{literal(code)}" 291: 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 299 299: def drop_function(name, opts=OPTS) 300: self << drop_function_sql(name, opts) 301: 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 308 308: def drop_language(name, opts=OPTS) 309: self << drop_language_sql(name, opts) 310: 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 317 317: def drop_schema(name, opts=OPTS) 318: self << drop_schema_sql(name, opts) 319: 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 327 327: def drop_trigger(table, name, opts=OPTS) 328: self << drop_trigger_sql(table, name, opts) 329: 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 333 333: def foreign_key_list(table, opts=OPTS) 334: m = output_identifier_meth 335: schema, _ = opts.fetch(:schema, schema_and_table(table)) 336: oid = regclass_oid(table) 337: 338: if server_version >= 90500 339: cpos = Sequel.expr{array_position(co[:conkey], att[:attnum])} 340: rpos = Sequel.expr{array_position(co[:confkey], att2[:attnum])} 341: else 342: range = 0...32 343: cpos = Sequel.expr{SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(co[:conkey], [x]), x]}, 32, att[:attnum])} 344: rpos = Sequel.expr{SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(co[:confkey], [x]), x]}, 32, att2[:attnum])} 345: end 346: 347: ds = metadata_dataset. 348: from{pg_constraint.as(:co)}. 349: join(Sequel[:pg_class].as(:cl), :oid=>:conrelid). 350: join(Sequel[:pg_attribute].as(:att), :attrelid=>:oid, :attnum=>SQL::Function.new(:ANY, Sequel[:co][:conkey])). 351: join(Sequel[:pg_class].as(:cl2), :oid=>Sequel[:co][:confrelid]). 352: join(Sequel[:pg_attribute].as(:att2), :attrelid=>:oid, :attnum=>SQL::Function.new(:ANY, Sequel[:co][:confkey])). 353: order{[co[:conname], cpos]}. 354: where{{ 355: cl[:relkind]=>'r', 356: co[:contype]=>'f', 357: cl[:oid]=>oid, 358: cpos=>rpos 359: }}. 360: select{[ 361: co[:conname].as(:name), 362: att[:attname].as(:column), 363: co[:confupdtype].as(:on_update), 364: co[:confdeltype].as(:on_delete), 365: cl2[:relname].as(:table), 366: att2[:attname].as(:refcolumn), 367: SQL::BooleanExpression.new(:AND, co[:condeferrable], co[:condeferred]).as(:deferrable) 368: ]} 369: 370: # If a schema is given, we only search in that schema, and the returned :table 371: # entry is schema qualified as well. 372: if schema 373: ds = ds.join(Sequel[:pg_namespace].as(:nsp2), :oid=>Sequel[:cl2][:relnamespace]). 374: select_append{nsp2[:nspname].as(:schema)} 375: end 376: 377: h = {} 378: fklod_map = FOREIGN_KEY_LIST_ON_DELETE_MAP 379: 380: ds.each do |row| 381: if r = h[row[:name]] 382: r[:columns] << m.call(row[:column]) 383: r[:key] << m.call(row[:refcolumn]) 384: else 385: h[row[:name]] = { 386: :name=>m.call(row[:name]), 387: :columns=>[m.call(row[:column])], 388: :key=>[m.call(row[:refcolumn])], 389: :on_update=>fklod_map[row[:on_update]], 390: :on_delete=>fklod_map[row[:on_delete]], 391: :deferrable=>row[:deferrable], 392: :table=>schema ? SQL::QualifiedIdentifier.new(m.call(row[:schema]), m.call(row[:table])) : m.call(row[:table]) 393: } 394: end 395: end 396: 397: h.values 398: end
# File lib/sequel/adapters/shared/postgres.rb, line 400 400: def freeze 401: server_version 402: supports_prepared_transactions? 403: @conversion_procs.freeze 404: super 405: end
Use the pg_* system tables to determine indexes on a table
# File lib/sequel/adapters/shared/postgres.rb, line 408 408: def indexes(table, opts=OPTS) 409: m = output_identifier_meth 410: oid = regclass_oid(table, opts) 411: 412: if server_version >= 90500 413: order = [Sequel[:indc][:relname], Sequel.function(:array_position, Sequel[:ind][:indkey], Sequel[:att][:attnum])] 414: else 415: range = 0...32 416: order = [Sequel[:indc][:relname], SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(Sequel[:ind][:indkey], [x]), x]}, 32, Sequel[:att][:attnum])] 417: attnums = range.map{|x| SQL::Subscript.new(Sequel[:ind][:indkey], [x])} unless server_version >= 80100 418: end 419: 420: attnums ||= SQL::Function.new(:ANY, Sequel[:ind][:indkey]) 421: 422: ds = metadata_dataset. 423: from{pg_class.as(:tab)}. 424: join(Sequel[:pg_index].as(:ind), :indrelid=>:oid). 425: join(Sequel[:pg_class].as(:indc), :oid=>:indexrelid). 426: join(Sequel[:pg_attribute].as(:att), :attrelid=>Sequel[:tab][:oid], :attnum=>attnums). 427: left_join(Sequel[:pg_constraint].as(:con), :conname=>Sequel[:indc][:relname]). 428: where{{ 429: indc[:relkind]=>'i', 430: ind[:indisprimary]=>false, 431: :indexprs=>nil, 432: :indpred=>nil, 433: :indisvalid=>true, 434: tab[:oid]=>oid}}. 435: order(*order). 436: select{[indc[:relname].as(:name), ind[:indisunique].as(:unique), att[:attname].as(:column), con[:condeferrable].as(:deferrable)]} 437: 438: ds = ds.where(:indisready=>true, :indcheckxmin=>false) if server_version >= 80300 439: 440: indexes = {} 441: ds.each do |r| 442: i = indexes[m.call(r[:name])] ||= {:columns=>[], :unique=>r[:unique], :deferrable=>r[:deferrable]} 443: i[:columns] << m.call(r[:column]) 444: end 445: indexes 446: 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 459 459: def notify(channel, opts=OPTS) 460: sql = String.new 461: sql << "NOTIFY " 462: dataset.send(:identifier_append, sql, channel) 463: if payload = opts[:payload] 464: sql << ", " 465: dataset.literal_append(sql, payload.to_s) 466: end 467: execute_ddl(sql, opts) 468: end
Return primary key for the given table.
# File lib/sequel/adapters/shared/postgres.rb, line 471 471: def primary_key(table, opts=OPTS) 472: quoted_table = quote_schema_table(table) 473: Sequel.synchronize{return @primary_keys[quoted_table] if @primary_keys.has_key?(quoted_table)} 474: sql = "#{SELECT_PK_SQL} AND pg_class.oid = #{literal(regclass_oid(table, opts))}" 475: value = fetch(sql).single_value 476: Sequel.synchronize{@primary_keys[quoted_table] = value} 477: end
Return the sequence providing the default for the primary key for the given table.
# File lib/sequel/adapters/shared/postgres.rb, line 480 480: def primary_key_sequence(table, opts=OPTS) 481: quoted_table = quote_schema_table(table) 482: Sequel.synchronize{return @primary_key_sequences[quoted_table] if @primary_key_sequences.has_key?(quoted_table)} 483: sql = "#{SELECT_SERIAL_SEQUENCE_SQL} AND t.oid = #{literal(regclass_oid(table, opts))}" 484: if pks = fetch(sql).single_record 485: value = literal(SQL::QualifiedIdentifier.new(pks[:schema], pks[:sequence])) 486: Sequel.synchronize{@primary_key_sequences[quoted_table] = value} 487: else 488: sql = "#{SELECT_CUSTOM_SEQUENCE_SQL} AND t.oid = #{literal(regclass_oid(table, opts))}" 489: if pks = fetch(sql).single_record 490: value = literal(SQL::QualifiedIdentifier.new(pks[:schema], LiteralString.new(pks[:sequence]))) 491: Sequel.synchronize{@primary_key_sequences[quoted_table] = value} 492: end 493: end 494: 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 502 502: def refresh_view(name, opts=OPTS) 503: run "REFRESH MATERIALIZED VIEW#{' CONCURRENTLY' if opts[:concurrently]} #{quote_schema_table(name)}" 504: 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 508 508: def reset_primary_key_sequence(table) 509: return unless seq = primary_key_sequence(table) 510: pk = SQL::Identifier.new(primary_key(table)) 511: db = self 512: seq_ds = db.from(LiteralString.new(seq)) 513: s, t = schema_and_table(table) 514: table = Sequel.qualify(s, t) if s 515: get{setval(seq, db[table].select{coalesce(max(pk)+seq_ds.select{:increment_by}, seq_ds.select(:min_value))}, false)} 516: end
# File lib/sequel/adapters/shared/postgres.rb, line 518 518: def rollback_prepared_transaction(transaction_id, opts=OPTS) 519: run("ROLLBACK PREPARED #{literal(transaction_id)}", opts) 520: end
PostgreSQL uses SERIAL psuedo-type instead of AUTOINCREMENT for managing incrementing primary keys.
# File lib/sequel/adapters/shared/postgres.rb, line 524 524: def serial_primary_key_options 525: {:primary_key => true, :serial => true, :type=>Integer} 526: end
The version of the PostgreSQL server, used for determining capability.
# File lib/sequel/adapters/shared/postgres.rb, line 529 529: def server_version(server=nil) 530: return @server_version if @server_version 531: @server_version = synchronize(server) do |conn| 532: (conn.server_version rescue nil) if conn.respond_to?(:server_version) 533: end 534: unless @server_version 535: @server_version = if m = /PostgreSQL (\d+)\.(\d+)(?:(?:rc\d+)|\.(\d+))?/.match(fetch('SELECT version()').single_value) 536: (m[1].to_i * 10000) + (m[2].to_i * 100) + m[3].to_i 537: else 538: 0 539: end 540: end 541: @server_version 542: end
PostgreSQL supports CREATE TABLE IF NOT EXISTS on 9.1+
# File lib/sequel/adapters/shared/postgres.rb, line 545 545: def supports_create_table_if_not_exists? 546: server_version >= 90100 547: end
PostgreSQL 9.0+ supports some types of deferrable constraints beyond foreign key constraints.
# File lib/sequel/adapters/shared/postgres.rb, line 550 550: def supports_deferrable_constraints? 551: server_version >= 90000 552: end
PostgreSQL supports deferrable foreign key constraints.
# File lib/sequel/adapters/shared/postgres.rb, line 555 555: def supports_deferrable_foreign_key_constraints? 556: true 557: end
PostgreSQL supports DROP TABLE IF EXISTS
# File lib/sequel/adapters/shared/postgres.rb, line 560 560: def supports_drop_table_if_exists? 561: true 562: end
PostgreSQL supports prepared transactions (two-phase commit) if max_prepared_transactions is greater than 0.
# File lib/sequel/adapters/shared/postgres.rb, line 576 576: def supports_prepared_transactions? 577: return @supports_prepared_transactions if defined?(@supports_prepared_transactions) 578: @supports_prepared_transactions = self['SHOW max_prepared_transactions'].get.to_i > 0 579: end
PostgreSQL supports savepoints
# File lib/sequel/adapters/shared/postgres.rb, line 582 582: def supports_savepoints? 583: true 584: end
PostgreSQL supports transaction isolation levels
# File lib/sequel/adapters/shared/postgres.rb, line 587 587: def supports_transaction_isolation_levels? 588: true 589: end
PostgreSQL supports transaction DDL statements.
# File lib/sequel/adapters/shared/postgres.rb, line 592 592: def supports_transactional_ddl? 593: true 594: end
PostgreSQL 9.0+ supports trigger conditions.
# File lib/sequel/adapters/shared/postgres.rb, line 570 570: def supports_trigger_conditions? 571: server_version >= 90000 572: 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 605 605: def tables(opts=OPTS, &block) 606: pg_class_relname('r', opts, &block) 607: 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 611 611: def type_supported?(type) 612: Sequel.synchronize{return @supported_types[type] if @supported_types.has_key?(type)} 613: supported = from(:pg_type).where(:typtype=>'b', :typname=>type.to_s).count > 0 614: Sequel.synchronize{return @supported_types[type] = supported} 615: 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 624 624: def values(v) 625: @default_dataset.clone(:values=>v) 626: end
Array of symbols specifying view names in the current database.
Options:
:materialized : | Return materialized views |
: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 636 636: def views(opts=OPTS) 637: relkind = opts[:materialized] ? 'm' : 'v' 638: pg_class_relname(relkind, opts) 639: end