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

Methods

Included Modules

UnmodifiedIdentifiers::DatabaseMethods

Constants

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], [/could not obtain lock on row in relation/, DatabaseLockTimeout], ].freeze

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

Set a conversion proc for the given oid. The callable can be passed either as a argument or a block.

[Source]

     # 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.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 208
208:       def add_named_conversion_proc(name, &block)
209:         unless oid = from(:pg_type).where(:typtype=>['b', 'e'], :typname=>name.to_s).get(:oid)
210:           raise Error, "No matching type in pg_type for #{name.inspect}"
211:         end
212:         add_conversion_proc(oid, block)
213:       end

A hash of metadata for CHECK constraints on the table. Keys are CHECK constraint name symbols. Values are hashes with the following keys:

:definition :An SQL fragment for the definition of the constraint
:columns :An array of column symbols for the columns referenced in the constraint

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 223
223:       def check_constraints(table)
224:         m = output_identifier_meth
225: 
226:         rows = metadata_dataset.
227:           from{pg_constraint.as(:co)}.
228:           join(Sequel[:pg_attribute].as(:att), :attrelid=>:conrelid, :attnum=>SQL::Function.new(:ANY, Sequel[:co][:conkey])).
229:           where(:conrelid=>regclass_oid(table), :contype=>'c').
230:           select{[co[:conname].as(:constraint), att[:attname].as(:column), pg_get_constraintdef(co[:oid]).as(:definition)]}
231: 
232:         hash = {}
233:         rows.each do |row|
234:           constraint = m.call(row[:constraint])
235:           if entry = hash[constraint]
236:             entry[:columns] << m.call(row[:column])
237:           else
238:             hash[constraint] = {:definition=>row[:definition], :columns=>[m.call(row[:column])]}
239:           end
240:         end
241:         
242:         hash
243:       end

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 215
215:       def commit_prepared_transaction(transaction_id, opts=OPTS)
216:         run("COMMIT PREPARED #{literal(transaction_id)}", opts)
217:       end

Convert the first primary key column in the table from being a serial column to being an identity column. If the column is already an identity column, assume it was already converted and make no changes.

Only supported on PostgreSQL 10.2+, since on those versions Sequel will use identity columns instead of serial columns for auto incrementing primary keys. Only supported when running as a superuser, since regular users cannot modify system tables, and there is no way to keep an existing sequence when changing an existing column to be an identity column.

This method can raise an exception in at least the following cases where it may otherwise succeed (there may be additional cases not listed here):

  • The serial column was added after table creation using PostgreSQL <7.3
  • A regular index also exists on the column (such an index can probably be dropped as the primary key index should suffice)

Options:

