module Sequel::Postgres::DatabaseMethods

Constants

DATABASE_ERROR_REGEXPS
FOREIGN_KEY_LIST_ON_DELETE_MAP
MAX_DATE
MAX_TIMESTAMP
MIN_DATE
MIN_TIMESTAMP
ON_COMMIT
SELECT_CUSTOM_SEQUENCE_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

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

SQL fragment for getting sequence associated with table’s primary key, assuming it was a serial primary key column.

TYPTYPE_METHOD_MAP
VALID_CLIENT_MIN_MESSAGES

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

add_conversion_proc(oid, callable=nil, &block) click to toggle source

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
356 def add_conversion_proc(oid, callable=nil, &block)
357   conversion_procs[oid] = callable || block
358 end
add_named_conversion_proc(name, &block) click to toggle source

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
363 def add_named_conversion_proc(name, &block)
364   unless oid = from(:pg_type).where(:typtype=>['b', 'e'], :typname=>name.to_s).get(:oid)
365     raise Error, "No matching type in pg_type for #{name.inspect}"
366   end
367   add_conversion_proc(oid, block)
368 end
check_constraints(table) click to toggle source

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, can be an empty array if the database cannot determine the column symbols.

    # File lib/sequel/adapters/shared/postgres.rb
379 def check_constraints(table)
380   m = output_identifier_meth
381 
382   hash = {}
383   _check_constraints_ds.where_each(:conrelid=>regclass_oid(table)) do |row|
384     constraint = m.call(row[:constraint])
385     entry = hash[constraint] ||= {:definition=>row[:definition], :columns=>[], :validated=>row[:validated], :enforced=>row[:enforced]}
386     entry[:columns] << m.call(row[:column]) if row[:column]
387   end
388   
389   hash
390 end
commit_prepared_transaction(transaction_id, opts=OPTS) click to toggle source
    # File lib/sequel/adapters/shared/postgres.rb
370 def commit_prepared_transaction(transaction_id, opts=OPTS)
371   run("COMMIT PREPARED #{literal(transaction_id)}".freeze, opts)
372 end
convert_serial_to_identity(table, opts=OPTS) click to toggle source

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

    # File lib/sequel/adapters/shared/postgres.rb
410 def convert_serial_to_identity(table, opts=OPTS)
411   raise Error, "convert_serial_to_identity is only supported on PostgreSQL 10.2+" unless server_version >= 100002
412 
413   server = opts[:server]
414   server_hash = server ? {:server=>server} : OPTS
415   ds = dataset
416   ds = ds.server(server) if server
417 
418   raise Error, "convert_serial_to_identity requires superuser permissions" unless ds.get{current_setting('is_superuser')} == 'on'
419 
420   table_oid = regclass_oid(table)
421   im = input_identifier_meth
422   unless column = (opts[:column] || ((sch = schema(table).find{|_, sc| sc[:primary_key] && sc[:auto_increment]}) && sch[0]))
423     raise Error, "could not determine column to convert from serial to identity automatically"
424   end
425   column = im.call(column)
426 
427   column_num = ds.from(:pg_attribute).
428     where(:attrelid=>table_oid, :attname=>column).
429     get(:attnum)
430 
431   pg_class = Sequel.cast('pg_class', :regclass)
432   res = ds.from(:pg_depend).
433     where(:refclassid=>pg_class, :refobjid=>table_oid, :refobjsubid=>column_num, :classid=>pg_class, :objsubid=>0, :deptype=>%w'a i').
434     select_map([:objid, Sequel.as({:deptype=>'i'}, :v)])
435 
436   case res.length
437   when 0
438     raise Error, "unable to find related sequence when converting serial to identity"
439   when 1
440     seq_oid, already_identity = res.first
441   else
442     raise Error, "more than one linked sequence found when converting serial to identity"
443   end
444 
445   return if already_identity
446 
447   transaction(server_hash) do
448     run("ALTER TABLE #{quote_schema_table(table)} ALTER COLUMN #{quote_identifier(column)} DROP DEFAULT".freeze, server_hash)
449 
450     ds.from(:pg_depend).
451       where(:classid=>pg_class, :objid=>seq_oid, :objsubid=>0, :deptype=>'a').
452       update(:deptype=>'i')
453 
454     ds.from(:pg_attribute).
455       where(:attrelid=>table_oid, :attname=>column).
456       update(:attidentity=>'d')
457   end
458 
459   remove_cached_schema(table)
460   nil
461 end
create_function(name, definition, opts=OPTS) click to toggle source

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.

:parallel

The thread safety attribute of the function. Should be SAFE, UNSAFE, RESTRICTED. PostgreSQL assumes UNSAFE 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.

    # File lib/sequel/adapters/shared/postgres.rb
484 def create_function(name, definition, opts=OPTS)
485   self << create_function_sql(name, definition, opts).freeze
486 end
create_language(name, opts=OPTS) click to toggle source

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.

    # File lib/sequel/adapters/shared/postgres.rb
495 def create_language(name, opts=OPTS)
496   self << create_language_sql(name, opts).freeze
497 end
create_schema(name, opts=OPTS) click to toggle source

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)

    # File lib/sequel/adapters/shared/postgres.rb
504 def create_schema(name, opts=OPTS)
505   self << create_schema_sql(name, opts).freeze
506 end
create_table(name, options=OPTS, &block) click to toggle source

Support partitions of tables using the :partition_of option.

Calls superclass method
    # File lib/sequel/adapters/shared/postgres.rb
509 def create_table(name, options=OPTS, &block)
510   if options[:partition_of]
511     create_partition_of_table_from_generator(name, CreatePartitionOfTableGenerator.new(&block), options)
512     return
513   end
514 
515   super
516 end
create_table?(name, options=OPTS, &block) click to toggle source

Support partitions of tables using the :partition_of option.

Calls superclass method
    # File lib/sequel/adapters/shared/postgres.rb
519 def create_table?(name, options=OPTS, &block)
520   if options[:partition_of]
521     create_table(name, options.merge!(:if_not_exists=>true), &block)
522     return
523   end
524 
525   super
526 end
create_trigger(table, name, function, opts=OPTS) click to toggle source

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.

:replace

Replace the trigger with the same name if it already exists (PostgreSQL 14+).

:when

A filter to use for the trigger

    # File lib/sequel/adapters/shared/postgres.rb
540 def create_trigger(table, name, function, opts=OPTS)
541   self << create_trigger_sql(table, name, function, opts).freeze
542 end
database_type() click to toggle source
    # File lib/sequel/adapters/shared/postgres.rb
544 def database_type
545   :postgres
546 end
defer_constraints(opts=OPTS) click to toggle source

For constraints that are deferrable, defer constraints until transaction commit. Options:

:constraints

An identifier of the constraint, or an array of identifiers for constraints, to apply this change to specific constraints.

:server

The server/shard on which to run the query.

Examples:

DB.defer_constraints
# SET CONSTRAINTS ALL DEFERRED

DB.defer_constraints(constraints: [:c1, Sequel[:sc][:c2]])
# SET CONSTRAINTS "c1", "sc"."s2" DEFERRED
    # File lib/sequel/adapters/shared/postgres.rb
563 def defer_constraints(opts=OPTS)
564   _set_constraints(' DEFERRED', opts)
565 end
do(code, opts=OPTS) click to toggle source

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
572 def do(code, opts=OPTS)
573   language = opts[:language]
574   run "DO #{"LANGUAGE #{literal(language.to_s)} " if language}#{literal(code)}".freeze
575 end
drop_function(name, opts=OPTS) click to toggle source

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.

    # File lib/sequel/adapters/shared/postgres.rb
583 def drop_function(name, opts=OPTS)
584   self << drop_function_sql(name, opts).freeze
585 end
drop_language(name, opts=OPTS) click to toggle source

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.

    # File lib/sequel/adapters/shared/postgres.rb
592 def drop_language(name, opts=OPTS)
593   self << drop_language_sql(name, opts).freeze
594 end
drop_schema(name, opts=OPTS) click to toggle source

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.

    # File lib/sequel/adapters/shared/postgres.rb
601 def drop_schema(name, opts=OPTS)
602   self << drop_schema_sql(name, opts).freeze
603   remove_all_cached_schemas
604 end
drop_trigger(table, name, opts=OPTS) click to toggle source

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.

    # File lib/sequel/adapters/shared/postgres.rb
612 def drop_trigger(table, name, opts=OPTS)
613   self << drop_trigger_sql(table, name, opts).freeze
614 end
foreign_key_list(table, opts=OPTS) click to toggle source

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.

    # File lib/sequel/adapters/shared/postgres.rb
626 def foreign_key_list(table, opts=OPTS)
627   m = output_identifier_meth
628   schema, _ = opts.fetch(:schema, schema_and_table(table))
629 
630   h = {}
631   fklod_map = FOREIGN_KEY_LIST_ON_DELETE_MAP 
632   reverse = opts[:reverse]
633 
634   (reverse ? _reverse_foreign_key_list_ds : _foreign_key_list_ds).where_each(Sequel[:cl][:oid]=>regclass_oid(table)) do |row|
635     if reverse
636       key = [row[:schema], row[:table], row[:name]]
637     else
638       key = row[:name]
639     end
640 
641     if r = h[key]
642       r[:columns] << m.call(row[:column])
643       r[:key] << m.call(row[:refcolumn])
644     else
645       entry = h[key] = {
646         :name=>m.call(row[:name]),
647         :columns=>[m.call(row[:column])],
648         :key=>[m.call(row[:refcolumn])],
649         :on_update=>fklod_map[row[:on_update]],
650         :on_delete=>fklod_map[row[:on_delete]],
651         :deferrable=>row[:deferrable],
652         :validated=>row[:validated],
653         :enforced=>row[:enforced],
654         :table=>schema ? SQL::QualifiedIdentifier.new(m.call(row[:schema]), m.call(row[:table])) : m.call(row[:table]),
655       }
656 
657       unless schema
658         # If not combining schema information into the :table entry
659         # include it as a separate entry.
660         entry[:schema] = m.call(row[:schema])
661       end
662     end
663   end
664 
665   h.values
666 end
freeze() click to toggle source
Calls superclass method
    # File lib/sequel/adapters/shared/postgres.rb
