Parent

Files

Class Index [+]

Quicksearch

ActiveRecord::ConnectionAdapters::PostgreSQLAdapter

The PostgreSQL adapter works both with the native C (ruby.scripting.ca/postgres/) and the pure Ruby (available both as gem and from rubyforge.org/frs/?group_id=234&release_id=1944) drivers.

Options:

Constants

ADAPTER_NAME
NATIVE_DATABASE_TYPES

Public Class Methods

new(connection, logger, connection_parameters, config) click to toggle source

Initializes and connects a PostgreSQL adapter.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 312
312:       def initialize(connection, logger, connection_parameters, config)
313:         super(connection, logger)
314: 
315:         if config.fetch(:prepared_statements) { true }
316:           @visitor = Arel::Visitors::PostgreSQL.new self
317:         else
318:           @visitor = BindSubstitution.new self
319:         end
320: 
321:         connection_parameters.delete :prepared_statements
322: 
323:         @connection_parameters, @config = connection_parameters, config
324: 
325:         # @local_tz is initialized as nil to avoid warnings when connect tries to use it
326:         @local_tz = nil
327:         @table_alias_length = nil
328: 
329:         connect
330:         @statements = StatementPool.new @connection,
331:                                         config.fetch(:statement_limit) { 1000 }
332: 
333:         if postgresql_version < 80200
334:           raise "Your version of PostgreSQL (#{postgresql_version}) is too old, please upgrade!"
335:         end
336: 
337:         @local_tz = execute('SHOW TIME ZONE', 'SCHEMA').first["TimeZone"]
338:       end

Public Instance Methods

active?() click to toggle source

Is this connection alive and ready for queries?

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 346
346:       def active?
347:         @connection.query 'SELECT 1'
348:         true
349:       rescue PGError
350:         false
351:       end
adapter_name() click to toggle source

Returns ‘PostgreSQL’ as adapter name for identification purposes.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 241
241:       def adapter_name
242:         ADAPTER_NAME
243:       end
add_column(table_name, column_name, type, options = {}) click to toggle source

Adds a new column to the named table. See TableDefinition#column for details of the options you can use.

      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1025
1025:       def add_column(table_name, column_name, type, options = {})
1026:         clear_cache!
1027:         add_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ADD COLUMN #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
1028:         add_column_options!(add_column_sql, options)
1029: 
1030:         execute add_column_sql
1031:       end
begin_db_transaction() click to toggle source

Begins a transaction.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 702
702:       def begin_db_transaction
703:         execute "BEGIN"
704:       end
change_column(table_name, column_name, type, options = {}) click to toggle source

Changes the column of a table.

      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1034
1034:       def change_column(table_name, column_name, type, options = {})
1035:         clear_cache!
1036:         quoted_table_name = quote_table_name(table_name)
1037: 
1038:         execute "ALTER TABLE #{quoted_table_name} ALTER COLUMN #{quote_column_name(column_name)} TYPE #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
1039: 
1040:         change_column_default(table_name, column_name, options[:default]) if options_include_default?(options)
1041:         change_column_null(table_name, column_name, options[:null], options[:default]) if options.key?(:null)
1042:       end
change_column_default(table_name, column_name, default) click to toggle source

Changes the default value of a table column.

      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1045
1045:       def change_column_default(table_name, column_name, default)
1046:         clear_cache!
1047:         execute "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} SET DEFAULT #{quote(default)}"
1048:       end
change_column_null(table_name, column_name, null, default = nil) click to toggle source
      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1050
1050:       def change_column_null(table_name, column_name, null, default = nil)
1051:         clear_cache!
1052:         unless null || default.nil?
1053:           execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL")
1054:         end
1055:         execute("ALTER TABLE #{quote_table_name(table_name)} ALTER #{quote_column_name(column_name)} #{null ? 'DROP' : 'SET'} NOT NULL")
1056:       end
clear_cache!() click to toggle source

