postgresql_adapter.rb 30.9 KB
Newer Older
D
Initial  
David Heinemeier Hansson 已提交
1 2 3 4 5 6 7
require 'active_record/connection_adapters/abstract_adapter'

module ActiveRecord
  class Base
    # Establishes a connection to the database that's used by all Active Record objects
    def self.postgresql_connection(config) # :nodoc:
      require_library_or_gem 'postgres' unless self.class.const_defined?(:PGconn)
8 9

      config = config.symbolize_keys
D
Initial  
David Heinemeier Hansson 已提交
10
      host     = config[:host]
11
      port     = config[:port] || 5432
D
Initial  
David Heinemeier Hansson 已提交
12 13 14 15 16 17 18 19 20
      username = config[:username].to_s
      password = config[:password].to_s

      if config.has_key?(:database)
        database = config[:database]
      else
        raise ArgumentError, "No database specified. Missing argument: database."
      end

21 22 23 24 25
      # The postgres drivers don't allow to create an unconnected PGconn object,
      # 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
26

27 28 29 30 31 32 33
  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
34

35 36 37 38 39 40
      private
        # 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
41

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
        # Extracts the precision from PostgreSQL-specific data types.
        def extract_precision(sql_type)
          # Actual code is defined dynamically in PostgreSQLAdapter.connect
          # depending on the server specifics
          super
        end
  
        # Escapes binary strings for bytea input to the database.
        def self.string_to_binary(value)
          if PGconn.respond_to?(:escape_bytea)
            self.class.module_eval do
              define_method(:string_to_binary) do |value|
                PGconn.escape_bytea(value) if value
              end
            end
          else
            self.class.module_eval do
              define_method(:string_to_binary) do |value|
                if value
                  result = ''
                  value.each_byte { |c| result << sprintf('\\\\%03o', c) }
                  result
                end
              end
            end
          end
          self.class.string_to_binary(value)
        end
  
        # Unescapes bytea output from a database to the binary string it represents.
        def self.binary_to_string(value)
          # In each case, check if the value actually is escaped PostgresSQL bytea output
          # or an unescaped Active Record attribute that was just written.
          if PGconn.respond_to?(:unescape_bytea)
            self.class.module_eval do
              define_method(:binary_to_string) do |value|
                if value =~ /\\\\\d{3}/
                  PGconn.unescape_bytea(value)
                else
                  value
                end
              end
            end
          else
            self.class.module_eval do
              define_method(:binary_to_string) do |value|
                if value =~ /\\\\\d{3}/
                  result = ''
                  i, max = 0, value.size
                  while i < max
                    char = value[i]
                    if char == ?\\
                      if value[i+1] == ?\\
                        char = ?\\
                        i += 1
                      else
                        char = value[i+1..i+3].oct
                        i += 3
                      end
                    end
                    result << char
                    i += 1
                  end
                  result
                else
                  value
                end
              end
            end
          end
          self.class.binary_to_string(value)
        end  
  
        # 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
            when /^money$/
              :decimal
            # Character types
            when /^(?:character varying|bpchar)(?:\(\d+\))?$/
              :string
            # Binary data types
            when /^bytea$/
              :binary
            # Date/time types
            when /^timestamp with(?:out)? time zone$/
              :datetime
            when /^interval$/
              :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
            when /^xml$/
              :string
            # Arrays
            when /^\D+\[\]$/
              :string              
            # Object identifier types
            when /^oid$/
              :integer
            # Pass through all types that are not specific to PostgreSQL.
            else
              super
          end
        end
  
        # Extracts the value from a PostgreSQL column default definition.
        def self.extract_value_from_default(default)
          case default
            # Numeric types
            when /^-?\d+(\.\d*)?$/
              default
            # Character types
            when /^'(.*)'::(?:character varying|bpchar|text)$/
              $1
            # Binary data types
            when /^'(.*)'::bytea$/
              $1
            # Date/time types
            when /^'(.+)'::(?:time(?:stamp)? with(?:out)? time zone|date)$/
              $1
            when /^'(.*)'::interval$/
              $1
            # Boolean type
            when /^true$/
              true
            when /^false$/
              false
            # Geometric types
            when /^'(.*)'::(?:point|line|lseg|box|"?path"?|polygon|circle)$/
              $1
            # Network address types
            when /^'(.*)'::(?:cidr|inet|macaddr)$/
              $1
            # Bit string types
            when /^B'(.*)'::"?bit(?: varying)?"?$/
              $1
            # XML type
            when /^'(.*)'::xml$/
              $1
            # Arrays
            when /^'(.*)'::"?\D+"?\[\]$/
              $1
            # Object identifier types
            when /^-?\d+$/
              $1
            else
              # Anything else is blank, some user type, or some function
              # and we can't know the value of that, so return nil.            
              nil
          end
        end