668 def freeze
669   server_version
670   supports_prepared_transactions?
671   _schema_ds
672   _select_serial_sequence_ds
673   _select_custom_sequence_ds
674   _select_pk_ds
675   _indexes_ds
676   _check_constraints_ds
677   _foreign_key_list_ds
678   _reverse_foreign_key_list_ds
679   @conversion_procs.freeze
680   super
681 end
immediate_constraints(opts=OPTS) click to toggle source

Immediately apply deferrable constraints.

:constraints

An identifier of the constraint, or an array of identifiers for constraints, to apply this change to specific constraints.

:server

The server/shard on which to run the query.

Examples:

DB.immediate_constraints
# SET CONSTRAINTS ALL IMMEDIATE

DB.immediate_constraints(constraints: [:c1, Sequel[:sc][:c2]])
# SET CONSTRAINTS "c1", "sc"."s2" IMMEDIATE
    # File lib/sequel/adapters/shared/postgres.rb
697 def immediate_constraints(opts=OPTS)
698   _set_constraints(' IMMEDIATE', opts)
699 end
indexes(table, opts=OPTS) click to toggle source

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

:include_partial

Set to true to include partial indexes

:invalid

Set to true or :only to only return invalid indexes. Set to :include to also return both valid and invalid indexes. When not set or other value given, does not return invalid indexes.

    # File lib/sequel/adapters/shared/postgres.rb
707 def indexes(table, opts=OPTS)
708   m = output_identifier_meth
709   cond = {Sequel[:tab][:oid]=>regclass_oid(table, opts)}
710   cond[:indpred] = nil unless opts[:include_partial]
711 
712   case opts[:invalid]
713   when true, :only
714     cond[:indisvalid] = false
715   when :include
716     # nothing
717   else
718     cond[:indisvalid] = true
719   end
720 
721   indexes = {}
722   _indexes_ds.where_each(cond) do |r|
723     i = indexes[m.call(r[:name])] ||= {:columns=>[], :unique=>r[:unique], :deferrable=>r[:deferrable]}
724     i[:columns] << m.call(r[:column])
725   end
726   indexes
727 end
locks() click to toggle source

Dataset containing all current database locks

    # File lib/sequel/adapters/shared/postgres.rb
730 def locks
731   dataset.from(:pg_class).join(:pg_locks, :relation=>:relfilenode).select{[pg_class[:relname], Sequel::SQL::ColumnAll.new(:pg_locks)]}
732 end
notify(channel, opts=OPTS) click to toggle source

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
740 def notify(channel, opts=OPTS)
741   sql = String.new
742   sql << "NOTIFY "
743   dataset.send(:identifier_append, sql, channel)
744   if payload = opts[:payload]
745     sql << ", "
746     dataset.literal_append(sql, payload.to_s)
747   end
748   execute_ddl(sql, opts)
749 end
primary_key(table, opts=OPTS) click to toggle source

Return primary key for the given table.

    # File lib/sequel/adapters/shared/postgres.rb
752 def primary_key(table, opts=OPTS)
753   quoted_table = quote_schema_table(table)
754   Sequel.synchronize{return @primary_keys[quoted_table] if @primary_keys.has_key?(quoted_table)}
755   value = _select_pk_ds.where_single_value(Sequel[:pg_class][:oid] => regclass_oid(table, opts))
756   Sequel.synchronize{@primary_keys[quoted_table] = value}
757 end
primary_key_sequence(table, opts=OPTS) click to toggle source

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

    # File lib/sequel/adapters/shared/postgres.rb
760 def primary_key_sequence(table, opts=OPTS)
761   quoted_table = quote_schema_table(table)
762   Sequel.synchronize{return @primary_key_sequences[quoted_table] if @primary_key_sequences.has_key?(quoted_table)}
763   cond = {Sequel[:t][:oid] => regclass_oid(table, opts)}
764   value = if pks = _select_serial_sequence_ds.first(cond)
765     literal(SQL::QualifiedIdentifier.new(pks[:schema], pks[:sequence]))
766   elsif pks = _select_custom_sequence_ds.first(cond)
767     literal(SQL::QualifiedIdentifier.new(pks[:schema], LiteralString.new(pks[:sequence])))
768   end
769 
770   Sequel.synchronize{@primary_key_sequences[quoted_table] = value} if value
771 end
refresh_view(name, opts=OPTS) click to toggle source

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
787 def refresh_view(name, opts=OPTS)
788   run "REFRESH MATERIALIZED VIEW#{' CONCURRENTLY' if opts[:concurrently]} #{quote_schema_table(name)}".freeze
789 end
rename_schema(name, new_name) click to toggle source

Rename a schema in the database. Arguments:

name

Current name of the schema

opts

New name for the schema

    # File lib/sequel/adapters/shared/postgres.rb
776 def rename_schema(name, new_name)
777   self << rename_schema_sql(name, new_name).freeze
778   remove_all_cached_schemas
779 end
reset_primary_key_sequence(table) click to toggle source

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
793 def reset_primary_key_sequence(table)
794   return unless seq = primary_key_sequence(table)
795   pk = SQL::Identifier.new(primary_key(table))
796   db = self
797   s, t = schema_and_table(table)
798   table = Sequel.qualify(s, t) if s
799 
800   if server_version >= 100000
801     seq_ds = metadata_dataset.from(:pg_sequence).where(:seqrelid=>regclass_oid(LiteralString.new(seq.freeze)))
802     increment_by = :seqincrement
803     min_value = :seqmin
804   # simplecov:disable
805   else
806     seq_ds = metadata_dataset.from(LiteralString.new(seq))
807     increment_by = :increment_by
808     min_value = :min_value
809   # simplecov:enable
810   end
811 
812   get{setval(seq, db[table].select(coalesce(max(pk)+seq_ds.select(increment_by), seq_ds.select(min_value))), false)}
813 end
rollback_prepared_transaction(transaction_id, opts=OPTS) click to toggle source
    # File lib/sequel/adapters/shared/postgres.rb
815 def rollback_prepared_transaction(transaction_id, opts=OPTS)
816   run("ROLLBACK PREPARED #{literal(transaction_id)}".freeze, opts)
817 end
serial_primary_key_options() click to toggle source

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

    # File lib/sequel/adapters/shared/postgres.rb
821 def serial_primary_key_options
822   # simplecov:disable
823   auto_increment_key = server_version >= 100002 ? :identity : :serial
824   # simplecov:enable
825   {:primary_key => true, auto_increment_key => true, :type=>Integer}
826 end
server_version(server=nil) click to toggle source

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

    # File lib/sequel/adapters/shared/postgres.rb
829 def server_version(server=nil)
830   return @server_version if @server_version
831   ds = dataset
832   ds = ds.server(server) if server
833   @server_version = swallow_database_error{ds.with_sql("SELECT CAST(current_setting('server_version_num') AS integer) AS v").single_value} || 0
834 end
supports_create_table_if_not_exists?() click to toggle source

PostgreSQL supports CREATE TABLE IF NOT EXISTS on 9.1+

    # File lib/sequel/adapters/shared/postgres.rb
837 def supports_create_table_if_not_exists?
838   server_version >= 90100
839 end
supports_deferrable_constraints?() click to toggle source

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

    # File lib/sequel/adapters/shared/postgres.rb
842 def supports_deferrable_constraints?
843   server_version >= 90000
844 end
supports_deferrable_foreign_key_constraints?() click to toggle source

PostgreSQL supports deferrable foreign key constraints.

    # File lib/sequel/adapters/shared/postgres.rb
847 def supports_deferrable_foreign_key_constraints?
848   true
849 end
supports_drop_table_if_exists?() click to toggle source

PostgreSQL supports DROP TABLE IF EXISTS

    # File lib/sequel/adapters/shared/postgres.rb
852 def supports_drop_table_if_exists?
853   true
854 end
supports_partial_indexes?() click to toggle source

PostgreSQL supports partial indexes.

    # File lib/sequel/adapters/shared/postgres.rb
857 def supports_partial_indexes?
858   true
859 end
supports_prepared_transactions?() click to toggle source

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

    # File lib/sequel/adapters/shared/postgres.rb
868 def supports_prepared_transactions?
869   return @supports_prepared_transactions if defined?(@supports_prepared_transactions)
870   @supports_prepared_transactions = self['SHOW max_prepared_transactions'].get.to_i > 0
871 end
supports_savepoints?() click to toggle source

PostgreSQL supports savepoints

    # File lib/sequel/adapters/shared/postgres.rb
874 def supports_savepoints?
875   true
876 end
supports_transaction_isolation_levels?() click to toggle source

PostgreSQL supports transaction isolation levels

    # File lib/sequel/adapters/shared/postgres.rb
879 def supports_transaction_isolation_levels?
880   true
881 end
supports_transactional_ddl?() click to toggle source

PostgreSQL supports transaction DDL statements.

    # File lib/sequel/adapters/shared/postgres.rb
884 def supports_transactional_ddl?
885   true
886 end
supports_trigger_conditions?() click to toggle source

PostgreSQL 9.0+ supports trigger conditions.

    # File lib/sequel/adapters/shared/postgres.rb
862 def supports_trigger_conditions?
863   server_version >= 90000
864 end
tables(opts=OPTS, &block) click to toggle source

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
897 def tables(opts=OPTS, &block)
898   pg_class_relname(['r', 'p'], opts, &block)
899 end
type_supported?(type) click to toggle source

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

    # File lib/sequel/adapters/shared/postgres.rb
