postgresql_adapter.rb 36.6 KB
Newer Older
D
Initial  
David Heinemeier Hansson 已提交
1
require 'active_record/connection_adapters/abstract_adapter'
J
Jeremy Kemper 已提交
2
require 'active_support/core_ext/kernel/requires'
3
require 'active_support/core_ext/object/blank'
4 5 6

# Make sure we're using pg high enough for PGResult#values
gem 'pg', '~> 0.11'
7
require 'pg'
D
Initial  
David Heinemeier Hansson 已提交
8 9 10 11 12

module ActiveRecord
  class Base
    # Establishes a connection to the database that's used by all Active Record objects
    def self.postgresql_connection(config) # :nodoc:
13
      config = config.symbolize_keys
D
Initial  
David Heinemeier Hansson 已提交
14
      host     = config[:host]
15
      port     = config[:port] || 5432
16 17
      username = config[:username].to_s if config[:username]
      password = config[:password].to_s if config[:password]
D
Initial  
David Heinemeier Hansson 已提交
18

19
      if config.key?(:database)
D
Initial  
David Heinemeier Hansson 已提交
20 21 22 23 24
        database = config[:database]
      else
        raise ArgumentError, "No database specified. Missing argument: database."
      end

25
      # The postgres drivers don't allow the creation of an unconnected PGconn object,
26 27 28 29
      # so just pass a nil connection object for the time being.
      ConnectionAdapters::PostgreSQLAdapter.new(nil, logger, [host, port, nil, nil, database, username, password], config)
    end
  end
30

31 32 33 34 35 36 37
  module ConnectionAdapters
    # PostgreSQL-specific extensions to column definitions in a table.
    class PostgreSQLColumn < Column #:nodoc:
      # Instantiates a new PostgreSQL column definition in a table.
      def initialize(name, default, sql_type = nil, null = true)
        super(name, self.class.extract_value_from_default(default), sql_type, null)
      end
38

39 40 41 42 43 44
      # :stopdoc:
      class << self
        attr_accessor :money_precision
      end
      # :startdoc:

45
      private
46
        def extract_limit(sql_type)
47 48 49 50 51
          case sql_type
          when /^bigint/i;    8
          when /^smallint/i;  2
          else super
          end
52 53
        end

54 55 56 57 58
        # Extracts the scale from PostgreSQL-specific data types.
        def extract_scale(sql_type)
          # Money type has a fixed scale of 2.
          sql_type =~ /^money/ ? 2 : super
        end
59

60 61
        # Extracts the precision from PostgreSQL-specific data types.
        def extract_precision(sql_type)
62 63 64 65 66
          if sql_type == 'money'
            self.class.money_precision
          else
            super
          end
67
        end
68

69 70 71 72 73 74 75
        # Maps PostgreSQL-specific data types to logical Rails types.
        def simplified_type(field_type)
          case field_type
            # Numeric and monetary types
            when /^(?:real|double precision)$/
              :float
            # Monetary types
76
            when 'money'
77 78 79 80 81
              :decimal
            # Character types
            when /^(?:character varying|bpchar)(?:\(\d+\))?$/
              :string
            # Binary data types
82
            when 'bytea'
83 84 85 86
              :binary
            # Date/time types
            when /^timestamp with(?:out)? time zone$/
              :datetime
87
            when 'interval'
88 89 90 91 92 93 94 95 96 97 98
              :string
            # Geometric types
            when /^(?:point|line|lseg|box|"?path"?|polygon|circle)$/
              :string
            # Network address types
            when /^(?:cidr|inet|macaddr)$/
              :string
            # Bit strings
            when /^bit(?: varying)?(?:\(\d+\))?$/
              :string
            # XML type
99
            when 'xml'
100
              :xml
101 102 103
            # tsvector type
            when 'tsvector'
              :tsvector
104 105
            # Arrays
            when /^\D+\[\]$/
106
              :string
107
            # Object identifier types
108
            when 'oid'
109
              :integer
110
            # UUID type
111
            when 'uuid'
112 113 114 115
              :string
            # Small and big integer types
            when /^(?:small|big)int$/
              :integer
116 117 118 119 120
            # Pass through all types that are not specific to PostgreSQL.
            else
              super
          end
        end
121

122 123 124
        # Extracts the value from a PostgreSQL column default definition.
        def self.extract_value_from_default(default)
          case default
125 126 127 128 129 130 131 132
            # This is a performance optimization for Ruby 1.9.2 in development.
            # If the value is nil, we return nil straight away without checking
            # the regular expressions. If we check each regular expression,
            # Regexp#=== will call NilClass#to_str, which will trigger
            # method_missing (defined by whiny nil in ActiveSupport) which
            # makes this method very very slow.
            when NilClass
              nil
133
            # Numeric types
134 135
            when /\A\(?(-?\d+(\.\d*)?\)?)\z/
              $1
136
            # Character types
