Module Sequel::Postgres::DatabaseMethods
In: lib/sequel/adapters/shared/postgres.rb

Methods shared by Database instances that connect to PostgreSQL.

Methods

Constants

EXCLUDE_SCHEMAS = /pg_*|information_schema/i
PREPARED_ARG_PLACEHOLDER = LiteralString.new('$').freeze
RE_CURRVAL_ERROR = /currval of sequence "(.*)" is not yet defined in this session|relation "(.*)" does not exist/.freeze
SYSTEM_TABLE_REGEXP = /^pg|sql/.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
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 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 cons.contype = 'p' end_sql   SQL fragment for getting sequence associated with table‘s primary key, assuming it was a serial primary key column.
RESET_PROCS_EXTENSIONS = [:pg_array, :pg_hstore, :pg_inet, :pg_interval, :pg_json, :pg_range].freeze   The Sequel extensions that require reseting of the conversion procs.

Attributes

conversion_procs  [R]  A hash of conversion procs, keyed by type integer (oid) and having callable values for the conversion proc for that type.

Public Instance methods

Commit an existing prepared transaction with the given transaction identifier string.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 163
163:       def commit_prepared_transaction(transaction_id)
164:         run("COMMIT PREPARED #{literal(transaction_id)}")
165:       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:
    • :args : function arguments, can be either a symbol or string specifying a type or an array of 1-3 elements:
      • element 1 : argument data type
      • element 2 : argument name
      • element 3 : argument mode (e.g. in, out, inout)
    • :behavior : Should be IMMUTABLE, STABLE, or VOLATILE. PostgreSQL assumes VOLATILE by default.
    • :cost : The estimated cost of the function, used by the query planner.
    • :language : The language the function uses. SQL is the default.
    • :link_symbol : For a dynamically loaded see function, the function‘s link symbol if different from the definition argument.
    • :returns : The data type returned by the function. If you are using OUT or INOUT argument modes, this is ignored. Otherwise, if this is not specified, void is used by default to specify the function is not supposed to return a value.
    • :rows : The estimated number of rows the function will return. Only use if the function returns SETOF something.
    • :security_definer : Makes the privileges of the function the same as the privileges of the user who defined the function instead of the privileges of the user who runs the function. There are security implications when doing this, see the PostgreSQL documentation.
    • :set : Configuration variables to set while the function is being run, can be a hash or an array of two pairs. search_path is often used here if :security_definer is used.
    • :strict : Makes the function return NULL when any argument is NULL.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 187
187:       def create_function(name, definition, opts={})
188:         self << create_function_sql(name, definition, opts)
189:       end

Create the procedural language in the database. Arguments:

  • name : Name of the procedural language (e.g. plpgsql)
  • opts : options hash:
    • :handler : The name of a previously registered function used as a call handler for this language.
    • :replace: Replace the installed language if it already exists (on PostgreSQL 9.0+).
    • :trusted : Marks the language being created as trusted, allowing unprivileged users to create functions using this language.
    • :validator : The name of previously registered function used as a validator of functions defined in this language.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 198
198:       def create_language(name, opts={})
199:         self << create_language_sql(name, opts)
200:       end

Create a schema in the database. Arguments:

  • name : Name of the schema (e.g. admin)

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 204
204:       def create_schema(name)
205:         self << create_schema_sql(name)
206:       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:
    • :after : Calls the trigger after execution instead of before.
    • :args : An argument or array of arguments to pass to the function.
    • :each_row : Calls the trigger for each row instead of for each statement.
    • :events : Can be :insert, :update, :delete, or an array of any of those. Calls the trigger whenever that type of statement is used. By default, the trigger is called for insert, update, or delete.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 218
218:       def create_trigger(table, name, function, opts={})
219:         self << create_trigger_sql(table, name, function, opts)
220:       end

PostgreSQL uses the :postgres database type.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 223
223:       def database_type
224:         :postgres
225:       end

