postgresql_adapter.rb 30.1 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_relative "abstract_adapter"
require_relative "statement_pool"
require_relative "postgresql/column"
require_relative "postgresql/database_statements"
require_relative "postgresql/explain_pretty_printer"
require_relative "postgresql/oid"
require_relative "postgresql/quoting"
require_relative "postgresql/referential_integrity"
require_relative "postgresql/schema_creation"
require_relative "postgresql/schema_definitions"
require_relative "postgresql/schema_dumper"
require_relative "postgresql/schema_statements"
require_relative "postgresql/type_metadata"
require_relative "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
    # http://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 http://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 79 80 81 82 83 84
        text:        { name: "text" },
        integer:     { name: "integer" },
        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
      include PostgreSQL::ColumnDumper
125

126 127 128 129
      def supports_index_sort_order?
        true
      end

130 131 132 133
      def supports_partial_index?
        true
      end

134 135 136 137
      def supports_expression_index?
        true
      end

138 139 140 141
      def supports_transaction_isolation?
        true
      end

142 143 144 145
      def supports_foreign_keys?
        true
      end

146 147 148 149
      def supports_views?
        true
      end

150 151 152 153
      def supports_datetime_with_precision?
        true
      end

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

158 159 160 161
      def supports_comments?
        true
      end

162 163 164 165
      def supports_savepoints?
        true
      end

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

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

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

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

185
        private
186

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

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

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

203
        @connection_parameters = connection_parameters
204

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

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

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

218 219
        add_pg_decoders

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

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

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

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

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

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

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

277
      def native_database_types #:nodoc:
278
        NATIVE_DATABASE_TYPES
279
      end
280

281
      def set_standard_conforming_strings
282
        execute("SET standard_conforming_strings = on", "SCHEMA")
283 284
      end

285 286 287
      def supports_ddl_transactions?
        true
      end
288

289 290 291 292
      def supports_advisory_locks?
        true
      end

293 294 295 296
      def supports_explain?
        true
      end

297
      def supports_extensions?
298
        true
299 300
      end

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

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

310 311 312 313
      def supports_pgcrypto_uuid?
        postgresql_version >= 90400
      end

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

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

328
      def enable_extension(name)
329
        exec_query("CREATE EXTENSION IF NOT EXISTS \"#{name}\"").tap {
330 331
          reload_type_map
        }
332 333 334
      end

      def disable_extension(name)
335
        exec_query("DROP EXTENSION IF EXISTS \"#{name}\" CASCADE").tap {
336 337
          reload_type_map
        }
338 339 340
      end

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

347 348
      def extensions
        if supports_extensions?
349
          exec_query("SELECT extname FROM pg_extension", "SCHEMA").cast_values
350
        else
351
          super
352 353 354
        end
      end

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

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

367 368
      def use_insert_returning?
        @use_insert_returning
369 370
      end

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

375 376 377 378 379 380 381 382 383 384
      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 已提交
385 386 387 388
      # Returns the version of the connected PostgreSQL server.
      def postgresql_version
        @connection.server_version
      end
389

390 391 392 393
      def default_index_type?(index) # :nodoc:
        index.using == :btree || super
      end

394
      private
395

396
        # See http://www.postgresql.org/docs/current/static/errcodes-appendix.html
397
        VALUE_LIMIT_VIOLATION = "22001"
398
        NUMERIC_VALUE_OUT_OF_RANGE = "22003"
399
        NOT_NULL_VIOLATION    = "23502"
400 401
        FOREIGN_KEY_VIOLATION = "23503"
        UNIQUE_VIOLATION      = "23505"
402
        SERIALIZATION_FAILURE = "40001"
403
        DEADLOCK_DETECTED     = "40P01"
404

405
        def translate_exception(exception, message)
406 407
          return exception unless exception.respond_to?(:result)

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

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

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

441
        def initialize_type_map(m = type_map)
