Class: ActiveRecord::ConnectionAdapters::PostgreSQLAdapter

Inherits:
AbstractAdapter
  • Object
show all
Includes:
DatabaseStatements, Quoting, ReferentialIntegrity, SchemaStatements
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 DatabaseStatements

#begin_db_transaction, #begin_isolated_db_transaction, #commit_db_transaction, #create, #create_savepoint, #exec_delete, #exec_insert, #exec_query, #execute, #explain, #insert_sql, #outside_transaction?, #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_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_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, #decrement_open_transactions, #disable_referential_integrity, #expire, #increment_open_transactions, #lease, #open_transactions, #prefetch_primary_key?, #raw_connection, #release_savepoint, #requires_reloading?, #rollback_to_savepoint, #substitute_at, #supports_bulk_alter?, #supports_count_distinct?, #transaction_joinable=, 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, #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_column_options!, #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, #distinct, #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.



540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 540

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

  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)


575
576
577
578
579
580
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 575

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

#active_threadsafe?Boolean

Returns:

  • (Boolean)


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

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

#adapter_nameObject

Returns ‘PostgreSQL’ as adapter name for identification purposes.



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

def adapter_name
  ADAPTER_NAME
end

#clear_cache!Object

Clears the prepared statements cache.



570
571
572
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 570

def clear_cache!
  @statements.clear
end

#disable_extension(name) ⇒ Object



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

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.



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

def disconnect!
  super
  @connection.close rescue nil
end

#enable_extension(name) ⇒ Object



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

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

#extension_enabled?(name) ⇒ Boolean

Returns:

  • (Boolean)


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

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



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

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



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

def index_algorithms
  { concurrently: 'CONCURRENTLY' }
end

#migration_keysObject

Adds ‘:array` as a valid migration key



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

def migration_keys
  super + [:array]
end

#native_database_typesObject

:nodoc:



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

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



448
449
450
451
452
453
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 448

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.



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

def reconnect!
  super
  @connection.reset
  configure_connection
end

#reset!Object



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

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



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

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

#set_standard_conforming_stringsObject

Enable standard-conforming strings if available.



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

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)


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

def supports_ddl_transactions?
  true
end

#supports_explain?Boolean

Returns true.

Returns:

  • (Boolean)


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

def supports_explain?
  true
end

#supports_extensions?Boolean

Returns true if pg > 9.1

Returns:

  • (Boolean)


646
647
648
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 646

def supports_extensions?
  postgresql_version >= 90100
end

#supports_index_sort_order?Boolean

Returns:

  • (Boolean)


466
467
468
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 466

def supports_index_sort_order?
  true
end

#supports_insert_with_returning?Boolean

Returns:

  • (Boolean)


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

def supports_insert_with_returning?
  true
end

#supports_migrations?Boolean

Returns true, since this connection adapter supports migrations.

Returns:

  • (Boolean)


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

def supports_migrations?
  true
end

#supports_partial_index?Boolean

Returns:

  • (Boolean)


470
471
472
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 470

def supports_partial_index?
  true
end

#supports_primary_key?Boolean

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

Returns:

  • (Boolean)


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

def supports_primary_key? #:nodoc:
  true
end

#supports_ranges?Boolean

Range datatypes weren’t introduced until PostgreSQL 9.2

Returns:

  • (Boolean)


651
652
653
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 651

def supports_ranges?
  postgresql_version >= 90200
end

#supports_savepoints?Boolean

Returns true, since this connection adapter supports savepoints.

Returns:

  • (Boolean)


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

def supports_savepoints?
  true
end

#supports_statement_cache?Boolean

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

Returns:

  • (Boolean)


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

def supports_statement_cache?
  true
end

#supports_transaction_isolation?Boolean

Returns:

  • (Boolean)


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

def supports_transaction_isolation?
  true
end

#table_alias_lengthObject

Returns the configured supported identifier length supported by PostgreSQL



685
686
687
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 685

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:



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

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

#use_insert_returning?Boolean

Returns:

  • (Boolean)


714
715
716
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 714

def use_insert_returning?
  @use_insert_returning
end

#valid_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


718
719
720
# File 'lib/active_record/connection_adapters/postgresql_adapter.rb', line 718

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