Class: ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
- Inherits:
-
AbstractAdapter
- Object
- AbstractAdapter
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
- Includes:
- DatabaseStatements, ReferentialIntegrity, SchemaStatements, Quoting, Savepoints
- 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 aSET client_encoding TO <encoding>
call on the connection. -
:min_messages
- An optional client min messages that is used in aSET client_min_messages TO <min_messages>
call on the connection. -
:variables
- An optional hash of additional parameters that will be used inSET SESSION key = val
calls on the connection. -
:insert_returning
- An optional boolean to control the use orRETURNING
forINSERT
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
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
-
#active? ⇒ Boolean
Is this connection alive and ready for queries?.
- #active_threadsafe? ⇒ Boolean
-
#adapter_name ⇒ Object
Returns ‘PostgreSQL’ as adapter name for identification purposes.
-
#clear_cache! ⇒ Object
Clears the prepared statements cache.
- #disable_extension(name) ⇒ Object
-
#disconnect! ⇒ Object
Disconnects from the database if already connected.
- #enable_extension(name) ⇒ Object
- #extension_enabled?(name) ⇒ Boolean
- #extensions ⇒ Object
- #index_algorithms ⇒ Object
-
#initialize(connection, logger, connection_parameters, config) ⇒ PostgreSQLAdapter
constructor
Initializes and connects a PostgreSQL adapter.
-
#migration_keys ⇒ Object
Adds ‘:array` as a valid migration key.
-
#native_database_types ⇒ Object
:nodoc:.
-
#prepare_column_options(column, types) ⇒ Object
Adds ‘:array` option to the default set provided by the AbstractAdapter.
-
#reconnect! ⇒ Object
Close then reopen the connection.
- #reset! ⇒ Object
- #schema_creation ⇒ Object
-
#session_auth=(user) ⇒ Object
Set the authorized user for this session.
-
#set_standard_conforming_strings ⇒ Object
Enable standard-conforming strings if available.
- #supports_ddl_transactions? ⇒ Boolean
- #supports_explain? ⇒ Boolean
-
#supports_extensions? ⇒ Boolean
Returns true if pg > 9.1.
- #supports_index_sort_order? ⇒ Boolean
- #supports_insert_with_returning? ⇒ Boolean
-
#supports_migrations? ⇒ Boolean
Returns true, since this connection adapter supports migrations.
- #supports_partial_index? ⇒ Boolean
-
#supports_primary_key? ⇒ Boolean
Does PostgreSQL support finding primary key on non-Active Record tables?.
-
#supports_ranges? ⇒ Boolean
Range datatypes weren’t introduced until PostgreSQL 9.2.
-
#supports_statement_cache? ⇒ Boolean
Returns
true
, since this connection adapter supports prepared statement caching. - #supports_transaction_isolation? ⇒ Boolean
-
#table_alias_length ⇒ Object
Returns the configured supported identifier length supported by PostgreSQL.
-
#update_table_definition(table_name, base) ⇒ Object
:nodoc:.
- #use_insert_returning? ⇒ Boolean
- #valid_type?(type) ⇒ Boolean
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
#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?, #supports_savepoints?, type_cast_config_to_boolean, type_cast_config_to_integer, #unprepared_statement, #unprepared_visitor, #verify!
Methods included from ColumnDumper
Methods included from ActiveSupport::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, #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 'activerecord/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?
588 589 590 591 592 593 |
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 588 def active? @connection.query 'SELECT 1' true rescue PGError false end |
#active_threadsafe? ⇒ Boolean
595 596 597 |
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 595 def active_threadsafe? @connection.connect_poll != PG::PGRES_POLLING_FAILED end |
#adapter_name ⇒ Object
Returns ‘PostgreSQL’ as adapter name for identification purposes.
454 455 456 |
# File 'activerecord/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 'activerecord/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 'activerecord/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 'activerecord/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 'activerecord/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
674 675 676 677 678 679 680 |
# File 'activerecord/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 |
#extensions ⇒ Object
682 683 684 685 686 687 688 689 |
# File 'activerecord/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_algorithms ⇒ Object
490 491 492 |
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 490 def index_algorithms { concurrently: 'CONCURRENTLY' } end |
#migration_keys ⇒ Object
Adds ‘:array` as a valid migration key
468 469 470 |
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 468 def migration_keys super + [:array] end |
#native_database_types ⇒ Object
:nodoc:
618 619 620 |
# File 'activerecord/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 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 460 def (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 'activerecord/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 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 606 def reset! clear_cache! super end |
#schema_creation ⇒ Object
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
697 698 699 700 |
# File 'activerecord/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_strings ⇒ Object
Enable standard-conforming strings if available.
633 634 635 636 637 638 |
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 633 def set_standard_conforming_strings old, self. = , 'panic' execute('SET standard_conforming_strings = on', 'SCHEMA') rescue nil ensure self. = old end |
#supports_ddl_transactions? ⇒ Boolean
644 645 646 |
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 644 def supports_ddl_transactions? true end |
#supports_explain? ⇒ Boolean
648 649 650 |
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 648 def supports_explain? true end |
#supports_extensions? ⇒ Boolean
Returns true if pg > 9.1
653 654 655 |
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 653 def supports_extensions? postgresql_version >= 90100 end |
#supports_index_sort_order? ⇒ Boolean
478 479 480 |
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 478 def supports_index_sort_order? true end |
#supports_insert_with_returning? ⇒ Boolean
640 641 642 |
# File 'activerecord/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.
623 624 625 |
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 623 def supports_migrations? true end |
#supports_partial_index? ⇒ Boolean
482 483 484 |
# File 'activerecord/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?
628 629 630 |
# File 'activerecord/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
658 659 660 |
# File 'activerecord/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.
474 475 476 |
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 474 def supports_statement_cache? true end |
#supports_transaction_isolation? ⇒ Boolean
486 487 488 |
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 486 def supports_transaction_isolation? true end |
#table_alias_length ⇒ Object
Returns the configured supported identifier length supported by PostgreSQL
692 693 694 |
# File 'activerecord/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 'activerecord/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
721 722 723 |
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 721 def use_insert_returning? @use_insert_returning end |
#valid_type?(type) ⇒ Boolean
725 726 727 |
# File 'activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb', line 725 def valid_type?(type) !native_database_types[type].nil? end |