137
            when /\A'(.*)'::(?:character varying|bpchar|text)\z/m
138
              $1
139 140 141
            # Character types (8.1 formatting)
            when /\AE'(.*)'::(?:character varying|bpchar|text)\z/m
              $1.gsub(/\\(\d\d\d)/) { $1.oct.chr }
142
            # Binary data types
143
            when /\A'(.*)'::bytea\z/m
144 145
              $1
            # Date/time types
146
            when /\A'(.+)'::(?:time(?:stamp)? with(?:out)? time zone|date)\z/
147
              $1
148
            when /\A'(.*)'::interval\z/
149 150
              $1
            # Boolean type
151
            when 'true'
152
              true
153
            when 'false'
154 155
              false
            # Geometric types
156
            when /\A'(.*)'::(?:point|line|lseg|box|"?path"?|polygon|circle)\z/
157 158
              $1
            # Network address types
159
            when /\A'(.*)'::(?:cidr|inet|macaddr)\z/
160 161
              $1
            # Bit string types
162
            when /\AB'(.*)'::"?bit(?: varying)?"?\z/
163 164
              $1
            # XML type
165
            when /\A'(.*)'::xml\z/m
166 167
              $1
            # Arrays
168
            when /\A'(.*)'::"?\D+"?\[\]\z/
169 170
              $1
            # Object identifier types
171
            when /\A-?\d+\z/
172 173 174
              $1
            else
              # Anything else is blank, some user type, or some function
175
              # and we can't know the value of that, so return nil.
176 177 178
              nil
          end
        end
D
Initial  
David Heinemeier Hansson 已提交
179 180
    end

181 182
    # The PostgreSQL adapter works both with the native C (http://ruby.scripting.ca/postgres/) and the pure
    # Ruby (available both as gem and from http://rubyforge.org/frs/?group_id=234&release_id=1944) drivers.
183 184 185
    #
    # Options:
    #
P
Pratik Naik 已提交
186 187 188 189 190
    # * <tt>:host</tt> - Defaults to "localhost".
    # * <tt>:port</tt> - Defaults to 5432.
    # * <tt>:username</tt> - Defaults to nothing.
    # * <tt>:password</tt> - Defaults to nothing.
    # * <tt>:database</tt> - The name of the database. No default, must be provided.
191
    # * <tt>:schema_search_path</tt> - An optional schema search path for the connection given
192
    #   as a string of comma-separated schema names.  This is backward-compatible with the <tt>:schema_order</tt> option.
193
    # * <tt>:encoding</tt> - An optional client encoding that is used in a <tt>SET client_encoding TO
194
    #   <encoding></tt> call on the connection.
195
    # * <tt>:min_messages</tt> - An optional client min messages that is used in a
196
    #   <tt>SET client_min_messages TO <min_messages></tt> call on the connection.
197
    class PostgreSQLAdapter < AbstractAdapter
198 199 200 201 202
      class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition
        def xml(*args)
          options = args.extract_options!
          column(args[0], 'xml', options)
        end
203 204 205 206 207

        def tsvector(*args)
          options = args.extract_options!
          column(args[0], 'tsvector', options)
        end
208 209
      end

210
      ADAPTER_NAME = 'PostgreSQL'
211 212

      NATIVE_DATABASE_TYPES = {
213
        :primary_key => "serial primary key",
214 215 216 217 218 219 220 221 222 223
        :string      => { :name => "character varying", :limit => 255 },
        :text        => { :name => "text" },
        :integer     => { :name => "integer" },
        :float       => { :name => "float" },
        :decimal     => { :name => "decimal" },
        :datetime    => { :name => "timestamp" },
        :timestamp   => { :name => "timestamp" },
        :time        => { :name => "time" },
        :date        => { :name => "date" },
        :binary      => { :name => "bytea" },
224
        :boolean     => { :name => "boolean" },
225 226
        :xml         => { :name => "xml" },
        :tsvector    => { :name => "tsvector" }
227 228
      }

229
      # Returns 'PostgreSQL' as adapter name for identification purposes.
230
      def adapter_name
231
        ADAPTER_NAME
232 233
      end

234 235
      # Returns +true+, since this connection adapter supports prepared statement
      # caching.
236 237 238 239
      def supports_statement_cache?
        true
      end

240 241
      # Initializes and connects a PostgreSQL adapter.
      def initialize(connection, logger, connection_parameters, config)
242
        super(connection, logger)
243
        @connection_parameters, @config = connection_parameters, config
244

245 246
        # @local_tz is initialized as nil to avoid warnings when connect tries to use it
        @local_tz = nil
247
        @table_alias_length = nil
248
        @statements = {}
249

250
        connect
251 252 253 254 255

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

256
        @local_tz = execute('SHOW TIME ZONE', 'SCHEMA').first["TimeZone"]
257 258
      end

X
Xavier Noria 已提交
259
      # Clears the prepared statements cache.