:column :Specify the column to convert instead of using the first primary key column
:server :Run the SQL on the given server

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 263
263:       def convert_serial_to_identity(table, opts=OPTS)
264:         raise Error, "convert_serial_to_identity is only supported on PostgreSQL 10.2+" unless server_version >= 100002
265: 
266:         server = opts[:server]
267:         server_hash = server ? {:server=>server} : OPTS
268:         ds = dataset
269:         ds = ds.server(server) if server
270: 
271:         raise Error, "convert_serial_to_identity requires superuser permissions" unless ds.get{current_setting('is_superuser')} == 'on'
272: 
273:         table_oid = regclass_oid(table)
274:         im = input_identifier_meth
275:         unless column = im.call(opts[:column] || ((sch = schema(table).find{|_, sc| sc[:primary_key] && sc[:auto_increment]}) && sch[0]))
276:           raise Error, "could not determine column to convert from serial to identity automatically"
277:         end
278: 
279:         column_num = ds.from(:pg_attribute).
280:           where(:attrelid=>table_oid, :attname=>column).
281:           get(:attnum)
282: 
283:         pg_class = Sequel.cast('pg_class', :regclass)
284:         res = ds.from(:pg_depend).
285:           where(:refclassid=>pg_class, :refobjid=>table_oid, :refobjsubid=>column_num, :classid=>pg_class, :objsubid=>0, :deptype=>%w'a i').
286:           select_map([:objid, Sequel.as({:deptype=>'i'}, :v)])
287: 
288:         case res.length
289:         when 0
290:           raise Error, "unable to find related sequence when converting serial to identity"
291:         when 1
292:           seq_oid, already_identity = res.first
293:         else
294:           raise Error, "more than one linked sequence found when converting serial to identity"
295:         end
296: 
297:         return if already_identity
298: 
299:         transaction(server_hash) do
300:           run("ALTER TABLE #{quote_schema_table(table)} ALTER COLUMN #{quote_identifier(column)} DROP DEFAULT", server_hash)
301: 
302:           ds.from(:pg_depend).
303:             where(:classid=>pg_class, :objid=>seq_oid, :objsubid=>0, :deptype=>'a').
304:             update(:deptype=>'i')
305: 
306:           ds.from(:pg_attribute).
307:             where(:attrelid=>table_oid, :attname=>column).
308:             update(:attidentity=>'d')
309:         end
310: 
311:         remove_cached_schema(table)
312:         nil
313:       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:
1 :argument data type
2 :argument name
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 335
335:       def create_function(name, definition, opts=OPTS)
336:         self << create_function_sql(name, definition, opts)
337:       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 346
346:       def create_language(name, opts=OPTS)
347:         self << create_language_sql(name, opts)
348:       end

Create a schema in the database. Arguments:

name :Name of the schema (e.g. admin)
opts :options hash:
:if_not_exists :Don‘t raise an error if the schema already exists (PostgreSQL 9.3+)
:owner :The owner to set for the schema (defaults to current user if not specified)

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 355
355:       def create_schema(name, opts=OPTS)
356:         self << create_schema_sql(name, opts)
357:       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.
:when :A filter to use for the trigger

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 370
370:       def create_trigger(table, name, function, opts=OPTS)
371:         self << create_trigger_sql(table, name, function, opts)
372:       end

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 374
374:       def database_type
375:         :postgres
376:       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.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 383
383:       def do(code, opts=OPTS)
384:         language = opts[:language]
385:         run "DO #{"LANGUAGE #{literal(language.to_s)} " if language}#{literal(code)}"
386:       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 394
394:       def drop_function(name, opts=OPTS)
395:         self << drop_function_sql(name, opts)
396:       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 403
403:       def drop_language(name, opts=OPTS)
404:         self << drop_language_sql(name, opts)
405:       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 412
412:       def drop_schema(name, opts=OPTS)
413:         self << drop_schema_sql(name, opts)
414:       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 422
422:       def drop_trigger(table, name, opts=OPTS)
423:         self << drop_trigger_sql(table, name, opts)
424:       end

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

Supports additional options:

