postgresql_adapter.rb 30.4 KB
Newer Older
1 2
# frozen_string_literal: true

3
# Make sure we're using pg high enough for type casts and Ruby 2.2+ compatibility
4 5
gem "pg", "~> 0.18"
require "pg"
6

7 8 9 10 11 12 13 14 15 16 17 18 19 20
require "active_record/connection_adapters/abstract_adapter"
require "active_record/connection_adapters/statement_pool"
require "active_record/connection_adapters/postgresql/column"
require "active_record/connection_adapters/postgresql/database_statements"
require "active_record/connection_adapters/postgresql/explain_pretty_printer"
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_creation"
require "active_record/connection_adapters/postgresql/schema_definitions"
require "active_record/connection_adapters/postgresql/schema_dumper"
require "active_record/connection_adapters/postgresql/schema_statements"
require "active_record/connection_adapters/postgresql/type_metadata"
require "active_record/connection_adapters/postgresql/utils"
21

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

28
      conn_params.delete_if { |_, v| v.nil? }
29 30 31 32

      # 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 已提交
33

34 35
      # Forward only valid config params to PG::Connection.connect.
      valid_conn_param_keys = PG::Connection.conndefaults_hash.keys + [:requiressl]
36
      conn_params.slice!(*valid_conn_param_keys)
37

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

44
  module ConnectionAdapters
45
    # The PostgreSQL adapter works with the native C (https://bitbucket.org/ged/ruby-pg) driver.
46 47 48
    #
    # Options:
    #
49 50
    # * <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 已提交
51
    # * <tt>:port</tt> - Defaults to 5432.
52 53 54
    # * <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.
55
    # * <tt>:schema_search_path</tt> - An optional schema search path for the connection given
56
    #   as a string of comma-separated schema names. This is backward-compatible with the <tt>:schema_order</tt> option.
57
    # * <tt>:encoding</tt> - An optional client encoding that is used in a <tt>SET client_encoding TO
58
    #   <encoding></tt> call on the connection.
59
    # * <tt>:min_messages</tt> - An optional client min messages that is used in a
60
    #   <tt>SET client_min_messages TO <min_messages></tt> call on the connection.
61 62
    # * <tt>:variables</tt> - An optional hash of additional parameters that
    #   will be used in <tt>SET SESSION key = val</tt> calls on the connection.
63
    # * <tt>:insert_returning</tt> - An optional boolean to control the use of <tt>RETURNING</tt> for <tt>INSERT</tt> statements
64
    #   defaults to true.
65 66
    #
    # Any further options are used as connection parameters to libpq. See
67
    # https://www.postgresql.org/docs/current/static/libpq-connect.html for the
68 69 70
    # list of parameters.
    #
    # In addition, default connection parameters of libpq can be set per environment variables.
71
    # See https://www.postgresql.org/docs/current/static/libpq-envars.html .
72
    class PostgreSQLAdapter < AbstractAdapter
73
      ADAPTER_NAME = "PostgreSQL".freeze
74 75

      NATIVE_DATABASE_TYPES = {
76
        primary_key: "bigserial primary key",
77
        string:      { name: "character varying" },
78
        text:        { name: "text" },
79
        integer:     { name: "integer", limit: 4 },
80 81 82 83 84
        float:       { name: "float" },
        decimal:     { name: "decimal" },
        datetime:    { name: "timestamp" },
        time:        { name: "time" },
        date:        { name: "date" },
B
bUg 已提交
85 86 87 88 89 90
        daterange:   { name: "daterange" },
        numrange:    { name: "numrange" },
        tsrange:     { name: "tsrange" },
        tstzrange:   { name: "tstzrange" },
        int4range:   { name: "int4range" },
        int8range:   { name: "int8range" },
91 92 93 94 95 96 97 98
        binary:      { name: "bytea" },
        boolean:     { name: "boolean" },
        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
        point:       { name: "point" },
105 106 107 108 109 110
        line:        { name: "line" },
        lseg:        { name: "lseg" },
        box:         { name: "box" },
        path:        { name: "path" },
        polygon:     { name: "polygon" },
        circle:      { name: "circle" },
S
Sean Griffin 已提交
111 112
        bit:         { name: "bit" },
        bit_varying: { name: "bit varying" },
113
        money:       { name: "money" },
114
        interval:    { name: "interval" },
115
        oid:         { name: "oid" },
116 117
      }