903 def type_supported?(type)
904   Sequel.synchronize{return @supported_types[type] if @supported_types.has_key?(type)}
905   supported = from(:pg_type).where(:typtype=>'b', :typname=>type.to_s).count > 0
906   Sequel.synchronize{return @supported_types[type] = supported}
907 end
values(v) click to toggle source

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
916 def values(v)
917   raise Error, "Cannot provide an empty array for values" if v.empty?
918   @default_dataset.clone(:values=>v)
919 end
views(opts=OPTS) click to toggle source

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
929 def views(opts=OPTS)
930   relkind = opts[:materialized] ? 'm' : 'v'
931   pg_class_relname(relkind, opts)
932 end
with_advisory_lock(lock_id, opts=OPTS) { || ... } click to toggle source

Attempt to acquire an exclusive advisory lock with the given lock_id (which should be a 64-bit integer). If successful, yield to the block, then release the advisory lock when the block exits. If unsuccessful, raise a Sequel::AdvisoryLockError.

DB.with_advisory_lock(1347){DB.get(1)}
# SELECT pg_try_advisory_lock(1357) LIMIT 1
# SELECT 1 AS v LIMIT 1
# SELECT pg_advisory_unlock(1357) LIMIT 1

Options:

:wait

Do not raise an error, instead, wait until the advisory lock can be acquired.

    # File lib/sequel/adapters/shared/postgres.rb
945 def with_advisory_lock(lock_id, opts=OPTS)
946   ds = dataset
947   if server = opts[:server]
948     ds = ds.server(server)
949   end
950 
951   synchronize(server) do |c|
952     begin
953       if opts[:wait]
954         ds.get{pg_advisory_lock(lock_id)}
955         locked = true
956       else
957         unless locked = ds.get{pg_try_advisory_lock(lock_id)}
958           raise AdvisoryLockError, "unable to acquire advisory lock #{lock_id.inspect}"
959         end
960       end
961 
962       yield
963     ensure
964       ds.get{pg_advisory_unlock(lock_id)} if locked
965     end
966   end
967 end

Private Instance Methods

__foreign_key_list_ds(reverse) click to toggle source

Build dataset used for foreign key list methods.

     # File lib/sequel/adapters/shared/postgres.rb
 995 def __foreign_key_list_ds(reverse)
 996   if reverse
 997     ctable = Sequel[:att2]
 998     cclass = Sequel[:cl2]
 999     rtable = Sequel[:att]
1000     rclass = Sequel[:cl]
1001   else
1002     ctable = Sequel[:att]
1003     cclass = Sequel[:cl]
1004     rtable = Sequel[:att2]
1005     rclass = Sequel[:cl2]
1006   end
1007 
1008   if server_version >= 90500
1009     cpos = Sequel.expr{array_position(co[:conkey], ctable[:attnum])}
1010     rpos = Sequel.expr{array_position(co[:confkey], rtable[:attnum])}
1011   # simplecov:disable
1012   else
1013     range = 0...32
1014     cpos = Sequel.expr{SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(co[:conkey], [x]), x]}, 32, ctable[:attnum])}
1015     rpos = Sequel.expr{SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(co[:confkey], [x]), x]}, 32, rtable[:attnum])}
1016   # simplecov:enable
1017   end
1018 
1019   ds = metadata_dataset.
1020     from{pg_constraint.as(:co)}.
1021     join(Sequel[:pg_class].as(cclass), :oid=>:conrelid).
1022     join(Sequel[:pg_attribute].as(ctable), :attrelid=>:oid, :attnum=>SQL::Function.new(:ANY, Sequel[:co][:conkey])).
1023     join(Sequel[:pg_class].as(rclass), :oid=>Sequel[:co][:confrelid]).
1024     join(Sequel[:pg_attribute].as(rtable), :attrelid=>:oid, :attnum=>SQL::Function.new(:ANY, Sequel[:co][:confkey])).
1025     join(Sequel[:pg_namespace].as(:nsp), :oid=>Sequel[:cl2][:relnamespace]).
1026     order{[co[:conname], cpos]}.
1027     where{{
1028       cl[:relkind]=>%w'r p',
1029       co[:contype]=>'f',
1030       cpos=>rpos
1031     }}.
1032     select{[
1033       co[:conname].as(:name),
1034       ctable[:attname].as(:column),
1035       co[:confupdtype].as(:on_update),
1036       co[:confdeltype].as(:on_delete),
1037       cl2[:relname].as(:table),
1038       rtable[:attname].as(:refcolumn),
1039       SQL::BooleanExpression.new(:AND, co[:condeferrable], co[:condeferred]).as(:deferrable),
1040       nsp[:nspname].as(:schema)
1041     ]}
1042 
1043   if reverse
1044     ds = ds.order_append(Sequel[:nsp][:nspname], Sequel[:cl2][:relname])
1045   end
1046 
1047   _add_validated_enforced_constraint_columns(ds)
1048 end
_add_validated_enforced_constraint_columns(ds) click to toggle source
     # File lib/sequel/adapters/shared/postgres.rb
1050 def _add_validated_enforced_constraint_columns(ds)
1051   validated_cond = if server_version >= 90100
1052     Sequel[:convalidated]
1053   # simplecov:disable
1054   else
1055     Sequel.cast(true, TrueClass)
1056   # simplecov:enable
1057   end
1058   ds = ds.select_append(validated_cond.as(:validated))
1059 
1060   enforced_cond = if server_version >= 180000
1061     Sequel[:conenforced]
1062   # simplecov:disable
1063   else
1064     Sequel.cast(true, TrueClass)
1065   # simplecov:enable
1066   end
1067   ds = ds.select_append(enforced_cond.as(:enforced))
1068 
1069   ds
1070 end
_check_constraints_ds() click to toggle source

Dataset used to retrieve CHECK constraint information

    # File lib/sequel/adapters/shared/postgres.rb
972 def _check_constraints_ds
973   @_check_constraints_ds ||= begin
974     ds = metadata_dataset.
975       from{pg_constraint.as(:co)}.
976       left_join(Sequel[:pg_attribute].as(:att), :attrelid=>:conrelid, :attnum=>SQL::Function.new(:ANY, Sequel[:co][:conkey])).
977       where(:contype=>'c').
978       select{[co[:conname].as(:constraint), att[:attname].as(:column), pg_get_constraintdef(co[:oid]).as(:definition)]}
979 
980     _add_validated_enforced_constraint_columns(ds)
981   end
982 end
_foreign_key_list_ds() click to toggle source

Dataset used to retrieve foreign keys referenced by a table

    # File lib/sequel/adapters/shared/postgres.rb
985 def _foreign_key_list_ds
986   @_foreign_key_list_ds ||= __foreign_key_list_ds(false)
987 end
_indexes_ds() click to toggle source

Dataset used to retrieve index information

     # File lib/sequel/adapters/shared/postgres.rb
1073 def _indexes_ds
1074   @_indexes_ds ||= begin
1075     if server_version >= 90500
1076       order = [Sequel[:indc][:relname], Sequel.function(:array_position, Sequel[:ind][:indkey], Sequel[:att][:attnum])]
1077     # simplecov:disable
1078     else
1079       range = 0...32
1080       order = [Sequel[:indc][:relname], SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(Sequel[:ind][:indkey], [x]), x]}, 32, Sequel[:att][:attnum])]
1081     # simplecov:enable
1082     end
1083 
1084     attnums = SQL::Function.new(:ANY, Sequel[:ind][:indkey])
1085 
1086     ds = metadata_dataset.
1087       from{pg_class.as(:tab)}.
1088       join(Sequel[:pg_index].as(:ind), :indrelid=>:oid).
1089       join(Sequel[:pg_class].as(:indc), :oid=>:indexrelid).
1090       join(Sequel[:pg_attribute].as(:att), :attrelid=>Sequel[:tab][:oid], :attnum=>attnums).
1091       left_join(Sequel[:pg_constraint].as(:con), :conname=>Sequel[:indc][:relname]).
1092       where{{
1093         indc[:relkind]=>%w'i I',
1094         ind[:indisprimary]=>false,
1095         :indexprs=>nil}}.
1096       order(*order).
1097       select{[indc[:relname].as(:name), ind[:indisunique].as(:unique), att[:attname].as(:column), con[:condeferrable].as(:deferrable)]}
1098 
1099     # simplecov:disable
1100     ds = ds.where(:indisready=>true) if server_version >= 80300
1101     ds = ds.where(:indislive=>true) if server_version >= 90300
1102     # simplecov:enable
1103 
1104     ds
1105   end
1106 end
_reverse_foreign_key_list_ds() click to toggle source

Dataset used to retrieve foreign keys referencing a table

    # File lib/sequel/adapters/shared/postgres.rb
990 def _reverse_foreign_key_list_ds
991   @_reverse_foreign_key_list_ds ||= __foreign_key_list_ds(true)
992 end
_schema_ds() click to toggle source

Dataset used to get schema for tables

     # File lib/sequel/adapters/shared/postgres.rb
