postgresql_adapter.rb 29.4 KB
Newer Older
1 2 3 4
# Make sure we're using pg high enough for type casts and Ruby 2.2+ compatibility
gem 'pg', '~> 0.18'
require 'pg'

S
Sean Griffin 已提交
5 6 7 8 9 10 11
require "active_record/connection_adapters/abstract_adapter"
require "active_record/connection_adapters/postgresql/column"
require "active_record/connection_adapters/postgresql/database_statements"
require "active_record/connection_adapters/postgresql/oid"
require "active_record/connection_adapters/postgresql/quoting"
require "active_record/connection_adapters/postgresql/referential_integrity"
require "active_record/connection_adapters/postgresql/schema_definitions"
12
require "active_record/connection_adapters/postgresql/schema_dumper"
S
Sean Griffin 已提交
13 14 15 16
require "active_record/connection_adapters/postgresql/schema_statements"
require "active_record/connection_adapters/postgresql/type_metadata"
require "active_record/connection_adapters/postgresql/utils"
require "active_record/connection_adapters/statement_pool"
17

D
Dan McClain 已提交
18 19
require 'ipaddr'

D
Initial  
David Heinemeier Hansson 已提交
20
module ActiveRecord
21
  module ConnectionHandling # :nodoc:
D
Initial  
David Heinemeier Hansson 已提交
22
    # Establishes a connection to the database that's used by all Active Record objects
23
    def postgresql_connection(config)
24
      conn_params = config.symbolize_keys
D
Initial  
David Heinemeier Hansson 已提交
25

26
      conn_params.delete_if { |_, v| v.nil? }
27 28 29 30

      # Map ActiveRecords param names to PGs.
      conn_params[:user] = conn_params.delete(:username) if conn_params[:username]
      conn_params[:dbname] = conn_params.delete(:database) if conn_params[:database]
D
Initial  
David Heinemeier Hansson 已提交
31

32
      # Forward only valid config params to PGconn.connect.
33 34
      valid_conn_param_keys = PGconn.conndefaults_hash.keys + [:requiressl]
      conn_params.slice!(*valid_conn_param_keys)
35

36
      # The postgres drivers don't allow the creation of an unconnected PGconn object,
37
      # so just pass a nil connection object for the time being.
38
      ConnectionAdapters::PostgreSQLAdapter.new(nil, logger, conn_params, config)
39 40
    end
  end
41

42
  module ConnectionAdapters
43
    # The PostgreSQL adapter works with the native C (https://bitbucket.org/ged/ruby-pg) driver.
44 45 46
    #
    # Options:
    #
47 48
    # * <tt>:host</tt> - Defaults to a Unix-domain socket in /tmp. On machines without Unix-domain sockets,
    #   the default is to connect to localhost.
P
Pratik Naik 已提交
49
    # * <tt>:port</tt> - Defaults to 5432.
50 51 52
    # * <tt>:username</tt> - Defaults to be the same as the operating system name of the user running the application.
    # * <tt>:password</tt> - Password to be used if the server demands password authentication.
    # * <tt>:database</tt> - Defaults to be the same as the user name.
53
    # * <tt>:schema_search_path</tt> - An optional schema search path for the connection given
54
    #   as a string of comma-separated schema names. This is backward-compatible with the <tt>:schema_order</tt> option.
55
    # * <tt>:encoding</tt> - An optional client encoding that is used in a <tt>SET client_encoding TO
56
    #   <encoding></tt> call on the connection.
57
    # * <tt>:min_messages</tt> - An optional client min messages that is used in a
58
    #   <tt>SET client_min_messages TO <min_messages></tt> call on the connection.
59 60
    # * <tt>:variables</tt> - An optional hash of additional parameters that
    #   will be used in <tt>SET SESSION key = val</tt> calls on the connection.
61
    # * <tt>:insert_returning</tt> - An optional boolean to control the use of <tt>RETURNING</tt> for <tt>INSERT</tt> statements
62
    #   defaults to true.
63 64
    #
    # Any further options are used as connection parameters to libpq. See
65
    # http://www.postgresql.org/docs/current/static/libpq-connect.html for the
66 67 68
    # list of parameters.
    #
    # In addition, default connection parameters of libpq can be set per environment variables.