D
Initial  
David Heinemeier Hansson 已提交
205 206 207 208
    end
  end

  module ConnectionAdapters
209 210
    # 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.
211 212 213 214 215 216 217 218
    #
    # Options:
    #
    # * <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.
219
    # * <tt>:schema_search_path</tt> -- An optional schema search path for the connection given as a string of comma-separated schema names.  This is backward-compatible with the :schema_order option.
220 221
    # * <tt>:encoding</tt> -- An optional client encoding that is using in a SET client_encoding TO <encoding> call on connection.
    # * <tt>:min_messages</tt> -- An optional client min messages that is using in a SET client_min_messages TO <min_messages> call on connection.
222
    # * <tt>:allow_concurrency</tt> -- If true, use async query methods so Ruby threads don't deadlock; otherwise, use blocking query methods.
223
    class PostgreSQLAdapter < AbstractAdapter
224
      # Returns 'PostgreSQL' as adapter name for identification purposes.
225 226 227 228
      def adapter_name
        'PostgreSQL'
      end

229 230
      # Initializes and connects a PostgreSQL adapter.
      def initialize(connection, logger, connection_parameters, config)
231
        super(connection, logger)
232
        @connection_parameters, @config = connection_parameters, config
233

234
        connect
235 236
      end

237 238 239
      # Is this connection alive and ready for queries?
      def active?
        if @connection.respond_to?(:status)
240
          @connection.status == PGconn::CONNECTION_OK
241
        else
242
          # We're asking the driver, not ActiveRecord, so use @connection.query instead of #query
243
          @connection.query 'SELECT 1'
244 245
          true
        end
246
      # postgres-pr raises a NoMethodError when querying if no connection is available.
247
      rescue PGError, NoMethodError
248
        false
249 250 251 252 253 254
      end

      # Close then reopen the connection.
      def reconnect!
        if @connection.respond_to?(:reset)
          @connection.reset
255
          configure_connection
256 257 258
        else
          disconnect!
          connect
259 260
        end
      end
261

262
      # Close the connection.
263 264 265
      def disconnect!
        @connection.close rescue nil
      end
266

267
      def native_database_types #:nodoc:
268 269 270 271 272 273
        {
          :primary_key => "serial primary key",
          :string      => { :name => "character varying", :limit => 255 },
          :text        => { :name => "text" },
          :integer     => { :name => "integer" },
          :float       => { :name => "float" },
274
          :decimal     => { :name => "decimal" },
275 276
          :datetime    => { :name => "timestamp" },
          :timestamp   => { :name => "timestamp" },
277
          :time        => { :name => "time" },
278 279
          :date        => { :name => "date" },
          :binary      => { :name => "bytea" },
280
          :boolean     => { :name => "boolean" }
281 282
        }
      end
283

284
      # Does PostgreSQL support migrations?
285 286
      def supports_migrations?
        true