1169 def _schema_ds
1170   @_schema_ds ||= begin
1171     ds = metadata_dataset.select{[
1172         pg_attribute[:attname].as(:name),
1173         SQL::Cast.new(pg_attribute[:atttypid], :integer).as(:oid),
1174         SQL::Cast.new(basetype[:oid], :integer).as(:base_oid),
1175         SQL::Function.new(:col_description, pg_class[:oid], pg_attribute[:attnum]).as(:comment),
1176         SQL::Function.new(:format_type, basetype[:oid], pg_type[:typtypmod]).as(:db_base_type),
1177         SQL::Function.new(:format_type, pg_type[:oid], pg_attribute[:atttypmod]).as(:db_type),
1178         SQL::Function.new(:pg_get_expr, pg_attrdef[:adbin], pg_class[:oid]).as(:default),
1179         SQL::BooleanExpression.new(:NOT, pg_attribute[:attnotnull]).as(:allow_null),
1180         SQL::Function.new(:COALESCE, SQL::BooleanExpression.from_value_pairs(pg_attribute[:attnum] => SQL::Function.new(:ANY, pg_index[:indkey])), false).as(:primary_key),
1181         Sequel[:pg_type][:typtype],
1182         (~Sequel[Sequel[:elementtype][:oid]=>nil]).as(:is_array),
1183       ]}.
1184       from(:pg_class).
1185       join(:pg_attribute, :attrelid=>:oid).
1186       join(:pg_type, :oid=>:atttypid).
1187       left_outer_join(Sequel[:pg_type].as(:basetype), :oid=>:typbasetype).
1188       left_outer_join(Sequel[:pg_type].as(:elementtype), :typarray=>Sequel[:pg_type][:oid]).
1189       left_outer_join(:pg_attrdef, :adrelid=>Sequel[:pg_class][:oid], :adnum=>Sequel[:pg_attribute][:attnum]).
1190       left_outer_join(:pg_index, :indrelid=>Sequel[:pg_class][:oid], :indisprimary=>true).
1191       where{{pg_attribute[:attisdropped]=>false}}.
1192       where{pg_attribute[:attnum] > 0}.
1193       order{pg_attribute[:attnum]}
1194 
1195     # simplecov:disable
1196     if server_version > 100000
1197     # simplecov:enable
1198       ds = ds.select_append{pg_attribute[:attidentity]}
1199 
1200       # simplecov:disable
1201       if server_version > 120000
1202       # simplecov:enable
1203         ds = ds.select_append{Sequel.~(pg_attribute[:attgenerated]=>'').as(:generated)}
1204       end
1205     end
1206 
1207     ds
1208   end
1209 end
_select_custom_sequence_ds() click to toggle source

Dataset used to determine custom serial sequences for tables

     # File lib/sequel/adapters/shared/postgres.rb
1109 def _select_custom_sequence_ds
1110   @_select_custom_sequence_ds ||= metadata_dataset.
1111     from{pg_class.as(:t)}.
1112     join(:pg_namespace, {:oid => :relnamespace}, :table_alias=>:name).
1113     join(:pg_attribute, {:attrelid => Sequel[:t][:oid]}, :table_alias=>:attr).
1114     join(:pg_attrdef, {:adrelid => :attrelid, :adnum => :attnum}, :table_alias=>:def).
1115     join(:pg_constraint, {:conrelid => :adrelid, Sequel[:cons][:conkey].sql_subscript(1) => :adnum}, :table_alias=>:cons).
1116     where{{cons[:contype] => 'p', pg_get_expr(self.def[:adbin], attr[:attrelid]) => /nextval/i}}.
1117     select{
1118       expr = split_part(pg_get_expr(self.def[:adbin], attr[:attrelid]), "'", 2)
1119       [
1120         name[:nspname].as(:schema),
1121         Sequel.case({{expr => /./} => substr(expr, strpos(expr, '.')+1)}, expr).as(:sequence)
1122       ]
1123     }
1124 end
_select_pk_ds() click to toggle source

Dataset used to determine primary keys for tables

     # File lib/sequel/adapters/shared/postgres.rb
1155 def _select_pk_ds
1156   @_select_pk_ds ||= metadata_dataset.
1157     from(:pg_class, :pg_attribute, :pg_index, :pg_namespace).
1158     where{[
1159       [pg_class[:oid], pg_attribute[:attrelid]],
1160       [pg_class[:relnamespace], pg_namespace[:oid]],
1161       [pg_class[:oid], pg_index[:indrelid]],
1162       [pg_index[:indkey].sql_subscript(0), pg_attribute[:attnum]],
1163       [pg_index[:indisprimary], 't']
1164     ]}.
1165     select{pg_attribute[:attname].as(:pk)}
1166 end
_select_serial_sequence_ds() click to toggle source

Dataset used to determine normal serial sequences for tables

     # File lib/sequel/adapters/shared/postgres.rb
1127 def _select_serial_sequence_ds
1128   @_serial_sequence_ds ||= metadata_dataset.
1129     from{[
1130       pg_class.as(:seq),
1131       pg_attribute.as(:attr),
1132       pg_depend.as(:dep),
1133       pg_namespace.as(:name),
1134       pg_constraint.as(:cons),
1135       pg_class.as(:t)
1136     ]}.
1137     where{[
1138       [seq[:oid], dep[:objid]],
1139       [seq[:relnamespace], name[:oid]],
1140       [seq[:relkind], 'S'],
1141       [attr[:attrelid], dep[:refobjid]],
1142       [attr[:attnum], dep[:refobjsubid]],
1143       [attr[:attrelid], cons[:conrelid]],
1144       [attr[:attnum], cons[:conkey].sql_subscript(1)],
1145       [attr[:attrelid], t[:oid]],
1146       [cons[:contype], 'p']
1147     ]}.
1148     select{[
1149       name[:nspname].as(:schema),
1150       seq[:relname].as(:sequence)
1151     ]}
1152 end
_set_constraints(type, opts) click to toggle source

Internals of defer_constraints/immediate_constraints

     # File lib/sequel/adapters/shared/postgres.rb
1212 def _set_constraints(type, opts)
1213   execute_ddl(_set_constraints_sql(type, opts), opts)
1214 end
_set_constraints_sql(type, opts) click to toggle source

SQL to use for SET CONSTRAINTS

     # File lib/sequel/adapters/shared/postgres.rb
1217 def _set_constraints_sql(type, opts)
1218   sql = String.new
1219   sql << "SET CONSTRAINTS "
1220   if constraints = opts[:constraints]
1221     dataset.send(:source_list_append, sql, Array(constraints))
1222   else
1223     sql << "ALL"
1224   end
1225   sql << type
1226 end
_table_exists?(ds) click to toggle source

Consider lock or statement timeout errors as evidence that the table exists but is locked.

Calls superclass method
     # File lib/sequel/adapters/shared/postgres.rb
1230 def _table_exists?(ds)
1231   super
1232 rescue DatabaseError => e    
1233   raise e unless /canceling statement due to (?:statement|lock) timeout/ =~ e.message 
1234 end
alter_table_add_column_sql(table, op) click to toggle source
     # File lib/sequel/adapters/shared/postgres.rb
1236 def alter_table_add_column_sql(table, op)
1237   "ADD COLUMN#{' IF NOT EXISTS' if op[:if_not_exists]} #{column_definition_sql(op)}"
1238 end
alter_table_alter_constraint_sql(table, op) click to toggle source
     # File lib/sequel/adapters/shared/postgres.rb
1247 def alter_table_alter_constraint_sql(table, op)
1248   sql = String.new
1249   sql << "ALTER CONSTRAINT #{quote_identifier(op[:name])}"
1250   
1251   constraint_deferrable_sql_append(sql, op[:deferrable])
1252 
1253   case op[:enforced]
1254   when nil
1255   when false
1256     sql << " NOT ENFORCED"
1257   else
1258     sql << " ENFORCED"
1259   end
1260 
1261   case op[:inherit]
1262   when nil
1263   when false
1264     sql << " NO INHERIT"
1265   else
1266     sql << " INHERIT"
1267   end
1268 
1269   sql
1270 end
alter_table_attach_partition_sql(table, op) click to toggle source
     # File lib/sequel/adapters/shared/postgres.rb
1240 def alter_table_attach_partition_sql(table, op)
1241   sql = String.new
1242   sql << "ATTACH PARTITION #{quote_identifier(op[:name])}"
1243   partition_bound_spec_sql_append(sql, op[:generator])
1244   sql
1245 end
alter_table_detach_partition_sql(table, op) click to toggle source
     # File lib/sequel/adapters/shared/postgres.rb
1290 def alter_table_detach_partition_sql(table, op)
1291   "DETACH PARTITION #{quote_identifier(op[:name])}#{' CONCURRENTLY' if op[:concurrently]}#{' FINALIZE' if op[:finalize]}"
1292 end
alter_table_drop_column_sql(table, op) click to toggle source
     # File lib/sequel/adapters/shared/postgres.rb
1294 def alter_table_drop_column_sql(table, op)
1295   "DROP COLUMN #{'IF EXISTS ' if op[:if_exists]}#{quote_identifier(op[:name])}#{' CASCADE' if op[:cascade]}"
1296 end
alter_table_generator_class() click to toggle source
     # File lib/sequel/adapters/shared/postgres.rb
1272 def alter_table_generator_class
1273   Postgres::AlterTableGenerator
1274 end
alter_table_rename_constraint_sql(table, op) click to toggle source
     # File lib/sequel/adapters/shared/postgres.rb
1276 def alter_table_rename_constraint_sql(table, op)
1277   "RENAME CONSTRAINT #{quote_identifier(op[:name])} TO #{quote_identifier(op[:new_name])}"
1278 end
alter_table_set_column_type_sql(table, op) click to toggle source
Calls superclass method
     # File lib/sequel/adapters/shared/postgres.rb
1280 def alter_table_set_column_type_sql(table, op)
1281   s = super
1282   if using = op[:using]
1283     using = Sequel::LiteralString.new(using) if using.is_a?(String)
1284     s += ' USING '
1285     s << literal(using)
1286   end
1287   s
1288 end
alter_table_validate_constraint_sql(table, op) click to toggle source
     # File lib/sequel/adapters/shared/postgres.rb
1298 def alter_table_validate_constraint_sql(table, op)
1299   "VALIDATE CONSTRAINT #{quote_identifier(op[:name])}"
1300 end
begin_new_transaction(conn, opts) click to toggle source