69
    # See http://www.postgresql.org/docs/current/static/libpq-envars.html .
70
    class PostgreSQLAdapter < AbstractAdapter
71
      ADAPTER_NAME = 'PostgreSQL'.freeze
72 73

      NATIVE_DATABASE_TYPES = {
74
        primary_key: "serial primary key",
A
Aaron Patterson 已提交
75
        bigserial: "bigserial",
76
        string:      { name: "character varying" },
77 78 79 80 81 82 83
        text:        { name: "text" },
        integer:     { name: "integer" },
        float:       { name: "float" },
        decimal:     { name: "decimal" },
        datetime:    { name: "timestamp" },
        time:        { name: "time" },
        date:        { name: "date" },
B
bUg 已提交
84 85 86 87 88 89
        daterange:   { name: "daterange" },
        numrange:    { name: "numrange" },
        tsrange:     { name: "tsrange" },
        tstzrange:   { name: "tstzrange" },
        int4range:   { name: "int4range" },
        int8range:   { name: "int8range" },
90 91
        binary:      { name: "bytea" },
        boolean:     { name: "boolean" },
A
Aaron Patterson 已提交
92
        bigint:      { name: "bigint" },
93 94 95 96 97 98
        xml:         { name: "xml" },
        tsvector:    { name: "tsvector" },
        hstore:      { name: "hstore" },
        inet:        { name: "inet" },
        cidr:        { name: "cidr" },
        macaddr:     { name: "macaddr" },
99
        uuid:        { name: "uuid" },
100
        json:        { name: "json" },
101
        jsonb:       { name: "jsonb" },
102
        ltree:       { name: "ltree" },
103
        citext:      { name: "citext" },
S
Sean Griffin 已提交
104 105 106
        point:       { name: "point" },
        bit:         { name: "bit" },
        bit_varying: { name: "bit varying" },
107
        money:       { name: "money" },
108 109
      }

110 111 112 113
      OID = PostgreSQL::OID #:nodoc:

      include PostgreSQL::Quoting
      include PostgreSQL::ReferentialIntegrity
114
      include PostgreSQL::SchemaStatements
115
      include PostgreSQL::DatabaseStatements
116
      include PostgreSQL::ColumnDumper
117
      include Savepoints
118

119
      def schema_creation # :nodoc:
120 121 122
        PostgreSQL::SchemaCreation.new self
      end

123
      # Returns true, since this connection adapter supports prepared statement
124
      # caching.
125 126 127 128
      def supports_statement_cache?
        true
      end

129 130 131 132
      def supports_index_sort_order?
        true
      end

133 134 135 136
      def supports_partial_index?
        true
      end

137 138 139 140
      def supports_transaction_isolation?
        true
      end

141 142 143 144
      def supports_foreign_keys?
        true
      end

145 146 147 148
      def supports_views?
        true
      end

149 150 151 152
      def supports_datetime_with_precision?
        true
      end

153 154 155 156
      def supports_json?
        postgresql_version >= 90200
      end

157 158 159 160
      def index_algorithms
        { concurrently: 'CONCURRENTLY' }
      end

161 162
      class StatementPool < ConnectionAdapters::StatementPool
        def initialize(connection, max)
163 164
          super(max)
          @connection = connection
165 166 167 168 169 170 171 172
          @counter = 0
        end

        def next_key
          "a#{@counter + 1}"
        end

        def []=(sql, key)
173
          super.tap { @counter += 1 }
174 175
        end

176
        private
177

178 179 180 181 182 183 184 185 186
          def dealloc(key)
            @connection.query "DEALLOCATE #{key}" if connection_active?
          end

          def connection_active?
            @connection.status == PGconn::CONNECTION_OK
          rescue PGError
            false
          end
187 188
      end

189 190
      # Initializes and connects a PostgreSQL adapter.
      def initialize(connection, logger, connection_parameters, config)
191
        super(connection, logger)
192

193
        @visitor = Arel::Visitors::PostgreSQL.new self
194
        if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true })
195
          @prepared_statements = true
196
          @visitor.extend(DetermineIfPreparableVisitor)
197
        else
198
          @prepared_statements = false
199 200
        end

201
        @connection_parameters, @config = connection_parameters, config