Drops the function from the database. Arguments:

  • name : name of the function to drop
  • opts : options hash:
    • :args : The arguments for the function. See create_function_sql.
    • :cascade : Drop other objects depending on this function.
    • :if_exists : Don‘t raise an error if the function doesn‘t exist.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 233
233:       def drop_function(name, opts={})
234:         self << drop_function_sql(name, opts)
235:       end

Drops a procedural language from the database. Arguments:

  • name : name of the procedural language to drop
  • opts : options hash:
    • :cascade : Drop other objects depending on this function.
    • :if_exists : Don‘t raise an error if the function doesn‘t exist.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 242
242:       def drop_language(name, opts={})
243:         self << drop_language_sql(name, opts)
244:       end

Drops a schema from the database. Arguments:

  • name : name of the schema to drop
  • opts : options hash:
    • :cascade : Drop all objects in this schema.
    • :if_exists : Don‘t raise an error if the schema doesn‘t exist.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 251
251:       def drop_schema(name, opts={})
252:         self << drop_schema_sql(name, opts)
253:       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:
    • :cascade : Drop other objects depending on this function.
    • :if_exists : Don‘t raise an error if the function doesn‘t exist.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 261
261:       def drop_trigger(table, name, opts={})
262:         self << drop_trigger_sql(table, name, opts)
263:       end

If any of the extensions that require reseting the conversion procs is loaded, reset them. This is done here so that if you load multiple pg_* extensions in the same call, the conversion procs are only reset once instead of once for every extension.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 269
269:       def extension(*exts)
270:         super
271:         unless (RESET_PROCS_EXTENSIONS & exts).empty?
272:           reset_conversion_procs
273:         end
274:       end

Return full foreign key information using the pg system tables, including :name, :on_delete, :on_update, and :deferrable entries in the hashes.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 278
278:       def foreign_key_list(table, opts={})
279:         m = output_identifier_meth
280:         im = input_identifier_meth
281:         schema, table = schema_and_table(table)
282:         range = 0...32
283: 
284:         base_ds = metadata_dataset.
285:           where(:cl__relkind=>'r', :co__contype=>'f', :cl__relname=>im.call(table)).
286:           from(:pg_constraint___co).
287:           join(:pg_class___cl, :oid=>:conrelid)
288: 
289:         # We split the parsing into two separate queries, which are merged manually later.
290:         # This is because PostgreSQL stores both the referencing and referenced columns in
291:         # arrays, and I don't know a simple way to not create a cross product, as PostgreSQL
292:         # doesn't appear to have a function that takes an array and element and gives you
293:         # the index of that element in the array.
294: 
295:         ds = base_ds.
296:           join(:pg_attribute___att, :attrelid=>:oid, :attnum=>SQL::Function.new(:ANY, :co__conkey)).
297:           order(:co__conname, SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(:co__conkey, [x]), x]}, 32, :att__attnum)).
298:           select(:co__conname___name, :att__attname___column, :co__confupdtype___on_update, :co__confdeltype___on_delete,
299:                  SQL::BooleanExpression.new(:AND, :co__condeferrable, :co__condeferred).as(:deferrable))
300: 
301:         ref_ds = base_ds.
302:           join(:pg_class___cl2, :oid=>:co__confrelid).
303:           join(:pg_attribute___att2, :attrelid=>:oid, :attnum=>SQL::Function.new(:ANY, :co__confkey)).
304:           order(:co__conname, SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(:co__conkey, [x]), x]}, 32, :att2__attnum)).
305:           select(:co__conname___name, :cl2__relname___table, :att2__attname___refcolumn)
306: 
307:         # If a schema is given, we only search in that schema, and the returned :table
308:         # entry is schema qualified as well.
309:         if schema
310:           ds = ds.join(:pg_namespace___nsp, :oid=>:cl__relnamespace).
311:             where(:nsp__nspname=>im.call(schema))
312:           ref_ds = ref_ds.join(:pg_namespace___nsp2, :oid=>:cl2__relnamespace).
313:             select_more(:nsp2__nspname___schema)
314:         end
315: 
316:         h = {}
317:         fklod_map = FOREIGN_KEY_LIST_ON_DELETE_MAP 
318:         ds.each do |row|
319:           if r = h[row[:name]]
320:             r[:columns] << m.call(row[:column])
321:           else
322:             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]}
323:           end
324:         end
325:         ref_ds.each do |row|
326:           r = h[row[:name]]
327:           r[:table] ||= schema ? SQL::QualifiedIdentifier.new(m.call(row[:schema]), m.call(row[:table])) : m.call(row[:table])
328:           r[:key] ||= []
329:           r[:key] << m.call(row[:refcolumn])
330:         end
331:         h.values
332:       end