118 119 120 121
      OID = PostgreSQL::OID #:nodoc:

      include PostgreSQL::Quoting
      include PostgreSQL::ReferentialIntegrity
122
      include PostgreSQL::SchemaStatements
123
      include PostgreSQL::DatabaseStatements
124

125 126 127 128
      def supports_index_sort_order?
        true
      end

129 130 131 132
      def supports_partial_index?
        true
      end

133 134 135 136
      def supports_expression_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 supports_comments?
        true
      end

161 162 163 164
      def supports_savepoints?
        true
      end

165
      def index_algorithms
166
        { concurrently: "CONCURRENTLY" }
167 168
      end

169 170
      class StatementPool < ConnectionAdapters::StatementPool
        def initialize(connection, max)
171 172
          super(max)
          @connection = connection
173 174 175 176 177 178 179 180
          @counter = 0
        end

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

        def []=(sql, key)
181
          super.tap { @counter += 1 }
182 183
        end

184
        private
185

186 187
          def dealloc(key)
            @connection.query "DEALLOCATE #{key}" if connection_active?
188
          rescue PG::Error
189 190 191
          end

          def connection_active?
192 193
            @connection.status == PG::CONNECTION_OK
          rescue PG::Error
194 195
            false
          end
196 197
      end

198 199
      # Initializes and connects a PostgreSQL adapter.
      def initialize(connection, logger, connection_parameters, config)
200
        super(connection, logger, config)
201

202
        @connection_parameters = connection_parameters
203

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

208
        connect
209
        add_pg_encoders
210
        @statements = StatementPool.new @connection,
V
Vipul A M 已提交
211
                                        self.class.type_cast_config_to_integer(config[:statement_limit])
212

213
        if postgresql_version < 90100
214
          raise "Your version of PostgreSQL (#{postgresql_version}) is too old. Active Record supports PostgreSQL >= 9.1."
215 216
        end

217 218
        add_pg_decoders

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

X
Xavier Noria 已提交
225
      # Clears the prepared statements cache.
226
      def clear_cache!
227 228 229
        @lock.synchronize do
          @statements.clear
        end
230 231
      end

232 233 234 235
      def truncate(table_name, name = nil)
        exec_query "TRUNCATE TABLE #{quote_table_name(table_name)}", name, []
      end

236 237
      # Is this connection alive and ready for queries?
      def active?
238 239 240
        @lock.synchronize do
          @connection.query "SELECT 1"
        end
241
        true
242
      rescue PG::Error
243
        false
244 245 246 247
      end

      # Close then reopen the connection.
      def reconnect!
248 249 250 251 252
        @lock.synchronize do
          super
          @connection.reset
          configure_connection
        end
253
      end
254

255
      def reset!
256 257 258 259 260 261 262 263
        @lock.synchronize do
          clear_cache!
          reset_transaction
          unless @connection.transaction_status == ::PG::PQTRANS_IDLE
            @connection.query "ROLLBACK"
          end
          @connection.query "DISCARD ALL"
          configure_connection
264
        end
265 266
      end

267 268
      # Disconnects from the database if already connected. Otherwise, this
      # method does nothing.
269
      def disconnect!
270 271 272 273
        @lock.synchronize do
          super
          @connection.close rescue nil
        end
274
      end
275

M
Matthew Draper 已提交
276 277 278 279 280
      def discard! # :nodoc:
        @connection.socket_io.reopen(IO::NULL)
        @connection = nil
      end

281
      def native_database_types #:nodoc:
282
        NATIVE_DATABASE_TYPES