202

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

207
        connect
208
        add_pg_encoders
209
        @statements = StatementPool.new @connection,
210
                                        self.class.type_cast_config_to_integer(config.fetch(:statement_limit) { 1000 })
211 212 213 214 215

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

216 217
        add_pg_decoders

218
        @type_map = Type::HashLookupTypeMap.new
219
        initialize_type_map(type_map)
220
        @local_tz = execute('SHOW TIME ZONE', 'SCHEMA').first["TimeZone"]
221
        @use_insert_returning = @config.key?(:insert_returning) ? self.class.type_cast_config_to_boolean(@config[:insert_returning]) : true
222 223
      end

X
Xavier Noria 已提交
224
      # Clears the prepared statements cache.
225 226 227 228
      def clear_cache!
        @statements.clear
      end

229 230 231 232
      def truncate(table_name, name = nil)
        exec_query "TRUNCATE TABLE #{quote_table_name(table_name)}", name, []
      end

233 234
      # Is this connection alive and ready for queries?
      def active?
235 236
        @connection.query 'SELECT 1'
        true
237
      rescue PGError
238
        false
239 240 241 242
      end

      # Close then reopen the connection.
      def reconnect!
243
        super
244 245
        @connection.reset
        configure_connection
246
      end
247

248 249
      def reset!
        clear_cache!
250 251 252 253 254 255
        reset_transaction
        unless @connection.transaction_status == ::PG::PQTRANS_IDLE
          @connection.query 'ROLLBACK'
        end
        @connection.query 'DISCARD ALL'
        configure_connection
256 257
      end

258 259
      # Disconnects from the database if already connected. Otherwise, this
      # method does nothing.
260
      def disconnect!
261
        super
262 263
        @connection.close rescue nil
      end
264

265
      def native_database_types #:nodoc:
266
        NATIVE_DATABASE_TYPES
267
      end
268

269
      # Returns true, since this connection adapter supports migrations.
270 271
      def supports_migrations?
        true
272 273
      end

274
      # Does PostgreSQL support finding primary key on non-Active Record tables?
275 276 277 278
      def supports_primary_key? #:nodoc:
        true
      end

279
      def set_standard_conforming_strings
280
        execute('SET standard_conforming_strings = on', 'SCHEMA')
281 282
      end

283 284 285
      def supports_ddl_transactions?
        true
      end
286

287 288 289 290
      def supports_advisory_locks?
        true
      end

291 292 293 294
      def supports_explain?
        true
      end

295
      # Returns true if pg > 9.1
296
      def supports_extensions?
297
        postgresql_version >= 90100
298 299
      end

A
Andrew White 已提交
300 301 302 303 304
      # Range datatypes weren't introduced until PostgreSQL 9.2
      def supports_ranges?
        postgresql_version >= 90200
      end

305 306 307 308
      def supports_materialized_views?
        postgresql_version >= 90300
      end

309 310 311 312 313 314 315 316 317 318 319 320 321 322
      def get_advisory_lock(key) # :nodoc:
        unless key.is_a?(Integer) && key.bit_length <= 63
          raise(ArgumentError, "Postgres requires advisory lock keys to be a signed 64 bit integer")
        end
        select_value("SELECT pg_try_advisory_lock(#{key});")
      end

      def release_advisory_lock(key) # :nodoc:
        unless key.is_a?(Integer) && key.bit_length <= 63
          raise(ArgumentError, "Postgres requires advisory lock keys to be a signed 64 bit integer")
        end
        select_value("SELECT pg_advisory_unlock(#{key})")
      end

323
      def enable_extension(name)
324
        exec_query("CREATE EXTENSION IF NOT EXISTS \"#{name}\"").tap {
325 326
          reload_type_map
        }
327 328 329
      end

      def disable_extension(name)
330
        exec_query("DROP EXTENSION IF EXISTS \"#{name}\" CASCADE").tap {
331 332
          reload_type_map
        }
333 334 335
      end

      def extension_enabled?(name)
R
Rafael Mendonça França 已提交
336
        if supports_extensions?
337
          res = exec_query "SELECT EXISTS(SELECT * FROM pg_available_extensions WHERE name = '#{name}' AND installed_version IS NOT NULL) as enabled",