260 261
      def clear_cache!
        @statements.each_value do |value|
262
          @connection.query "DEALLOCATE #{value}"
263 264 265 266
        end
        @statements.clear
      end

267 268
      # Is this connection alive and ready for queries?
      def active?
269 270
        @connection.status == PGconn::CONNECTION_OK
      rescue PGError
271
        false
272 273 274 275
      end

      # Close then reopen the connection.
      def reconnect!
276 277 278
        clear_cache!
        @connection.reset
        configure_connection
279
      end
280

281 282 283 284 285
      def reset!
        clear_cache!
        super
      end

286 287
      # Disconnects from the database if already connected. Otherwise, this
      # method does nothing.
288
      def disconnect!
289
        clear_cache!
290 291
        @connection.close rescue nil
      end
292

293
      def native_database_types #:nodoc:
294
        NATIVE_DATABASE_TYPES
295
      end
296

297
      # Returns true, since this connection adapter supports migrations.
298 299
      def supports_migrations?
        true
300 301
      end

302
      # Does PostgreSQL support finding primary key on non-Active Record tables?
303 304 305 306
      def supports_primary_key? #:nodoc:
        true
      end

307 308 309
      # Enable standard-conforming strings if available.
      def set_standard_conforming_strings
        old, self.client_min_messages = client_min_messages, 'panic'
310
        execute('SET standard_conforming_strings = on', 'SCHEMA') rescue nil
311 312
      ensure
        self.client_min_messages = old
313 314
      end

315
      def supports_insert_with_returning?
316
        true
317 318
      end

319 320 321
      def supports_ddl_transactions?
        true
      end
322

323
      # Returns true, since this connection adapter supports savepoints.
324 325 326
      def supports_savepoints?
        true
      end
327

328
      # Returns the configured supported identifier length supported by PostgreSQL
329
      def table_alias_length
330
        @table_alias_length ||= query('SHOW max_identifier_length')[0][0].to_i
331
      end
332

333 334
      # QUOTING ==================================================

335
      # Escapes binary strings for bytea input to the database.
336 337
      def escape_bytea(value)
        @connection.escape_bytea(value) if value
338 339 340 341 342
      end

      # Unescapes bytea output from a database to the binary string it represents.
      # NOTE: This is NOT an inverse of escape_bytea! This is only to be used
      #       on escaped binary output from database drive.
343 344
      def unescape_bytea(value)
        @connection.unescape_bytea(value) if value
345 346
      end

347 348
      # Quotes PostgreSQL-specific data types for SQL input.
      def quote(value, column = nil) #:nodoc:
349 350
        return super unless column

A
Aaron Patterson 已提交
351 352 353
        case value
        when Numeric
          return super unless column.sql_type == 'money'
354
          # Not truly string input, so doesn't require (or allow) escape string syntax.
355
          "'#{value}'"
A
Aaron Patterson 已提交
356 357 358 359 360 361 362 363 364 365 366
        when String
          case column.sql_type
          when 'bytea' then "'#{escape_bytea(value)}'"
          when 'xml'   then "xml '#{quote_string(value)}'"
          when /^bit/
            case value
            when /^[01]*$/      then "B'#{value}'" # Bit-string notation
            when /^[0-9A-F]*$/i then "X'#{value}'" # Hexadecimal notation
            end
          else
            super
367
          end
368 369 370 371 372
        else
          super
        end
      end

373 374 375 376 377 378
      def type_cast(value, column)
        return super unless column

        case value
        when String
          return super unless 'bytea' == column.sql_type
379
          { :value => value, :format => 1 }
380 381 382 383 384
        else
          super
        end
      end

385 386 387
      # Quotes strings for use in SQL input.
      def quote_string(s) #:nodoc:
        @connection.escape(s)
388 389
      end

390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
      # Checks the following cases:
      #
      # - table_name
      # - "table.name"
      # - schema_name.table_name
      # - schema_name."table.name"
      # - "schema.name".table_name
      # - "schema.name"."table.name"
      def quote_table_name(name)
        schema, name_part = extract_pg_identifier_from_name(name.to_s)

        unless name_part
          quote_column_name(schema)
        else
          table_name, name_part = extract_pg_identifier_from_name(name_part)
          "#{quote_column_name(schema)}.#{quote_column_name(table_name)}"
        end
      end

409 410
      # Quotes column names for use in SQL queries.
      def quote_column_name(name) #:nodoc:
411
        PGconn.quote_ident(name.to_s)
412 413
      end

414 415 416
      # Quote date/time values for use in SQL input. Includes microseconds
      # if the value is a Time responding to usec.
      def quoted_date(value) #:nodoc:
417 418 419 420 421
        if value.acts_like?(:time) && value.respond_to?(:usec)
          "#{super}.#{sprintf("%06d", value.usec)}"
        else
          super
        end
422 423
      end

424 425
      # Set the authorized user for this session
      def session_auth=(user)
426
        clear_cache!
