Class: ActiveRecord::ConnectionAdapters::PostgreSQLAdapter

Inherits:
AbstractAdapter show all
Includes:
DatabaseStatements, ReferentialIntegrity, SchemaStatements, Quoting
Defined in:
activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb,
activerecord/lib/active_record/connection_adapters/postgresql/oid.rb,
activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb,
activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb,
activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb,
activerecord/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

Constants included from ActiveSupport::Callbacks

ActiveSupport::Callbacks::CALLBACK_FILTER_TYPES

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 DatabaseStatements

#begin_db_transaction, #begin_isolated_db_transaction, #commit_db_transaction, #create, #create_savepoint, #exec_delete, #exec_insert, #exec_query, #execute, #explain, #insert_sql, #query, #release_savepoint, #result_as_array, #rollback_db_transaction, #rollback_to_savepoint, #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, #columns, #columns_for_distinct, #create_database, #create_schema, #ctype, #current_database, #current_schema, #default_sequence_name, #drop_database, #drop_schema, #encoding, #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

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

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?, type_cast_config_to_boolean, type_cast_config_to_integer, #unprepared_statement, #unprepared_visitor, #verify!

Methods included from ColumnDumper

#column_spec

Methods included from ActiveSupport::Callbacks

#run_callbacks

Methods included from ActiveSupport::Concern

#append_features, extended, #included

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 DatabaseStatements

#add_transaction_record, #begin_db_transaction, #begin_isolated_db_transaction, #begin_transaction, #case_sensitive_equality_operator, #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.


526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 526

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

  if self.class.type_cast_config_to_boolean(config.fetch(: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

  initialize_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)

560
561
562
563
564
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 560

def active?
  @connection.connect_poll != PG::PGRES_POLLING_FAILED
rescue PGError
  false
end

#adapter_nameObject

Returns 'PostgreSQL' as adapter name for identification purposes.


429
430
431
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 429

def adapter_name
  ADAPTER_NAME
end

#clear_cache!Object

Clears the prepared statements cache.


555
556
557
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 555

def clear_cache!
  @statements.clear
end

#disable_extension(name) ⇒ Object


641
642
643
644
645
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 641

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.


580
581
582
583
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 580

def disconnect!
  super
  @connection.close rescue nil
end

#enable_extension(name) ⇒ Object


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

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

#extension_enabled?(name) ⇒ Boolean

Returns:

  • (Boolean)

647
648
649
650
651
652
653
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 647

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


655
656
657
658
659
660
661
662
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 655

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


464
465
466
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 464

def index_algorithms
  { concurrently: 'CONCURRENTLY' }
end

#migration_keysObject

Adds `:array` as a valid migration key


442
443
444
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 442

def migration_keys
  super + [:array]
end

#native_database_typesObject

:nodoc:


585
586
587
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 585

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


435
436
437
438
439
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 435

def prepare_column_options(column, types)
  spec = super
  spec[:array] = 'true' if column.respond_to?(:array) && column.array
  spec
end

#reconnect!Object

Close then reopen the connection.


567
568
569
570
571
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 567

def reconnect!
  super
  @connection.reset
  configure_connection
end

#reset!Object


573
574
575
576
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 573

def reset!
  clear_cache!
  super
end

#schema_creationObject


36
37
38
# File 'activerecord/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


670
671
672
673
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 670

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

#set_standard_conforming_stringsObject

Enable standard-conforming strings if available.


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

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)

611
612
613
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 611

def supports_ddl_transactions?
  true
end

#supports_explain?Boolean

Returns true.

Returns:

  • (Boolean)

621
622
623
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 621

def supports_explain?
  true
end

#supports_extensions?Boolean

Returns true if pg > 9.1

Returns:

  • (Boolean)

626
627
628
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 626

def supports_extensions?
  postgresql_version >= 90100
end

#supports_index_sort_order?Boolean

Returns:

  • (Boolean)

452
453
454
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 452

def supports_index_sort_order?
  true
end

#supports_insert_with_returning?Boolean

Returns:

  • (Boolean)

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

def supports_insert_with_returning?
  true
end

#supports_migrations?Boolean

Returns true, since this connection adapter supports migrations.

Returns:

  • (Boolean)

590
591
592
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 590

def supports_migrations?
  true
end

#supports_partial_index?Boolean

Returns:

  • (Boolean)

456
457
458
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 456

def supports_partial_index?
  true
end

#supports_primary_key?Boolean

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

Returns:

  • (Boolean)

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

def supports_primary_key? #:nodoc:
  true
end

#supports_ranges?Boolean

Range datatypes weren't introduced until PostgreSQL 9.2

Returns:

  • (Boolean)

631
632
633
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 631

def supports_ranges?
  postgresql_version >= 90200
end

#supports_savepoints?Boolean

Returns true, since this connection adapter supports savepoints.

Returns:

  • (Boolean)

616
617
618
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 616

def supports_savepoints?
  true
end

#supports_statement_cache?Boolean

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

Returns:

  • (Boolean)

448
449
450
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 448

def supports_statement_cache?
  true
end

#supports_transaction_isolation?Boolean

Returns:

  • (Boolean)

460
461
462
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 460

def supports_transaction_isolation?
  true
end

#table_alias_lengthObject

Returns the configured supported identifier length supported by PostgreSQL


665
666
667
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 665

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

#use_insert_returning?Boolean

Returns:

  • (Boolean)

694
695
696
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 694

def use_insert_returning?
  @use_insert_returning
end

#valid_type?(type) ⇒ Boolean

Returns:

  • (Boolean)

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

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