338
            'SCHEMA'
339
          res.cast_values.first
340
        end
341 342
      end

343 344
      def extensions
        if supports_extensions?
345
          exec_query("SELECT extname from pg_extension", "SCHEMA").cast_values
346
        else
347
          super
348 349 350
        end
      end

351
      # Returns the configured supported identifier length supported by PostgreSQL
352
      def table_alias_length
K
kennyj 已提交
353
        @table_alias_length ||= query('SHOW max_identifier_length', 'SCHEMA')[0][0].to_i
354
      end
355

356 357
      # Set the authorized user for this session
      def session_auth=(user)
358
        clear_cache!
A
Aaron Patterson 已提交
359
        exec_query "SET SESSION AUTHORIZATION #{user}"
360 361
      end

362 363
      def use_insert_returning?
        @use_insert_returning
364 365
      end

366 367 368 369
      def valid_type?(type)
        !native_database_types[type].nil?
      end

370
      def update_table_definition(table_name, base) #:nodoc:
371
        PostgreSQL::Table.new(table_name, base)
372 373
      end

374 375 376 377 378
      def lookup_cast_type(sql_type) # :nodoc:
        oid = execute("SELECT #{quote(sql_type)}::regtype::oid", "SCHEMA").first['oid'].to_i
        super(oid)
      end

379 380 381 382 383 384 385 386 387 388
      def column_name_for_operation(operation, node) # :nodoc:
        OPERATION_ALIASES.fetch(operation) { operation.downcase }
      end

      OPERATION_ALIASES = { # :nodoc:
        "maximum" => "max",
        "minimum" => "min",
        "average" => "avg",
      }

389
      protected
390

391
        # Returns the version of the connected PostgreSQL server.
392
        def postgresql_version
393
          @connection.server_version
394 395
        end

396
        # See http://www.postgresql.org/docs/current/static/errcodes-appendix.html
397 398 399
        FOREIGN_KEY_VIOLATION = "23503"
        UNIQUE_VIOLATION      = "23505"

400
        def translate_exception(exception, message)
401 402
          return exception unless exception.respond_to?(:result)

403
          case exception.result.try(:error_field, PGresult::PG_DIAG_SQLSTATE)
404
          when UNIQUE_VIOLATION
405
            RecordNotUnique.new(message)
406
          when FOREIGN_KEY_VIOLATION
407
            InvalidForeignKey.new(message)
408 409 410 411 412
          else
            super
          end
        end

D
Initial  
David Heinemeier Hansson 已提交
413
      private
414

415
        def get_oid_type(oid, fmod, column_name, sql_type = '') # :nodoc:
416
          if !type_map.key?(oid)
417
            load_additional_types(type_map, [oid])
418 419
          end

420 421 422 423 424 425
          type_map.fetch(oid, fmod, sql_type) {
            warn "unknown OID #{oid}: failed to recognize type of '#{column_name}'. It will be treated as String."
            Type::Value.new.tap do |cast_type|
              type_map.register_type(oid, cast_type)
            end
          }
426 427
        end

428
        def initialize_type_map(m) # :nodoc:
429 430 431
          register_class_with_limit m, 'int2', Type::Integer
          register_class_with_limit m, 'int4', Type::Integer
          register_class_with_limit m, 'int8', Type::Integer
432
          m.alias_type 'oid', 'int2'
433
          m.register_type 'float4', Type::Float.new
434 435
          m.alias_type 'float8', 'float4'
          m.register_type 'text', Type::Text.new
S
Sean Griffin 已提交
436
          register_class_with_limit m, 'varchar', Type::String
437 438 439 440
          m.alias_type 'char', 'varchar'
          m.alias_type 'name', 'varchar'
          m.alias_type 'bpchar', 'varchar'
          m.register_type 'bool', Type::Boolean.new
S
Sean Griffin 已提交
441 442
          register_class_with_limit m, 'bit', OID::Bit
          register_class_with_limit m, 'varbit', OID::BitVarying
443
          m.alias_type 'timestamptz', 'timestamp'
444
          m.register_type 'date', Type::Date.new
445 446 447 448 449

          m.register_type 'money', OID::Money.new
          m.register_type 'bytea', OID::Bytea.new
          m.register_type 'point', OID::Point.new
          m.register_type 'hstore', OID::Hstore.new