Clears the prepared statements cache.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 341
341:       def clear_cache!
342:         @statements.clear
343:       end
client_min_messages() click to toggle source

Returns the current client message level.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 900
900:       def client_min_messages
901:         query('SHOW client_min_messages', 'SCHEMA')[0][0]
902:       end
client_min_messages=(level) click to toggle source

Set the client message level.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 905
905:       def client_min_messages=(level)
906:         execute("SET client_min_messages TO '#{level}'", 'SCHEMA')
907:       end
columns(table_name, name = nil) click to toggle source

Returns the list of all column definitions for a table.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 857
857:       def columns(table_name, name = nil)
858:         # Limit, precision, and scale are all handled by the superclass.
859:         column_definitions(table_name).collect do |column_name, type, default, notnull|
860:           PostgreSQLColumn.new(column_name, default, type, notnull == 'f')
861:         end
862:       end
commit_db_transaction() click to toggle source

Commits a transaction.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 707
707:       def commit_db_transaction
708:         execute "COMMIT"
709:       end
create_database(name, options = {}) click to toggle source

Create a new PostgreSQL database. Options include :owner, :template, :encoding, :tablespace, and :connection_limit (note that MySQL uses :charset while PostgreSQL uses :encoding).

Example:

  create_database config[:database], config
  create_database 'foo_development', :encoding => 'unicode'
     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 748
748:       def create_database(name, options = {})
749:         options = options.reverse_merge(:encoding => "utf8")
750: 
751:         option_string = options.symbolize_keys.sum do |key, value|
752:           case key
753:           when :owner
754:             " OWNER = \"#{value}\""
755:           when :template
756:             " TEMPLATE = \"#{value}\""
757:           when :encoding
758:             " ENCODING = '#{value}'"
759:           when :tablespace
760:             " TABLESPACE = \"#{value}\""
761:           when :connection_limit
762:             " CONNECTION LIMIT = #{value}"
763:           else
764:             ""
765:           end
766:         end
767: 
768:         execute "CREATE DATABASE #{quote_table_name(name)}#{option_string}"
769:       end
create_savepoint() click to toggle source
     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 720
720:       def create_savepoint
721:         execute("SAVEPOINT #{current_savepoint_name}")
722:       end
current_database() click to toggle source

Returns the current database name.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 865
865:       def current_database
866:         query('select current_database()')[0][0]
867:       end
current_schema() click to toggle source

Returns the current schema name.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 870
870:       def current_schema
871:         query('SELECT current_schema', 'SCHEMA')[0][0]
872:       end
disconnect!() click to toggle source

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

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 367
367:       def disconnect!
368:         clear_cache!
369:         @connection.close rescue nil
370:       end
encoding() click to toggle source

Returns the current database encoding format.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 875
875:       def encoding
876:         query(          SELECT pg_encoding_to_char(pg_database.encoding) FROM pg_database          WHERE pg_database.datname LIKE '#{current_database}')[0][0]
877:       end
escape_bytea(value) click to toggle source

Escapes binary strings for bytea input to the database.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 420
420:       def escape_bytea(value)
421:         @connection.escape_bytea(value) if value
422:       end
exec_delete(sql, name = 'SQL', binds = []) click to toggle source
     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 673
673:       def exec_delete(sql, name = 'SQL', binds = [])
674:         log(sql, name, binds) do
675:           result = binds.empty? ? exec_no_cache(sql, binds) :
676:                                   exec_cache(sql, binds)
677:           affected = result.cmd_tuples
678:           result.clear
679:           affected
680:         end
681:       end
Also aliased as: exec_update
exec_query(sql, name = 'SQL', binds = []) click to toggle source
     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 662