287 288
      end

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
      # Does PostgreSQL support standard conforming strings?
      def supports_standard_conforming_strings?
        # Temporarily set the client message level above error to prevent unintentional
        # error messages in the logs when working on a PostgreSQL database server that
        # does not support standard conforming strings.
        client_min_messages_old = client_min_messages
        self.client_min_messages = 'panic'

        # postgres-pr does not raise an exception when client_min_messages is set higher
        # than error and "SHOW standard_conforming_strings" fails, but returns an empty
        # PGresult instead.
        has_support = execute('SHOW standard_conforming_strings')[0][0] rescue false
        self.client_min_messages = client_min_messages_old
        has_support
      end

      # Returns the configured supported identifier length supported by PostgreSQL,
      # or report the default of 63 on PostgreSQL 7.x.
307
      def table_alias_length
308
        @table_alias_length ||= (postgresql_version >= 80000 ? query('SHOW max_identifier_length')[0][0].to_i : 63)
309
      end
310

311 312
      # QUOTING ==================================================

313 314
      # Quotes PostgreSQL-specific data types for SQL input.
      def quote(value, column = nil) #:nodoc:
315
        if value.kind_of?(String) && column && column.type == :binary
316 317 318 319 320 321 322 323 324 325 326 327 328
          "#{quoted_string_prefix}'#{column.class.string_to_binary(value)}'"
        elsif value.kind_of?(String) && column && column.sql_type =~ /^xml$/
          "xml '#{quote_string(value)}'"
        elsif value.kind_of?(Numeric) && column && column.sql_type =~ /^money$/
          # Not truly string input, so doesn't require (or allow) escape string syntax.
          "'#{value.to_s}'"
        elsif value.kind_of?(String) && column && column.sql_type =~ /^bit/
          case value
            when /^[01]*$/
              "B'#{value}'" # Bit-string notation
            when /^[0-9A-F]*$/i
              "X'#{value}'" # Hexadecimal notation
          end
329 330 331 332 333
        else
          super
        end
      end

334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
      # Quotes strings for use in SQL input in the postgres driver for better performance.
      def quote_string(s) #:nodoc:
        if PGconn.respond_to?(:escape)
          self.class.instance_eval do
            define_method(:quote_string) do |s|
              PGconn.escape(s)
            end
          end
        else
          # There are some incorrectly compiled postgres drivers out there
          # that don't define PGconn.escape.
          self.class.instance_eval do
            undef_method(:quote_string)
          end
        end
        quote_string(s)
      end

      # Quotes column names for use in SQL queries.
      def quote_column_name(name) #:nodoc:
354 355 356
        %("#{name}")
      end

357 358 359
      # 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:
360 361 362 363 364
        if value.acts_like?(:time) && value.respond_to?(:usec)
          "#{super}.#{sprintf("%06d", value.usec)}"
        else
          super
        end
365 366
      end

367 368 369

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

370 371
      # Executes an INSERT query and returns the new record's ID
      def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)        
372 373
        execute(sql, name)
        table = sql.split(" ", 4)[2]
374
        id_value || last_insert_id(table, sequence_name || default_sequence_name(table, pk))
375 376
      end

377
      # Queries the database and returns the results in an Array or nil otherwise.
378
      def query(sql, name = nil) #:nodoc:
379 380 381 382 383 384 385
        log(sql, name) do
          if @async
            @connection.async_query(sql)
          else
            @connection.query(sql)
          end
        end
386 387
      end

388 389 390
      # Executes a SQL statement, returning a PGresult object on success
      # or raising a PGError exception otherwise.
      def execute(sql, name = nil)
391 392 393 394 395 396 397
        log(sql, name) do
          if @async
            @connection.async_exec(sql)
          else
            @connection.exec(sql)
          end
        end
398 399
      end

400 401
      # Executes an UPDATE query and returns the number of affected tuples.
      def update(sql, name = nil)
402 403 404
        execute(sql, name).cmdtuples
      end

405 406
      # Begins a transaction.
      def begin_db_transaction