Use the pg_* system tables to determine indexes on a table

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 335
335:       def indexes(table, opts={})
336:         m = output_identifier_meth
337:         im = input_identifier_meth
338:         schema, table = schema_and_table(table)
339:         range = 0...32
340:         attnums = server_version >= 80100 ? SQL::Function.new(:ANY, :ind__indkey) : range.map{|x| SQL::Subscript.new(:ind__indkey, [x])}
341:         ds = metadata_dataset.
342:           from(:pg_class___tab).
343:           join(:pg_index___ind, :indrelid=>:oid, im.call(table)=>:relname).
344:           join(:pg_class___indc, :oid=>:indexrelid).
345:           join(:pg_attribute___att, :attrelid=>:tab__oid, :attnum=>attnums).
346:           filter(:indc__relkind=>'i', :ind__indisprimary=>false, :indexprs=>nil, :indpred=>nil, :indisvalid=>true).
347:           order(:indc__relname, SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(:ind__indkey, [x]), x]}, 32, :att__attnum)).
348:           select(:indc__relname___name, :ind__indisunique___unique, :att__attname___column)
349: 
350:         ds.join!(:pg_namespace___nsp, :oid=>:tab__relnamespace, :nspname=>schema.to_s) if schema
351:         ds.filter!(:indisready=>true, :indcheckxmin=>false) if server_version >= 80300
352: 
353:         indexes = {}
354:         ds.each do |r|
355:           i = indexes[m.call(r[:name])] ||= {:columns=>[], :unique=>r[:unique]}
356:           i[:columns] << m.call(r[:column])
357:         end
358:         indexes
359:       end