A
Aaron Patterson 已提交
427
        exec_query "SET SESSION AUTHORIZATION #{user}"
428 429
      end

430 431
      # REFERENTIAL INTEGRITY ====================================

432
      def supports_disable_referential_integrity? #:nodoc:
433
        true
434 435
      end

436
      def disable_referential_integrity #:nodoc:
437
        if supports_disable_referential_integrity? then
438 439
          execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} DISABLE TRIGGER ALL" }.join(";"))
        end
440 441
        yield
      ensure
442
        if supports_disable_referential_integrity? then
443 444
          execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} ENABLE TRIGGER ALL" }.join(";"))
        end
445
      end
446 447 448

      # DATABASE STATEMENTS ======================================

449 450 451 452 453 454
      # Executes a SELECT query and returns an array of rows. Each row is an
      # array of field values.
      def select_rows(sql, name = nil)
        select_raw(sql, name).last
      end

455
      # Executes an INSERT query and returns the new record's ID
456
      def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
457
        # Extract the table from the insert sql. Yuck.
458
        _, table = extract_schema_and_table(sql.split(" ", 4)[2])
459

460
        pk ||= primary_key(table)
461

462
        if pk
463 464 465
          select_value("#{sql} RETURNING #{quote_column_name(pk)}")
        else
          super
466
        end
467
      end
468
      alias :create :insert
469

470 471
      # create a 2D array representing the result set
      def result_as_array(res) #:nodoc:
472
        # check if we have any binary column and if they need escaping
473 474
        ftypes = Array.new(res.nfields) do |i|
          [i, res.ftype(i)]
475 476
        end

477 478 479 480 481 482
        rows = res.values
        return rows unless ftypes.any? { |_, x|
          x == BYTEA_COLUMN_TYPE_OID || x == MONEY_COLUMN_TYPE_OID
        }

        typehash = ftypes.group_by { |_, type| type }
483 484
        binaries = typehash[BYTEA_COLUMN_TYPE_OID] || []
        monies   = typehash[MONEY_COLUMN_TYPE_OID] || []
485 486 487

        rows.each do |row|
          # unescape string passed BYTEA field (OID == 17)
488 489
          binaries.each do |index, _|
            row[index] = unescape_bytea(row[index])
490 491 492 493 494 495
          end

          # If this is a money type column and there are any currency symbols,
          # then strip them off. Indeed it would be prettier to do this in
          # PostgreSQLColumn.string_to_decimal but would break form input
          # fields that call value_before_type_cast.
496
          monies.each do |index, _|
497 498 499 500 501 502 503 504 505 506
            data = row[index]
            # Because money output is formatted according to the locale, there are two
            # cases to consider (note the decimal separators):
            #  (1) $12,345,678.12
            #  (2) $12.345.678,12
            case data
            when /^-?\D+[\d,]+\.\d{2}$/  # (1)
              data.gsub!(/[^-\d.]/, '')
            when /^-?\D+[\d.]+,\d{2}$/  # (2)
              data.gsub!(/[^-\d,]/, '').sub!(/,/, '.')
507
            end
508 509 510 511 512 513
          end
        end
      end


      # Queries the database and returns the results in an Array-like object
514
      def query(sql, name = nil) #:nodoc:
515
        log(sql, name) do
516
          result_as_array @connection.async_exec(sql)
517
        end
518 519
      end

520
      # Executes an SQL statement, returning a PGresult object on success
521 522
      # or raising a PGError exception otherwise.
      def execute(sql, name = nil)
523
        log(sql, name) do
524
          @connection.async_exec(sql)
525
        end
526 527
      end

528 529
      def substitute_at(column, index)
        Arel.sql("$#{index + 1}")
530 531
      end

A
Aaron Patterson 已提交
532
      def exec_query(sql, name = 'SQL', binds = [])
533
        log(sql, name, binds) do
534 535
          result = binds.empty? ? exec_no_cache(sql, binds) :
                                  exec_cache(sql, binds)
536

537 538 539
          ret = ActiveRecord::Result.new(result.fields, result_as_array(result))
          result.clear
          return ret
540 541 542
        end
      end

543 544 545 546 547 548 549 550 551
      def exec_delete(sql, name = 'SQL', binds = [])
        log(sql, name, binds) do
          result = binds.empty? ? exec_no_cache(sql, binds) :
                                  exec_cache(sql, binds)
          affected = result.cmd_tuples
          result.clear
          affected
        end
      end
552
      alias :exec_update :exec_delete
553

554 555 556 557 558 559 560 561 562 563 564 565
      def sql_for_insert(sql, pk, id_value, sequence_name, binds)
        unless pk
          _, table = extract_schema_and_table(sql.split(" ", 4)[2])

          pk = primary_key(table)
        end

        sql = "#{sql} RETURNING #{quote_column_name(pk)}" if pk

        [sql, binds]
      end

566
      # Executes an UPDATE query and returns the number of affected tuples.
