Class: ActiveRecord::ConnectionAdapters::PostgreSQLAdapter

Inherits:
AbstractAdapter
  • Object
show all
Includes:
DatabaseStatements, Quoting, ReferentialIntegrity, SchemaStatements, Savepoints
Defined in:
lib/active_record/connection_adapters/postgresql_adapter.rb,
lib/active_record/connection_adapters/postgresql/oid.rb,
lib/active_record/connection_adapters/postgresql/quoting.rb,
lib/active_record/connection_adapters/postgresql/schema_statements.rb,
lib/active_record/connection_adapters/postgresql/database_statements.rb,
lib/active_record/connection_adapters/postgresql/referential_integrity.rb

Overview

The PostgreSQL adapter works with the native C (bitbucket.org/ged/ruby-pg) driver.

Options:

  • :host - Defaults to a Unix-domain socket in /tmp. On machines without Unix-domain sockets, the default is to connect to localhost.

  • :port - Defaults to 5432.

  • :username - Defaults to be the same as the operating system name of the user running the application.

  • :password - Password to be used if the server demands password authentication.

  • :database - Defaults to be the same as the user name.

  • :schema_search_path - An optional schema search path for the connection given as a string of comma-separated schema names. This is backward-compatible with the :schema_order option.

  • :encoding - An optional client encoding that is used in a SET client_encoding TO <encoding> call on the connection.

  • :min_messages - An optional client min messages that is used in a SET client_min_messages TO <min_messages> call on the connection.

  • :variables - An optional hash of additional parameters that will be used in SET SESSION key = val calls on the connection.

  • :insert_returning - An optional boolean to control the use or RETURNING for INSERT statements defaults to true.

Any further options are used as connection parameters to libpq. See www.postgresql.org/docs/9.1/static/libpq-connect.html for the list of parameters.

In addition, default connection parameters of libpq can be set per environment variables. See www.postgresql.org/docs/9.1/static/libpq-envars.html .

Defined Under Namespace

Modules: ColumnMethods, DatabaseStatements, OID, Quoting, ReferentialIntegrity, SchemaStatements, Utils Classes: BindSubstitution, ColumnDefinition, SchemaCreation, StatementPool, Table, TableDefinition

Constant Summary collapse

ADAPTER_NAME =
'PostgreSQL'
NATIVE_DATABASE_TYPES =
{
  primary_key: "serial primary key",
  string:      { name: "character varying", limit: 255 },
  text:        { name: "text" },
  integer:     { name: "integer" },
  float:       { name: "float" },
  decimal:     { name: "decimal" },
  datetime:    { name: "timestamp" },
  timestamp:   { name: "timestamp" },
  time:        { name: "time" },
  date:        { name: "date" },
  daterange:   { name: "daterange" },
  numrange:    { name: "numrange" },
  tsrange:     { name: "tsrange" },
  tstzrange:   { name: "tstzrange" },
  int4range:   { name: "int4range" },
  int8range:   { name: "int8range" },
  binary:      { name: "bytea" },
  boolean:     { name: "boolean" },
  xml:         { name: "xml" },
  tsvector:    { name: "tsvector" },
  hstore:      { name: "hstore" },
  inet:        { name: "inet" },
  cidr:        { name: "cidr" },
  macaddr:     { name: "macaddr" },
  uuid:        { name: "uuid" },
  json:        { name: "json" },
  ltree:       { name: "ltree" }
}

Constants inherited from AbstractAdapter

AbstractAdapter::SIMPLE_INT

Instance Attribute Summary

Attributes inherited from AbstractAdapter

#in_use, #last_use, #logger, #pool, #schema_cache, #visitor

Attributes included from QueryCache

#query_cache, #query_cache_enabled

Instance Method Summary collapse

Methods included from Savepoints

#create_savepoint, #release_savepoint, #rollback_to_savepoint, #supports_savepoints?

Methods included from DatabaseStatements

#begin_db_transaction, #begin_isolated_db_transaction, #commit_db_transaction, #create, #exec_delete, #exec_insert, #exec_query, #execute, #explain, #insert_sql, #query, #result_as_array, #rollback_db_transaction, #select_rows, #sql_for_insert, #substitute_at, #update_sql

Methods included from SchemaStatements

#add_column, #add_index, #change_column, #change_column_default, #change_column_null, #client_min_messages, #client_min_messages=, #collation, #column_for, #columns, #columns_for_distinct, #create_database, #create_schema, #ctype, #current_database, #current_schema, #default_sequence_name, #drop_database, #drop_schema, #encoding, #index_name_exists?, #index_name_length, #indexes, #pk_and_sequence_for, #primary_key, #recreate_database, #remove_index!, #rename_column, #rename_index, #rename_table, #reset_pk_sequence!, #schema_exists?, #schema_names, #schema_search_path, #schema_search_path=, #serial_sequence, #table_exists?, #tables, #type_to_sql

Methods included from ReferentialIntegrity

#disable_referential_integrity, #supports_disable_referential_integrity?

Methods included from Quoting

#escape_bytea, #quote, #quote_column_name, #quote_default_value, #quote_string, #quote_table_name, #quote_table_name_for_assignment, #quoted_date, #type_cast, #unescape_bytea