450
          m.register_type 'json', OID::Json.new
451
          m.register_type 'jsonb', OID::Jsonb.new
452 453 454
          m.register_type 'cidr', OID::Cidr.new
          m.register_type 'inet', OID::Inet.new
          m.register_type 'uuid', OID::Uuid.new
455
          m.register_type 'xml', OID::Xml.new
456 457 458 459 460 461 462 463 464 465 466 467 468 469
          m.register_type 'tsvector', OID::SpecializedString.new(:tsvector)
          m.register_type 'macaddr', OID::SpecializedString.new(:macaddr)
          m.register_type 'citext', OID::SpecializedString.new(:citext)
          m.register_type 'ltree', OID::SpecializedString.new(:ltree)

          # FIXME: why are we keeping these types as strings?
          m.alias_type 'interval', 'varchar'
          m.alias_type 'path', 'varchar'
          m.alias_type 'line', 'varchar'
          m.alias_type 'polygon', 'varchar'
          m.alias_type 'circle', 'varchar'
          m.alias_type 'lseg', 'varchar'
          m.alias_type 'box', 'varchar'

470 471
          register_class_with_precision m, 'time', Type::Time
          register_class_with_precision m, 'timestamp', OID::DateTime
S
Sean Griffin 已提交
472

473
          m.register_type 'numeric' do |_, fmod, sql_type|
S
Sean Griffin 已提交
474
            precision = extract_precision(sql_type)
S
Sean Griffin 已提交
475
            scale = extract_scale(sql_type)
S
Sean Griffin 已提交
476

477 478 479 480 481 482 483 484
            # The type for the numeric depends on the width of the field,
            # so we'll do something special here.
            #
            # When dealing with decimal columns:
            #
            # places after decimal  = fmod - 4 & 0xffff
            # places before decimal = (fmod - 4) >> 16 & 0xffff
            if fmod && (fmod - 4 & 0xffff).zero?
485 486
              # FIXME: Remove this class, and the second argument to
              # lookups on PG
487 488 489 490
              Type::DecimalWithoutScale.new(precision: precision)
            else
              OID::Decimal.new(precision: precision, scale: scale)
            end
S
Sean Griffin 已提交
491 492
          end

493 494 495
          load_additional_types(m)
        end

S
Sean Griffin 已提交
496 497
        def extract_limit(sql_type) # :nodoc:
          case sql_type
498 499 500 501 502 503
          when /^bigint/i, /^int8/i
            8
          when /^smallint/i
            2
          else
            super
S
Sean Griffin 已提交
504 505 506
          end
        end

507
        # Extracts the value from a PostgreSQL column default definition.
S
Sean Griffin 已提交
508
        def extract_value_from_default(default) # :nodoc:
509
          case default