662:       def exec_query(sql, name = 'SQL', binds = [])
663:         log(sql, name, binds) do
664:           result = binds.empty? ? exec_no_cache(sql, binds) :
665:                                   exec_cache(sql, binds)
666: 
667:           ret = ActiveRecord::Result.new(result.fields, result_as_array(result))
668:           result.clear
669:           return ret
670:         end
671:       end
exec_update(sql, name = 'SQL', binds = []) click to toggle source
Alias for: exec_delete
execute(sql, name = nil) click to toggle source

Executes an SQL statement, returning a PGresult object on success or raising a PGError exception otherwise.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 652
652:       def execute(sql, name = nil)
653:         log(sql, name) do
654:           @connection.async_exec(sql)
655:         end
656:       end
explain(arel, binds = []) click to toggle source

DATABASE STATEMENTS ======================================

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 536
536:       def explain(arel, binds = [])
537:         sql = "EXPLAIN #{to_sql(arel, binds)}"
538:         ExplainPrettyPrinter.new.pp(exec_query(sql, 'EXPLAIN', binds))
539:       end
index_name_length() click to toggle source
      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1072
1072:       def index_name_length
1073:         63
1074:       end
indexes(table_name, name = nil) click to toggle source

Returns an array of indexes for the given table.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 818
818:       def indexes(table_name, name = nil)
819:          result = query(           SELECT distinct i.relname, d.indisunique, d.indkey, pg_get_indexdef(d.indexrelid), t.oid           FROM pg_class t           INNER JOIN pg_index d ON t.oid = d.indrelid           INNER JOIN pg_class i ON d.indexrelid = i.oid           WHERE i.relkind = 'i'             AND d.indisprimary = 'f'             AND t.relname = '#{table_name}'             AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname = ANY (current_schemas(false)) )          ORDER BY i.relname, name)
820: 
821: 
822:         result.map do |row|
823:           index_name = row[0]
824:           unique = row[1] == 't'
825:           indkey = row[2].split(" ")
826:           inddef = row[3]
827:           oid = row[4]
828: 
829:           columns = Hash[query(          SELECT a.attnum, a.attname          FROM pg_attribute a          WHERE a.attrelid = #{oid}          AND a.attnum IN (#{indkey.join(",")}), "Columns for index #{row[0]} on #{table_name}")]
830: 
831:           column_names = columns.values_at(*indkey).compact
832: 
833:           # add info on sort order for columns (only desc order is explicitly specified, asc is the default)
834:           desc_order_columns = inddef.scan(/(\w+) DESC/).flatten
835:           orders = desc_order_columns.any? ? Hash[desc_order_columns.map {|order_column| [order_column, :desc]}] : {}
836:       
837:           column_names.empty? ? nil : IndexDefinition.new(table_name, index_name, unique, column_names, [], orders)
838:         end.compact
839:       end
insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) click to toggle source

Executes an INSERT query and returns the new record’s ID

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 585
585:       def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
586:         unless pk
587:           # Extract the table from the insert sql. Yuck.
588:           table_ref = extract_table_ref_from_insert_sql(sql)
589:           pk = primary_key(table_ref) if table_ref
590:         end
591: 
592:         if pk
593:           select_value("#{sql} RETURNING #{quote_column_name(pk)}")
594:         else
595:           super
596:         end
597:       end
outside_transaction?() click to toggle source
     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 716
716:       def outside_transaction?
717:         @connection.transaction_status == PGconn::PQTRANS_IDLE
718:       end
primary_key(table) click to toggle source

Returns just a table’s primary key

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 994
994:       def primary_key(table)
995:         row = exec_query(          SELECT DISTINCT(attr.attname)          FROM pg_attribute attr          INNER JOIN pg_depend dep ON attr.attrelid = dep.refobjid AND attr.attnum = dep.refobjsubid          INNER JOIN pg_constraint cons ON attr.attrelid = cons.conrelid AND attr.attnum = cons.conkey[1]          WHERE cons.contype = 'p'            AND dep.refobjid = $1::regclass, 'SCHEMA', [[nil, table]]).rows.first
996: 
997:         row && row.first
998:       end
quote_table_name(name) click to toggle source

Checks the following cases:

  • table_name

  • “table.name“

  • schema_name.table_name

  • schema_name.“table.name“

  • “schema.name“.table_name

  • “schema.name“.“table.name“

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 485
485:       def quote_table_name(name)
486:         schema, name_part = extract_pg_identifier_from_name(name.to_s)
487: 
488:         unless name_part
489:           quote_column_name(schema)
490:         else
491:           table_name, name_part = extract_pg_identifier_from_name(name_part)
492:           "#{quote_column_name(schema)}.#{quote_column_name(table_name)}"
493:         end
494:       end
reconnect!() click to toggle source

Close then reopen the connection.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 354
354:       def reconnect!
355:         clear_cache!
356:         @connection.reset
357:         configure_connection
358:       end
release_savepoint() click to toggle source
     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 728
728:       def release_savepoint
729:         execute("RELEASE SAVEPOINT #{current_savepoint_name}")
730:       end
rename_column(table_name, column_name, new_column_name) click to toggle source

Renames a column in a table.

      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1059
1059:       def rename_column(table_name, column_name, new_column_name)
1060:         clear_cache!
1061:         execute "ALTER TABLE #{quote_table_name(table_name)} RENAME COLUMN #{quote_column_name(column_name)} TO #{quote_column_name(new_column_name)}"
1062:       end
rename_index(table_name, old_name, new_name) click to toggle source
      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1068
1068:       def rename_index(table_name, old_name, new_name)
1069:         execute "ALTER INDEX #{quote_column_name(old_name)} RENAME TO #{quote_table_name(new_name)}"
1070:       end
rename_table(name, new_name) click to toggle source

Renames a table. Also renames a table’s primary key sequence if the sequence name matches the Active Record default.

Example:

  rename_table('octopuses', 'octopi')
      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1013
1013:       def rename_table(name, new_name)
1014:         clear_cache!
1015:         execute "ALTER TABLE #{quote_table_name(name)} RENAME TO #{quote_table_name(new_name)}"
1016:         pk, seq = pk_and_sequence_for(new_name)
1017:         if seq == "#{name}_#{pk}_seq"
1018:           new_seq = "#{new_name}_#{pk}_seq"
1019:           execute "ALTER TABLE #{quote_table_name(seq)} RENAME TO #{quote_table_name(new_seq)}"
1020:         end
1021:       end
reset!() click to toggle source
     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 360
360:       def reset!
361:         clear_cache!
362:         super
363:       end
rollback_db_transaction() click to toggle source

Aborts a transaction.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 712
712:       def rollback_db_transaction
713:         execute "ROLLBACK"
714:       end
rollback_to_savepoint() click to toggle source
     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 724
724:       def rollback_to_savepoint
725:         execute("ROLLBACK TO SAVEPOINT #{current_savepoint_name}")
726:       end
schema_exists?(name) click to toggle source

Returns true if schema exists.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 809
809:       def schema_exists?(name)
810:         exec_query(          SELECT COUNT(*)          FROM pg_namespace          WHERE nspname = $1, 'SCHEMA', [[nil, name]]).rows.first[0].to_i > 0
811:       end
schema_search_path() click to toggle source

Returns the active schema search path.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 895
895:       def schema_search_path
896:         @schema_search_path ||= query('SHOW search_path', 'SCHEMA')[0][0]
897:       end
schema_search_path=(schema_csv) click to toggle source

Sets the schema search path to a string of comma-separated schema names. Names beginning with $ have to be quoted (e.g. $user => ’$user’). See: www.postgresql.org/docs/current/static/ddl-schemas.html

This should be not be called manually but set in database.yml.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 887
887:       def schema_search_path=(schema_csv)
888:         if schema_csv
889:           execute("SET search_path TO #{schema_csv}", 'SCHEMA')
890:           @schema_search_path = schema_csv
891:         end
892:       end
select_rows(sql, name = nil) click to toggle source

Executes a SELECT query and returns an array of rows. Each row is an array of field values.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 580
580:       def select_rows(sql, name = nil)
581:         select_raw(sql, name).last
582:       end
serial_sequence(table, column) click to toggle source
     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 916
916:       def serial_sequence(table, column)
917:         result = exec_query(          SELECT pg_get_serial_sequence($1, $2), 'SCHEMA', [[nil, table], [nil, column]])
918:         result.rows.first.first
919:       end
session_auth=(user) click to toggle source

Set the authorized user for this session

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 512
512:       def session_auth=(user)
513:         clear_cache!
514:         exec_query "SET SESSION AUTHORIZATION #{user}"
515:       end
set_standard_conforming_strings() click to toggle source

Enable standard-conforming strings if available.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 387
387:       def set_standard_conforming_strings
388:         old, self.client_min_messages = client_min_messages, 'panic'
389:         execute('SET standard_conforming_strings = on', 'SCHEMA') rescue nil
390:       ensure
391:         self.client_min_messages = old
392:       end
sql_for_insert(sql, pk, id_value, sequence_name, binds) click to toggle source
     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 684
684:       def sql_for_insert(sql, pk, id_value, sequence_name, binds)
685:         unless pk
686:           # Extract the table from the insert sql. Yuck.
687:           table_ref = extract_table_ref_from_insert_sql(sql)
688:           pk = primary_key(table_ref) if table_ref
689:         end
690: 
691:         sql = "#{sql} RETURNING #{quote_column_name(pk)}" if pk
692: 
693:         [sql, binds]
694:       end
substitute_at(column, index) click to toggle source
     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 658
658:       def substitute_at(column, index)
659:         Arel::Nodes::BindParam.new "$#{index + 1}"
660:       end
supports_ddl_transactions?() click to toggle source
     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 398
398:       def supports_ddl_transactions?
399:         true
400:       end
supports_explain?() click to toggle source

Returns true.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 408
408:       def supports_explain?
409:         true
410:       end
supports_index_sort_order?() click to toggle source
     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 251
251:       def supports_index_sort_order?
252:         true
253:       end
supports_insert_with_returning?() click to toggle source
     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 394
394:       def supports_insert_with_returning?
395:         true
396:       end
supports_migrations?() click to toggle source

Returns true, since this connection adapter supports migrations.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 377
377:       def supports_migrations?
378:         true
379:       end
supports_savepoints?() click to toggle source

Returns true, since this connection adapter supports savepoints.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 403
403:       def supports_savepoints?
404:         true
405:       end
supports_statement_cache?() click to toggle source

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

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 247
247:       def supports_statement_cache?
248:         true
249:       end
table_alias_length() click to toggle source

Returns the configured supported identifier length supported by PostgreSQL

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 413
413:       def table_alias_length
414:         @table_alias_length ||= query('SHOW max_identifier_length')[0][0].to_i
415:       end
table_exists?(name) click to toggle source

Returns true if table exists. If the schema is not specified as part of name then it will only find tables within the current schema search path (regardless of permissions to access tables in other schemas)

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 791
791:       def table_exists?(name)
792:         schema, table = Utils.extract_schema_and_table(name.to_s)
793:         return false unless table
794: 
795:         binds = [[nil, table]]
796:         binds << [nil, schema] if schema
797: 
798:         exec_query(            SELECT COUNT(*)            FROM pg_class c            LEFT JOIN pg_namespace n ON n.oid = c.relnamespace            WHERE c.relkind in ('v','r')            AND c.relname = $1            AND n.nspname = #{schema ? '$2' : 'ANY (current_schemas(false))'}, 'SCHEMA', binds).rows.first[0].to_i > 0
799:       end
tables(name = nil) click to toggle source

Returns the list of all tables in the schema search path or a specified schema.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 780
780:       def tables(name = nil)
781:         query(          SELECT tablename          FROM pg_tables          WHERE schemaname = ANY (current_schemas(false)), 'SCHEMA').map { |row| row[0] }
782:       end
type_cast(value, column) click to toggle source
     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 460
460:       def type_cast(value, column)
461:         return super unless column
462: 
463:         case value
464:         when String
465:           return super unless 'bytea' == column.sql_type
466:           { :value => value, :format => 1 }
467:         else
468:           super
469:         end
470:       end
type_to_sql(type, limit = nil, precision = nil, scale = nil) click to toggle source

Maps logical Rails types to PostgreSQL-specific data types.

      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1077
1077:       def type_to_sql(type, limit = nil, precision = nil, scale = nil)
1078:         case type.to_s
1079:         when 'binary'
1080:           # PostgreSQL doesn't support limits on binary (bytea) columns.
1081:           # The hard limit is 1Gb, because of a 32-bit size field, and TOAST.
1082:           case limit
1083:           when nil, 0..0x3fffffff; super(type)
1084:           else raise(ActiveRecordError, "No binary type has byte size #{limit}.")
1085:           end
1086:         when 'integer'
1087:           return 'integer' unless limit
1088:   
1089:           case limit
1090:             when 1, 2; 'smallint'
1091:             when 3, 4; 'integer'
1092:             when 5..8; 'bigint'
1093:             else raise(ActiveRecordError, "No integer type has byte size #{limit}. Use a numeric with precision 0 instead.")
1094:           end
1095:         else
1096:           super
1097:         end
1098:       end
unescape_bytea(value) click to toggle source

Unescapes bytea output from a database to the binary string it represents. NOTE: This is NOT an inverse of escape_bytea! This is only to be used

      on escaped binary output from database drive.
     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 427
427:       def unescape_bytea(value)
428:         @connection.unescape_bytea(value) if value
429:       end
update_sql(sql, name = nil) click to toggle source

Executes an UPDATE query and returns the number of affected tuples.

     # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 697
697:       def update_sql(sql, name = nil)
698:         super.cmd_tuples
699:       end

Protected Instance Methods

postgresql_version() click to toggle source

Returns the version of the connected PostgreSQL server.

      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1139
1139:         def postgresql_version
1140:           @connection.server_version
1141:         end
translate_exception(exception, message) click to toggle source
      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1143
1143:         def translate_exception(exception, message)
1144:           case exception.message
1145:           when /duplicate key value violates unique constraint/
1146:             RecordNotUnique.new(message, exception)
1147:           when /violates foreign key constraint/
1148:             InvalidForeignKey.new(message, exception)
1149:           else
1150:             super
1151:           end
1152:         end

Private Instance Methods

configure_connection() click to toggle source

Configures the encoding, verbosity, schema search path, and time zone of the connection. This is called by # and should not be called manually.

      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1225
1225:         def configure_connection
1226:           if @config[:encoding]
1227:             @connection.set_client_encoding(@config[:encoding])
1228:           end
1229:           self.client_min_messages = @config[:min_messages] if @config[:min_messages]
1230:           self.schema_search_path = @config[:schema_search_path] || @config[:schema_order]
1231: 
1232:           # Use standard-conforming strings if available so we don't have to do the E'...' dance.
1233:           set_standard_conforming_strings
1234: 
1235:           # If using Active Record's time zone support configure the connection to return
1236:           # TIMESTAMP WITH ZONE types in UTC.
1237:           if ActiveRecord::Base.default_timezone == :utc
1238:             execute("SET time zone 'UTC'", 'SCHEMA')
1239:           elsif @local_tz
1240:             execute("SET time zone '#{@local_tz}'", 'SCHEMA')
1241:           end
1242:         end
connect() click to toggle source

Connects to a PostgreSQL server and sets up the adapter depending on the connected server’s characteristics.

      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1212
1212:         def connect
1213:           @connection = PGconn.connect(*@connection_parameters)
1214: 
1215:           # Money type has a fixed precision of 10 in PostgreSQL 8.2 and below, and as of
1216:           # PostgreSQL 8.3 it has a fixed precision of 19. PostgreSQLColumn.extract_precision
1217:           # should know about this but can't detect it there, so deal with it here.
1218:           PostgreSQLColumn.money_precision = (postgresql_version >= 80300) ? 19 : 10
1219: 
1220:           configure_connection
1221:         end
exec_cache(sql, binds) click to toggle source
      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1161
1161:         def exec_cache(sql, binds)
1162:           begin
1163:             stmt_key = prepare_statement sql
1164: 
1165:             # Clear the queue
1166:             @connection.get_last_result
1167:             @connection.send_query_prepared(stmt_key, binds.map { |col, val|
1168:               type_cast(val, col)
1169:             })
1170:             @connection.block
1171:             @connection.get_last_result
1172:           rescue PGError => e
1173:             # Get the PG code for the failure.  Annoyingly, the code for
1174:             # prepared statements whose return value may have changed is
1175:             # FEATURE_NOT_SUPPORTED.  Check here for more details:
1176:             # http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/cache/plancache.c#l573
1177:             code = e.result.result_error_field(PGresult::PG_DIAG_SQLSTATE)
1178:             if FEATURE_NOT_SUPPORTED == code
1179:               @statements.delete sql_key(sql)
1180:               retry
1181:             else
1182:               raise e
1183:             end
1184:           end
1185:         end
exec_no_cache(sql, binds) click to toggle source
      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1157
1157:         def exec_no_cache(sql, binds)
1158:           @connection.async_exec(sql)
1159:         end
extract_pg_identifier_from_name(name) click to toggle source
      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1293
1293:         def extract_pg_identifier_from_name(name)
1294:           match_data = name.start_with?('"') ? name.match(/\"([^\"]+)\"/) : name.match(/([^\.]+)/)
1295: 
1296:           if match_data
1297:             rest = name[match_data[0].length, name.length]
1298:             rest = rest[1, rest.length] if rest.start_with? "."
1299:             [match_data[1], (rest.length > 0 ? rest : nil)]
1300:           end
1301:         end
extract_table_ref_from_insert_sql(sql) click to toggle source
      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1303
1303:         def extract_table_ref_from_insert_sql(sql)
1304:           sql[/into\s+([^\(]*).*values\s*\(/]
1305:           $1.strip if $1
1306:         end
prepare_statement(sql) click to toggle source

Prepare the statement if it hasn’t been prepared, return the statement key.

      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1195
1195:         def prepare_statement(sql)
1196:           sql_key = sql_key(sql)
1197:           unless @statements.key? sql_key
1198:             nextkey = @statements.next_key
1199:             @connection.prepare nextkey, sql
1200:             @statements[sql_key] = nextkey
1201:           end
1202:           @statements[sql_key]
1203:         end
select(sql, name = nil, binds = []) click to toggle source

Executes a SELECT query and returns the results, performing any data type conversions that are required to be performed here instead of in PostgreSQLColumn.

      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1252
1252:         def select(sql, name = nil, binds = [])
1253:           exec_query(sql, name, binds).to_a
1254:         end
select_raw(sql, name = nil) click to toggle source
      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1256
1256:         def select_raw(sql, name = nil)
1257:           res = execute(sql, name)
1258:           results = result_as_array(res)
1259:           fields = res.fields
1260:           res.clear
1261:           return fields, results
1262:         end
sql_key(sql) click to toggle source

Returns the statement identifier for the client side cache of statements

      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1189
1189:         def sql_key(sql)
1190:           "#{schema_search_path}-#{sql}"
1191:         end
table_definition() click to toggle source
      # File lib/active_record/connection_adapters/postgresql_adapter.rb, line 1308
1308:         def table_definition
1309:           TableDefinition.new(self)
1310:         end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.