283
      end
284

285
      def set_standard_conforming_strings
286
        execute("SET standard_conforming_strings = on", "SCHEMA")
287 288
      end

289 290 291
      def supports_ddl_transactions?
        true
      end
292

293 294 295 296
      def supports_advisory_locks?
        true
      end

297 298 299 300
      def supports_explain?
        true
      end

301
      def supports_extensions?
302
        true
303 304
      end

A
Andrew White 已提交
305
      def supports_ranges?
306
        # Range datatypes weren't introduced until PostgreSQL 9.2
A
Andrew White 已提交
307 308 309
        postgresql_version >= 90200
      end

310 311 312 313
      def supports_materialized_views?
        postgresql_version >= 90300
      end

314 315 316 317
      def supports_pgcrypto_uuid?
        postgresql_version >= 90400
      end

318 319
      def get_advisory_lock(lock_id) # :nodoc:
        unless lock_id.is_a?(Integer) && lock_id.bit_length <= 63
320
          raise(ArgumentError, "PostgreSQL requires advisory lock ids to be a signed 64 bit integer")
321
        end
322
        query_value("SELECT pg_try_advisory_lock(#{lock_id})")
323 324
      end

325 326
      def release_advisory_lock(lock_id) # :nodoc:
        unless lock_id.is_a?(Integer) && lock_id.bit_length <= 63
327
          raise(ArgumentError, "PostgreSQL requires advisory lock ids to be a signed 64 bit integer")
328
        end
329
        query_value("SELECT pg_advisory_unlock(#{lock_id})")
330 331
      end

332
      def enable_extension(name)
333
        exec_query("CREATE EXTENSION IF NOT EXISTS \"#{name}\"").tap {
334 335
          reload_type_map
        }
336 337 338
      end

      def disable_extension(name)
339
        exec_query("DROP EXTENSION IF EXISTS \"#{name}\" CASCADE").tap {
340 341
          reload_type_map
        }
342 343 344
      end

      def extension_enabled?(name)
345 346
        res = exec_query("SELECT EXISTS(SELECT * FROM pg_available_extensions WHERE name = '#{name}' AND installed_version IS NOT NULL) as enabled", "SCHEMA")
        res.cast_values.first
347 348
      end

349
      def extensions
350
        exec_query("SELECT extname FROM pg_extension", "SCHEMA").cast_values
351 352
      end

353
      # Returns the configured supported identifier length supported by PostgreSQL
354
      def max_identifier_length
355
        @max_identifier_length ||= query_value("SHOW max_identifier_length", "SCHEMA").to_i
356
      end
357 358
      alias table_alias_length max_identifier_length
      alias index_name_length max_identifier_length
359

360 361
      # Set the authorized user for this session
      def session_auth=(user)
362
        clear_cache!
363
        execute("SET SESSION AUTHORIZATION #{user}")
364 365
      end

366 367
      def use_insert_returning?
        @use_insert_returning
368 369
      end

370 371 372 373 374 375 376 377 378 379
      def column_name_for_operation(operation, node) # :nodoc:
        OPERATION_ALIASES.fetch(operation) { operation.downcase }
      end

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

D
Derek Prior 已提交
380 381 382 383
      # Returns the version of the connected PostgreSQL server.
      def postgresql_version
        @connection.server_version
      end
384

385 386 387 388
      def default_index_type?(index) # :nodoc:
        index.using == :btree || super
      end

389
      private
390

391
        # See https://www.postgresql.org/docs/current/static/errcodes-appendix.html
392
        VALUE_LIMIT_VIOLATION = "22001"
393
        NUMERIC_VALUE_OUT_OF_RANGE = "22003"
394
        NOT_NULL_VIOLATION    = "23502"
395 396
        FOREIGN_KEY_VIOLATION = "23503"
        UNIQUE_VIOLATION      = "23505"
397
        SERIALIZATION_FAILURE = "40001"
398
        DEADLOCK_DETECTED     = "40P01"