510 511
            # Quoted types
            when /\A[\(B]?'(.*)'::/m
B
brainopia 已提交
512
              $1.gsub("''".freeze, "'".freeze)
513
            # Boolean types
B
brainopia 已提交
514
            when 'true'.freeze, 'false'.freeze
515
              default
516
            # Numeric types
517
            when /\A\(?(-?\d+(\.\d*)?)\)?(::bigint)?\z/
518 519 520 521 522 523 524 525 526 527 528
              $1
            # Object identifier types
            when /\A-?\d+\z/
              $1
            else
              # Anything else is blank, some user type, or some function
              # and we can't know the value of that, so return nil.
              nil
          end
        end

529
        def extract_default_function(default_value, default) # :nodoc:
530 531 532
          default if has_default_function?(default_value, default)
        end

533
        def has_default_function?(default_value, default) # :nodoc:
534 535 536
          !default_value && (%r{\w+\(.*\)} === default)
        end

537
        def load_additional_types(type_map, oids = nil) # :nodoc:
538 539
          initializer = OID::TypeMapInitializer.new(type_map)

540
          if supports_ranges?
541
            query = <<-SQL
542
              SELECT t.oid, t.typname, t.typelem, t.typdelim, t.typinput, r.rngsubtype, t.typtype, t.typbasetype
543 544 545 546
              FROM pg_type as t
              LEFT JOIN pg_range as r ON oid = rngtypid
            SQL
          else
547
            query = <<-SQL
548
              SELECT t.oid, t.typname, t.typelem, t.typdelim, t.typinput, t.typtype, t.typbasetype
549 550 551
              FROM pg_type as t
            SQL
          end
552 553 554

          if oids
            query += "WHERE t.oid::integer IN (%s)" % oids.join(", ")
555 556
          else
            query += initializer.query_conditions_for_initial_load(type_map)
557 558
          end

559 560 561
          execute_and_clear(query, 'SCHEMA', []) do |records|
            initializer.run(records)
          end
562 563
        end

564
        FEATURE_NOT_SUPPORTED = "0A000" #:nodoc:
565

566 567 568 569 570 571 572 573
        def execute_and_clear(sql, name, binds, prepare: false)
          if without_prepared_statement?(binds)
            result = exec_no_cache(sql, name, [])
          elsif !prepare
            result = exec_no_cache(sql, name, binds)
          else
            result = exec_cache(sql, name, binds)
          end
574 575 576 577 578
          ret = yield result
          result.clear
          ret
        end

579
        def exec_no_cache(sql, name, binds)
580 581
          type_casted_binds = binds.map { |attr| type_cast(attr.value_for_database) }
          log(sql, name, binds) { @connection.async_exec(sql, type_casted_binds) }
582
        end
583

584
        def exec_cache(sql, name, binds)
585
          stmt_key = prepare_statement(sql)
S
Sean Griffin 已提交
586
          type_casted_binds = binds.map { |attr| type_cast(attr.value_for_database) }
587

S
Sean Griffin 已提交
588 589
          log(sql, name, binds, stmt_key) do
            @connection.exec_prepared(stmt_key, type_casted_binds)
590 591
          end
        rescue ActiveRecord::StatementInvalid => e
592
          pgerror = e.cause
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607

          # Get the PG code for the failure.  Annoyingly, the code for
          # prepared statements whose return value may have changed is
          # FEATURE_NOT_SUPPORTED.  Check here for more details:
          # http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/cache/plancache.c#l573
          begin
            code = pgerror.result.result_error_field(PGresult::PG_DIAG_SQLSTATE)
          rescue
            raise e
          end
          if FEATURE_NOT_SUPPORTED == code
            @statements.delete sql_key(sql)
            retry
          else
            raise e
608 609 610 611 612 613 614 615 616 617 618 619 620
          end
        end

        # Returns the statement identifier for the client side cache
        # of statements
        def sql_key(sql)
          "#{schema_search_path}-#{sql}"
        end

        # Prepare the statement if it hasn't been prepared, return
        # the statement key.
        def prepare_statement(sql)
          sql_key = sql_key(sql)
621
          unless @statements.key? sql_key
622
            nextkey = @statements.next_key
623 624 625
            begin
              @connection.prepare nextkey, sql
            rescue => e
A
Aaron Patterson 已提交
626
              raise translate_exception_class(e, sql)
627
            end
628 629
            # Clear the queue
            @connection.get_last_result
630
            @statements[sql_key] = nextkey
631
          end
632
          @statements[sql_key]
633
        end
634

635 636 637
        # Connects to a PostgreSQL server and sets up the adapter depending on the
        # connected server's characteristics.
        def connect
638
          @connection = PGconn.connect(@connection_parameters)
639 640 641 642

          # Money type has a fixed precision of 10 in PostgreSQL 8.2 and below, and as of
          # PostgreSQL 8.3 it has a fixed precision of 19. PostgreSQLColumn.extract_precision
          # should know about this but can't detect it there, so deal with it here.
643
          OID::Money.precision = (postgresql_version >= 80300) ? 19 : 10
644

645
          configure_connection
646 647
        rescue ::PG::Error => error
          if error.message.include?("does not exist")
648
            raise ActiveRecord::NoDatabaseError
649
          else
650
            raise
651
          end
652 653
        end

654
        # Configures the encoding, verbosity, schema search path, and time zone of the connection.
655
        # This is called by #connect and should not be called manually.
656 657
        def configure_connection
          if @config[:encoding]
658
            @connection.set_client_encoding(@config[:encoding])
659
          end
660
          self.client_min_messages = @config[:min_messages] || 'warning'
661
          self.schema_search_path = @config[:schema_search_path] || @config[:schema_order]
662

663
          # Use standard-conforming strings so we don't have to do the E'...' dance.
664 665
          set_standard_conforming_strings

666
          # If using Active Record's time zone support configure the connection to return
667
          # TIMESTAMP WITH ZONE types in UTC.
668
          # (SET TIME ZONE does not use an equals sign like other SET variables)
669
          if ActiveRecord::Base.default_timezone == :utc
670
            execute("SET time zone 'UTC'", 'SCHEMA')
671
          elsif @local_tz
672
            execute("SET time zone '#{@local_tz}'", 'SCHEMA')
673
          end
674 675

          # SET statements from :variables config hash
676
          # http://www.postgresql.org/docs/current/static/sql-set.html
677 678 679 680
          variables = @config[:variables] || {}
          variables.map do |k, v|
            if v == ':default' || v == :default
              # Sets the value to the global or compile default
681
              execute("SET SESSION #{k} TO DEFAULT", 'SCHEMA')
682
            elsif !v.nil?
683
              execute("SET SESSION #{k} TO #{quote(v)}", 'SCHEMA')
684 685
            end
          end
686 687
        end

688
        # Returns the current ID of a table's sequence.
689
        def last_insert_id(sequence_name) #:nodoc:
690 691 692
          Integer(last_insert_id_value(sequence_name))
        end

D
Doug Cole 已提交
693 694 695 696 697
        def last_insert_id_value(sequence_name)
          last_insert_id_result(sequence_name).rows.first.first
        end

        def last_insert_id_result(sequence_name) #:nodoc:
698
          exec_query("SELECT currval('#{sequence_name}')", 'SQL')
D
Initial  
David Heinemeier Hansson 已提交
699 700
        end

701
        # Returns the list of a table's column names, data types, and default values.
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
        #
        # The underlying query is roughly:
        #  SELECT column.name, column.type, default.value
        #    FROM column LEFT JOIN default
        #      ON column.table_id = default.table_id
        #     AND column.num = default.column_num
        #   WHERE column.table_id = get_table_id('table_name')
        #     AND column.num > 0
        #     AND NOT column.is_dropped
        #   ORDER BY column.num
        #
        # If the table name is not prefixed with a schema, the database will
        # take the first match from the schema search path.
        #
        # Query implementation notes:
        #  - format_type includes the column size constraint, e.g. varchar(50)
        #  - ::regclass is a function that gives the id for a table name
719
        def column_definitions(table_name) # :nodoc:
720
          query(<<-end_sql, 'SCHEMA')
721
              SELECT a.attname, format_type(a.atttypid, a.atttypmod),
722 723 724
                     pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod,
             (SELECT c.collname FROM pg_collation c, pg_type t
               WHERE c.oid = a.attcollation AND t.oid = a.atttypid AND a.attcollation <> t.typcollation)
725 726 727 728 729
                FROM pg_attribute a LEFT JOIN pg_attrdef d
                  ON a.attrelid = d.adrelid AND a.attnum = d.adnum
               WHERE a.attrelid = '#{quote_table_name(table_name)}'::regclass
                 AND a.attnum > 0 AND NOT a.attisdropped
               ORDER BY a.attnum
730
          end_sql
D
Initial  
David Heinemeier Hansson 已提交
731
        end
732

733
        def extract_table_ref_from_insert_sql(sql) # :nodoc:
734
          sql[/into\s("[A-Za-z0-9_."\[\]\s]+"|[A-Za-z0-9_."\[\]]+)\s*/im]