442 443 444
          register_class_with_limit m, "int2", Type::Integer
          register_class_with_limit m, "int4", Type::Integer
          register_class_with_limit m, "int8", Type::Integer
445
          m.register_type "oid", OID::Oid.new
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
          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
463
          m.register_type "json", Type::Json.new
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
          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)
479

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

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

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

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

508
          load_additional_types
509 510
        end

A
Akira Matsuda 已提交
511
        def extract_limit(sql_type)
S
Sean Griffin 已提交
512
          case sql_type
513 514 515 516 517 518
          when /^bigint/i, /^int8/i
            8
          when /^smallint/i
            2
          else
            super
S
Sean Griffin 已提交
519 520 521
          end
        end

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

A
Akira Matsuda 已提交
549
        def extract_default_function(default_value, default)
550 551 552
          default if has_default_function?(default_value, default)
        end

A
Akira Matsuda 已提交
553
        def has_default_function?(default_value, default)
554
          !default_value && %r{\w+\(.*\)|\(.*\)::\w+|CURRENT_DATE|CURRENT_TIMESTAMP}.match?(default)
555 556
        end

557
        def load_additional_types(oids = nil)
558 559
          initializer = OID::TypeMapInitializer.new(type_map)

560
          if supports_ranges?
561
            query = <<-SQL
562
              SELECT t.oid, t.typname, t.typelem, t.typdelim, t.typinput, r.rngsubtype, t.typtype, t.typbasetype
563 564 565 566
              FROM pg_type as t
              LEFT JOIN pg_range as r ON oid = rngtypid
            SQL
          else
567
            query = <<-SQL
568
              SELECT t.oid, t.typname, t.typelem, t.typdelim, t.typinput, t.typtype, t.typbasetype
569 570 571
              FROM pg_type as t
            SQL
          end
572 573 574

          if oids
            query += "WHERE t.oid::integer IN (%s)" % oids.join(", ")
575
          else
576
            query += initializer.query_conditions_for_initial_load
577 578
          end

579
          execute_and_clear(query, "SCHEMA", []) do |records|
580 581
            initializer.run(records)
          end
582 583
        end

584
        FEATURE_NOT_SUPPORTED = "0A000" #:nodoc:
585

586 587 588 589 590 591 592 593
        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
594 595 596 597 598
          ret = yield result
          result.clear
          ret
        end

599
        def exec_no_cache(sql, name, binds)
600
          type_casted_binds = type_casted_binds(binds)
601 602 603 604 605
          log(sql, name, binds, type_casted_binds) do
            ActiveSupport::Dependencies.interlock.permit_concurrent_loads do
              @connection.async_exec(sql, type_casted_binds)
            end
          end
606
        end
607

608
        def exec_cache(sql, name, binds)
609
          stmt_key = prepare_statement(sql)
610
          type_casted_binds = type_casted_binds(binds)
611

612
          log(sql, name, binds, type_casted_binds, stmt_key) do
613 614 615
            ActiveSupport::Dependencies.interlock.permit_concurrent_loads do
              @connection.exec_prepared(stmt_key, type_casted_binds)
            end
616 617
          end
        rescue ActiveRecord::StatementInvalid => e
618
          raise unless is_cached_plan_failure?(e)
619

620 621 622 623 624
          # 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
625 626 627 628
            @lock.synchronize do
              # outside of transactions we can simply flush this query and retry
              @statements.delete sql_key(sql)
            end
629
            retry
630 631 632
          end
        end

633 634 635 636 637 638 639 640 641
        # 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:
        # http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/cache/plancache.c#l573
642
        CACHED_PLAN_HEURISTIC = "cached plan must not change result type".freeze
643 644
        def is_cached_plan_failure?(e)
          pgerror = e.cause
645
          code = pgerror.result.result_error_field(PG::PG_DIAG_SQLSTATE)
646 647 648 649 650 651 652 653 654
          code == FEATURE_NOT_SUPPORTED && pgerror.message.include?(CACHED_PLAN_HEURISTIC)
        rescue
          false
        end

        def in_transaction?
          open_transactions > 0
        end