:reverse :Instead of returning foreign keys in the current table, return foreign keys in other tables that reference the current table.
:schema :Set to true to have the :table value in the hashes be a qualified identifier. Set to false to use a separate :schema value with the related schema. Defaults to whether the given table argument is a qualified identifier.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 436
436:       def foreign_key_list(table, opts=OPTS)
437:         m = output_identifier_meth
438:         schema, _ = opts.fetch(:schema, schema_and_table(table))
439:         oid = regclass_oid(table)
440:         reverse = opts[:reverse]
441: 
442:         if reverse
443:           ctable = Sequel[:att2]
444:           cclass = Sequel[:cl2]
445:           rtable = Sequel[:att]
446:           rclass = Sequel[:cl]
447:         else
448:           ctable = Sequel[:att]
449:           cclass = Sequel[:cl]
450:           rtable = Sequel[:att2]
451:           rclass = Sequel[:cl2]
452:         end
453: 
454:         if server_version >= 90500
455:           cpos = Sequel.expr{array_position(co[:conkey], ctable[:attnum])}
456:           rpos = Sequel.expr{array_position(co[:confkey], rtable[:attnum])}
457:         else
458:           range = 0...32
459:           cpos = Sequel.expr{SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(co[:conkey], [x]), x]}, 32, ctable[:attnum])}
460:           rpos = Sequel.expr{SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(co[:confkey], [x]), x]}, 32, rtable[:attnum])}
461:         end
462: 
463:         ds = metadata_dataset.
464:           from{pg_constraint.as(:co)}.
465:           join(Sequel[:pg_class].as(cclass), :oid=>:conrelid).
466:           join(Sequel[:pg_attribute].as(ctable), :attrelid=>:oid, :attnum=>SQL::Function.new(:ANY, Sequel[:co][:conkey])).
467:           join(Sequel[:pg_class].as(rclass), :oid=>Sequel[:co][:confrelid]).
468:           join(Sequel[:pg_attribute].as(rtable), :attrelid=>:oid, :attnum=>SQL::Function.new(:ANY, Sequel[:co][:confkey])).
469:           join(Sequel[:pg_namespace].as(:nsp), :oid=>Sequel[:cl2][:relnamespace]).
470:           order{[co[:conname], cpos]}.
471:           where{{
472:             cl[:relkind]=>'r',
473:             co[:contype]=>'f',
474:             cl[:oid]=>oid,
475:             cpos=>rpos
476:           }}.
477:           select{[
478:             co[:conname].as(:name),
479:             ctable[:attname].as(:column),
480:             co[:confupdtype].as(:on_update),
481:             co[:confdeltype].as(:on_delete),
482:             cl2[:relname].as(:table),
483:             rtable[:attname].as(:refcolumn),
484:             SQL::BooleanExpression.new(:AND, co[:condeferrable], co[:condeferred]).as(:deferrable),
485:             nsp[:nspname].as(:schema)
486:           ]}
487: 
488:         if reverse
489:           ds = ds.order_append(Sequel[:nsp][:nspname], Sequel[:cl2][:relname])
490:         end
491: 
492:         h = {}
493:         fklod_map = FOREIGN_KEY_LIST_ON_DELETE_MAP 
494: 
495:         ds.each do |row|
496:           if reverse
497:             key = [row[:schema], row[:table], row[:name]]
498:           else
499:             key = row[:name]
500:           end
501: 
502:           if r = h[key]
503:             r[:columns] << m.call(row[:column])
504:             r[:key] << m.call(row[:refcolumn])
505:           else
506:             entry = h[key] = {
507:               :name=>m.call(row[:name]),
508:               :columns=>[m.call(row[:column])],
509:               :key=>[m.call(row[:refcolumn])],
510:               :on_update=>fklod_map[row[:on_update]],
511:               :on_delete=>fklod_map[row[:on_delete]],
512:               :deferrable=>row[:deferrable],
513:               :table=>schema ? SQL::QualifiedIdentifier.new(m.call(row[:schema]), m.call(row[:table])) : m.call(row[:table]),
514:             }
515: 
516:             unless schema
517:               # If not combining schema information into the :table entry
518:               # include it as a separate entry.
519:               entry[:schema] = m.call(row[:schema])
520:             end
521:           end
522:         end
523: 
524:         h.values
525:       end

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 527
527:       def freeze
528:         server_version
529:         supports_prepared_transactions?
530:         @conversion_procs.freeze
531:         super
532:       end

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

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 535
535:       def indexes(table, opts=OPTS)
536:         m = output_identifier_meth
537:         oid = regclass_oid(table, opts)
538: 
539:         if server_version >= 90500
540:           order = [Sequel[:indc][:relname], Sequel.function(:array_position, Sequel[:ind][:indkey], Sequel[:att][:attnum])]
541:         else
542:           range = 0...32
543:           order = [Sequel[:indc][:relname], SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(Sequel[:ind][:indkey], [x]), x]}, 32, Sequel[:att][:attnum])]
544:         end
545: 
546:         attnums = SQL::Function.new(:ANY, Sequel[:ind][:indkey])
547: 
548:         ds = metadata_dataset.
549:           from{pg_class.as(:tab)}.
550:           join(Sequel[:pg_index].as(:ind), :indrelid=>:oid).
551:           join(Sequel[:pg_class].as(:indc), :oid=>:indexrelid).
552:           join(Sequel[:pg_attribute].as(:att), :attrelid=>Sequel[:tab][:oid], :attnum=>attnums).
553:           left_join(Sequel[:pg_constraint].as(:con), :conname=>Sequel[:indc][:relname]).
554:           where{{
555:             indc[:relkind]=>'i',
556:             ind[:indisprimary]=>false,
557:             :indexprs=>nil,
558:             :indisvalid=>true,
559:             tab[:oid]=>oid}}.
560:           order(*order).
561:           select{[indc[:relname].as(:name), ind[:indisunique].as(:unique), att[:attname].as(:column), con[:condeferrable].as(:deferrable)]}
562: 
563:         ds = ds.where(:indpred=>nil) unless opts[:include_partial]
564:         ds = ds.where(:indisready=>true) if server_version >= 80300
565:         ds = ds.where(:indislive=>true) if server_version >= 90300
566: 
567:         indexes = {}
568:         ds.each do |r|
569:           i = indexes[m.call(r[:name])] ||= {:columns=>[], :unique=>r[:unique], :deferrable=>r[:deferrable]}
570:           i[:columns] << m.call(r[:column])
571:         end
572:         indexes
573:       end