567
      def update_sql(sql, name = nil)
568
        super.cmd_tuples
569 570
      end

571 572
      # Begins a transaction.
      def begin_db_transaction
573 574 575
        execute "BEGIN"
      end

576 577
      # Commits a transaction.
      def commit_db_transaction
578 579
        execute "COMMIT"
      end
580

581 582
      # Aborts a transaction.
      def rollback_db_transaction
583 584
        execute "ROLLBACK"
      end
585

586 587
      def outside_transaction?
        @connection.transaction_status == PGconn::PQTRANS_IDLE
588
      end
589

J
Jonathan Viney 已提交
590 591 592 593 594 595 596 597
      def create_savepoint
        execute("SAVEPOINT #{current_savepoint_name}")
      end

      def rollback_to_savepoint
        execute("ROLLBACK TO SAVEPOINT #{current_savepoint_name}")
      end

598
      def release_savepoint
J
Jonathan Viney 已提交
599 600
        execute("RELEASE SAVEPOINT #{current_savepoint_name}")
      end
601

602 603
      # SCHEMA STATEMENTS ========================================

604 605 606 607 608
      def recreate_database(name) #:nodoc:
        drop_database(name)
        create_database(name)
      end

609 610 611
      # Create a new PostgreSQL database.  Options include <tt>:owner</tt>, <tt>:template</tt>,
      # <tt>:encoding</tt>, <tt>:tablespace</tt>, and <tt>:connection_limit</tt> (note that MySQL uses
      # <tt>:charset</tt> while PostgreSQL uses <tt>:encoding</tt>).
612 613 614 615 616 617 618 619 620 621
      #
      # Example:
      #   create_database config[:database], config
      #   create_database 'foo_development', :encoding => 'unicode'
      def create_database(name, options = {})
        options = options.reverse_merge(:encoding => "utf8")

        option_string = options.symbolize_keys.sum do |key, value|
          case key
          when :owner
622
            " OWNER = \"#{value}\""
623
          when :template
624
            " TEMPLATE = \"#{value}\""
625 626 627
          when :encoding
            " ENCODING = '#{value}'"
          when :tablespace
628
            " TABLESPACE = \"#{value}\""
629 630 631 632 633 634 635
          when :connection_limit
            " CONNECTION LIMIT = #{value}"
          else
            ""
          end
        end

636
        execute "CREATE DATABASE #{quote_table_name(name)}#{option_string}"
637 638
      end

639
      # Drops a PostgreSQL database.
640 641 642 643
      #
      # Example:
      #   drop_database 'matt_development'
      def drop_database(name) #:nodoc:
644
        execute "DROP DATABASE IF EXISTS #{quote_table_name(name)}"
645 646
      end

647 648
      # Returns the list of all tables in the schema search path or a specified schema.
      def tables(name = nil)
649
        query(<<-SQL, 'SCHEMA').map { |row| row[0] }
650
          SELECT tablename
651 652 653 654 655 656
          FROM pg_tables
          WHERE schemaname = ANY (current_schemas(false))
        SQL
      end

      def table_exists?(name)
657 658
        schema, table = extract_schema_and_table(name.to_s)

659 660 661 662
        binds = [[nil, table.gsub(/(^"|"$)/,'')]]
        binds << [nil, schema] if schema

        exec_query(<<-SQL, 'SCHEMA', binds).rows.first[0].to_i > 0
663 664
            SELECT COUNT(*)
            FROM pg_tables
665 666
            WHERE tablename = $1
            #{schema ? "AND schemaname = $2" : ''}
667 668 669 670 671
        SQL
      end

      # Extracts the table and schema name from +name+
      def extract_schema_and_table(name)
672 673 674 675 676 677 678 679 680 681 682
        schema, table = name.split('.', 2)

        unless table # A table was provided without a schema
          table  = schema
          schema = nil
        end

        if name =~ /^"/ # Handle quoted table names
          table  = name
          schema = nil
        end
683
        [schema, table]
684 685
      end

686
      # Returns an array of indexes for the given table.
687
      def indexes(table_name, name = nil)
688 689
         schemas = schema_search_path.split(/,/).map { |p| quote(p) }.join(',')
         result = query(<<-SQL, name)
690 691
           SELECT distinct i.relname, d.indisunique, d.indkey, t.oid
             FROM pg_class t, pg_class i, pg_index d
692 693 694 695 696
           WHERE i.relkind = 'i'
             AND d.indexrelid = i.oid
             AND d.indisprimary = 'f'
             AND t.oid = d.indrelid
             AND t.relname = '#{table_name}'