If the :synchronous option is given and non-nil, set synchronous_commit appropriately. Valid values for the :synchronous option are true, :on, false, :off, :local, :remote_apply, and :remote_write.

Calls superclass method
     # File lib/sequel/adapters/shared/postgres.rb
1305 def begin_new_transaction(conn, opts)
1306   super
1307   if opts.has_key?(:synchronous)
1308     case sync = opts[:synchronous]
1309     when true
1310       sync = :on
1311     when false
1312       sync = :off
1313     when nil
1314       return
1315     when :on, :off, :local, :remote_apply, :remote_write
1316       nil
1317     else
1318       # SEQUEL6: raise
1319       Sequel::Deprecation.deprecate("Unsupported :synchronous option given to Database#transaction: #{sync.inspect}, this will raise an error in Sequel 6.")
1320       return
1321     end
1322 
1323     log_connection_execute(conn, "SET LOCAL synchronous_commit = #{sync}")
1324   end
1325 end
begin_savepoint(conn, opts) click to toggle source

Set the READ ONLY transaction setting per savepoint, as PostgreSQL supports that.

Calls superclass method
     # File lib/sequel/adapters/shared/postgres.rb
1328 def begin_savepoint(conn, opts)
1329   super
1330 
1331   unless (read_only = opts[:read_only]).nil?
1332     log_connection_execute(conn, "SET TRANSACTION READ #{read_only ? 'ONLY' : 'WRITE'}")
1333   end
1334 end
column_definition_add_references_sql(sql, column) click to toggle source
Calls superclass method
     # File lib/sequel/adapters/shared/postgres.rb
1509 def column_definition_add_references_sql(sql, column)
1510   super
1511   if column[:not_enforced]
1512     sql << " NOT ENFORCED"
1513   end
1514 end
column_definition_append_include_sql(sql, constraint) click to toggle source
     # File lib/sequel/adapters/shared/postgres.rb
1363 def column_definition_append_include_sql(sql, constraint)
1364   if include_cols = constraint[:include]
1365     sql << " INCLUDE " << literal(Array(include_cols))
1366   end
1367 end
column_definition_append_primary_key_sql(sql, constraint) click to toggle source
Calls superclass method
     # File lib/sequel/adapters/shared/postgres.rb
1369 def column_definition_append_primary_key_sql(sql, constraint)
1370   super
1371   column_definition_append_include_sql(sql, constraint)
1372 end
column_definition_append_unique_sql(sql, constraint) click to toggle source
Calls superclass method
     # File lib/sequel/adapters/shared/postgres.rb
1374 def column_definition_append_unique_sql(sql, constraint)
1375   super
1376   column_definition_append_include_sql(sql, constraint)
1377 end
column_definition_collate_sql(sql, column) click to toggle source

Literalize non-String collate options. This is because unquoted collatations are folded to lowercase, and PostgreSQL used mixed case or capitalized collations.

     # File lib/sequel/adapters/shared/postgres.rb
1381 def column_definition_collate_sql(sql, column)
1382   if collate = column[:collate]
1383     collate = literal(collate) unless collate.is_a?(String)
1384     sql << " COLLATE #{collate}"
1385   end
1386 end
column_definition_default_sql(sql, column) click to toggle source

Support identity columns, but only use the identity SQL syntax if no default value is given.

Calls superclass method
     # File lib/sequel/adapters/shared/postgres.rb
1390 def column_definition_default_sql(sql, column)
1391   super
1392   if !column[:serial] && !['smallserial', 'serial', 'bigserial'].include?(column[:type].to_s) && !column[:default]
1393     if (identity = column[:identity])
1394       sql << " GENERATED "
1395       sql << (identity == :always ? "ALWAYS" : "BY DEFAULT")
1396       sql << " AS IDENTITY"
1397     elsif (generated = column[:generated_always_as])
1398       sql << " GENERATED ALWAYS AS (#{literal(generated)}) #{column[:virtual] ? 'VIRTUAL' : 'STORED'}"
1399     end
1400   end
1401 end
column_definition_null_sql(sql, column) click to toggle source
Calls superclass method
     # File lib/sequel/adapters/shared/postgres.rb
1516 def column_definition_null_sql(sql, column)
1517   constraint = column[:not_null]
1518   constraint = nil unless constraint.is_a?(Hash)
1519   if constraint && (name = constraint[:name])
1520     sql << " CONSTRAINT #{quote_identifier(name)}"
1521   end
1522   super
1523   if constraint && constraint[:no_inherit]
1524     sql << " NO INHERIT"
1525   end
1526 end
column_definition_sql(column) click to toggle source
Calls superclass method
     # File lib/sequel/adapters/shared/postgres.rb
1336 def column_definition_sql(column)
1337   if table = column[:like_table]
1338     sql = String.new
1339     sql << "LIKE #{quote_schema_table(table)}"
1340     allowed_options = %i[comments compression constraints defaults generated identity indexes statistics storage all].freeze
1341 
1342     %i[including excluding].freeze.each do |type|
1343       options = column[type]
1344       next if options.empty?
1345 
1346       unallowed_options = options - allowed_options
1347       if unallowed_options.empty?
1348         type = type.to_s.upcase
1349         options.each do |opt|
1350           sql << " #{type} #{opt.to_s.upcase}"
1351         end
1352       else
1353         raise Error, "unsupported like :#{type} options: #{unallowed_options.inspect}"
1354       end
1355     end
1356 
1357     sql
1358   else
1359     super
1360   end
1361 end
column_references_add_period(cols) click to toggle source
     # File lib/sequel/adapters/shared/postgres.rb
1543 def column_references_add_period(cols)
1544   cols= cols.dup
1545   cols[-1] = Sequel.lit("PERIOD #{quote_identifier(cols[-1])}".freeze)
1546   cols
1547 end
column_references_append_key_sql(sql, column) click to toggle source
     # File lib/sequel/adapters/shared/postgres.rb
1537 def column_references_append_key_sql(sql, column)
1538   cols = Array(column[:key])
1539   cols = column_references_add_period(cols) if column[:period]
1540   sql << "(#{cols.map{|x| quote_identifier(x)}.join(', ')})"
1541 end
column_references_table_constraint_sql(constraint) click to toggle source

Handle :period option

     # File lib/sequel/adapters/shared/postgres.rb
1529 def column_references_table_constraint_sql(constraint)
1530   sql = String.new
1531   sql << "FOREIGN KEY "
1532   cols = constraint[:columns]
1533   cols = column_references_add_period(cols) if constraint[:period]
1534   sql << literal(cols) << column_references_sql(constraint)
1535 end
column_schema_normalize_default(default, type) click to toggle source

Handle PostgreSQL specific default format.

Calls superclass method
     # File lib/sequel/adapters/shared/postgres.rb