735 736 737
          $1.strip if $1
        end

738
        def create_table_definition(name, temporary = false, options = nil, as = nil) # :nodoc:
739
          PostgreSQL::TableDefinition.new native_database_types, name, temporary, options, as
740
        end
S
Sean Griffin 已提交
741 742 743 744 745 746 747 748 749 750 751 752 753 754

        def can_perform_case_insensitive_comparison_for?(column)
          @case_insensitive_cache ||= {}
          @case_insensitive_cache[column.sql_type] ||= begin
            sql = <<-end_sql
              SELECT exists(
                SELECT * FROM pg_proc
                INNER JOIN pg_cast
                  ON casttarget::text::oidvector = proargtypes
                WHERE proname = 'lower'
                  AND castsource = '#{column.sql_type}'::regtype::oid
              )
            end_sql
            execute_and_clear(sql, "SCHEMA", []) do |result|
755
              result.getvalue(0, 0)
S
Sean Griffin 已提交
756 757 758
            end
          end
        end
759

760 761 762 763 764 765 766 767 768
        def add_pg_encoders
          map = PG::TypeMapByClass.new
          map[Integer] = PG::TextEncoder::Integer.new
          map[TrueClass] = PG::TextEncoder::Boolean.new
          map[FalseClass] = PG::TextEncoder::Boolean.new
          map[Float] = PG::TextEncoder::Float.new
          @connection.type_map_for_queries = map
        end