697
             AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname IN (#{schemas}) )
698 699 700
          ORDER BY i.relname
        SQL

701

702
        result.map do |row|
703 704 705 706 707
          index_name = row[0]
          unique = row[1] == 't'
          indkey = row[2].split(" ")
          oid = row[3]

708 709
          columns = Hash[query(<<-SQL, "Columns for index #{row[0]} on #{table_name}")]
          SELECT a.attnum, a.attname
710 711 712 713 714
          FROM pg_attribute a
          WHERE a.attrelid = #{oid}
          AND a.attnum IN (#{indkey.join(",")})
          SQL

715 716
          column_names = columns.values_at(*indkey).compact
          column_names.empty? ? nil : IndexDefinition.new(table_name, index_name, unique, column_names)
717
        end.compact
718 719
      end

720 721
      # Returns the list of all column definitions for a table.
      def columns(table_name, name = nil)
722
        # Limit, precision, and scale are all handled by the superclass.
723 724
        column_definitions(table_name).collect do |column_name, type, default, notnull|
          PostgreSQLColumn.new(column_name, default, type, notnull == 'f')
D
Initial  
David Heinemeier Hansson 已提交
725 726 727
        end
      end

728 729 730 731 732 733 734 735 736 737 738 739 740
      # Returns the current database name.
      def current_database
        query('select current_database()')[0][0]
      end

      # Returns the current database encoding format.
      def encoding
        query(<<-end_sql)[0][0]
          SELECT pg_encoding_to_char(pg_database.encoding) FROM pg_database
          WHERE pg_database.datname LIKE '#{current_database}'
        end_sql
      end

741 742 743 744 745 746
      # Sets the schema search path to a string of comma-separated schema names.
      # Names beginning with $ have to be quoted (e.g. $user => '$user').
      # See: http://www.postgresql.org/docs/current/static/ddl-schemas.html
      #
      # This should be not be called manually but set in database.yml.
      def schema_search_path=(schema_csv)
747 748
        if schema_csv
          execute "SET search_path TO #{schema_csv}"
749
          @schema_search_path = schema_csv
750
        end
D
Initial  
David Heinemeier Hansson 已提交
751 752
      end

753 754
      # Returns the active schema search path.
      def schema_search_path
755
        @schema_search_path ||= query('SHOW search_path')[0][0]
756
      end
757

758 759
      # Returns the current client message level.
      def client_min_messages
760
        query('SHOW client_min_messages', 'SCHEMA')[0][0]
761 762 763 764
      end

      # Set the client message level.
      def client_min_messages=(level)
765
        execute("SET client_min_messages TO '#{level}'", 'SCHEMA')
766 767 768 769
      end

      # Returns the sequence name for a table's primary key or some other specified key.
      def default_sequence_name(table_name, pk = nil) #:nodoc:
770 771 772 773 774 775 776 777 778 779
        serial_sequence(table_name, pk || 'id').split('.').last
      rescue ActiveRecord::StatementInvalid
        "#{table_name}_#{pk || 'id'}_seq"
      end

      def serial_sequence(table, column)
        result = exec_query(<<-eosql, 'SCHEMA', [[nil, table], [nil, column]])
          SELECT pg_get_serial_sequence($1, $2)
        eosql
        result.rows.first.first
780 781
      end

782 783
      # Resets the sequence of a table's primary key to the maximum value.
      def reset_pk_sequence!(table, pk = nil, sequence = nil) #:nodoc:
784 785
        unless pk and sequence
          default_pk, default_sequence = pk_and_sequence_for(table)
786

787 788 789
          pk ||= default_pk
          sequence ||= default_sequence
        end
790

791 792 793 794 795 796 797 798 799 800
        if @logger && pk && !sequence
          @logger.warn "#{table} has primary key #{pk} with no default sequence"
        end

        if pk && sequence
          quoted_sequence = quote_column_name(sequence)

          select_value <<-end_sql, 'Reset sequence'
            SELECT setval('#{quoted_sequence}', (SELECT COALESCE(MAX(#{quote_column_name pk})+(SELECT increment_by FROM #{quoted_sequence}), (SELECT min_value FROM #{quoted_sequence})) FROM #{quote_table_name(table)}), false)
          end_sql
801 802 803
        end
      end

804 805
      # Returns a table's primary key and belonging sequence.
      def pk_and_sequence_for(table) #:nodoc:
806 807
        # First try looking for a sequence with a dependency on the
        # given table's primary key.
808
        result = exec_query(<<-end_sql, 'SCHEMA').rows.first
809
          SELECT attr.attname, seq.relname
810 811 812 813 814 815 816 817 818 819 820 821
          FROM pg_class      seq,
               pg_attribute  attr,
               pg_depend     dep,
               pg_namespace  name,
               pg_constraint cons
          WHERE seq.oid           = dep.objid
            AND seq.relkind       = 'S'
            AND attr.attrelid     = dep.refobjid
            AND attr.attnum       = dep.refobjsubid
            AND attr.attrelid     = cons.conrelid
            AND attr.attnum       = cons.conkey[1]
            AND cons.contype      = 'p'
822
            AND dep.refobjid      = '#{quote_table_name(table)}'::regclass
823
        end_sql
824

825
        # [primary_key, sequence]
826
        [result.first, result.last]
827 828
      rescue
        nil
829 830
      end

831 832
      # Returns just a table's primary key
      def primary_key(table)
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
        row = exec_query(<<-end_sql, 'SCHEMA', [[nil, table]]).rows.first
          SELECT DISTINCT(attr.attname)
          FROM pg_attribute  attr,
               pg_depend     dep,
               pg_namespace  name,
               pg_constraint cons
          WHERE attr.attrelid     = dep.refobjid
            AND attr.attnum       = dep.refobjsubid
            AND attr.attrelid     = cons.conrelid
            AND attr.attnum       = cons.conkey[1]
            AND cons.contype      = 'p'
            AND dep.refobjid      = $1::regclass
        end_sql

        row && row.first
848 849
      end

850
      # Renames a table.
851 852 853
      #
      # Example:
      #   rename_table('octopuses', 'octopi')
854
      def rename_table(name, new_name)
855
        execute "ALTER TABLE #{quote_table_name(name)} RENAME TO #{quote_table_name(new_name)}"
856
      end
857

858 859
      # Adds a new column to the named table.
      # See TableDefinition#column for details of the options you can use.
S
Scott Barron 已提交
860
      def add_column(table_name, column_name, type, options = {})
861 862
        add_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ADD COLUMN #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
        add_column_options!(add_column_sql, options)
863

864
        execute add_column_sql
S
Scott Barron 已提交
865
      end
D
Initial  
David Heinemeier Hansson 已提交
866

867 868
      # Changes the column of a table.
      def change_column(table_name, column_name, type, options = {})
869 870
        quoted_table_name = quote_table_name(table_name)

871
        execute "ALTER TABLE #{quoted_table_name} ALTER COLUMN #{quote_column_name(column_name)} TYPE #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
872

873 874
        change_column_default(table_name, column_name, options[:default]) if options_include_default?(options)
        change_column_null(table_name, column_name, options[:null], options[:default]) if options.key?(:null)
875
      end
876

877 878
      # Changes the default value of a table column.
      def change_column_default(table_name, column_name, default)
879
        execute "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} SET DEFAULT #{quote(default)}"
880
      end
881

882 883
      def change_column_null(table_name, column_name, null, default = nil)
        unless null || default.nil?
884
          execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL")
885
        end
886
        execute("ALTER TABLE #{quote_table_name(table_name)} ALTER #{quote_column_name(column_name)} #{null ? 'DROP' : 'SET'} NOT NULL")
887 888
      end

889 890
      # Renames a column in a table.
      def rename_column(table_name, column_name, new_column_name)
891
        execute "ALTER TABLE #{quote_table_name(table_name)} RENAME COLUMN #{quote_column_name(column_name)} TO #{quote_column_name(new_column_name)}"
892
      end
893

894 895 896 897
      def remove_index!(table_name, index_name) #:nodoc:
        execute "DROP INDEX #{quote_table_name(index_name)}"
      end

898 899 900 901
      def rename_index(table_name, old_name, new_name)
        execute "ALTER INDEX #{quote_column_name(old_name)} RENAME TO #{quote_table_name(new_name)}"
      end

902 903
      def index_name_length
        63
904
      end
905

906 907
      # Maps logical Rails types to PostgreSQL-specific data types.
      def type_to_sql(type, limit = nil, precision = nil, scale = nil)
908
        return super unless type.to_s == 'integer'
909
        return 'integer' unless limit
910

911
        case limit
912 913 914
          when 1, 2; 'smallint'
          when 3, 4; 'integer'
          when 5..8; 'bigint'
915
          else raise(ActiveRecordError, "No integer type has byte size #{limit}. Use a numeric with precision 0 instead.")
916 917
        end
      end
918

919
      # Returns a SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
920 921 922
      #
      # PostgreSQL requires the ORDER BY columns in the select list for distinct queries, and
      # requires that the ORDER BY include the distinct column.
923
      #
924
      #   distinct("posts.id", "posts.created_at desc")
925 926
      def distinct(columns, orders) #:nodoc:
        return "DISTINCT #{columns}" if orders.empty?
927

928 929
        # Construct a clean list of column names from the ORDER BY clause, removing
        # any ASC/DESC modifiers
930
        order_columns = orders.collect { |s| s =~ /^(.+)\s+(ASC|DESC)\s*$/i ? $1 : s }
931
        order_columns.delete_if { |c| c.blank? }
932
        order_columns = order_columns.zip((0...order_columns.size).to_a).map { |s,i| "#{s} AS alias_#{i}" }
933

934
        "DISTINCT #{columns}, #{order_columns * ', '}"
935
      end
936

937
      protected
938
        # Returns the version of the connected PostgreSQL server.
939
        def postgresql_version
940
          @connection.server_version
941 942
        end

943 944 945
        def translate_exception(exception, message)
          case exception.message
          when /duplicate key value violates unique constraint/
946
            RecordNotUnique.new(message, exception)
947
          when /violates foreign key constraint/
948
            InvalidForeignKey.new(message, exception)
949 950 951 952 953
          else
            super
          end
        end

D
Initial  
David Heinemeier Hansson 已提交
954
      private
955 956 957 958 959 960 961 962 963
      def exec_no_cache(sql, binds)
        @connection.async_exec(sql)
      end

      def exec_cache(sql, binds)
        unless @statements.key? sql
          nextkey = "a#{@statements.length + 1}"
          @connection.prepare nextkey, sql
          @statements[sql] = nextkey
964
        end
965 966 967 968 969 970 971 972 973 974

        key = @statements[sql]

        # Clear the queue
        @connection.get_last_result
        @connection.send_query_prepared(key, binds.map { |col, val|
          type_cast(val, col)
        })
        @connection.block
        @connection.get_last_result
975 976
      end

P
Pratik Naik 已提交
977
        # The internal PostgreSQL identifier of the money data type.
978
        MONEY_COLUMN_TYPE_OID = 790 #:nodoc:
979 980
        # The internal PostgreSQL identifier of the BYTEA data type.
        BYTEA_COLUMN_TYPE_OID = 17 #:nodoc:
981 982 983 984 985 986 987 988 989

        # Connects to a PostgreSQL server and sets up the adapter depending on the
        # connected server's characteristics.
        def connect
          @connection = PGconn.connect(*@connection_parameters)

          # 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.
990 991
          PostgreSQLColumn.money_precision = (postgresql_version >= 80300) ? 19 : 10

992 993 994
          configure_connection
        end

995
        # Configures the encoding, verbosity, schema search path, and time zone of the connection.
996
        # This is called by #connect and should not be called manually.
997 998
        def configure_connection
          if @config[:encoding]
999
            @connection.set_client_encoding(@config[:encoding])
1000
          end
1001 1002
          self.client_min_messages = @config[:min_messages] if @config[:min_messages]
          self.schema_search_path = @config[:schema_search_path] || @config[:schema_order]
1003 1004 1005 1006

          # Use standard-conforming strings if available so we don't have to do the E'...' dance.
          set_standard_conforming_strings

1007
          # If using Active Record's time zone support configure the connection to return
1008
          # TIMESTAMP WITH ZONE types in UTC.
1009
          if ActiveRecord::Base.default_timezone == :utc
1010
            execute("SET time zone 'UTC'", 'SCHEMA')
1011
          elsif @local_tz
1012
            execute("SET time zone '#{@local_tz}'", 'SCHEMA')
1013
          end
1014 1015
        end

1016
        # Returns the current ID of a table's sequence.
1017 1018 1019
        def last_insert_id(sequence_name) #:nodoc:
          r = exec_query("SELECT currval($1)", 'SQL', [[nil, sequence_name]])
          Integer(r.rows.first.first)
D
Initial  
David Heinemeier Hansson 已提交
1020 1021
        end

1022
        # Executes a SELECT query and returns the results, performing any data type
1023
        # conversions that are required to be performed here instead of in PostgreSQLColumn.
1024
        def select(sql, name = nil, binds = [])
A
Aaron Patterson 已提交
1025
          exec_query(sql, name, binds).to_a
1026 1027 1028
        end

        def select_raw(sql, name = nil)
1029
          res = execute(sql, name)
1030
          results = result_as_array(res)
1031
          fields = res.fields
1032
          res.clear
1033
          return fields, results
M
Marcel Molina 已提交
1034 1035
        end

1036
        # Returns the list of a table's column names, data types, and default values.
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
        #
        # 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
1054
        def column_definitions(table_name) #:nodoc:
1055
          exec_query(<<-end_sql, 'SCHEMA').rows
1056
            SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull
1057 1058
              FROM pg_attribute a LEFT JOIN pg_attrdef d
                ON a.attrelid = d.adrelid AND a.attnum = d.adnum
1059
             WHERE a.attrelid = '#{quote_table_name(table_name)}'::regclass
1060 1061 1062
               AND a.attnum > 0 AND NOT a.attisdropped
             ORDER BY a.attnum
          end_sql
D
Initial  
David Heinemeier Hansson 已提交
1063
        end
1064 1065

        def extract_pg_identifier_from_name(name)
1066
          match_data = name.start_with?('"') ? name.match(/\"([^\"]+)\"/) : name.match(/([^\.]+)/)
1067 1068

          if match_data
1069 1070
            rest = name[match_data[0].length, name.length]
            rest = rest[1, rest.length] if rest.start_with? "."
1071 1072 1073
            [match_data[1], (rest.length > 0 ? rest : nil)]
          end
        end
1074 1075 1076 1077

      def table_definition
        TableDefinition.new(self)
      end
D
Initial  
David Heinemeier Hansson 已提交
1078 1079 1080
    end
  end
end