407 408 409
        execute "BEGIN"
      end

410 411
      # Commits a transaction.
      def commit_db_transaction
412 413
        execute "COMMIT"
      end
414

415 416
      # Aborts a transaction.
      def rollback_db_transaction
417 418 419 420 421
        execute "ROLLBACK"
      end

      # SCHEMA STATEMENTS ========================================

422 423
      # Returns the list of all tables in the schema search path or a specified schema.
      def tables(name = nil)
424 425 426 427 428 429 430 431
        schemas = schema_search_path.split(/,/).map { |p| quote(p) }.join(',')
        query(<<-SQL, name).map { |row| row[0] }
          SELECT tablename
            FROM pg_tables
           WHERE schemaname IN (#{schemas})
        SQL
      end

432 433
      # Returns the list of all indexes for a table.
      def indexes(table_name, name = nil)
434 435 436 437 438 439 440 441 442
        result = query(<<-SQL, name)
          SELECT i.relname, d.indisunique, a.attname
            FROM pg_class t, pg_class i, pg_index d, pg_attribute a
           WHERE i.relkind = 'i'
             AND d.indexrelid = i.oid
             AND d.indisprimary = 'f'
             AND t.oid = d.indrelid
             AND t.relname = '#{table_name}'
             AND a.attrelid = t.oid
443 444 445 446 447
             AND ( d.indkey[0]=a.attnum OR d.indkey[1]=a.attnum
                OR d.indkey[2]=a.attnum OR d.indkey[3]=a.attnum
                OR d.indkey[4]=a.attnum OR d.indkey[5]=a.attnum
                OR d.indkey[6]=a.attnum OR d.indkey[7]=a.attnum
                OR d.indkey[8]=a.attnum OR d.indkey[9]=a.attnum )
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
          ORDER BY i.relname
        SQL

        current_index = nil
        indexes = []

        result.each do |row|
          if current_index != row[0]
            indexes << IndexDefinition.new(table_name, row[0], row[1] == "t", [])
            current_index = row[0]
          end

          indexes.last.columns << row[2]
        end

        indexes
      end

466 467 468 469 470
      # Returns the list of all column definitions for a table.
      def columns(table_name, name = nil)
        # Limit, precision, and scale are all handled by superclass.
        column_definitions(table_name).collect do |name, type, default, notnull|
          PostgreSQLColumn.new(name, default, type, notnull == 'f')
D
Initial  
David Heinemeier Hansson 已提交
471 472 473
        end
      end

474 475 476 477 478 479
      # 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)
480 481
        if schema_csv
          execute "SET search_path TO #{schema_csv}"
482
          @schema_search_path = schema_csv
483
        end
D
Initial  
David Heinemeier Hansson 已提交
484 485
      end

486 487
      # Returns the active schema search path.
      def schema_search_path
488
        @schema_search_path ||= query('SHOW search_path')[0][0]
489
      end
490

491 492 493 494 495 496 497 498 499 500 501 502
      # Returns the current client message level.
      def client_min_messages
        query('SHOW client_min_messages')[0][0]
      end

      # Set the client message level.
      def client_min_messages=(level)
        execute("SET client_min_messages TO '#{level}'")
      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:
503
        default_pk, default_seq = pk_and_sequence_for(table_name)
504
        default_seq || "#{table_name}_#{pk || default_pk || 'id'}_seq"
505 506
      end

507 508
      # Resets the sequence of a table's primary key to the maximum value.
      def reset_pk_sequence!(table, pk = nil, sequence = nil) #:nodoc:
509 510 511 512 513 514 515 516 517 518 519 520 521
        unless pk and sequence
          default_pk, default_sequence = pk_and_sequence_for(table)
          pk ||= default_pk
          sequence ||= default_sequence
        end
        if pk
          if sequence
            select_value <<-end_sql, 'Reset sequence'
              SELECT setval('#{sequence}', (SELECT COALESCE(MAX(#{pk})+(SELECT increment_by FROM #{sequence}), (SELECT min_value FROM #{sequence})) FROM #{table}), false)
            end_sql
          else
            @logger.warn "#{table} has primary key #{pk} with no default sequence" if @logger
          end
522 523 524
        end
      end

525 526
      # Returns a table's primary key and belonging sequence.
      def pk_and_sequence_for(table) #:nodoc:
527 528
        # First try looking for a sequence with a dependency on the
        # given table's primary key.
529
        result = query(<<-end_sql, 'PK and serial sequence')[0]
530
          SELECT attr.attname, seq.relname
531 532 533 534 535 536 537 538 539 540 541 542 543
          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'
            AND dep.refobjid      = '#{table}'::regclass
544
        end_sql
545 546 547 548 549

        if result.nil? or result.empty?
          # If that fails, try parsing the primary key's default value.
          # Support the 7.x and 8.0 nextval('foo'::text) as well as
          # the 8.1+ nextval('foo'::regclass).
550
          result = query(<<-end_sql, 'PK and custom sequence')[0]
551
            SELECT attr.attname, split_part(def.adsrc, '''', 2)
552 553 554 555 556 557
            FROM pg_class       t
            JOIN pg_attribute   attr ON (t.oid = attrelid)
            JOIN pg_attrdef     def  ON (adrelid = attrelid AND adnum = attnum)
            JOIN pg_constraint  cons ON (conrelid = adrelid AND adnum = conkey[1])
            WHERE t.oid = '#{table}'::regclass
              AND cons.contype = 'p'
558
              AND def.adsrc ~* 'nextval'
559 560
          end_sql
        end
561
        # [primary_key, sequence]
562
        [result.first, result.last]
563 564
      rescue
        nil
565 566
      end

567
      # Renames a table.
568 569 570
      def rename_table(name, new_name)
        execute "ALTER TABLE #{name} RENAME TO #{new_name}"
      end
571

572
      # Adds a column to a table.
S
Scott Barron 已提交
573
      def add_column(table_name, column_name, type, options = {})
574 575 576
        default = options[:default]
        notnull = options[:null] == false

577 578
        quoted_column_name = quote_column_name(column_name)

579
        # Add the column.
580
        execute("ALTER TABLE #{table_name} ADD COLUMN #{quoted_column_name} #{type_to_sql(type, options[:limit])}")
581 582

        # Set optional default. If not null, update nulls to the new default.
583
        if options_include_default?(options)
584 585
          change_column_default(table_name, column_name, default)
          if notnull
586
            execute("UPDATE #{table_name} SET #{quoted_column_name}=#{quote(default, options[:column])} WHERE #{quoted_column_name} IS NULL")
587 588 589 590
          end
        end

        if notnull
591
          execute("ALTER TABLE #{table_name} ALTER #{quoted_column_name} SET NOT NULL")
592
        end
S
Scott Barron 已提交
593
      end
D
Initial  
David Heinemeier Hansson 已提交
594

595 596
      # Changes the column of a table.
      def change_column(table_name, column_name, type, options = {})
597
        begin
598
          execute "ALTER TABLE #{table_name} ALTER COLUMN #{quote_column_name(column_name)} TYPE #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
599
        rescue ActiveRecord::StatementInvalid
600
          # This is PostgreSQL 7.x, so we have to use a more arcane way of doing it.
601
          begin_db_transaction
602 603 604
          tmp_column_name = "#{column_name}_ar_tmp"
          add_column(table_name, tmp_column_name, type, options)
          execute "UPDATE #{table_name} SET #{quote_column_name(tmp_column_name)} = CAST(#{quote_column_name(column_name)} AS #{type_to_sql(type, options[:limit], options[:precision], options[:scale])})"
605
          remove_column(table_name, column_name)
606
          rename_column(table_name, tmp_column_name, column_name)
607 608
          commit_db_transaction
        end
609 610 611 612

        if options_include_default?(options)
          change_column_default(table_name, column_name, options[:default])
        end
613
      end
614

615 616
      # Changes the default value of a table column.
      def change_column_default(table_name, column_name, default)
617
        execute "ALTER TABLE #{table_name} ALTER COLUMN #{quote_column_name(column_name)} SET DEFAULT #{quote(default)}"
618
      end
619

620 621
      # Renames a column in a table.
      def rename_column(table_name, column_name, new_column_name)
622
        execute "ALTER TABLE #{table_name} RENAME COLUMN #{quote_column_name(column_name)} TO #{quote_column_name(new_column_name)}"
623
      end
624

625 626
      # Drops an index from a table.
      def remove_index(table_name, options = {})
627
        execute "DROP INDEX #{index_name(table_name, options)}"
628
      end
629

630 631
      # Maps logical Rails types to PostgreSQL-specific data types.
      def type_to_sql(type, limit = nil, precision = nil, scale = nil)
632 633 634 635 636 637 638 639 640 641
        return super unless type.to_s == 'integer'

        if limit.nil? || limit == 4
          'integer'
        elsif limit < 4
          'smallint'
        else
          'bigint'
        end
      end
642
      
643
      # Returns a SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
644 645 646
      #
      # PostgreSQL requires the ORDER BY columns in the select list for distinct queries, and
      # requires that the ORDER BY include the distinct column.
647
      #
648
      #   distinct("posts.id", "posts.created_at desc")
649
      def distinct(columns, order_by) #:nodoc:
650 651
        return "DISTINCT #{columns}" if order_by.blank?

652 653
        # Construct a clean list of column names from the ORDER BY clause, removing
        # any ASC/DESC modifiers
654
        order_columns = order_by.split(',').collect { |s| s.split.first }
655
        order_columns.delete_if &:blank?
656
        order_columns = order_columns.zip((0...order_columns.size).to_a).map { |s,i| "#{s} AS alias_#{i}" }
657

658 659
        # Return a DISTINCT ON() clause that's distinct on the columns we want but includes
        # all the required columns for the ORDER BY to work properly.
660 661
        sql = "DISTINCT ON (#{columns}) #{columns}, "
        sql << order_columns * ', '
662
      end
663
      
664
      # Returns a ORDER BY clause for the passed order option.
665 666 667
      # 
      # PostgreSQL does not allow arbitrary ordering when using DISTINCT ON, so we work around this
      # by wrapping the sql as a sub-select and ordering in that query.
668
      def add_order_by_for_association_limiting!(sql, options) #:nodoc:
669 670 671 672 673 674 675 676
        return sql if options[:order].blank?
        
        order = options[:order].split(',').collect { |s| s.strip }.reject(&:blank?)
        order.map! { |s| 'DESC' if s =~ /\bdesc$/i }
        order = order.zip((0...order.size).to_a).map { |s,i| "id_list.alias_#{i} #{s}" }.join(', ')
        
        sql.replace "SELECT * FROM (#{sql}) AS id_list ORDER BY #{order}"
      end
677

678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
      protected
        # Returns the version of the connected PostgreSQL version.
        def postgresql_version
          @postgresql_version ||=
            if @connection.respond_to?(:server_version)
              @connection.server_version
            else
              # Mimic PGconn.server_version behavior
              begin
                query('SELECT version()')[0][0] =~ /PostgreSQL (\d+)\.(\d+)\.(\d+)/
                ($1.to_i * 10000) + ($2.to_i * 100) + $3.to_i
              rescue
                0
              end
            end
        end

D
Initial  
David Heinemeier Hansson 已提交
695
      private
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
        # The internal PostgreSQL identifer of the money data type.
        MONEY_COLUMN_TYPE_OID = 790 #:nodoc:

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

          # Ignore async_exec and async_query when using postgres-pr.
          @async = @config[:allow_concurrency] && @connection.respond_to?(:async_exec)

          # Use escape string syntax if available. We cannot do this lazily when encountering
          # the first string, because that could then break any transactions in progress.
          # See: http://www.postgresql.org/docs/current/static/runtime-config-compatible.html
          # If PostgreSQL doesn't know the standard_conforming_strings parameter then it doesn't
          # support escape string syntax. Don't override the inherited quoted_string_prefix.
          if supports_standard_conforming_strings?
            self.class.instance_eval do
              define_method(:quoted_string_prefix) { 'E' }
            end
          end
718

719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
          # 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.
          money_precision = (postgresql_version >= 80300) ? 19 : 10
          PostgreSQLColumn.module_eval(<<-end_eval)
            def extract_precision(sql_type)
              if sql_type =~ /^money$/
                #{money_precision}
              else
                super
              end
            end
          end_eval

          configure_connection
        end

        # Configures the encoding, verbosity, and schema search path of the connection.
        # This is called by #connect and should not be called manually.
738 739
        def configure_connection
          if @config[:encoding]
740 741 742 743 744
            if @connection.respond_to?(:set_client_encoding)
              @connection.set_client_encoding(@config[:encoding])
            else
              execute("SET client_encoding TO '#{@config[:encoding]}'")
            end
745
          end
746 747
          self.client_min_messages = @config[:min_messages] if @config[:min_messages]
          self.schema_search_path = @config[:schema_search_path] || @config[:schema_order]
748 749
        end

750 751
        # Returns the current ID of a table's sequence.
        def last_insert_id(table, sequence_name) #:nodoc:
752
          Integer(select_value("SELECT currval('#{sequence_name}')"))
D
Initial  
David Heinemeier Hansson 已提交
753 754
        end

755 756
        # Executes a SELECT query and returns the results, performing any data type
        # conversions that require to be performed here instead of in PostgreSQLColumn.
D
Initial  
David Heinemeier Hansson 已提交
757
        def select(sql, name = nil)
758
          res = execute(sql, name)
759
          results = res.result
M
Marcel Molina 已提交
760 761 762 763 764
          rows = []
          if results.length > 0
            fields = res.fields
            results.each do |row|
              hashed_row = {}
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
              row.each_index do |cell_index|
                column = row[cell_index]

                # 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
                # PostgresSQLColumn.string_to_decimal but would break form input
                # fields that call value_before_type_cast.
                if res.type(cell_index) == MONEY_COLUMN_TYPE_OID
                  # Because money output is formatted according to the locale, there are two
                  # cases to consider (note the decimal seperators):
                  #  (1) $12,345,678.12        
                  #  (2) $12.345.678,12
                  case column
                    when /^-?\D+[\d,]+\.\d{2}$/  # (1)
                      column = column.gsub(/[^-\d\.]/, '')
                    when /^-?\D+[\d\.]+,\d{2}$/  # (2)
                      column = column.gsub(/[^-\d,]/, '').sub(/,/, '.')
                  end
M
Marcel Molina 已提交
783
                end
784

785
                hashed_row[fields[cell_index]] = column
M
Marcel Molina 已提交
786 787 788 789
              end
              rows << hashed_row
            end
          end
790
          res.clear
M
Marcel Molina 已提交
791 792 793
          return rows
        end

794
        # Returns the list of a table's column names, data types, and default values.
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
        #
        # 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
812
        def column_definitions(table_name) #:nodoc:
813
          query <<-end_sql
814
            SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull
815 816 817 818 819 820
              FROM pg_attribute a LEFT JOIN pg_attrdef d
                ON a.attrelid = d.adrelid AND a.attnum = d.adnum
             WHERE a.attrelid = '#{table_name}'::regclass
               AND a.attnum > 0 AND NOT a.attisdropped
             ORDER BY a.attnum
          end_sql
D
Initial  
David Heinemeier Hansson 已提交
821 822 823 824
        end
    end
  end
end