Dataset containing all current database locks

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 576
576:       def locks
577:         dataset.from(:pg_class).join(:pg_locks, :relation=>:relfilenode).select{[pg_class[:relname], Sequel::SQL::ColumnAll.new(:pg_locks)]}
578:       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 586
586:       def notify(channel, opts=OPTS)
587:         sql = String.new
588:         sql << "NOTIFY "
589:         dataset.send(:identifier_append, sql, channel)
590:         if payload = opts[:payload]
591:           sql << ", "
592:           dataset.literal_append(sql, payload.to_s)
593:         end
594:         execute_ddl(sql, opts)
595:       end

Return primary key for the given table.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 598
598:       def primary_key(table, opts=OPTS)
599:         quoted_table = quote_schema_table(table)
600:         Sequel.synchronize{return @primary_keys[quoted_table] if @primary_keys.has_key?(quoted_table)}
601:         sql = "#{SELECT_PK_SQL} AND pg_class.oid = #{literal(regclass_oid(table, opts))}"
602:         value = fetch(sql).single_value
603:         Sequel.synchronize{@primary_keys[quoted_table] = value}
604:       end

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

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 607
607:       def primary_key_sequence(table, opts=OPTS)
608:         quoted_table = quote_schema_table(table)
609:         Sequel.synchronize{return @primary_key_sequences[quoted_table] if @primary_key_sequences.has_key?(quoted_table)}
610:         sql = "#{SELECT_SERIAL_SEQUENCE_SQL} AND t.oid = #{literal(regclass_oid(table, opts))}"
611:         if pks = fetch(sql).single_record
612:           value = literal(SQL::QualifiedIdentifier.new(pks[:schema], pks[:sequence]))
613:           Sequel.synchronize{@primary_key_sequences[quoted_table] = value}
614:         else
615:           sql = "#{SELECT_CUSTOM_SEQUENCE_SQL} AND t.oid = #{literal(regclass_oid(table, opts))}"
616:           if pks = fetch(sql).single_record
617:             value = literal(SQL::QualifiedIdentifier.new(pks[:schema], LiteralString.new(pks[:sequence])))
618:             Sequel.synchronize{@primary_key_sequences[quoted_table] = value}
619:           end
620:         end
621:       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

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 629
629:       def refresh_view(name, opts=OPTS)
630:         run "REFRESH MATERIALIZED VIEW#{' CONCURRENTLY' if opts[:concurrently]} #{quote_schema_table(name)}"
631:       end

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

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 635
635:       def reset_primary_key_sequence(table)
636:         return unless seq = primary_key_sequence(table)
637:         pk = SQL::Identifier.new(primary_key(table))
638:         db = self
639:         s, t = schema_and_table(table)
640:         table = Sequel.qualify(s, t) if s
641: 
642:         if server_version >= 100000
643:           seq_ds = metadata_dataset.from(:pg_sequence).where(:seqrelid=>regclass_oid(LiteralString.new(seq)))
644:           increment_by = :seqincrement
645:           min_value = :seqmin
646:         else
647:           seq_ds = metadata_dataset.from(LiteralString.new(seq))
648:           increment_by = :increment_by
649:           min_value = :min_value
650:         end
651: 
652:         get{setval(seq, db[table].select(coalesce(max(pk)+seq_ds.select(increment_by), seq_ds.select(min_value))), false)}
653:       end

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 655
655:       def rollback_prepared_transaction(transaction_id, opts=OPTS)
656:         run("ROLLBACK PREPARED #{literal(transaction_id)}", opts)
657:       end

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

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 661
661:       def serial_primary_key_options
662:         auto_increment_key = server_version >= 100002 ? :identity : :serial
663:         {:primary_key => true, auto_increment_key => true, :type=>Integer}
664:       end

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

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 667
667:       def server_version(server=nil)
668:         return @server_version if @server_version
669:         ds = dataset
670:         ds = ds.server(server) if server
671:         @server_version ||= ds.with_sql("SELECT CAST(current_setting('server_version_num') AS integer) AS v").single_value rescue 0
672:       end