399
        LOCK_NOT_AVAILABLE    = "55P03"
400
        QUERY_CANCELED        = "57014"
401

402
        def translate_exception(exception, message)
403 404
          return exception unless exception.respond_to?(:result)

405
          case exception.result.try(:error_field, PG::PG_DIAG_SQLSTATE)
406
          when UNIQUE_VIOLATION
407
            RecordNotUnique.new(message)
408
          when FOREIGN_KEY_VIOLATION
409
            InvalidForeignKey.new(message)
410 411
          when VALUE_LIMIT_VIOLATION
            ValueTooLong.new(message)
412 413
          when NUMERIC_VALUE_OUT_OF_RANGE
            RangeError.new(message)
414 415
          when NOT_NULL_VIOLATION
            NotNullViolation.new(message)
416
          when SERIALIZATION_FAILURE
417
            SerializationFailure.new(message)
418
          when DEADLOCK_DETECTED
419
            Deadlocked.new(message)
420 421
          when LOCK_NOT_AVAILABLE
            TransactionTimeout.new(message)
422 423
          when QUERY_CANCELED
            StatementTimeout.new(message)
424 425 426 427 428
          else
            super
          end
        end

429
        def get_oid_type(oid, fmod, column_name, sql_type = "".freeze)
430
          if !type_map.key?(oid)
431
            load_additional_types([oid])
432 433
          end

434 435
          type_map.fetch(oid, fmod, sql_type) {
            warn "unknown OID #{oid}: failed to recognize type of '#{column_name}'. It will be treated as String."
436
            Type.default_value.tap do |cast_type|
437 438 439
              type_map.register_type(oid, cast_type)
            end
          }
440 441
        end

442
        def initialize_type_map(m = type_map)
443 444 445
          m.register_type "int2", Type::Integer.new(limit: 2)
          m.register_type "int4", Type::Integer.new(limit: 4)
          m.register_type "int8", Type::Integer.new(limit: 8)
446
          m.register_type "oid", OID::Oid.new
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
          m.register_type "float4", Type::Float.new
          m.alias_type "float8", "float4"
          m.register_type "text", Type::Text.new
          register_class_with_limit m, "varchar", Type::String
          m.alias_type "char", "varchar"
          m.alias_type "name", "varchar"
          m.alias_type "bpchar", "varchar"
          m.register_type "bool", Type::Boolean.new
          register_class_with_limit m, "bit", OID::Bit
          register_class_with_limit m, "varbit", OID::BitVarying
          m.alias_type "timestamptz", "timestamp"
          m.register_type "date", Type::Date.new

          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
464
          m.register_type "json", Type::Json.new
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
          m.register_type "jsonb", OID::Jsonb.new
          m.register_type "cidr", OID::Cidr.new
          m.register_type "inet", OID::Inet.new
          m.register_type "uuid", OID::Uuid.new
          m.register_type "xml", OID::Xml.new
          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)
          m.register_type "line", OID::SpecializedString.new(:line)
          m.register_type "lseg", OID::SpecializedString.new(:lseg)
          m.register_type "box", OID::SpecializedString.new(:box)
          m.register_type "path", OID::SpecializedString.new(:path)
          m.register_type "polygon", OID::SpecializedString.new(:polygon)
          m.register_type "circle", OID::SpecializedString.new(:circle)
480

481 482 483 484
          m.register_type "interval" do |_, _, sql_type|
            precision = extract_precision(sql_type)
            OID::SpecializedString.new(:interval, precision: precision)
          end
485

486 487
          register_class_with_precision m, "time", Type::Time
          register_class_with_precision m, "timestamp", OID::DateTime
S
Sean Griffin 已提交
488

489
          m.register_type "numeric" do |_, fmod, sql_type|
S
Sean Griffin 已提交
490
            precision = extract_precision(sql_type)
S
Sean Griffin 已提交
491
            scale = extract_scale(sql_type)
S
Sean Griffin 已提交
492

493 494 495 496 497 498 499 500
            # 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?