Methods inherited from AbstractAdapter

#case_insensitive_comparison, #case_sensitive_modifier, #close, #create_savepoint, #current_savepoint_name, #disable_referential_integrity, #expire, #lease, #open_transactions, #prefetch_primary_key?, #raw_connection, #release_savepoint, #requires_reloading?, #rollback_to_savepoint, #substitute_at, #supports_bulk_alter?, #supports_count_distinct?, #supports_savepoints?, type_cast_config_to_boolean, type_cast_config_to_integer, #unprepared_statement, #unprepared_visitor, #verify!

Methods included from ColumnDumper

#column_spec

Methods included from QueryCache

#cache, #clear_query_cache, dirties_query_cache, #disable_query_cache!, #enable_query_cache!, included, #select_all, #uncached

Methods included from DatabaseLimits

#allowed_index_name_length, #column_name_length, #columns_per_multicolumn_index, #columns_per_table, #in_clause_length, #index_name_length, #indexes_per_table, #joins_per_query, #sql_query_length, #table_name_length

Methods included from Quoting

#quote, #quote_column_name, #quote_string, #quote_table_name, #quote_table_name_for_assignment, #quoted_date, #quoted_false, #quoted_true, #type_cast

Methods included from DatabaseStatements

#add_transaction_record, #begin_db_transaction, #begin_isolated_db_transaction, #begin_transaction, #commit_db_transaction, #commit_transaction, #current_transaction, #default_sequence_name, #delete, #empty_insert_statement_value, #exec_delete, #exec_insert, #exec_query, #exec_update, #execute, #insert, #insert_fixture, #join_to_delete, #join_to_update, #limited_update_conditions, #reset_sequence!, #reset_transaction, #rollback_db_transaction, #rollback_transaction, #sanitize_limit, #select_all, #select_one, #select_rows, #select_value, #select_values, #to_sql, #transaction, #transaction_isolation_levels, #transaction_open?, #update, #within_new_transaction

Methods included from SchemaStatements

#add_column, #add_index, #add_reference, #add_timestamps, #assume_migrated_upto_version, #change_column, #change_column_default, #change_column_null, #change_table, #column_exists?, #columns, #columns_for_distinct, #create_join_table, #create_table, #drop_join_table, #drop_table, #dump_schema_information, #index_exists?, #index_name, #index_name_exists?, #initialize_schema_migrations_table, #remove_column, #remove_columns, #remove_index, #remove_index!, #remove_reference, #remove_timestamps, #rename_column, #rename_index, #rename_table, #table_alias_for, #table_exists?, #type_to_sql

Constructor Details

#initialize(connection, logger, connection_parameters, config) ⇒ PostgreSQLAdapter

Initializes and connects a PostgreSQL adapter.



552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 552

def initialize(connection, logger, connection_parameters, config)
  super(connection, logger)

  if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true })
    @prepared_statements = true
    @visitor = Arel::Visitors::PostgreSQL.new self
  else
    @visitor = unprepared_visitor
  end

  @connection_parameters, @config = connection_parameters, config

  # @local_tz is initialized as nil to avoid warnings when connect tries to use it
  @local_tz = nil
  @table_alias_length = nil

  connect
  @statements = StatementPool.new @connection,
                                  self.class.type_cast_config_to_integer(config.fetch(:statement_limit) { 1000 })

  if postgresql_version < 80200
    raise "Your version of PostgreSQL (#{postgresql_version}) is too old, please upgrade!"
  end

  @type_map = OID::TypeMap.new
  initialize_type_map(type_map)
  @local_tz = execute('SHOW TIME ZONE', 'SCHEMA').first["TimeZone"]
  @use_insert_returning = @config.key?(:insert_returning) ? self.class.type_cast_config_to_boolean(@config[:insert_returning]) : true
end

Instance Method Details

#active?Boolean

Is this connection alive and ready for queries?

Returns:

  • (Boolean)


588
589
590
591
592
593
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 588

def active?
  @connection.query 'SELECT 1'
  true
rescue PGError
  false
end

#active_threadsafe?Boolean

Returns:

  • (Boolean)


595
596
597
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 595

def active_threadsafe?
  @connection.connect_poll != PG::PGRES_POLLING_FAILED
end

#adapter_nameObject

Returns ‘PostgreSQL’ as adapter name for identification purposes.



454
455
456
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 454

def adapter_name
  ADAPTER_NAME
end

#clear_cache!Object

Clears the prepared statements cache.



583
584
585
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 583

def clear_cache!
  @statements.clear
end

#disable_extension(name) ⇒ Object



668
669
670
671
672
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 668

def disable_extension(name)
  exec_query("DROP EXTENSION IF EXISTS \"#{name}\" CASCADE").tap {
    reload_type_map
  }
end

#disconnect!Object

Disconnects from the database if already connected. Otherwise, this method does nothing.



613
614
615
616
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 613

def disconnect!
  super
  @connection.close rescue nil
end

#enable_extension(name) ⇒ Object



662
663
664
665
666
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 662