PostgreSQL supports CREATE TABLE IF NOT EXISTS on 9.1+

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 675
675:       def supports_create_table_if_not_exists?
676:         server_version >= 90100
677:       end

PostgreSQL 9.0+ supports some types of deferrable constraints beyond foreign key constraints.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 680
680:       def supports_deferrable_constraints?
681:         server_version >= 90000
682:       end

PostgreSQL supports deferrable foreign key constraints.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 685
685:       def supports_deferrable_foreign_key_constraints?
686:         true
687:       end

PostgreSQL supports DROP TABLE IF EXISTS

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 690
690:       def supports_drop_table_if_exists?
691:         true
692:       end

PostgreSQL supports partial indexes.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 695
695:       def supports_partial_indexes?
696:         true
697:       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 706
706:       def supports_prepared_transactions?
707:         return @supports_prepared_transactions if defined?(@supports_prepared_transactions)
708:         @supports_prepared_transactions = self['SHOW max_prepared_transactions'].get.to_i > 0
709:       end

PostgreSQL supports savepoints

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 712
712:       def supports_savepoints?
713:         true
714:       end

PostgreSQL supports transaction isolation levels

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 717
717:       def supports_transaction_isolation_levels?
718:         true
719:       end

PostgreSQL supports transaction DDL statements.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 722
722:       def supports_transactional_ddl?
723:         true
724:       end

PostgreSQL 9.0+ supports trigger conditions.

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 700
700:       def supports_trigger_conditions?
701:         server_version >= 90000
702:       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

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 735
735:       def tables(opts=OPTS, &block)
736:         pg_class_relname('r', opts, &block)
737:       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 741
741:       def type_supported?(type)
742:         Sequel.synchronize{return @supported_types[type] if @supported_types.has_key?(type)}
743:         supported = from(:pg_type).where(:typtype=>'b', :typname=>type.to_s).count > 0
744:         Sequel.synchronize{return @supported_types[type] = supported}
745:       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

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 754
754:       def values(v)
755:         @default_dataset.clone(:values=>v)
756:       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

[Source]

     # File lib/sequel/adapters/shared/postgres.rb, line 766
766:       def views(opts=OPTS)
767:         relkind = opts[:materialized] ? 'm' : 'v'
768:         pg_class_relname(relkind, opts)
769:       end

[Validate]