769 770 771 772 773 774 775 776 777 778
        def add_pg_decoders
          coders_by_name = {
            'int2' => PG::TextDecoder::Integer,
            'int4' => PG::TextDecoder::Integer,
            'int8' => PG::TextDecoder::Integer,
            'oid' => PG::TextDecoder::Integer,
            'float4' => PG::TextDecoder::Float,
            'float8' => PG::TextDecoder::Float,
            'bool' => PG::TextDecoder::Boolean,
          }
779 780
          known_coder_types = coders_by_name.keys.map { |n| quote(n) }
          query = <<-SQL % known_coder_types.join(", ")
781
            SELECT t.oid, t.typname
782
            FROM pg_type as t
783
            WHERE t.typname IN (%s)
784 785 786
          SQL
          coders = execute_and_clear(query, "SCHEMA", []) do |result|
            result
787
              .map { |row| construct_coder(row, coders_by_name[row['typname']]) }
788 789 790 791 792 793 794 795 796 797
              .compact
          end

          map = PG::TypeMapByOid.new
          coders.each { |coder| map.add_coder(coder) }
          @connection.type_map_for_results = map
        end

        def construct_coder(row, coder_class)
          return unless coder_class
798
          coder_class.new(oid: row['oid'].to_i, name: row['typname'])
799
        end
800 801 802 803 804 805 806 807 808 809 810 811

        ActiveRecord::Type.add_modifier({ array: true }, OID::Array, adapter: :postgresql)
        ActiveRecord::Type.add_modifier({ range: true }, OID::Range, adapter: :postgresql)
        ActiveRecord::Type.register(:bit, OID::Bit, adapter: :postgresql)
        ActiveRecord::Type.register(:bit_varying, OID::BitVarying, adapter: :postgresql)
        ActiveRecord::Type.register(:binary, OID::Bytea, adapter: :postgresql)
        ActiveRecord::Type.register(:cidr, OID::Cidr, adapter: :postgresql)
        ActiveRecord::Type.register(:date_time, OID::DateTime, adapter: :postgresql)
        ActiveRecord::Type.register(:decimal, OID::Decimal, adapter: :postgresql)
        ActiveRecord::Type.register(:enum, OID::Enum, adapter: :postgresql)
        ActiveRecord::Type.register(:hstore, OID::Hstore, adapter: :postgresql)
        ActiveRecord::Type.register(:inet, OID::Inet, adapter: :postgresql)
812
        ActiveRecord::Type.register(:json, OID::Json, adapter: :postgresql)
813 814 815
        ActiveRecord::Type.register(:jsonb, OID::Jsonb, adapter: :postgresql)
        ActiveRecord::Type.register(:money, OID::Money, adapter: :postgresql)
        ActiveRecord::Type.register(:point, OID::Point, adapter: :postgresql)
816 817
        ActiveRecord::Type.register(:legacy_point, OID::Point, adapter: :postgresql)
        ActiveRecord::Type.register(:rails_5_1_point, OID::Rails51Point, adapter: :postgresql)
818 819 820
        ActiveRecord::Type.register(:uuid, OID::Uuid, adapter: :postgresql)
        ActiveRecord::Type.register(:vector, OID::Vector, adapter: :postgresql)
        ActiveRecord::Type.register(:xml, OID::Xml, adapter: :postgresql)
D
Initial  
David Heinemeier Hansson 已提交
821 822 823
    end
  end
end