655 656 657 658 659 660 661 662 663
        # 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)
664 665 666 667 668 669 670 671 672 673 674 675
          @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
676
            end
677
            @statements[sql_key]
678 679
          end
        end
680

681 682 683
        # Connects to a PostgreSQL server and sets up the adapter depending on the
        # connected server's characteristics.
        def connect
684
          @connection = PG.connect(@connection_parameters)
685
          configure_connection
686 687
        rescue ::PG::Error => error
          if error.message.include?("does not exist")
688
            raise ActiveRecord::NoDatabaseError
689
          else
690
            raise
691
          end
692 693
        end

694
        # Configures the encoding, verbosity, schema search path, and time zone of the connection.
695
        # This is called by #connect and should not be called manually.
696 697
        def configure_connection
          if @config[:encoding]
698
            @connection.set_client_encoding(@config[:encoding])
699
          end
700
          self.client_min_messages = @config[:min_messages] || "warning"
701
          self.schema_search_path = @config[:schema_search_path] || @config[:schema_order]
702

703
          # Use standard-conforming strings so we don't have to do the E'...' dance.
704 705
          set_standard_conforming_strings

706
          # If using Active Record's time zone support configure the connection to return
707
          # TIMESTAMP WITH ZONE types in UTC.
708
          # (SET TIME ZONE does not use an equals sign like other SET variables)
709
          if ActiveRecord::Base.default_timezone == :utc
710
            execute("SET time zone 'UTC'", "SCHEMA")
711
          elsif @local_tz
712
            execute("SET time zone '#{@local_tz}'", "SCHEMA")
713
          end
714 715

          # SET statements from :variables config hash
716
          # http://www.postgresql.org/docs/current/static/sql-set.html
717 718
          variables = @config[:variables] || {}
          variables.map do |k, v|
719
            if v == ":default" || v == :default
720
              # Sets the value to the global or compile default
721
              execute("SET SESSION #{k} TO DEFAULT", "SCHEMA")
722
            elsif !v.nil?
723
              execute("SET SESSION #{k} TO #{quote(v)}", "SCHEMA")
724 725
            end
          end
726 727
        end

728
        # Returns the list of a table's column names, data types, and default values.
729 730
        #
        # The underlying query is roughly:
731
        #  SELECT column.name, column.type, default.value, column.comment
732 733 734 735 736 737 738 739 740 741 742 743 744 745
        #    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 已提交
746
        def column_definitions(table_name)
747
          query(<<-end_sql, "SCHEMA")
748
              SELECT a.attname, format_type(a.atttypid, a.atttypmod),
749
                     pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod,
750 751 752 753 754
                     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 已提交
755
               WHERE a.attrelid = #{quote(quote_table_name(table_name))}::regclass
756 757
                 AND a.attnum > 0 AND NOT a.attisdropped
               ORDER BY a.attnum
758
          end_sql
D
Initial  
David Heinemeier Hansson 已提交
759
        end
760

A
Akira Matsuda 已提交
761
        def extract_table_ref_from_insert_sql(sql)
762
          sql[/into\s("[A-Za-z0-9_."\[\]\s]+"|[A-Za-z0-9_."\[\]]+)\s*/im]
763 764 765
          $1.strip if $1
        end

766 767
        def arel_visitor
          Arel::Visitors::PostgreSQL.new(self)
768
        end
S
Sean Griffin 已提交
769 770 771 772 773 774

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

792 793 794 795 796 797 798 799
        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

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

        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 已提交
838
        ActiveRecord::Type.register(:datetime, OID::DateTime, adapter: :postgresql)
839 840 841 842 843 844
        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)
845 846
        ActiveRecord::Type.register(:point, OID::Point, adapter: :postgresql)
        ActiveRecord::Type.register(:legacy_point, OID::LegacyPoint, adapter: :postgresql)
847 848 849
        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 已提交
850 851 852
    end
  end
end