Dataset containing all current database locks

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 362
362:       def locks
363:         dataset.from(:pg_class).join(:pg_locks, :relation=>:relfilenode).select(:pg_class__relname, Sequel::SQL::ColumnAll.new(:pg_locks))
364:       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.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 372
372:       def notify(channel, opts={})
373:         execute_ddl("NOTIFY #{channel}#{", #{literal(opts[:payload].to_s)}" if opts[:payload]}", opts)
374:       end

Return primary key for the given table.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 377
377:       def primary_key(table, opts={})
378:         quoted_table = quote_schema_table(table)
379:         @primary_keys.fetch(quoted_table) do
380:           schema, table = schema_and_table(table)
381:           sql = "#{SELECT_PK_SQL} AND pg_class.relname = #{literal(table)}"
382:           sql << "AND pg_namespace.nspname = #{literal(schema)}" if schema
383:           @primary_keys[quoted_table] = fetch(sql).single_value
384:         end
385:       end

Return the sequence providing the default for the primary key for the given table.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 388
388:       def primary_key_sequence(table, opts={})
389:         quoted_table = quote_schema_table(table)
390:         @primary_key_sequences.fetch(quoted_table) do
391:           schema, table = schema_and_table(table)
392:           table = literal(table)
393:           sql = "#{SELECT_SERIAL_SEQUENCE_SQL} AND seq.relname = #{table}"
394:           sql << " AND name.nspname = #{literal(schema)}" if schema
395:           unless pks = fetch(sql).single_record
396:             sql = "#{SELECT_CUSTOM_SEQUENCE_SQL} AND t.relname = #{table}"
397:             sql << " AND name.nspname = #{literal(schema)}" if schema
398:             pks = fetch(sql).single_record
399:           end
400: 
401:           @primary_key_sequences[quoted_table] = if pks
402:             literal(SQL::QualifiedIdentifier.new(pks[:schema], LiteralString.new(pks[:sequence])))
403:           end
404:         end
405:       end

Reset the database‘s conversion procs, requires a server query if there any named types.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 409
409:       def reset_conversion_procs
410:         @conversion_procs = get_conversion_procs
411:       end

Reset the primary key sequence for the given table, baseing it on the maximum current value of the table‘s primary key.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 415
415:       def reset_primary_key_sequence(table)
416:         return unless seq = primary_key_sequence(table)
417:         pk = SQL::Identifier.new(primary_key(table))
418:         db = self
419:         seq_ds = db.from(LiteralString.new(seq))
420:         get{setval(seq, db[table].select{coalesce(max(pk)+seq_ds.select{:increment_by}, seq_ds.select(:min_value))}, false)}
421:       end

Rollback an existing prepared transaction with the given transaction identifier string.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 425
425:       def rollback_prepared_transaction(transaction_id)
426:         run("ROLLBACK PREPARED #{literal(transaction_id)}")
427:       end

PostgreSQL uses SERIAL psuedo-type instead of AUTOINCREMENT for managing incrementing primary keys.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 431
431:       def serial_primary_key_options
432:         {:primary_key => true, :serial => true, :type=>Integer}
433:       end

The version of the PostgreSQL server, used for determining capability.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 436
436:       def server_version(server=nil)
437:         return @server_version if @server_version
438:         @server_version = synchronize(server) do |conn|
439:           (conn.server_version rescue nil) if conn.respond_to?(:server_version)
440:         end
441:         unless @server_version
442:           @server_version = if m = /PostgreSQL (\d+)\.(\d+)(?:(?:rc\d+)|\.(\d+))?/.match(fetch('SELECT version()').single_value)
443:             (m[1].to_i * 10000) + (m[2].to_i * 100) + m[3].to_i
444:           else
445:             0
446:           end
447:         end
448:         warn 'Sequel no longer supports PostgreSQL <8.2, some things may not work' if @server_version < 80200
449:         @server_version
450:       end

PostgreSQL supports CREATE TABLE IF NOT EXISTS on 9.1+

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 453
453:       def supports_create_table_if_not_exists?
454:         server_version >= 90100
455:       end

PostgreSQL supports DROP TABLE IF EXISTS

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 458
458:       def supports_drop_table_if_exists?
459:         true
460:       end

PostgreSQL supports prepared transactions (two-phase commit) if max_prepared_transactions is greater than 0.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 464
464:       def supports_prepared_transactions?
465:         return @supports_prepared_transactions if defined?(@supports_prepared_transactions)
466:         @supports_prepared_transactions = self['SHOW max_prepared_transactions'].get.to_i > 0
467:       end

PostgreSQL supports savepoints

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 470
470:       def supports_savepoints?
471:         true
472:       end

PostgreSQL supports transaction isolation levels

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 475
475:       def supports_transaction_isolation_levels?
476:         true
477:       end

PostgreSQL supports transaction DDL statements.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 480
480:       def supports_transactional_ddl?
481:         true
482:       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:

  • :schema - The schema to search (default_schema by default)
  • :server - The server to use

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 491
491:       def tables(opts={}, &block)
492:         pg_class_relname('r', opts, &block)
493:       end

Check whether the given type name string/symbol (e.g. :hstore) is supported by the database.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 497
497:       def type_supported?(type)
498:         @supported_types ||= {}
499:         @supported_types.fetch(type){@supported_types[type] = (from(:pg_type).filter(:typtype=>'b', :typname=>type.to_s).count > 0)}
500:       end

Array of symbols specifying view names in the current database.

Options:

  • :schema - The schema to search (default_schema by default)
  • :server - The server to use

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 507
507:       def views(opts={})
508:         pg_class_relname('v', opts)
509:       end

[Validate]