1404 def column_schema_normalize_default(default, type)
1405   if m = /\A(?:B?('.*')::[^']+|\((-?\d+(?:\.\d+)?)\))\z/.match(default)
1406     default = m[1] || m[2]
1407   end
1408   super(default, type)
1409 end
combinable_alter_table_op?(op) click to toggle source

PostgreSQL can’t combine rename_column operations, and it can combine validate_constraint and alter_constraint operations.

Calls superclass method
     # File lib/sequel/adapters/shared/postgres.rb
1423 def combinable_alter_table_op?(op)
1424   (super || op[:op] == :validate_constraint || op[:op] == :alter_constraint) && op[:op] != :rename_column
1425 end
commit_transaction(conn, opts=OPTS) click to toggle source

If the :prepare option is given and we aren’t in a savepoint, prepare the transaction for a two-phase commit.

Calls superclass method
     # File lib/sequel/adapters/shared/postgres.rb
1413 def commit_transaction(conn, opts=OPTS)
1414   if (s = opts[:prepare]) && savepoint_level(conn) <= 1
1415     log_connection_execute(conn, "PREPARE TRANSACTION #{literal(s)}")
1416   else
1417     super
1418   end
1419 end
connection_configuration_sqls(opts=@opts) click to toggle source

The SQL queries to execute when starting a new connection.

     # File lib/sequel/adapters/shared/postgres.rb
1429 def connection_configuration_sqls(opts=@opts)
1430   sqls = []
1431 
1432   sqls << "SET standard_conforming_strings = ON" if typecast_value_boolean(opts.fetch(:force_standard_strings, true))
1433 
1434   cmm = opts.fetch(:client_min_messages, :warning)
1435   if cmm && !cmm.to_s.empty?
1436     cmm = cmm.to_s.upcase.strip
1437     unless VALID_CLIENT_MIN_MESSAGES.include?(cmm)
1438       raise Error, "Unsupported client_min_messages setting: #{cmm}"
1439     end
1440     sqls << "SET client_min_messages = '#{cmm.to_s.upcase}'"
1441   end
1442 
1443   if search_path = opts[:search_path]
1444     case search_path
1445     when String
1446       search_path = search_path.split(",").map(&:strip)
1447     when Array
1448       # nil
1449     else
1450       raise Error, "unrecognized value for :search_path option: #{search_path.inspect}"
1451     end
1452     sqls << "SET search_path = #{search_path.map{|s| "\"#{s.gsub('"', '""')}\""}.join(',')}"
1453   end
1454 
1455   sqls
1456 end
constraint_definition_sql(constraint) click to toggle source

Handle PostgreSQL-specific constraint features.

Calls superclass method
     # File lib/sequel/adapters/shared/postgres.rb
1459 def constraint_definition_sql(constraint)
1460   case type = constraint[:type]
1461   when :exclude
1462     elements = constraint[:elements].map{|c, op| "#{literal(c)} WITH #{op}"}.join(', ')
1463     sql = String.new
1464     sql << "CONSTRAINT #{quote_identifier(constraint[:name])} " if constraint[:name]
1465     sql << "EXCLUDE USING #{constraint[:using]||'gist'} (#{elements})"
1466     column_definition_append_include_sql(sql, constraint)
1467     sql << " WHERE #{filter_expr(constraint[:where])}" if constraint[:where]
1468     constraint_deferrable_sql_append(sql, constraint[:deferrable])
1469     sql
1470   when :primary_key, :unique
1471     sql = String.new
1472     sql << "CONSTRAINT #{quote_identifier(constraint[:name])} " if constraint[:name]
1473 
1474     if type == :primary_key
1475       sql << primary_key_constraint_sql_fragment(constraint)
1476     else
1477       sql << unique_constraint_sql_fragment(constraint)
1478     end
1479 
1480     if using_index = constraint[:using_index]
1481       sql << " USING INDEX " << quote_identifier(using_index)
1482     else
1483       cols = literal(constraint[:columns])
1484       cols.insert(-2, " WITHOUT OVERLAPS") if constraint[:without_overlaps]
1485       sql << " " << cols
1486 
1487       if include_cols = constraint[:include]
1488         sql << " INCLUDE " << literal(Array(include_cols))
1489       end
1490     end
1491 
1492     constraint_deferrable_sql_append(sql, constraint[:deferrable])
1493     sql
1494   else # when :foreign_key, :check
1495     sql = super
1496     if constraint[:no_inherit]
1497       sql << " NO INHERIT"
1498     end
1499     if constraint[:not_enforced]
1500       sql << " NOT ENFORCED"
1501     end
1502     if constraint[:not_valid]
1503       sql << " NOT VALID"
1504     end
1505     sql
1506   end
1507 end
copy_into_sql(table, opts) click to toggle source

SQL for doing fast table insert from stdin.

     # File lib/sequel/adapters/shared/postgres.rb
1578 def copy_into_sql(table, opts)
1579   sql = String.new
1580   sql << "COPY #{literal(table)}"
1581   if cols = opts[:columns]
1582     sql << literal(Array(cols))
1583   end
1584   sql << " FROM STDIN"
1585   if opts[:options] || opts[:format]
1586     sql << " ("
1587     sql << "FORMAT #{opts[:format]}" if opts[:format]
1588     sql << "#{', ' if opts[:format]}#{opts[:options]}" if opts[:options]
1589     sql << ')'
1590   end
1591   sql
1592 end
copy_table_sql(table, opts) click to toggle source

SQL for doing fast table output to stdout.

     # File lib/sequel/adapters/shared/postgres.rb
1595 def copy_table_sql(table, opts)
1596   if table.is_a?(String)
1597     table
1598   else
1599     if opts[:options] || opts[:format]
1600       options = String.new
1601       options << " ("
1602       if format = opts[:format]
1603         sql_format = format.to_s.downcase
1604         unless %w[text csv json binary].freeze.include?(sql_format)
1605           raise Error, "unsupported COPY TO format: #{format.inspect}"
1606         end
1607         options << "FORMAT #{format}"
1608       end
1609       options << "#{', ' if format}#{opts[:options]}" if opts[:options]
1610       options << ')'
1611     end
1612     table = if table.is_a?(::Sequel::Dataset)
1613       "(#{table.sql})"
1614     else
1615       literal(table)
1616     end
1617     "COPY #{table} TO STDOUT#{options}"
1618   end
1619 end
create_function_sql(name, definition, opts=OPTS) click to toggle source

SQL statement to create database function.

     # File lib/sequel/adapters/shared/postgres.rb
1622       def create_function_sql(name, definition, opts=OPTS)
1623         args = opts[:args]
1624         in_out = %w'OUT INOUT'
1625         if (!opts[:args].is_a?(Array) || !opts[:args].any?{|a| Array(a).length == 3 && in_out.include?(a[2].to_s)})
1626           returns = opts[:returns] || 'void'
1627         end
1628         language = opts[:language] || 'SQL'
1629         <<-END
1630         CREATE#{' OR REPLACE' if opts[:replace]} FUNCTION #{name}#{sql_function_args(args)}
1631         #{"RETURNS #{returns}" if returns}
1632         LANGUAGE #{language}
1633         #{opts[:behavior].to_s.upcase if opts[:behavior]}
1634         #{'STRICT' if opts[:strict]}
1635         #{'SECURITY DEFINER' if opts[:security_definer]}
1636         #{"PARALLEL #{opts[:parallel].to_s.upcase}" if opts[:parallel]}
1637         #{"COST #{opts[:cost]}" if opts[:cost]}
1638         #{"ROWS #{opts[:rows]}" if opts[:rows]}
1639         #{opts[:set].map{|k,v| " SET #{k} = #{v}"}.join("\n") if opts[:set]}
1640         AS #{literal(definition.to_s)}#{", #{literal(opts[:link_symbol].to_s)}" if opts[:link_symbol]}
1641         END
1642       end
create_language_sql(name, opts=OPTS) click to toggle source

SQL for creating a procedural language.

     # File lib/sequel/adapters/shared/postgres.rb
1645 def create_language_sql(name, opts=OPTS)
1646   "CREATE#{' OR REPLACE' if opts[:replace] && server_version >= 90000}#{' TRUSTED' if opts[:trusted]} LANGUAGE #{name}#{" HANDLER #{opts[:handler]}" if opts[:handler]}#{" VALIDATOR #{opts[:validator]}" if opts[:validator]}"
1647 end
create_partition_of_table_from_generator(name, generator, options) click to toggle source

Create a partition of another table, used when the create_table with the :partition_of option is given.

     # File lib/sequel/adapters/shared/postgres.rb
1651 def create_partition_of_table_from_generator(name, generator, options)
1652   execute_ddl(create_partition_of_table_sql(name, generator, options))
1653 end
create_partition_of_table_sql(name, generator, options) click to toggle source

SQL for creating a partition of another table.

     # File lib/sequel/adapters/shared/postgres.rb
1656 def create_partition_of_table_sql(name, generator, options)
1657   sql = create_table_prefix_sql(name, options).dup
1658   sql << " PARTITION OF #{quote_schema_table(options[:partition_of])}"
1659   partition_bound_spec_sql_append(sql, generator)
1660   sql << create_table_suffix_sql(name, options)
1661   sql
1662 end
create_schema_sql(name, opts=OPTS) click to toggle source

SQL for creating a schema.

     # File lib/sequel/adapters/shared/postgres.rb
1680 def create_schema_sql(name, opts=OPTS)
1681   "CREATE SCHEMA #{'IF NOT EXISTS ' if opts[:if_not_exists]}#{quote_identifier(name)}#{" AUTHORIZATION #{literal(opts[:owner])}" if opts[:owner]}"
1682 end
create_table_as_sql(name, sql, options) click to toggle source
     # File lib/sequel/adapters/shared/postgres.rb
1738 def create_table_as_sql(name, sql, options)
1739   result = create_table_prefix_sql name, options
1740   if on_commit = options[:on_commit]
1741     result += " ON COMMIT #{ON_COMMIT[on_commit]}"
1742   end
1743   result += " AS #{sql}"
1744 end
create_table_generator_class() click to toggle source
     # File lib/sequel/adapters/shared/postgres.rb
1746 def create_table_generator_class
1747   Postgres::CreateTableGenerator
1748 end
create_table_prefix_sql(name, options) click to toggle source

DDL statement for creating a table with the given name, columns, and options

     # File lib/sequel/adapters/shared/postgres.rb
1685 def create_table_prefix_sql(name, options)
1686   prefix_sql = if options[:temp]
1687     raise(Error, "can't provide both :temp and :unlogged to create_table") if options[:unlogged]
1688     raise(Error, "can't provide both :temp and :foreign to create_table") if options[:foreign]
1689     temporary_table_sql
1690   elsif options[:foreign]
1691     raise(Error, "can't provide both :foreign and :unlogged to create_table") if options[:unlogged]
1692     'FOREIGN '
1693   elsif options.fetch(:unlogged){typecast_value_boolean(@opts[:unlogged_tables_default])}
1694     'UNLOGGED '
1695   end
1696 
1697   "CREATE #{prefix_sql}TABLE#{' IF NOT EXISTS' if options[:if_not_exists]} #{create_table_table_name_sql(name, options)}"
1698 end
create_table_sql(name, generator, options) click to toggle source

SQL for creating a table with PostgreSQL specific options

     # File lib/sequel/adapters/shared/postgres.rb
1701 def create_table_sql(name, generator, options)
1702   "#{super}#{create_table_suffix_sql(name, options)}"
1703 end
create_table_suffix_sql(name, options) click to toggle source

Handle various PostgreSQL specific table extensions such as inheritance, partitioning, tablespaces, and foreign tables.

     # File lib/sequel/adapters/shared/postgres.rb
1707 def create_table_suffix_sql(name, options)
1708   sql = String.new
1709 
1710   if inherits = options[:inherits]
1711     sql << " INHERITS (#{Array(inherits).map{|t| quote_schema_table(t)}.join(', ')})"
1712   end
1713 
1714   if partition_by = options[:partition_by]
1715     sql << " PARTITION BY #{options[:partition_type]||'RANGE'} #{literal(Array(partition_by))}"
1716   end
1717 
1718   if on_commit = options[:on_commit]
1719     raise(Error, "can't provide :on_commit without :temp to create_table") unless options[:temp]
1720     raise(Error, "unsupported on_commit option: #{on_commit.inspect}") unless ON_COMMIT.has_key?(on_commit)
1721     sql << " ON COMMIT #{ON_COMMIT[on_commit]}"
1722   end
1723 
1724   if tablespace = options[:tablespace]
1725     sql << " TABLESPACE #{quote_identifier(tablespace)}"
1726   end
1727 
1728   if server = options[:foreign]
1729     sql << " SERVER #{quote_identifier(server)}"
1730     if foreign_opts = options[:options]
1731       sql << " OPTIONS (#{foreign_opts.map{|k, v| "#{k} #{literal(v.to_s)}"}.join(', ')})"
1732     end
1733   end
1734 
1735   sql
1736 end
create_trigger_sql(table, name, function, opts=OPTS) click to toggle source

SQL for creating a database trigger.

     # File lib/sequel/adapters/shared/postgres.rb
1751 def create_trigger_sql(table, name, function, opts=OPTS)
1752   events = opts[:events] ? Array(opts[:events]) : [:insert, :update, :delete]
1753   whence = opts[:after] ? 'AFTER' : 'BEFORE'
1754   if filter = opts[:when]
1755     raise Error, "Trigger conditions are not supported for this database" unless supports_trigger_conditions?
1756     filter = " WHEN #{filter_expr(filter)}"
1757   end
1758   "CREATE #{'OR REPLACE ' if opts[:replace]}TRIGGER #{name} #{whence} #{events.map{|e| e.to_s.upcase}.join(' OR ')} ON #{quote_schema_table(table)}#{' FOR EACH ROW' if opts[:each_row]}#{filter} EXECUTE PROCEDURE #{function}(#{Array(opts[:args]).map{|a| literal(a)}.join(', ')})"
1759 end
create_view_prefix_sql(name, options) click to toggle source

DDL fragment for initial part of CREATE VIEW statement

     # File lib/sequel/adapters/shared/postgres.rb
1762 def create_view_prefix_sql(name, options)
1763   sql = create_view_sql_append_columns("CREATE #{'OR REPLACE 'if options[:replace]}#{'TEMPORARY 'if options[:temp]}#{'RECURSIVE ' if options[:recursive]}#{'MATERIALIZED ' if options[:materialized]}VIEW #{quote_schema_table(name)}", options[:columns] || options[:recursive])
1764 
1765   if options[:security_invoker]
1766     sql += " WITH (security_invoker)"
1767   end
1768 
1769   if tablespace = options[:tablespace]
1770     sql += " TABLESPACE #{quote_identifier(tablespace)}"
1771   end
1772 
1773   sql
1774 end
database_error_regexps() click to toggle source
     # File lib/sequel/adapters/shared/postgres.rb
1573 def database_error_regexps
1574   DATABASE_ERROR_REGEXPS
1575 end
database_specific_error_class_from_sqlstate(sqlstate) click to toggle source
Calls superclass method
     # File lib/sequel/adapters/shared/postgres.rb
1549 def database_specific_error_class_from_sqlstate(sqlstate)
1550   if sqlstate == '23P01'
1551     ExclusionConstraintViolation
1552   elsif sqlstate == '40P01'
1553     SerializationFailure
1554   elsif sqlstate == '55P03'
1555     DatabaseLockTimeout
1556   else
1557     super
1558   end
1559 end
drop_function_sql(name, opts=OPTS) click to toggle source

SQL for dropping a function from the database.

     # File lib/sequel/adapters/shared/postgres.rb
1777 def drop_function_sql(name, opts=OPTS)
1778   "DROP FUNCTION#{' IF EXISTS' if opts[:if_exists]} #{name}#{sql_function_args(opts[:args])}#{' CASCADE' if opts[:cascade]}"
1779 end
drop_index_sql(table, op) click to toggle source

Support :if_exists, :cascade, and :concurrently options.

     # File lib/sequel/adapters/shared/postgres.rb
1782 def drop_index_sql(table, op)
1783   sch, _ = schema_and_table(table)
1784   "DROP INDEX#{' CONCURRENTLY' if op[:concurrently]}#{' IF EXISTS' if op[:if_exists]} #{"#{quote_identifier(sch)}." if sch}#{quote_identifier(op[:name] || default_index_name(table, op[:columns]))}#{' CASCADE' if op[:cascade]}"
1785 end
drop_language_sql(name, opts=OPTS) click to toggle source

SQL for dropping a procedural language from the database.

     # File lib/sequel/adapters/shared/postgres.rb
1788 def drop_language_sql(name, opts=OPTS)
1789   "DROP LANGUAGE#{' IF EXISTS' if opts[:if_exists]} #{name}#{' CASCADE' if opts[:cascade]}"
1790 end
drop_schema_sql(name, opts=OPTS) click to toggle source

SQL for dropping a schema from the database.

     # File lib/sequel/adapters/shared/postgres.rb
1793 def drop_schema_sql(name, opts=OPTS)
1794   "DROP SCHEMA#{' IF EXISTS' if opts[:if_exists]} #{quote_identifier(name)}#{' CASCADE' if opts[:cascade]}"
1795 end
drop_table_sql(name, options) click to toggle source

Support :foreign tables

     # File lib/sequel/adapters/shared/postgres.rb
1803 def drop_table_sql(name, options)
1804   "DROP#{' FOREIGN' if options[:foreign]} TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_schema_table(name)}#{' CASCADE' if options[:cascade]}"
1805 end
drop_trigger_sql(table, name, opts=OPTS) click to toggle source

SQL for dropping a trigger from the database.

     # File lib/sequel/adapters/shared/postgres.rb
1798 def drop_trigger_sql(table, name, opts=OPTS)
1799   "DROP TRIGGER#{' IF EXISTS' if opts[:if_exists]} #{name} ON #{quote_schema_table(table)}#{' CASCADE' if opts[:cascade]}"
1800 end
drop_view_sql(name, opts=OPTS) click to toggle source

SQL for dropping a view from the database.

     # File lib/sequel/adapters/shared/postgres.rb
1808 def drop_view_sql(name, opts=OPTS)
1809   "DROP #{'MATERIALIZED ' if opts[:materialized]}VIEW#{' IF EXISTS' if opts[:if_exists]} #{quote_schema_table(name)}#{' CASCADE' if opts[:cascade]}"
1810 end
filter_schema(ds, opts) click to toggle source

If opts includes a :schema option, use it, otherwise restrict the filter to only the currently visible schemas.

     # File lib/sequel/adapters/shared/postgres.rb
1814 def filter_schema(ds, opts)
1815   expr = if schema = opts[:schema]
1816     if schema.is_a?(SQL::Identifier)
1817       schema.value.to_s
1818     else
1819       schema.to_s
1820     end
1821   else
1822     Sequel.function(:any, Sequel.function(:current_schemas, false))
1823   end
1824   ds.where{{pg_namespace[:nspname]=>expr}}
1825 end
index_definition_sql(table_name, index) click to toggle source
     # File lib/sequel/adapters/shared/postgres.rb
1827 def index_definition_sql(table_name, index)
1828   cols = index[:columns]
1829   index_name = index[:name] || default_index_name(table_name, cols)
1830 
1831   expr = if o = index[:opclass]
1832     "(#{Array(cols).map{|c| "#{literal(c)} #{o}"}.join(', ')})"
1833   else
1834     literal(Array(cols))
1835   end
1836 
1837   if_not_exists = " IF NOT EXISTS" if index[:if_not_exists]
1838   unique = "UNIQUE " if index[:unique]
1839   index_type = index[:type]
1840   filter = index[:where] || index[:filter]
1841   filter = " WHERE #{filter_expr(filter)}" if filter
1842   nulls_distinct = " NULLS#{' NOT' if index[:nulls_distinct] == false} DISTINCT" unless index[:nulls_distinct].nil?
1843 
1844   case index_type
1845   when :full_text
1846     expr = "(to_tsvector(#{literal(index[:language] || 'simple')}::regconfig, #{literal(dataset.send(:full_text_string_join, cols))}))"
1847     index_type = index[:index_type] || :gin
1848   when :spatial
1849     index_type = :gist
1850   end
1851 
1852   "CREATE #{unique}INDEX#{' CONCURRENTLY' if index[:concurrently]}#{if_not_exists} #{quote_identifier(index_name)} ON#{' ONLY' if index[:only]} #{quote_schema_table(table_name)} #{"USING #{index_type} " if index_type}#{expr}#{" INCLUDE #{literal(Array(index[:include]))}" if index[:include]}#{nulls_distinct}#{" TABLESPACE #{quote_identifier(index[:tablespace])}" if index[:tablespace]}#{filter}"
1853 end
initialize_postgres_adapter() click to toggle source

Setup datastructures shared by all postgres adapters.

     # File lib/sequel/adapters/shared/postgres.rb
1856 def initialize_postgres_adapter
1857   @primary_keys = {}
1858   @primary_key_sequences = {}
1859   @supported_types = {}
1860   procs = @conversion_procs = CONVERSION_PROCS.dup
1861   procs[1184] = procs[1114] = method(:to_application_timestamp)
1862 end
partition_bound_spec_sql_append(sql, generator) click to toggle source
     # File lib/sequel/adapters/shared/postgres.rb
1664 def partition_bound_spec_sql_append(sql, generator)
1665   sql << case generator.partition_type
1666   when :range
1667     from, to = generator.range
1668     " FOR VALUES FROM #{literal(from)} TO #{literal(to)}"
1669   when :list
1670     " FOR VALUES IN #{literal(generator.list)}"
1671   when :hash
1672     mod, remainder = generator.hash_values
1673     " FOR VALUES WITH (MODULUS #{literal(mod)}, REMAINDER #{literal(remainder)})"
1674   else # when :default
1675     " DEFAULT"
1676   end
1677 end
pg_class_relname(type, opts) { || ... } click to toggle source

Backbone of the tables and views support.

     # File lib/sequel/adapters/shared/postgres.rb
1865 def pg_class_relname(type, opts)
1866   ds = metadata_dataset.from(:pg_class).where(:relkind=>type).select(:relname).server(opts[:server]).join(:pg_namespace, :oid=>:relnamespace)
1867   ds = filter_schema(ds, opts)
1868   m = output_identifier_meth
1869   if defined?(yield)
1870     yield(ds)
1871   elsif opts[:qualify]
1872     ds.select_append{pg_namespace[:nspname]}.map{|r| Sequel.qualify(m.call(r[:nspname]).to_s, m.call(r[:relname]).to_s)}
1873   else
1874     ds.map{|r| m.call(r[:relname])}
1875   end
1876 end
regclass_oid(expr, opts=OPTS) click to toggle source

Return an expression the oid for the table expr. Used by the metadata parsing code to disambiguate unqualified tables.

     # File lib/sequel/adapters/shared/postgres.rb
1880 def regclass_oid(expr, opts=OPTS)
1881   if expr.is_a?(String) && !expr.is_a?(LiteralString)
1882     expr = Sequel.identifier(expr)
1883   end
1884 
1885   sch, table = schema_and_table(expr)
1886   sch ||= opts[:schema]
1887   if sch
1888     expr = Sequel.qualify(sch, table)
1889   end
1890   
1891   expr = if ds = opts[:dataset]
1892     ds.literal(expr)
1893   else
1894     literal(expr)
1895   end
1896 
1897   Sequel.cast(expr.to_s,:regclass).cast(:oid)
1898 end
remove_all_cached_schemas() click to toggle source

Clear all cached schema information

     # File lib/sequel/adapters/shared/postgres.rb
1911 def remove_all_cached_schemas
1912   @primary_keys.clear
1913   @primary_key_sequences.clear
1914   @schemas.clear
1915 end
remove_cached_schema(table) click to toggle source

Remove the cached entries for primary keys and sequences when a table is changed.

Calls superclass method
     # File lib/sequel/adapters/shared/postgres.rb
1901 def remove_cached_schema(table)
1902   tab = quote_schema_table(table)
1903   Sequel.synchronize do
1904     @primary_keys.delete(tab)
1905     @primary_key_sequences.delete(tab)
1906   end
1907   super
1908 end
rename_schema_sql(name, new_name) click to toggle source

SQL for renaming a schema.

     # File lib/sequel/adapters/shared/postgres.rb
1918 def rename_schema_sql(name, new_name)
1919   "ALTER SCHEMA #{quote_identifier(name)} RENAME TO #{quote_identifier(new_name)}"
1920 end
rename_table_sql(name, new_name) click to toggle source

SQL DDL statement for renaming a table. PostgreSQL doesn’t allow you to change a table’s schema in a rename table operation, so specifying a new schema in new_name will not have an effect.

     # File lib/sequel/adapters/shared/postgres.rb
1924 def rename_table_sql(name, new_name)
1925   "ALTER TABLE #{quote_schema_table(name)} RENAME TO #{quote_identifier(schema_and_table(new_name).last)}"
1926 end
schema_array_type(db_type) click to toggle source

The schema :type entry to use for array types.

     # File lib/sequel/adapters/shared/postgres.rb
1941 def schema_array_type(db_type)
1942   :array
1943 end
schema_column_type(db_type) click to toggle source

Handle interval and citext types.

Calls superclass method
     # File lib/sequel/adapters/shared/postgres.rb
1929 def schema_column_type(db_type)
1930   case db_type
1931   when /\Ainterval\z/i
1932     :interval
1933   when /\Acitext\z/i
1934     :string
1935   else
1936     super
1937   end
1938 end
schema_composite_type(db_type) click to toggle source

The schema :type entry to use for row/composite types.

     # File lib/sequel/adapters/shared/postgres.rb
1946 def schema_composite_type(db_type)
1947   :composite
1948 end
schema_enum_type(db_type) click to toggle source

The schema :type entry to use for enum types.

     # File lib/sequel/adapters/shared/postgres.rb
1951 def schema_enum_type(db_type)
1952   :enum
1953 end
schema_multirange_type(db_type) click to toggle source

The schema :type entry to use for multirange types.

     # File lib/sequel/adapters/shared/postgres.rb
1961 def schema_multirange_type(db_type)
1962   :multirange
1963 end
schema_parse_table(table_name, opts) click to toggle source

The dataset used for parsing table schemas, using the pg_* system catalogs.

     # File lib/sequel/adapters/shared/postgres.rb
1978 def schema_parse_table(table_name, opts)
1979   m = output_identifier_meth(opts[:dataset])
1980 
1981   _schema_ds.where_all(Sequel[:pg_class][:oid]=>regclass_oid(table_name, opts)).map do |row|
1982     row[:default] = nil if blank_object?(row[:default])
1983     if row[:base_oid]
1984       row[:domain_oid] = row[:oid]
1985       row[:oid] = row.delete(:base_oid)
1986       row[:db_domain_type] = row[:db_type]
1987       row[:db_type] = row.delete(:db_base_type)
1988     else
1989       row.delete(:base_oid)
1990       row.delete(:db_base_type)
1991     end
1992 
1993     db_type = row[:db_type]
1994     row[:type] = if row.delete(:is_array)
1995       schema_array_type(db_type)
1996     else
1997       send(TYPTYPE_METHOD_MAP[row.delete(:typtype)], db_type)
1998     end
1999     identity = row.delete(:attidentity)
2000     if row[:primary_key]
2001       row[:auto_increment] = !!(row[:default] =~ /\A(?:nextval)/i) || identity == 'a' || identity == 'd'
2002     end
2003 
2004     # simplecov:disable
2005     if server_version >= 90600
2006     # simplecov:enable
2007       case row[:oid]
2008       when 1082
2009         row[:min_value] = MIN_DATE
2010         row[:max_value] = MAX_DATE
2011       when 1184, 1114
2012         if Sequel.datetime_class == Time
2013           row[:min_value] = MIN_TIMESTAMP
2014           row[:max_value] = MAX_TIMESTAMP
2015         end
2016       end
2017     end
2018 
2019     [m.call(row.delete(:name)), row]
2020   end
2021 end
schema_range_type(db_type) click to toggle source

The schema :type entry to use for range types.

     # File lib/sequel/adapters/shared/postgres.rb
1956 def schema_range_type(db_type)
1957   :range
1958 end
set_transaction_isolation(conn, opts) click to toggle source

Set the transaction isolation level on the given connection

     # File lib/sequel/adapters/shared/postgres.rb
2024 def set_transaction_isolation(conn, opts)
2025   level = opts.fetch(:isolation, transaction_isolation_level)
2026   read_only = opts[:read_only]
2027   deferrable = opts[:deferrable]
2028   if level || !read_only.nil? || !deferrable.nil?
2029     sql = String.new
2030     sql << "SET TRANSACTION"
2031     sql << " ISOLATION LEVEL #{Sequel::Database::TRANSACTION_ISOLATION_LEVELS[level]}" if level
2032     sql << " READ #{read_only ? 'ONLY' : 'WRITE'}" unless read_only.nil?
2033     sql << " #{'NOT ' unless deferrable}DEFERRABLE" unless deferrable.nil?
2034     log_connection_execute(conn, sql)
2035   end
2036 end
sql_function_args(args) click to toggle source

Turns an array of argument specifiers into an SQL fragment used for function arguments. See create_function_sql.

     # File lib/sequel/adapters/shared/postgres.rb
2039 def sql_function_args(args)
2040   "(#{Array(args).map{|a| Array(a).reverse.join(' ')}.join(', ')})"
2041 end
supports_combining_alter_table_ops?() click to toggle source

PostgreSQL can combine multiple alter table ops into a single query.

     # File lib/sequel/adapters/shared/postgres.rb
2044 def supports_combining_alter_table_ops?
2045   true
2046 end
supports_create_or_replace_view?() click to toggle source

PostgreSQL supports CREATE OR REPLACE VIEW.

     # File lib/sequel/adapters/shared/postgres.rb
2049 def supports_create_or_replace_view?
2050   true
2051 end
type_literal_generic_bignum_symbol(column) click to toggle source

Handle bigserial type if :serial option is present

Calls superclass method
     # File lib/sequel/adapters/shared/postgres.rb
2054 def type_literal_generic_bignum_symbol(column)
2055   column[:serial] ? :bigserial : super
2056 end
type_literal_generic_file(column) click to toggle source

PostgreSQL uses the bytea data type for blobs

     # File lib/sequel/adapters/shared/postgres.rb
2059 def type_literal_generic_file(column)
2060   :bytea
2061 end
type_literal_generic_integer(column) click to toggle source

Handle serial type if :serial option is present

Calls superclass method
     # File lib/sequel/adapters/shared/postgres.rb
2064 def type_literal_generic_integer(column)
2065   column[:serial] ? :serial : super
2066 end
type_literal_generic_string(column) click to toggle source

PostgreSQL prefers the text datatype. If a fixed size is requested, the char type is used. If the text type is specifically disallowed or there is a size specified, use the varchar type. Otherwise use the text type.

     # File lib/sequel/adapters/shared/postgres.rb
2072 def type_literal_generic_string(column)
2073   if column[:text]
2074     :text
2075   elsif column[:fixed]
2076     "char(#{column[:size]||default_string_column_size})"
2077   elsif column[:text] == false || column[:size]
2078     "varchar(#{column[:size]||default_string_column_size})"
2079   else
2080     :text
2081   end
2082 end
unique_constraint_sql_fragment(constraint) click to toggle source

Support :nulls_not_distinct option.

     # File lib/sequel/adapters/shared/postgres.rb
2085 def unique_constraint_sql_fragment(constraint)
2086   if constraint[:nulls_not_distinct]
2087     'UNIQUE NULLS NOT DISTINCT'
2088   else
2089     'UNIQUE'
2090   end
2091 end
view_with_check_option_support() click to toggle source

PostgreSQL 9.4+ supports views with check option.

     # File lib/sequel/adapters/shared/postgres.rb
2094 def view_with_check_option_support
2095   # simplecov:disable
2096   :local if server_version >= 90400
2097   # simplecov:enable
2098 end