def enable_extension(name)
  exec_query("CREATE EXTENSION IF NOT EXISTS \"#{name}\"").tap {
    reload_type_map
  }
end

#extension_enabled?(name) ⇒ Boolean

Returns:

  • (Boolean)


674
675
676
677
678
679
680
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 674

def extension_enabled?(name)
  if supports_extensions?
    res = exec_query "SELECT EXISTS(SELECT * FROM pg_available_extensions WHERE name = '#{name}' AND installed_version IS NOT NULL) as enabled",
      'SCHEMA'
    res.column_types['enabled'].type_cast res.rows.first.first
  end
end

#extensionsObject



682
683
684
685
686
687
688
689
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 682

def extensions
  if supports_extensions?
    res = exec_query "SELECT extname from pg_extension", "SCHEMA"
    res.rows.map { |r| res.column_types['extname'].type_cast r.first }
  else
    super
  end
end

#index_algorithmsObject



490
491
492
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 490

def index_algorithms
  { concurrently: 'CONCURRENTLY' }
end

#migration_keysObject

Adds ‘:array` as a valid migration key



468
469
470
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 468

def migration_keys
  super + [:array]
end

#native_database_typesObject

:nodoc:



618
619
620
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 618

def native_database_types #:nodoc:
  NATIVE_DATABASE_TYPES
end

#prepare_column_options(column, types) ⇒ Object

Adds ‘:array` option to the default set provided by the AbstractAdapter



460
461
462
463
464
465
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 460

def prepare_column_options(column, types)
  spec = super
  spec[:array] = 'true' if column.respond_to?(:array) && column.array
  spec[:default] = "\"#{column.default_function}\"" if column.default_function
  spec
end

#reconnect!Object

Close then reopen the connection.



600
601
602
603
604
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 600

def reconnect!
  super
  @connection.reset
  configure_connection
end

#reset!Object



606
607
608
609
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 606

def reset!
  clear_cache!
  super
end

#schema_creationObject



36
37
38
# File 'lib/active_record/connection_adapters/postgresql/schema_statements.rb', line 36

def schema_creation
  SchemaCreation.new self
end

#session_auth=(user) ⇒ Object

Set the authorized user for this session



697
698
699
700
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 697

def session_auth=(user)
  clear_cache!
  exec_query "SET SESSION AUTHORIZATION #{user}"
end

#set_standard_conforming_stringsObject

Enable standard-conforming strings if available.



633
634
635
636
637
638
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 633

def set_standard_conforming_strings
  old, self.client_min_messages = client_min_messages, 'panic'
  execute('SET standard_conforming_strings = on', 'SCHEMA') rescue nil
ensure
  self.client_min_messages = old
end

#supports_ddl_transactions?Boolean

Returns:

  • (Boolean)


644
645
646
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 644

def supports_ddl_transactions?
  true
end

#supports_explain?Boolean

Returns:

  • (Boolean)


648
649
650
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 648

def supports_explain?
  true
end

#supports_extensions?Boolean

Returns true if pg > 9.1

Returns:

  • (Boolean)


653
654
655
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 653

def supports_extensions?
  postgresql_version >= 90100
end

#supports_index_sort_order?Boolean

Returns:

  • (Boolean)


478
479
480
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 478

def supports_index_sort_order?
  true
end

#supports_insert_with_returning?Boolean

Returns:

  • (Boolean)


640
641
642
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 640

def supports_insert_with_returning?
  true
end

#supports_migrations?Boolean

Returns true, since this connection adapter supports migrations.

Returns:

  • (Boolean)


623
624
625
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 623

def supports_migrations?
  true
end

#supports_partial_index?Boolean

Returns:

  • (Boolean)


482
483
484
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 482

def supports_partial_index?
  true
end

#supports_primary_key?Boolean

Does PostgreSQL support finding primary key on non-Active Record tables?

Returns:

  • (Boolean)


628
629
630
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 628

def supports_primary_key? #:nodoc:
  true
end

#supports_ranges?Boolean

Range datatypes weren’t introduced until PostgreSQL 9.2

Returns:

  • (Boolean)


658
659
660
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 658

def supports_ranges?
  postgresql_version >= 90200
end

#supports_statement_cache?Boolean

Returns true, since this connection adapter supports prepared statement caching.

Returns:

  • (Boolean)


474
475
476
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 474

def supports_statement_cache?
  true
end

#supports_transaction_isolation?Boolean

Returns:

  • (Boolean)


486
487
488
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 486

def supports_transaction_isolation?
  true
end

#table_alias_lengthObject

Returns the configured supported identifier length supported by PostgreSQL



692
693
694
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 692

def table_alias_length
  @table_alias_length ||= query('SHOW max_identifier_length', 'SCHEMA')[0][0].to_i
end

#update_table_definition(table_name, base) ⇒ Object

:nodoc:



729
730
731
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 729

def update_table_definition(table_name, base) #:nodoc:
  Table.new(table_name, base)
end

#use_insert_returning?Boolean

Returns:

  • (Boolean)


721
722
723
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 721

def use_insert_returning?
  @use_insert_returning
end

#valid_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


725
726
727
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 725

def valid_type?(type)
  !native_database_types[type].nil?
end