501 502
              # FIXME: Remove this class, and the second argument to
              # lookups on PG
503 504 505 506
              Type::DecimalWithoutScale.new(precision: precision)
            else
              OID::Decimal.new(precision: precision, scale: scale)
            end
S
Sean Griffin 已提交
507 508
          end

509
          load_additional_types
510
        end
S
Sean Griffin 已提交
511

512
        # Extracts the value from a PostgreSQL column default definition.
A
Akira Matsuda 已提交
513
        def extract_value_from_default(default)
514
          case default
515
            # Quoted types
516
          when /\A[\(B]?'(.*)'.*::"?([\w. ]+)"?(?:\[\])?\z/m
517
            # The default 'now'::date is CURRENT_DATE
518 519 520 521 522
            if $1 == "now".freeze && $2 == "date".freeze
              nil
            else
              $1.gsub("''".freeze, "'".freeze)
            end
523
            # Boolean types
524 525
          when "true".freeze, "false".freeze
            default
526
            # Numeric types
527 528
          when /\A\(?(-?\d+(\.\d*)?)\)?(::bigint)?\z/
            $1
529
            # Object identifier types
530 531
          when /\A-?\d+\z/
            $1
532 533 534
          else
            # Anything else is blank, some user type, or some function
            # and we can't know the value of that, so return nil.
535
            nil
536 537 538
          end
        end

A
Akira Matsuda 已提交
539
        def extract_default_function(default_value, default)
540 541 542
          default if has_default_function?(default_value, default)
        end

A
Akira Matsuda 已提交
543
        def has_default_function?(default_value, default)
544
          !default_value && %r{\w+\(.*\)|\(.*\)::\w+|CURRENT_DATE|CURRENT_TIMESTAMP}.match?(default)
545 546
        end

547
        def load_additional_types(oids = nil)
548 549
          initializer = OID::TypeMapInitializer.new(type_map)

550
          if supports_ranges?
551
            query = <<-SQL
552
              SELECT t.oid, t.typname, t.typelem, t.typdelim, t.typinput, r.rngsubtype, t.typtype, t.typbasetype
553 554 555 556
              FROM pg_type as t
              LEFT JOIN pg_range as r ON oid = rngtypid
            SQL
          else
557
            query = <<-SQL
558
              SELECT t.oid, t.typname, t.typelem, t.typdelim, t.typinput, t.typtype, t.typbasetype
559 560 561
              FROM pg_type as t
            SQL
          end
562 563 564

          if oids
            query += "WHERE t.oid::integer IN (%s)" % oids.join(", ")
565
          else
566
            query += initializer.query_conditions_for_initial_load
567 568
          end

569
          execute_and_clear(query, "SCHEMA", []) do |records|
570 571
            initializer.run(records)
          end
572 573
        end

574
        FEATURE_NOT_SUPPORTED = "0A000" #:nodoc:
575

576 577 578 579 580 581 582 583
        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
584 585 586 587 588
          ret = yield result
          result.clear
          ret
        end

589
        def exec_no_cache(sql, name, binds)
590
          type_casted_binds = type_casted_binds(binds)
591 592 593 594 595
          log(sql, name, binds, type_casted_binds) do
            ActiveSupport::Dependencies.interlock.permit_concurrent_loads do
              @connection.async_exec(sql, type_casted_binds)
            end
          end
596
        end
597

598
        def exec_cache(sql, name, binds)
599
          stmt_key = prepare_statement(sql)
600
          type_casted_binds = type_casted_binds(binds)
601

602
          log(sql, name, binds, type_casted_binds, stmt_key) do
603 604 605
            ActiveSupport::Dependencies.interlock.permit_concurrent_loads do
              @connection.exec_prepared(stmt_key, type_casted_binds)
            end
606 607
          end
        rescue ActiveRecord::StatementInvalid => e
608
          raise unless is_cached_plan_failure?(e)
609

610 611 612 613 614
          # Nothing we can do if we are in a transaction because all commands
          # will raise InFailedSQLTransaction
          if in_transaction?
            raise ActiveRecord::PreparedStatementCacheExpired.new(e.cause.message)
          else
615 616 617 618
            @lock.synchronize do
              # outside of transactions we can simply flush this query and retry
              @statements.delete sql_key(sql)
            end
619
            retry
620 621 622
          end
        end

623 624 625 626 627 628 629 630
        # Annoyingly, the code for prepared statements whose return value may
        # have changed is FEATURE_NOT_SUPPORTED.
        #
        # This covers various different error types so we need to do additional
        # work to classify the exception definitively as a
        # ActiveRecord::PreparedStatementCacheExpired
        #
        # Check here for more details:
631
        # https://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/cache/plancache.c#l573
632
        CACHED_PLAN_HEURISTIC = "cached plan must not change result type".freeze
633 634
        def is_cached_plan_failure?(e)
          pgerror = e.cause
635
          code = pgerror.result.result_error_field(PG::PG_DIAG_SQLSTATE)
636 637 638 639 640 641 642 643 644
          code == FEATURE_NOT_SUPPORTED && pgerror.message.include?(CACHED_PLAN_HEURISTIC)
        rescue
          false
        end

        def in_transaction?
          open_transactions > 0
        end

645 646 647 648 649 650 651 652 653
        # 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)
654 655 656 657 658 659 660 661 662 663 664 665
          @lock.synchronize do
            sql_key = sql_key(sql)
            unless @statements.key? sql_key
              nextkey = @statements.next_key
              begin
                @connection.prepare nextkey, sql
              rescue => e
                raise translate_exception_class(e, sql)
              end
              # Clear the queue
              @connection.get_last_result
              @statements[sql_key] = nextkey
666
            end
667
            @statements[sql_key]
668 669
          end
        end
670

671 672 673
        # Connects to a PostgreSQL server and sets up the adapter depending on the
        # connected server's characteristics.
        def connect
674
          @connection = PG.connect(@connection_parameters)
675
          configure_connection
676 677
        rescue ::PG::Error => error
          if error.message.include?("does not exist")
678
            raise ActiveRecord::NoDatabaseError
679
          else
680
            raise
681
          end
682 683
        end

684
        # Configures the encoding, verbosity, schema search path, and time zone of the connection.
685
        # This is called by #connect and should not be called manually.
686 687
        def configure_connection
          if @config[:encoding]
688
            @connection.set_client_encoding(@config[:encoding])
689
          end
690
          self.client_min_messages = @config[:min_messages] || "warning"
691
          self.schema_search_path = @config[:schema_search_path] || @config[:schema_order]
692

693
          # Use standard-conforming strings so we don't have to do the E'...' dance.
694 695
          set_standard_conforming_strings

696 697
          variables = @config.fetch(:variables, {}).stringify_keys

698
          # If using Active Record's time zone support configure the connection to return
699
          # TIMESTAMP WITH ZONE types in UTC.
700 701 702 703 704 705
          unless variables["timezone"]
            if ActiveRecord::Base.default_timezone == :utc
              variables["timezone"] = "UTC"
            elsif @local_tz
              variables["timezone"] = @local_tz
            end
706
          end
707 708

          # SET statements from :variables config hash
709
          # https://www.postgresql.org/docs/current/static/sql-set.html
710
          variables.map do |k, v|
711
            if v == ":default" || v == :default
712
              # Sets the value to the global or compile default
713
              execute("SET SESSION #{k} TO DEFAULT", "SCHEMA")
714
            elsif !v.nil?
715
              execute("SET SESSION #{k} TO #{quote(v)}", "SCHEMA")
716 717
            end
          end
718 719
        end

720
        # Returns the list of a table's column names, data types, and default values.
721 722
        #
        # The underlying query is roughly:
723
        #  SELECT column.name, column.type, default.value, column.comment
724 725 726 727 728 729 730 731 732 733 734 735 736 737
        #    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
A
Akira Matsuda 已提交
738
        def column_definitions(table_name)
739
          query(<<-end_sql, "SCHEMA")
740
              SELECT a.attname, format_type(a.atttypid, a.atttypmod),
741
                     pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod,
742 743 744 745 746
                     c.collname, col_description(a.attrelid, a.attnum) AS comment
                FROM pg_attribute a
                LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum
                LEFT JOIN pg_type t ON a.atttypid = t.oid
                LEFT JOIN pg_collation c ON a.attcollation = c.oid AND a.attcollation <> t.typcollation
R
Ryuta Kamizono 已提交
747
               WHERE a.attrelid = #{quote(quote_table_name(table_name))}::regclass
748 749
                 AND a.attnum > 0 AND NOT a.attisdropped
               ORDER BY a.attnum
750
          end_sql
D
Initial  
David Heinemeier Hansson 已提交
751
        end
752

A
Akira Matsuda 已提交
753
        def extract_table_ref_from_insert_sql(sql)
754
          sql[/into\s("[A-Za-z0-9_."\[\]\s]+"|[A-Za-z0-9_."\[\]]+)\s*/im]
