# 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
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
-
SQLfragment 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
-
SQLfragment 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
-
SQLfragment 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
A hash of conversion procs, keyed by type integer (oid) and having callable values for the conversion proc for that type.
Public Instance Methods
Source
# File lib/sequel/adapters/shared/postgres.rb 356 def add_conversion_proc(oid, callable=nil, &block) 357 conversion_procs[oid] = callable || block 358 end
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 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
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 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
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
SQLfragment 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.
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
Source
# 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
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
SQLon the given server
Source
# 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
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.
SQLis 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 495 def create_language(name, opts=OPTS) 496 self << create_language_sql(name, opts).freeze 497 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 504 def create_schema(name, opts=OPTS) 505 self << create_schema_sql(name, opts).freeze 506 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 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
Support partitions of tables using the :partition_of option.
Source
# 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
Support partitions of tables using the :partition_of option.
Source
# 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
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
Source
# File lib/sequel/adapters/shared/postgres.rb 544 def database_type 545 :postgres 546 end
Source
# File lib/sequel/adapters/shared/postgres.rb 563 def defer_constraints(opts=OPTS) 564 _set_constraints(' DEFERRED', opts) 565 end
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
Source
# 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
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 583 def drop_function(name, opts=OPTS) 584 self << drop_function_sql(name, opts).freeze 585 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 592 def drop_language(name, opts=OPTS) 593 self << drop_language_sql(name, opts).freeze 594 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 601 def drop_schema(name, opts=OPTS) 602 self << drop_schema_sql(name, opts).freeze 603 remove_all_cached_schemas 604 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 612 def drop_trigger(table, name, opts=OPTS) 613 self << drop_trigger_sql(table, name, opts).freeze 614 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 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
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 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
Source
# File lib/sequel/adapters/shared/postgres.rb 697 def immediate_constraints(opts=OPTS) 698 _set_constraints(' IMMEDIATE', opts) 699 end
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
Source
# 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
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.
Source
# 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
Dataset containing all current database locks
Source
# 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
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
Return primary key for the given table.
Source
# 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
Return the sequence providing the default for the primary key for the given table.
Source
# 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
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 776 def rename_schema(name, new_name) 777 self << rename_schema_sql(name, new_name).freeze 778 remove_all_cached_schemas 779 end
Rename a schema in the database. Arguments:
- name
-
Current name of the schema
- opts
-
New name for the schema
Source
# 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
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 815 def rollback_prepared_transaction(transaction_id, opts=OPTS) 816 run("ROLLBACK PREPARED #{literal(transaction_id)}".freeze, opts) 817 end
Source
# 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
PostgreSQL uses SERIAL psuedo-type instead of AUTOINCREMENT for managing incrementing primary keys.
Source
# 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
The version of the PostgreSQL server, used for determining capability.
Source
# File lib/sequel/adapters/shared/postgres.rb 837 def supports_create_table_if_not_exists? 838 server_version >= 90100 839 end
PostgreSQL supports CREATE TABLE IF NOT EXISTS on 9.1+
Source
# File lib/sequel/adapters/shared/postgres.rb 842 def supports_deferrable_constraints? 843 server_version >= 90000 844 end
PostgreSQL 9.0+ supports some types of deferrable constraints beyond foreign key constraints.
Source
# File lib/sequel/adapters/shared/postgres.rb 847 def supports_deferrable_foreign_key_constraints? 848 true 849 end
PostgreSQL supports deferrable foreign key constraints.
Source
# File lib/sequel/adapters/shared/postgres.rb 852 def supports_drop_table_if_exists? 853 true 854 end
PostgreSQL supports DROP TABLE IF EXISTS
Source
# File lib/sequel/adapters/shared/postgres.rb 857 def supports_partial_indexes? 858 true 859 end
PostgreSQL supports partial indexes.
Source
# 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
PostgreSQL supports prepared transactions (two-phase commit) if max_prepared_transactions is greater than 0.
Source
# File lib/sequel/adapters/shared/postgres.rb 874 def supports_savepoints? 875 true 876 end
PostgreSQL supports savepoints
Source
# File lib/sequel/adapters/shared/postgres.rb 879 def supports_transaction_isolation_levels? 880 true 881 end
PostgreSQL supports transaction isolation levels
Source
# File lib/sequel/adapters/shared/postgres.rb 884 def supports_transactional_ddl? 885 true 886 end
PostgreSQL supports transaction DDL statements.
Source
# File lib/sequel/adapters/shared/postgres.rb 862 def supports_trigger_conditions? 863 server_version >= 90000 864 end
PostgreSQL 9.0+ supports trigger conditions.
Source
# File lib/sequel/adapters/shared/postgres.rb 897 def tables(opts=OPTS, &block) 898 pg_class_relname(['r', 'p'], opts, &block) 899 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::QualifiedIdentifierinstances, 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 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
Check whether the given type name string/symbol (e.g. :hstore) is supported by the database.
Source
# 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
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 929 def views(opts=OPTS) 930 relkind = opts[:materialized] ? 'm' : 'v' 931 pg_class_relname(relkind, opts) 932 end
Array of symbols specifying view names in the current database.
Options:
- :materialized
-
Return materialized views
- :qualify
-
Return the views as
Sequel::SQL::QualifiedIdentifierinstances, 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 942 def wait_for_lsn(lsn, mode: nil, timeout: nil, no_throw: nil, server: nil) 943 wait_for_lsn_dataset(lsn, mode: mode, timeout: timeout, no_throw: no_throw, server: server). 944 single_value! 945 end
Run the WAIT FOR LSN command with the given options. Returns either “success”, “timeout”, or “not in recovery”. Arguments:
mode-
The type of LSN processing to wait for. Can be
nil,:standby_replay,:standby_write,:standby_flush, orprimary_flush server-
The server on which to run the command.
timeout-
Timeout to wait for.
0means indefinitely. no_throw-
Uses
NO_THROW, which avoids throwing an error if there is a timeout or when run on the primary.
Source
# File lib/sequel/adapters/shared/postgres.rb 958 def with_advisory_lock(lock_id, opts=OPTS) 959 ds = dataset 960 if server = opts[:server] 961 ds = ds.server(server) 962 end 963 964 synchronize(server) do |c| 965 begin 966 if opts[:wait] 967 ds.get{pg_advisory_lock(lock_id)} 968 locked = true 969 else 970 unless locked = ds.get{pg_try_advisory_lock(lock_id)} 971 raise AdvisoryLockError, "unable to acquire advisory lock #{lock_id.inspect}" 972 end 973 end 974 975 yield 976 ensure 977 ds.get{pg_advisory_unlock(lock_id)} if locked 978 end 979 end 980 end
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.
Private Instance Methods
Source
# File lib/sequel/adapters/shared/postgres.rb 1008 def __foreign_key_list_ds(reverse) 1009 if reverse 1010 ctable = Sequel[:att2] 1011 cclass = Sequel[:cl2] 1012 rtable = Sequel[:att] 1013 rclass = Sequel[:cl] 1014 else 1015 ctable = Sequel[:att] 1016 cclass = Sequel[:cl] 1017 rtable = Sequel[:att2] 1018 rclass = Sequel[:cl2] 1019 end 1020 1021 if server_version >= 90500 1022 cpos = Sequel.expr{array_position(co[:conkey], ctable[:attnum])} 1023 rpos = Sequel.expr{array_position(co[:confkey], rtable[:attnum])} 1024 # simplecov:disable 1025 else 1026 range = 0...32 1027 cpos = Sequel.expr{SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(co[:conkey], [x]), x]}, 32, ctable[:attnum])} 1028 rpos = Sequel.expr{SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(co[:confkey], [x]), x]}, 32, rtable[:attnum])} 1029 # simplecov:enable 1030 end 1031 1032 ds = metadata_dataset. 1033 from{pg_constraint.as(:co)}. 1034 join(Sequel[:pg_class].as(cclass), :oid=>:conrelid). 1035 join(Sequel[:pg_attribute].as(ctable), :attrelid=>:oid, :attnum=>SQL::Function.new(:ANY, Sequel[:co][:conkey])). 1036 join(Sequel[:pg_class].as(rclass), :oid=>Sequel[:co][:confrelid]). 1037 join(Sequel[:pg_attribute].as(rtable), :attrelid=>:oid, :attnum=>SQL::Function.new(:ANY, Sequel[:co][:confkey])). 1038 join(Sequel[:pg_namespace].as(:nsp), :oid=>Sequel[:cl2][:relnamespace]). 1039 order{[co[:conname], cpos]}. 1040 where{{ 1041 cl[:relkind]=>%w'r p', 1042 co[:contype]=>'f', 1043 cpos=>rpos 1044 }}. 1045 select{[ 1046 co[:conname].as(:name), 1047 ctable[:attname].as(:column), 1048 co[:confupdtype].as(:on_update), 1049 co[:confdeltype].as(:on_delete), 1050 cl2[:relname].as(:table), 1051 rtable[:attname].as(:refcolumn), 1052 SQL::BooleanExpression.new(:AND, co[:condeferrable], co[:condeferred]).as(:deferrable), 1053 nsp[:nspname].as(:schema) 1054 ]} 1055 1056 if reverse 1057 ds = ds.order_append(Sequel[:nsp][:nspname], Sequel[:cl2][:relname]) 1058 end 1059 1060 _add_validated_enforced_constraint_columns(ds) 1061 end
Build dataset used for foreign key list methods.
Source
# File lib/sequel/adapters/shared/postgres.rb 1063 def _add_validated_enforced_constraint_columns(ds) 1064 validated_cond = if server_version >= 90100 1065 Sequel[:convalidated] 1066 # simplecov:disable 1067 else 1068 Sequel.cast(true, TrueClass) 1069 # simplecov:enable 1070 end 1071 ds = ds.select_append(validated_cond.as(:validated)) 1072 1073 enforced_cond = if server_version >= 180000 1074 Sequel[:conenforced] 1075 # simplecov:disable 1076 else 1077 Sequel.cast(true, TrueClass) 1078 # simplecov:enable 1079 end 1080 ds = ds.select_append(enforced_cond.as(:enforced)) 1081 1082 ds 1083 end
Source
# File lib/sequel/adapters/shared/postgres.rb 985 def _check_constraints_ds 986 @_check_constraints_ds ||= begin 987 ds = metadata_dataset. 988 from{pg_constraint.as(:co)}. 989 left_join(Sequel[:pg_attribute].as(:att), :attrelid=>:conrelid, :attnum=>SQL::Function.new(:ANY, Sequel[:co][:conkey])). 990 where(:contype=>'c'). 991 select{[co[:conname].as(:constraint), att[:attname].as(:column), pg_get_constraintdef(co[:oid]).as(:definition)]} 992 993 _add_validated_enforced_constraint_columns(ds) 994 end 995 end
Dataset used to retrieve CHECK constraint information
Source
# File lib/sequel/adapters/shared/postgres.rb 998 def _foreign_key_list_ds 999 @_foreign_key_list_ds ||= __foreign_key_list_ds(false) 1000 end
Dataset used to retrieve foreign keys referenced by a table
Source
# File lib/sequel/adapters/shared/postgres.rb 1086 def _indexes_ds 1087 @_indexes_ds ||= begin 1088 if server_version >= 90500 1089 order = [Sequel[:indc][:relname], Sequel.function(:array_position, Sequel[:ind][:indkey], Sequel[:att][:attnum])] 1090 # simplecov:disable 1091 else 1092 range = 0...32 1093 order = [Sequel[:indc][:relname], SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(Sequel[:ind][:indkey], [x]), x]}, 32, Sequel[:att][:attnum])] 1094 # simplecov:enable 1095 end 1096 1097 attnums = SQL::Function.new(:ANY, Sequel[:ind][:indkey]) 1098 1099 ds = metadata_dataset. 1100 from{pg_class.as(:tab)}. 1101 join(Sequel[:pg_index].as(:ind), :indrelid=>:oid). 1102 join(Sequel[:pg_class].as(:indc), :oid=>:indexrelid). 1103 join(Sequel[:pg_attribute].as(:att), :attrelid=>Sequel[:tab][:oid], :attnum=>attnums). 1104 left_join(Sequel[:pg_constraint].as(:con), :conname=>Sequel[:indc][:relname]). 1105 where{{ 1106 indc[:relkind]=>%w'i I', 1107 ind[:indisprimary]=>false, 1108 :indexprs=>nil}}. 1109 order(*order). 1110 select{[indc[:relname].as(:name), ind[:indisunique].as(:unique), att[:attname].as(:column), con[:condeferrable].as(:deferrable)]} 1111 1112 # simplecov:disable 1113 ds = ds.where(:indisready=>true) if server_version >= 80300 1114 ds = ds.where(:indislive=>true) if server_version >= 90300 1115 # simplecov:enable 1116 1117 ds 1118 end 1119 end
Dataset used to retrieve index information
Source
# File lib/sequel/adapters/shared/postgres.rb 1003 def _reverse_foreign_key_list_ds 1004 @_reverse_foreign_key_list_ds ||= __foreign_key_list_ds(true) 1005 end
Dataset used to retrieve foreign keys referencing a table
Source
# File lib/sequel/adapters/shared/postgres.rb 1182 def _schema_ds 1183 @_schema_ds ||= begin 1184 ds = metadata_dataset.select{[ 1185 pg_attribute[:attname].as(:name), 1186 SQL::Cast.new(pg_attribute[:atttypid], :integer).as(:oid), 1187 SQL::Cast.new(basetype[:oid], :integer).as(:base_oid), 1188 SQL::Function.new(:col_description, pg_class[:oid], pg_attribute[:attnum]).as(:comment), 1189 SQL::Function.new(:format_type, basetype[:oid], pg_type[:typtypmod]).as(:db_base_type), 1190 SQL::Function.new(:format_type, pg_type[:oid], pg_attribute[:atttypmod]).as(:db_type), 1191 SQL::Function.new(:pg_get_expr, pg_attrdef[:adbin], pg_class[:oid]).as(:default), 1192 SQL::BooleanExpression.new(:NOT, pg_attribute[:attnotnull]).as(:allow_null), 1193 SQL::Function.new(:COALESCE, SQL::BooleanExpression.from_value_pairs(pg_attribute[:attnum] => SQL::Function.new(:ANY, pg_index[:indkey])), false).as(:primary_key), 1194 Sequel[:pg_type][:typtype], 1195 (~Sequel[Sequel[:elementtype][:oid]=>nil]).as(:is_array), 1196 ]}. 1197 from(:pg_class). 1198 join(:pg_attribute, :attrelid=>:oid). 1199 join(:pg_type, :oid=>:atttypid). 1200 left_outer_join(Sequel[:pg_type].as(:basetype), :oid=>:typbasetype). 1201 left_outer_join(Sequel[:pg_type].as(:elementtype), :typarray=>Sequel[:pg_type][:oid]). 1202 left_outer_join(:pg_attrdef, :adrelid=>Sequel[:pg_class][:oid], :adnum=>Sequel[:pg_attribute][:attnum]). 1203 left_outer_join(:pg_index, :indrelid=>Sequel[:pg_class][:oid], :indisprimary=>true). 1204 where{{pg_attribute[:attisdropped]=>false}}. 1205 where{pg_attribute[:attnum] > 0}. 1206 order{pg_attribute[:attnum]} 1207 1208 # simplecov:disable 1209 if server_version > 100000 1210 # simplecov:enable 1211 ds = ds.select_append{pg_attribute[:attidentity]} 1212 1213 # simplecov:disable 1214 if server_version > 120000 1215 # simplecov:enable 1216 ds = ds.select_append{Sequel.~(pg_attribute[:attgenerated]=>'').as(:generated)} 1217 end 1218 end 1219 1220 ds 1221 end 1222 end
Dataset used to get schema for tables
Source
# File lib/sequel/adapters/shared/postgres.rb 1122 def _select_custom_sequence_ds 1123 @_select_custom_sequence_ds ||= metadata_dataset. 1124 from{pg_class.as(:t)}. 1125 join(:pg_namespace, {:oid => :relnamespace}, :table_alias=>:name). 1126 join(:pg_attribute, {:attrelid => Sequel[:t][:oid]}, :table_alias=>:attr). 1127 join(:pg_attrdef, {:adrelid => :attrelid, :adnum => :attnum}, :table_alias=>:def). 1128 join(:pg_constraint, {:conrelid => :adrelid, Sequel[:cons][:conkey].sql_subscript(1) => :adnum}, :table_alias=>:cons). 1129 where{{cons[:contype] => 'p', pg_get_expr(self.def[:adbin], attr[:attrelid]) => /nextval/i}}. 1130 select{ 1131 expr = split_part(pg_get_expr(self.def[:adbin], attr[:attrelid]), "'", 2) 1132 [ 1133 name[:nspname].as(:schema), 1134 Sequel.case({{expr => /./} => substr(expr, strpos(expr, '.')+1)}, expr).as(:sequence) 1135 ] 1136 } 1137 end
Dataset used to determine custom serial sequences for tables
Source
# File lib/sequel/adapters/shared/postgres.rb 1168 def _select_pk_ds 1169 @_select_pk_ds ||= metadata_dataset. 1170 from(:pg_class, :pg_attribute, :pg_index, :pg_namespace). 1171 where{[ 1172 [pg_class[:oid], pg_attribute[:attrelid]], 1173 [pg_class[:relnamespace], pg_namespace[:oid]], 1174 [pg_class[:oid], pg_index[:indrelid]], 1175 [pg_index[:indkey].sql_subscript(0), pg_attribute[:attnum]], 1176 [pg_index[:indisprimary], 't'] 1177 ]}. 1178 select{pg_attribute[:attname].as(:pk)} 1179 end
Dataset used to determine primary keys for tables
Source
# File lib/sequel/adapters/shared/postgres.rb 1140 def _select_serial_sequence_ds 1141 @_serial_sequence_ds ||= metadata_dataset. 1142 from{[ 1143 pg_class.as(:seq), 1144 pg_attribute.as(:attr), 1145 pg_depend.as(:dep), 1146 pg_namespace.as(:name), 1147 pg_constraint.as(:cons), 1148 pg_class.as(:t) 1149 ]}. 1150 where{[ 1151 [seq[:oid], dep[:objid]], 1152 [seq[:relnamespace], name[:oid]], 1153 [seq[:relkind], 'S'], 1154 [attr[:attrelid], dep[:refobjid]], 1155 [attr[:attnum], dep[:refobjsubid]], 1156 [attr[:attrelid], cons[:conrelid]], 1157 [attr[:attnum], cons[:conkey].sql_subscript(1)], 1158 [attr[:attrelid], t[:oid]], 1159 [cons[:contype], 'p'] 1160 ]}. 1161 select{[ 1162 name[:nspname].as(:schema), 1163 seq[:relname].as(:sequence) 1164 ]} 1165 end
Dataset used to determine normal serial sequences for tables
Source
# File lib/sequel/adapters/shared/postgres.rb 1225 def _set_constraints(type, opts) 1226 execute_ddl(_set_constraints_sql(type, opts), opts) 1227 end
Internals of defer_constraints/immediate_constraints
Source
# File lib/sequel/adapters/shared/postgres.rb 1230 def _set_constraints_sql(type, opts) 1231 sql = String.new 1232 sql << "SET CONSTRAINTS " 1233 if constraints = opts[:constraints] 1234 dataset.send(:source_list_append, sql, Array(constraints)) 1235 else 1236 sql << "ALL" 1237 end 1238 sql << type 1239 end
SQL to use for SET CONSTRAINTS
Source
# File lib/sequel/adapters/shared/postgres.rb 1243 def _table_exists?(ds) 1244 super 1245 rescue DatabaseError => e 1246 raise e unless /canceling statement due to (?:statement|lock) timeout/ =~ e.message 1247 end
Consider lock or statement timeout errors as evidence that the table exists but is locked.
Source
# File lib/sequel/adapters/shared/postgres.rb 1249 def alter_table_add_column_sql(table, op) 1250 "ADD COLUMN#{' IF NOT EXISTS' if op[:if_not_exists]} #{column_definition_sql(op)}" 1251 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1260 def alter_table_alter_constraint_sql(table, op) 1261 sql = String.new 1262 sql << "ALTER CONSTRAINT #{quote_identifier(op[:name])}" 1263 1264 constraint_deferrable_sql_append(sql, op[:deferrable]) 1265 1266 case op[:enforced] 1267 when nil 1268 when false 1269 sql << " NOT ENFORCED" 1270 else 1271 sql << " ENFORCED" 1272 end 1273 1274 case op[:inherit] 1275 when nil 1276 when false 1277 sql << " NO INHERIT" 1278 else 1279 sql << " INHERIT" 1280 end 1281 1282 sql 1283 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1253 def alter_table_attach_partition_sql(table, op) 1254 sql = String.new 1255 sql << "ATTACH PARTITION #{quote_identifier(op[:name])}" 1256 partition_bound_spec_sql_append(sql, op[:generator]) 1257 sql 1258 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1303 def alter_table_detach_partition_sql(table, op) 1304 "DETACH PARTITION #{quote_identifier(op[:name])}#{' CONCURRENTLY' if op[:concurrently]}#{' FINALIZE' if op[:finalize]}" 1305 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1307 def alter_table_drop_column_sql(table, op) 1308 "DROP COLUMN #{'IF EXISTS ' if op[:if_exists]}#{quote_identifier(op[:name])}#{' CASCADE' if op[:cascade]}" 1309 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1285 def alter_table_generator_class 1286 Postgres::AlterTableGenerator 1287 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1289 def alter_table_rename_constraint_sql(table, op) 1290 "RENAME CONSTRAINT #{quote_identifier(op[:name])} TO #{quote_identifier(op[:new_name])}" 1291 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1293 def alter_table_set_column_type_sql(table, op) 1294 s = super 1295 if using = op[:using] 1296 using = Sequel::LiteralString.new(using) if using.is_a?(String) 1297 s += ' USING ' 1298 s << literal(using) 1299 end 1300 s 1301 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1311 def alter_table_validate_constraint_sql(table, op) 1312 "VALIDATE CONSTRAINT #{quote_identifier(op[:name])}" 1313 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1318 def begin_new_transaction(conn, opts) 1319 super 1320 if opts.has_key?(:synchronous) 1321 case sync = opts[:synchronous] 1322 when true 1323 sync = :on 1324 when false 1325 sync = :off 1326 when nil 1327 return 1328 when :on, :off, :local, :remote_apply, :remote_write 1329 nil 1330 else 1331 # SEQUEL6: raise 1332 Sequel::Deprecation.deprecate("Unsupported :synchronous option given to Database#transaction: #{sync.inspect}, this will raise an error in Sequel 6.") 1333 return 1334 end 1335 1336 log_connection_execute(conn, "SET LOCAL synchronous_commit = #{sync}") 1337 end 1338 end
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.
Source
# File lib/sequel/adapters/shared/postgres.rb 1341 def begin_savepoint(conn, opts) 1342 super 1343 1344 unless (read_only = opts[:read_only]).nil? 1345 log_connection_execute(conn, "SET TRANSACTION READ #{read_only ? 'ONLY' : 'WRITE'}") 1346 end 1347 end
Set the READ ONLY transaction setting per savepoint, as PostgreSQL supports that.
Source
# File lib/sequel/adapters/shared/postgres.rb 1522 def column_definition_add_references_sql(sql, column) 1523 super 1524 if column[:not_enforced] 1525 sql << " NOT ENFORCED" 1526 end 1527 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1376 def column_definition_append_include_sql(sql, constraint) 1377 if include_cols = constraint[:include] 1378 sql << " INCLUDE " << literal(Array(include_cols)) 1379 end 1380 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1382 def column_definition_append_primary_key_sql(sql, constraint) 1383 super 1384 column_definition_append_include_sql(sql, constraint) 1385 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1387 def column_definition_append_unique_sql(sql, constraint) 1388 super 1389 column_definition_append_include_sql(sql, constraint) 1390 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1394 def column_definition_collate_sql(sql, column) 1395 if collate = column[:collate] 1396 collate = literal(collate) unless collate.is_a?(String) 1397 sql << " COLLATE #{collate}" 1398 end 1399 end
Literalize non-String collate options. This is because unquoted collatations are folded to lowercase, and PostgreSQL used mixed case or capitalized collations.
Source
# File lib/sequel/adapters/shared/postgres.rb 1403 def column_definition_default_sql(sql, column) 1404 super 1405 if !column[:serial] && !['smallserial', 'serial', 'bigserial'].include?(column[:type].to_s) && !column[:default] 1406 if (identity = column[:identity]) 1407 sql << " GENERATED " 1408 sql << (identity == :always ? "ALWAYS" : "BY DEFAULT") 1409 sql << " AS IDENTITY" 1410 elsif (generated = column[:generated_always_as]) 1411 sql << " GENERATED ALWAYS AS (#{literal(generated)}) #{column[:virtual] ? 'VIRTUAL' : 'STORED'}" 1412 end 1413 end 1414 end
Support identity columns, but only use the identity SQL syntax if no default value is given.
Source
# File lib/sequel/adapters/shared/postgres.rb 1529 def column_definition_null_sql(sql, column) 1530 constraint = column[:not_null] 1531 constraint = nil unless constraint.is_a?(Hash) 1532 if constraint && (name = constraint[:name]) 1533 sql << " CONSTRAINT #{quote_identifier(name)}" 1534 end 1535 super 1536 if constraint && constraint[:no_inherit] 1537 sql << " NO INHERIT" 1538 end 1539 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1349 def column_definition_sql(column) 1350 if table = column[:like_table] 1351 sql = String.new 1352 sql << "LIKE #{quote_schema_table(table)}" 1353 allowed_options = %i[comments compression constraints defaults generated identity indexes statistics storage all].freeze 1354 1355 %i[including excluding].freeze.each do |type| 1356 options = column[type] 1357 next if options.empty? 1358 1359 unallowed_options = options - allowed_options 1360 if unallowed_options.empty? 1361 type = type.to_s.upcase 1362 options.each do |opt| 1363 sql << " #{type} #{opt.to_s.upcase}" 1364 end 1365 else 1366 raise Error, "unsupported like :#{type} options: #{unallowed_options.inspect}" 1367 end 1368 end 1369 1370 sql 1371 else 1372 super 1373 end 1374 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1556 def column_references_add_period(cols) 1557 cols= cols.dup 1558 cols[-1] = Sequel.lit("PERIOD #{quote_identifier(cols[-1])}".freeze) 1559 cols 1560 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1550 def column_references_append_key_sql(sql, column) 1551 cols = Array(column[:key]) 1552 cols = column_references_add_period(cols) if column[:period] 1553 sql << "(#{cols.map{|x| quote_identifier(x)}.join(', ')})" 1554 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1542 def column_references_table_constraint_sql(constraint) 1543 sql = String.new 1544 sql << "FOREIGN KEY " 1545 cols = constraint[:columns] 1546 cols = column_references_add_period(cols) if constraint[:period] 1547 sql << literal(cols) << column_references_sql(constraint) 1548 end
Handle :period option
Source
# File lib/sequel/adapters/shared/postgres.rb 1417 def column_schema_normalize_default(default, type) 1418 if m = /\A(?:B?('.*')::[^']+|\((-?\d+(?:\.\d+)?)\))\z/.match(default) 1419 default = m[1] || m[2] 1420 end 1421 super(default, type) 1422 end
Handle PostgreSQL specific default format.
Source
# File lib/sequel/adapters/shared/postgres.rb 1436 def combinable_alter_table_op?(op) 1437 (super || op[:op] == :validate_constraint || op[:op] == :alter_constraint) && op[:op] != :rename_column 1438 end
PostgreSQL can’t combine rename_column operations, and it can combine validate_constraint and alter_constraint operations.
Source
# File lib/sequel/adapters/shared/postgres.rb 1426 def commit_transaction(conn, opts=OPTS) 1427 if (s = opts[:prepare]) && savepoint_level(conn) <= 1 1428 log_connection_execute(conn, "PREPARE TRANSACTION #{literal(s)}") 1429 else 1430 super 1431 end 1432 end
If the :prepare option is given and we aren’t in a savepoint, prepare the transaction for a two-phase commit.
Source
# File lib/sequel/adapters/shared/postgres.rb 1442 def connection_configuration_sqls(opts=@opts) 1443 sqls = [] 1444 1445 sqls << "SET standard_conforming_strings = ON" if typecast_value_boolean(opts.fetch(:force_standard_strings, true)) 1446 1447 cmm = opts.fetch(:client_min_messages, :warning) 1448 if cmm && !cmm.to_s.empty? 1449 cmm = cmm.to_s.upcase.strip 1450 unless VALID_CLIENT_MIN_MESSAGES.include?(cmm) 1451 raise Error, "Unsupported client_min_messages setting: #{cmm}" 1452 end 1453 sqls << "SET client_min_messages = '#{cmm.to_s.upcase}'" 1454 end 1455 1456 if search_path = opts[:search_path] 1457 case search_path 1458 when String 1459 search_path = search_path.split(",").map(&:strip) 1460 when Array 1461 # nil 1462 else 1463 raise Error, "unrecognized value for :search_path option: #{search_path.inspect}" 1464 end 1465 sqls << "SET search_path = #{search_path.map{|s| "\"#{s.gsub('"', '""')}\""}.join(',')}" 1466 end 1467 1468 sqls 1469 end
The SQL queries to execute when starting a new connection.
Source
# File lib/sequel/adapters/shared/postgres.rb 1472 def constraint_definition_sql(constraint) 1473 case type = constraint[:type] 1474 when :exclude 1475 elements = constraint[:elements].map{|c, op| "#{literal(c)} WITH #{op}"}.join(', ') 1476 sql = String.new 1477 sql << "CONSTRAINT #{quote_identifier(constraint[:name])} " if constraint[:name] 1478 sql << "EXCLUDE USING #{constraint[:using]||'gist'} (#{elements})" 1479 column_definition_append_include_sql(sql, constraint) 1480 sql << " WHERE #{filter_expr(constraint[:where])}" if constraint[:where] 1481 constraint_deferrable_sql_append(sql, constraint[:deferrable]) 1482 sql 1483 when :primary_key, :unique 1484 sql = String.new 1485 sql << "CONSTRAINT #{quote_identifier(constraint[:name])} " if constraint[:name] 1486 1487 if type == :primary_key 1488 sql << primary_key_constraint_sql_fragment(constraint) 1489 else 1490 sql << unique_constraint_sql_fragment(constraint) 1491 end 1492 1493 if using_index = constraint[:using_index] 1494 sql << " USING INDEX " << quote_identifier(using_index) 1495 else 1496 cols = literal(constraint[:columns]) 1497 cols.insert(-2, " WITHOUT OVERLAPS") if constraint[:without_overlaps] 1498 sql << " " << cols 1499 1500 if include_cols = constraint[:include] 1501 sql << " INCLUDE " << literal(Array(include_cols)) 1502 end 1503 end 1504 1505 constraint_deferrable_sql_append(sql, constraint[:deferrable]) 1506 sql 1507 else # when :foreign_key, :check 1508 sql = super 1509 if constraint[:no_inherit] 1510 sql << " NO INHERIT" 1511 end 1512 if constraint[:not_enforced] 1513 sql << " NOT ENFORCED" 1514 end 1515 if constraint[:not_valid] 1516 sql << " NOT VALID" 1517 end 1518 sql 1519 end 1520 end
Handle PostgreSQL-specific constraint features.
Source
# File lib/sequel/adapters/shared/postgres.rb 1591 def copy_into_sql(table, opts) 1592 sql = String.new 1593 sql << "COPY #{literal(table)}" 1594 if cols = opts[:columns] 1595 sql << literal(Array(cols)) 1596 end 1597 sql << " FROM STDIN" 1598 if opts[:options] || opts[:format] 1599 sql << " (" 1600 sql << "FORMAT #{opts[:format]}" if opts[:format] 1601 sql << "#{', ' if opts[:format]}#{opts[:options]}" if opts[:options] 1602 sql << ')' 1603 end 1604 sql 1605 end
SQL for doing fast table insert from stdin.
Source
# File lib/sequel/adapters/shared/postgres.rb 1608 def copy_table_sql(table, opts) 1609 if table.is_a?(String) 1610 table 1611 else 1612 if opts[:options] || opts[:format] 1613 options = String.new 1614 options << " (" 1615 if format = opts[:format] 1616 sql_format = format.to_s.downcase 1617 unless %w[text csv json binary].freeze.include?(sql_format) 1618 raise Error, "unsupported COPY TO format: #{format.inspect}" 1619 end 1620 options << "FORMAT #{format}" 1621 end 1622 options << "#{', ' if format}#{opts[:options]}" if opts[:options] 1623 options << ')' 1624 end 1625 table = if table.is_a?(::Sequel::Dataset) 1626 "(#{table.sql})" 1627 else 1628 literal(table) 1629 end 1630 "COPY #{table} TO STDOUT#{options}" 1631 end 1632 end
SQL for doing fast table output to stdout.
Source
# File lib/sequel/adapters/shared/postgres.rb 1635 def create_function_sql(name, definition, opts=OPTS) 1636 args = opts[:args] 1637 in_out = %w'OUT INOUT' 1638 if (!opts[:args].is_a?(Array) || !opts[:args].any?{|a| Array(a).length == 3 && in_out.include?(a[2].to_s)}) 1639 returns = opts[:returns] || 'void' 1640 end 1641 language = opts[:language] || 'SQL' 1642 <<-END 1643 CREATE#{' OR REPLACE' if opts[:replace]} FUNCTION #{name}#{sql_function_args(args)} 1644 #{"RETURNS #{returns}" if returns} 1645 LANGUAGE #{language} 1646 #{opts[:behavior].to_s.upcase if opts[:behavior]} 1647 #{'STRICT' if opts[:strict]} 1648 #{'SECURITY DEFINER' if opts[:security_definer]} 1649 #{"PARALLEL #{opts[:parallel].to_s.upcase}" if opts[:parallel]} 1650 #{"COST #{opts[:cost]}" if opts[:cost]} 1651 #{"ROWS #{opts[:rows]}" if opts[:rows]} 1652 #{opts[:set].map{|k,v| " SET #{k} = #{v}"}.join("\n") if opts[:set]} 1653 AS #{literal(definition.to_s)}#{", #{literal(opts[:link_symbol].to_s)}" if opts[:link_symbol]} 1654 END 1655 end
SQL statement to create database function.
Source
# File lib/sequel/adapters/shared/postgres.rb 1658 def create_language_sql(name, opts=OPTS) 1659 "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]}" 1660 end
SQL for creating a procedural language.
Source
# File lib/sequel/adapters/shared/postgres.rb 1664 def create_partition_of_table_from_generator(name, generator, options) 1665 execute_ddl(create_partition_of_table_sql(name, generator, options)) 1666 end
Create a partition of another table, used when the create_table with the :partition_of option is given.
Source
# File lib/sequel/adapters/shared/postgres.rb 1669 def create_partition_of_table_sql(name, generator, options) 1670 sql = create_table_prefix_sql(name, options).dup 1671 sql << " PARTITION OF #{quote_schema_table(options[:partition_of])}" 1672 partition_bound_spec_sql_append(sql, generator) 1673 sql << create_table_suffix_sql(name, options) 1674 sql 1675 end
SQL for creating a partition of another table.
Source
# File lib/sequel/adapters/shared/postgres.rb 1693 def create_schema_sql(name, opts=OPTS) 1694 "CREATE SCHEMA #{'IF NOT EXISTS ' if opts[:if_not_exists]}#{quote_identifier(name)}#{" AUTHORIZATION #{literal(opts[:owner])}" if opts[:owner]}" 1695 end
SQL for creating a schema.
Source
# File lib/sequel/adapters/shared/postgres.rb 1751 def create_table_as_sql(name, sql, options) 1752 result = create_table_prefix_sql name, options 1753 if on_commit = options[:on_commit] 1754 result += " ON COMMIT #{ON_COMMIT[on_commit]}" 1755 end 1756 result += " AS #{sql}" 1757 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1759 def create_table_generator_class 1760 Postgres::CreateTableGenerator 1761 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1698 def create_table_prefix_sql(name, options) 1699 prefix_sql = if options[:temp] 1700 raise(Error, "can't provide both :temp and :unlogged to create_table") if options[:unlogged] 1701 raise(Error, "can't provide both :temp and :foreign to create_table") if options[:foreign] 1702 temporary_table_sql 1703 elsif options[:foreign] 1704 raise(Error, "can't provide both :foreign and :unlogged to create_table") if options[:unlogged] 1705 'FOREIGN ' 1706 elsif options.fetch(:unlogged){typecast_value_boolean(@opts[:unlogged_tables_default])} 1707 'UNLOGGED ' 1708 end 1709 1710 "CREATE #{prefix_sql}TABLE#{' IF NOT EXISTS' if options[:if_not_exists]} #{create_table_table_name_sql(name, options)}" 1711 end
DDL statement for creating a table with the given name, columns, and options
Source
# File lib/sequel/adapters/shared/postgres.rb 1714 def create_table_sql(name, generator, options) 1715 "#{super}#{create_table_suffix_sql(name, options)}" 1716 end
SQL for creating a table with PostgreSQL specific options
Source
# File lib/sequel/adapters/shared/postgres.rb 1720 def create_table_suffix_sql(name, options) 1721 sql = String.new 1722 1723 if inherits = options[:inherits] 1724 sql << " INHERITS (#{Array(inherits).map{|t| quote_schema_table(t)}.join(', ')})" 1725 end 1726 1727 if partition_by = options[:partition_by] 1728 sql << " PARTITION BY #{options[:partition_type]||'RANGE'} #{literal(Array(partition_by))}" 1729 end 1730 1731 if on_commit = options[:on_commit] 1732 raise(Error, "can't provide :on_commit without :temp to create_table") unless options[:temp] 1733 raise(Error, "unsupported on_commit option: #{on_commit.inspect}") unless ON_COMMIT.has_key?(on_commit) 1734 sql << " ON COMMIT #{ON_COMMIT[on_commit]}" 1735 end 1736 1737 if tablespace = options[:tablespace] 1738 sql << " TABLESPACE #{quote_identifier(tablespace)}" 1739 end 1740 1741 if server = options[:foreign] 1742 sql << " SERVER #{quote_identifier(server)}" 1743 if foreign_opts = options[:options] 1744 sql << " OPTIONS (#{foreign_opts.map{|k, v| "#{k} #{literal(v.to_s)}"}.join(', ')})" 1745 end 1746 end 1747 1748 sql 1749 end
Handle various PostgreSQL specific table extensions such as inheritance, partitioning, tablespaces, and foreign tables.
Source
# File lib/sequel/adapters/shared/postgres.rb 1764 def create_trigger_sql(table, name, function, opts=OPTS) 1765 events = opts[:events] ? Array(opts[:events]) : [:insert, :update, :delete] 1766 whence = opts[:after] ? 'AFTER' : 'BEFORE' 1767 if filter = opts[:when] 1768 raise Error, "Trigger conditions are not supported for this database" unless supports_trigger_conditions? 1769 filter = " WHEN #{filter_expr(filter)}" 1770 end 1771 "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(', ')})" 1772 end
SQL for creating a database trigger.
Source
# File lib/sequel/adapters/shared/postgres.rb 1775 def create_view_prefix_sql(name, options) 1776 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]) 1777 1778 if options[:security_invoker] 1779 sql += " WITH (security_invoker)" 1780 end 1781 1782 if tablespace = options[:tablespace] 1783 sql += " TABLESPACE #{quote_identifier(tablespace)}" 1784 end 1785 1786 sql 1787 end
DDL fragment for initial part of CREATE VIEW statement
Source
# File lib/sequel/adapters/shared/postgres.rb 1586 def database_error_regexps 1587 DATABASE_ERROR_REGEXPS 1588 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1562 def database_specific_error_class_from_sqlstate(sqlstate) 1563 if sqlstate == '23P01' 1564 ExclusionConstraintViolation 1565 elsif sqlstate == '40P01' 1566 SerializationFailure 1567 elsif sqlstate == '55P03' 1568 DatabaseLockTimeout 1569 else 1570 super 1571 end 1572 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1790 def drop_function_sql(name, opts=OPTS) 1791 "DROP FUNCTION#{' IF EXISTS' if opts[:if_exists]} #{name}#{sql_function_args(opts[:args])}#{' CASCADE' if opts[:cascade]}" 1792 end
SQL for dropping a function from the database.
Source
# File lib/sequel/adapters/shared/postgres.rb 1795 def drop_index_sql(table, op) 1796 sch, _ = schema_and_table(table) 1797 "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]}" 1798 end
Support :if_exists, :cascade, and :concurrently options.
Source
# File lib/sequel/adapters/shared/postgres.rb 1801 def drop_language_sql(name, opts=OPTS) 1802 "DROP LANGUAGE#{' IF EXISTS' if opts[:if_exists]} #{name}#{' CASCADE' if opts[:cascade]}" 1803 end
SQL for dropping a procedural language from the database.
Source
# File lib/sequel/adapters/shared/postgres.rb 1806 def drop_schema_sql(name, opts=OPTS) 1807 "DROP SCHEMA#{' IF EXISTS' if opts[:if_exists]} #{quote_identifier(name)}#{' CASCADE' if opts[:cascade]}" 1808 end
SQL for dropping a schema from the database.
Source
# File lib/sequel/adapters/shared/postgres.rb 1816 def drop_table_sql(name, options) 1817 "DROP#{' FOREIGN' if options[:foreign]} TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_schema_table(name)}#{' CASCADE' if options[:cascade]}" 1818 end
Support :foreign tables
Source
# File lib/sequel/adapters/shared/postgres.rb 1811 def drop_trigger_sql(table, name, opts=OPTS) 1812 "DROP TRIGGER#{' IF EXISTS' if opts[:if_exists]} #{name} ON #{quote_schema_table(table)}#{' CASCADE' if opts[:cascade]}" 1813 end
SQL for dropping a trigger from the database.
Source
# File lib/sequel/adapters/shared/postgres.rb 1821 def drop_view_sql(name, opts=OPTS) 1822 "DROP #{'MATERIALIZED ' if opts[:materialized]}VIEW#{' IF EXISTS' if opts[:if_exists]} #{quote_schema_table(name)}#{' CASCADE' if opts[:cascade]}" 1823 end
SQL for dropping a view from the database.
Source
# File lib/sequel/adapters/shared/postgres.rb 1827 def filter_schema(ds, opts) 1828 expr = if schema = opts[:schema] 1829 if schema.is_a?(SQL::Identifier) 1830 schema.value.to_s 1831 else 1832 schema.to_s 1833 end 1834 else 1835 Sequel.function(:any, Sequel.function(:current_schemas, false)) 1836 end 1837 ds.where{{pg_namespace[:nspname]=>expr}} 1838 end
If opts includes a :schema option, use it, otherwise restrict the filter to only the currently visible schemas.
Source
# File lib/sequel/adapters/shared/postgres.rb 1840 def index_definition_sql(table_name, index) 1841 cols = index[:columns] 1842 index_name = index[:name] || default_index_name(table_name, cols) 1843 1844 expr = if o = index[:opclass] 1845 "(#{Array(cols).map{|c| "#{literal(c)} #{o}"}.join(', ')})" 1846 else 1847 literal(Array(cols)) 1848 end 1849 1850 if_not_exists = " IF NOT EXISTS" if index[:if_not_exists] 1851 unique = "UNIQUE " if index[:unique] 1852 index_type = index[:type] 1853 filter = index[:where] || index[:filter] 1854 filter = " WHERE #{filter_expr(filter)}" if filter 1855 nulls_distinct = " NULLS#{' NOT' if index[:nulls_distinct] == false} DISTINCT" unless index[:nulls_distinct].nil? 1856 1857 case index_type 1858 when :full_text 1859 expr = "(to_tsvector(#{literal(index[:language] || 'simple')}::regconfig, #{literal(dataset.send(:full_text_string_join, cols))}))" 1860 index_type = index[:index_type] || :gin 1861 when :spatial 1862 index_type = :gist 1863 end 1864 1865 "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}" 1866 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1869 def initialize_postgres_adapter 1870 @primary_keys = {} 1871 @primary_key_sequences = {} 1872 @supported_types = {} 1873 procs = @conversion_procs = CONVERSION_PROCS.dup 1874 procs[1184] = procs[1114] = method(:to_application_timestamp) 1875 end
Setup datastructures shared by all postgres adapters.
Source
# File lib/sequel/adapters/shared/postgres.rb 1677 def partition_bound_spec_sql_append(sql, generator) 1678 sql << case generator.partition_type 1679 when :range 1680 from, to = generator.range 1681 " FOR VALUES FROM #{literal(from)} TO #{literal(to)}" 1682 when :list 1683 " FOR VALUES IN #{literal(generator.list)}" 1684 when :hash 1685 mod, remainder = generator.hash_values 1686 " FOR VALUES WITH (MODULUS #{literal(mod)}, REMAINDER #{literal(remainder)})" 1687 else # when :default 1688 " DEFAULT" 1689 end 1690 end
Source
# File lib/sequel/adapters/shared/postgres.rb 1878 def pg_class_relname(type, opts) 1879 ds = metadata_dataset.from(:pg_class).where(:relkind=>type).select(:relname).server(opts[:server]).join(:pg_namespace, :oid=>:relnamespace) 1880 ds = filter_schema(ds, opts) 1881 m = output_identifier_meth 1882 if defined?(yield) 1883 yield(ds) 1884 elsif opts[:qualify] 1885 ds.select_append{pg_namespace[:nspname]}.map{|r| Sequel.qualify(m.call(r[:nspname]).to_s, m.call(r[:relname]).to_s)} 1886 else 1887 ds.map{|r| m.call(r[:relname])} 1888 end 1889 end
Backbone of the tables and views support.
Source
# File lib/sequel/adapters/shared/postgres.rb 1893 def regclass_oid(expr, opts=OPTS) 1894 if expr.is_a?(String) && !expr.is_a?(LiteralString) 1895 expr = Sequel.identifier(expr) 1896 end 1897 1898 sch, table = schema_and_table(expr) 1899 sch ||= opts[:schema] 1900 if sch 1901 expr = Sequel.qualify(sch, table) 1902 end 1903 1904 expr = if ds = opts[:dataset] 1905 ds.literal(expr) 1906 else 1907 literal(expr) 1908 end 1909 1910 Sequel.cast(expr.to_s,:regclass).cast(:oid) 1911 end
Return an expression the oid for the table expr. Used by the metadata parsing code to disambiguate unqualified tables.
Source
# File lib/sequel/adapters/shared/postgres.rb 1924 def remove_all_cached_schemas 1925 @primary_keys.clear 1926 @primary_key_sequences.clear 1927 @schemas.clear 1928 end
Clear all cached schema information
Source
# File lib/sequel/adapters/shared/postgres.rb 1914 def remove_cached_schema(table) 1915 tab = quote_schema_table(table) 1916 Sequel.synchronize do 1917 @primary_keys.delete(tab) 1918 @primary_key_sequences.delete(tab) 1919 end 1920 super 1921 end
Remove the cached entries for primary keys and sequences when a table is changed.
Source
# File lib/sequel/adapters/shared/postgres.rb 1931 def rename_schema_sql(name, new_name) 1932 "ALTER SCHEMA #{quote_identifier(name)} RENAME TO #{quote_identifier(new_name)}" 1933 end
SQL for renaming a schema.
Source
# File lib/sequel/adapters/shared/postgres.rb 1937 def rename_table_sql(name, new_name) 1938 "ALTER TABLE #{quote_schema_table(name)} RENAME TO #{quote_identifier(schema_and_table(new_name).last)}" 1939 end
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.
Source
# File lib/sequel/adapters/shared/postgres.rb 1954 def schema_array_type(db_type) 1955 :array 1956 end
The schema :type entry to use for array types.
Source
# File lib/sequel/adapters/shared/postgres.rb 1942 def schema_column_type(db_type) 1943 case db_type 1944 when /\Ainterval\z/i 1945 :interval 1946 when /\Acitext\z/i 1947 :string 1948 else 1949 super 1950 end 1951 end
Handle interval and citext types.
Source
# File lib/sequel/adapters/shared/postgres.rb 1959 def schema_composite_type(db_type) 1960 :composite 1961 end
The schema :type entry to use for row/composite types.
Source
# File lib/sequel/adapters/shared/postgres.rb 1964 def schema_enum_type(db_type) 1965 :enum 1966 end
The schema :type entry to use for enum types.
Source
# File lib/sequel/adapters/shared/postgres.rb 1974 def schema_multirange_type(db_type) 1975 :multirange 1976 end
The schema :type entry to use for multirange types.
Source
# File lib/sequel/adapters/shared/postgres.rb 1991 def schema_parse_table(table_name, opts) 1992 m = output_identifier_meth(opts[:dataset]) 1993 1994 _schema_ds.where_all(Sequel[:pg_class][:oid]=>regclass_oid(table_name, opts)).map do |row| 1995 row[:default] = nil if blank_object?(row[:default]) 1996 if row[:base_oid] 1997 row[:domain_oid] = row[:oid] 1998 row[:oid] = row.delete(:base_oid) 1999 row[:db_domain_type] = row[:db_type] 2000 row[:db_type] = row.delete(:db_base_type) 2001 else 2002 row.delete(:base_oid) 2003 row.delete(:db_base_type) 2004 end 2005 2006 db_type = row[:db_type] 2007 row[:type] = if row.delete(:is_array) 2008 schema_array_type(db_type) 2009 else 2010 send(TYPTYPE_METHOD_MAP[row.delete(:typtype)], db_type) 2011 end 2012 identity = row.delete(:attidentity) 2013 if row[:primary_key] 2014 row[:auto_increment] = !!(row[:default] =~ /\A(?:nextval)/i) || identity == 'a' || identity == 'd' 2015 end 2016 2017 # simplecov:disable 2018 if server_version >= 90600 2019 # simplecov:enable 2020 case row[:oid] 2021 when 1082 2022 row[:min_value] = MIN_DATE 2023 row[:max_value] = MAX_DATE 2024 when 1184, 1114 2025 if Sequel.datetime_class == Time 2026 row[:min_value] = MIN_TIMESTAMP 2027 row[:max_value] = MAX_TIMESTAMP 2028 end 2029 end 2030 end 2031 2032 [m.call(row.delete(:name)), row] 2033 end 2034 end
The dataset used for parsing table schemas, using the pg_* system catalogs.
Source
# File lib/sequel/adapters/shared/postgres.rb 1969 def schema_range_type(db_type) 1970 :range 1971 end
The schema :type entry to use for range types.
Source
# File lib/sequel/adapters/shared/postgres.rb 2037 def set_transaction_isolation(conn, opts) 2038 level = opts.fetch(:isolation, transaction_isolation_level) 2039 read_only = opts[:read_only] 2040 deferrable = opts[:deferrable] 2041 if level || !read_only.nil? || !deferrable.nil? 2042 sql = String.new 2043 sql << "SET TRANSACTION" 2044 sql << " ISOLATION LEVEL #{Sequel::Database::TRANSACTION_ISOLATION_LEVELS[level]}" if level 2045 sql << " READ #{read_only ? 'ONLY' : 'WRITE'}" unless read_only.nil? 2046 sql << " #{'NOT ' unless deferrable}DEFERRABLE" unless deferrable.nil? 2047 log_connection_execute(conn, sql) 2048 end 2049 end
Set the transaction isolation level on the given connection
Source
# File lib/sequel/adapters/shared/postgres.rb 2052 def sql_function_args(args) 2053 "(#{Array(args).map{|a| Array(a).reverse.join(' ')}.join(', ')})" 2054 end
Turns an array of argument specifiers into an SQL fragment used for function arguments. See create_function_sql.
Source
# File lib/sequel/adapters/shared/postgres.rb 2057 def supports_combining_alter_table_ops? 2058 true 2059 end
PostgreSQL can combine multiple alter table ops into a single query.
Source
# File lib/sequel/adapters/shared/postgres.rb 2062 def supports_create_or_replace_view? 2063 true 2064 end
PostgreSQL supports CREATE OR REPLACE VIEW.
Source
# File lib/sequel/adapters/shared/postgres.rb 2067 def type_literal_generic_bignum_symbol(column) 2068 column[:serial] ? :bigserial : super 2069 end
Handle bigserial type if :serial option is present
Source
# File lib/sequel/adapters/shared/postgres.rb 2072 def type_literal_generic_file(column) 2073 :bytea 2074 end
PostgreSQL uses the bytea data type for blobs
Source
# File lib/sequel/adapters/shared/postgres.rb 2077 def type_literal_generic_integer(column) 2078 column[:serial] ? :serial : super 2079 end
Handle serial type if :serial option is present
Source
# File lib/sequel/adapters/shared/postgres.rb 2085 def type_literal_generic_string(column) 2086 if column[:text] 2087 :text 2088 elsif column[:fixed] 2089 "char(#{column[:size]||default_string_column_size})" 2090 elsif column[:text] == false || column[:size] 2091 "varchar(#{column[:size]||default_string_column_size})" 2092 else 2093 :text 2094 end 2095 end
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.
Source
# File lib/sequel/adapters/shared/postgres.rb 2098 def unique_constraint_sql_fragment(constraint) 2099 if constraint[:nulls_not_distinct] 2100 'UNIQUE NULLS NOT DISTINCT' 2101 else 2102 'UNIQUE' 2103 end 2104 end
Support :nulls_not_distinct option.
Source
# File lib/sequel/adapters/shared/postgres.rb 2107 def view_with_check_option_support 2108 # simplecov:disable 2109 :local if server_version >= 90400 2110 # simplecov:enable 2111 end
PostgreSQL 9.4+ supports views with check option.
Source
# File lib/sequel/adapters/shared/postgres.rb 2114 def wait_for_lsn_dataset(lsn, mode: nil, timeout: nil, no_throw: nil, server: nil) 2115 sql = String.new 2116 sql << "WAIT FOR LSN ?" 2117 args = [lsn] 2118 2119 if mode || timeout || no_throw 2120 sql << " WITH (" 2121 sep = "" 2122 2123 case mode 2124 when nil 2125 # nothing 2126 when :standby_replay, :standby_write, :standby_flush, :primary_flush 2127 sql << sep << "MODE ?" 2128 sep = ", " 2129 args << mode.to_s 2130 else 2131 raise Error, "invalid wait_for_lsn mode argument: #{mode.inspect}" 2132 end 2133 2134 if timeout 2135 sql << sep << "TIMEOUT ?" 2136 sep = ", " 2137 args << timeout 2138 end 2139 2140 if no_throw 2141 sql << sep << "NO_THROW" 2142 end 2143 2144 sql << ")" 2145 end 2146 2147 ds = dataset 2148 ds = ds.server(server) if server 2149 ds.with_sql(Sequel::SQL::PlaceholderLiteralString.new(sql.freeze, args)) 2150 end
Internals of wait_for_lsn