755 756 757
          $1.strip if $1
        end

758 759
        def arel_visitor
          Arel::Visitors::PostgreSQL.new(self)
760
        end
S
Sean Griffin 已提交
761 762 763 764 765 766

        def can_perform_case_insensitive_comparison_for?(column)
          @case_insensitive_cache ||= {}
          @case_insensitive_cache[column.sql_type] ||= begin
            sql = <<-end_sql
              SELECT exists(
767 768 769 770
                SELECT * FROM pg_proc
                WHERE proname = 'lower'
                  AND proargtypes = ARRAY[#{quote column.sql_type}::regtype]::oidvector
              ) OR exists(
S
Sean Griffin 已提交
771 772
                SELECT * FROM pg_proc
                INNER JOIN pg_cast
N
nanaya 已提交
773
                  ON ARRAY[casttarget]::oidvector = proargtypes
S
Sean Griffin 已提交
774
                WHERE proname = 'lower'
N
nanaya 已提交
775
                  AND castsource = #{quote column.sql_type}::regtype
S
Sean Griffin 已提交
776 777 778
              )
            end_sql
            execute_and_clear(sql, "SCHEMA", []) do |result|
779
              result.getvalue(0, 0)
S
Sean Griffin 已提交
780 781 782
            end
          end
        end
783

784 785 786 787 788 789 790 791
        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
          @connection.type_map_for_queries = map
        end

792 793
        def add_pg_decoders
          coders_by_name = {
794 795 796 797 798 799 800
            "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,
801
          }
802 803
          known_coder_types = coders_by_name.keys.map { |n| quote(n) }
          query = <<-SQL % known_coder_types.join(", ")
804
            SELECT t.oid, t.typname
805
            FROM pg_type as t
806
            WHERE t.typname IN (%s)
807 808 809
          SQL
          coders = execute_and_clear(query, "SCHEMA", []) do |result|
            result
810
              .map { |row| construct_coder(row, coders_by_name[row["typname"]]) }
811 812 813 814 815 816 817 818 819 820
              .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
821
          coder_class.new(oid: row["oid"].to_i, name: row["typname"])
822
        end
823 824 825 826 827 828 829

        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)
Y
yuuji.yaginuma 已提交
830
        ActiveRecord::Type.register(:datetime, OID::DateTime, adapter: :postgresql)
831 832 833 834 835 836
        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)
        ActiveRecord::Type.register(:jsonb, OID::Jsonb, adapter: :postgresql)
        ActiveRecord::Type.register(:money, OID::Money, adapter: :postgresql)
837 838
        ActiveRecord::Type.register(:point, OID::Point, adapter: :postgresql)
        ActiveRecord::Type.register(:legacy_point, OID::LegacyPoint, adapter: :postgresql)
839 840 841
        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 已提交
842 843 844
    end
  end
end