postgresql_adapter.rb 44.8 KB
Newer Older
D
Initial  
David Heinemeier Hansson 已提交
1
require 'active_record/connection_adapters/abstract_adapter'
2
require 'active_support/core_ext/object/blank'
3
require 'active_record/connection_adapters/statement_pool'
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

module ActiveRecord
10
  module ConnectionHandling
D
Initial  
David Heinemeier Hansson 已提交
11
    # Establishes a connection to the database that's used by all Active Record objects
J
Jon Leighton 已提交
12
    def postgresql_connection(config) # :nodoc:
13
      conn_params = config.symbolize_keys
D
Initial  
David Heinemeier Hansson 已提交
14

15
      # Forward any unused config params to PGconn.connect.
16
      [:statement_limit, :encoding, :min_messages, :schema_search_path,
17
       :schema_order, :adapter, :pool, :wait_timeout, :template,
18 19 20
       :reaping_frequency].each do |key|
        conn_params.delete key
      end
21
      conn_params.delete_if { |k,v| v.nil? }
22 23 24 25

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

27
      # The postgres drivers don't allow the creation of an unconnected PGconn object,
28
      # so just pass a nil connection object for the time being.
29
      ConnectionAdapters::PostgreSQLAdapter.new(nil, logger, conn_params, config)
30 31
    end
  end
32

33 34 35 36 37 38 39
  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
40

41 42 43
      # :stopdoc:
      class << self
        attr_accessor :money_precision
44 45 46 47 48 49 50 51 52 53
        def string_to_time(string)
          return string unless String === string

          case string
          when 'infinity'  then 1.0 / 0.0
          when '-infinity' then -1.0 / 0.0
          else
            super
          end
        end
54

55
        def hstore_to_string(object)
56
          if Hash === object
A
Aaron Patterson 已提交
57 58
            object.map { |k,v|
              "#{escape_hstore(k)}=>#{escape_hstore(v)}"
59
            }.join ','
60
          else
61
            object
A
Aaron Patterson 已提交
62 63 64
          end
        end

65 66 67 68 69 70 71 72 73 74 75 76
        def string_to_hstore(string)
          if string.nil?
            nil
          elsif String === string
            Hash[string.scan(HstorePair).map { |k,v|
              v = v.upcase == 'NULL' ? nil : v.gsub(/^"(.*)"$/,'\1').gsub(/\\(.)/, '\1')
              k = k.gsub(/^"(.*)"$/,'\1').gsub(/\\(.)/, '\1')
              [k,v]
            }]
          else
            string
          end
77
        end
78

79
        private
80 81 82 83
        HstorePair = begin
          quoted_string = /"[^"\\]*(?:\\.[^"\\]*)*"/
          unquoted_string = /(?:\\.|[^\s,])[^\s=,\\]*(?:\\.[^\s=,\\]*|=[^,>])*/
          /(#{quoted_string}|#{unquoted_string})\s*=>\s*(#{quoted_string}|#{unquoted_string})/
A
Aaron Patterson 已提交
84 85 86
        end

        def escape_hstore(value)
87 88 89
            value.nil?         ? 'NULL'
          : value =~ /[=\s,>]/ ? '"%s"' % value.gsub(/(["\\])/, '\\\\\1')
          : value == ""        ? '""'
J
Joel 已提交
90
          :                      value.to_s.gsub(/(["\\])/, '\\\\\1')
91
        end
92 93 94
      end
      # :startdoc:

95
      private
96
        def extract_limit(sql_type)
97 98 99 100 101
          case sql_type
          when /^bigint/i;    8
          when /^smallint/i;  2
          else super
          end
102 103
        end

104 105 106 107 108
        # 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
109

110 111
        # Extracts the precision from PostgreSQL-specific data types.
        def extract_precision(sql_type)
112 113 114 115 116
          if sql_type == 'money'
            self.class.money_precision
          else
            super
          end
117
        end
118

119 120 121
        # Maps PostgreSQL-specific data types to logical Rails types.
        def simplified_type(field_type)
          case field_type
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
          # Numeric and monetary types
          when /^(?:real|double precision)$/
            :float
          # Monetary types
          when 'money'
            :decimal
          when 'hstore'
            :hstore
          # 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'
            :xml
          # tsvector type
          when 'tsvector'
            :tsvector
          # Arrays
          when /^\D+\[\]$/
            :string
          # Object identifier types
          when 'oid'
            :integer
          # UUID type
          when 'uuid'
            :string
          # Small and big integer types
          when /^(?:small|big)int$/
            :integer
          # Pass through all types that are not specific to PostgreSQL.
          else
            super
171 172
          end
        end
173

174 175
        # Extracts the value from a PostgreSQL column default definition.
        def self.extract_value_from_default(default)
A
Aaron Patterson 已提交
176 177 178 179 180 181 182 183
          # 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.
          return default unless default

184 185
          case default
            # Numeric types
186 187
            when /\A\(?(-?\d+(\.\d*)?\)?)\z/
              $1
188
            # Character types
189
            when /\A'(.*)'::(?:character varying|bpchar|text)\z/m
190
              $1
191 192 193
            # Character types (8.1 formatting)
            when /\AE'(.*)'::(?:character varying|bpchar|text)\z/m
              $1.gsub(/\\(\d\d\d)/) { $1.oct.chr }
194
            # Binary data types
195
            when /\A'(.*)'::bytea\z/m
196 197
              $1
            # Date/time types
198
            when /\A'(.+)'::(?:time(?:stamp)? with(?:out)? time zone|date)\z/
199
              $1
200
            when /\A'(.*)'::interval\z/
201 202
              $1
            # Boolean type
203
            when 'true'
204
              true
205
            when 'false'
206 207
              false
            # Geometric types
208
            when /\A'(.*)'::(?:point|line|lseg|box|"?path"?|polygon|circle)\z/
209 210
              $1
            # Network address types
211
            when /\A'(.*)'::(?:cidr|inet|macaddr)\z/
212 213
              $1
            # Bit string types
214
            when /\AB'(.*)'::"?bit(?: varying)?"?\z/
215 216
              $1
            # XML type
217
            when /\A'(.*)'::xml\z/m
218 219
              $1
            # Arrays
220
            when /\A'(.*)'::"?\D+"?\[\]\z/
221
              $1
222 223 224
            # Hstore
            when /\A'(.*)'::hstore\z/
              $1
225
            # Object identifier types
226
            when /\A-?\d+\z/
227 228 229
              $1
            else
              # Anything else is blank, some user type, or some function
230
              # and we can't know the value of that, so return nil.
231 232 233
              nil
          end
        end
D
Initial  
David Heinemeier Hansson 已提交
234 235
    end

236
    # The PostgreSQL adapter works with the native C (https://bitbucket.org/ged/ruby-pg) driver.
237 238 239
    #
    # Options:
    #
240 241
    # * <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 已提交
242
    # * <tt>:port</tt> - Defaults to 5432.
243 244 245
    # * <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.
246
    # * <tt>:schema_search_path</tt> - An optional schema search path for the connection given
247
    #   as a string of comma-separated schema names. This is backward-compatible with the <tt>:schema_order</tt> option.
248
    # * <tt>:encoding</tt> - An optional client encoding that is used in a <tt>SET client_encoding TO
249
    #   <encoding></tt> call on the connection.
250
    # * <tt>:min_messages</tt> - An optional client min messages that is used in a
251
    #   <tt>SET client_min_messages TO <min_messages></tt> call on the connection.
252 253 254 255 256 257 258
    #
    # Any further options are used as connection parameters to libpq. See
    # http://www.postgresql.org/docs/9.1/static/libpq-connect.html for the
    # list of parameters.
    #
    # In addition, default connection parameters of libpq can be set per environment variables.
    # See http://www.postgresql.org/docs/9.1/static/libpq-envars.html .
259
    class PostgreSQLAdapter < AbstractAdapter
260 261 262 263 264
      class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition
        def xml(*args)
          options = args.extract_options!
          column(args[0], 'xml', options)
        end
265 266 267 268 269

        def tsvector(*args)
          options = args.extract_options!
          column(args[0], 'tsvector', options)
        end
270 271 272 273

        def hstore(name, options = {})
          column(name, 'hstore', options)
        end
274 275
      end

276
      ADAPTER_NAME = 'PostgreSQL'
277 278

      NATIVE_DATABASE_TYPES = {
279
        :primary_key => "serial primary key",
280 281 282 283 284 285 286 287 288 289
        :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" },
290
        :boolean     => { :name => "boolean" },
291
        :xml         => { :name => "xml" },
292 293
        :tsvector    => { :name => "tsvector" },
        :hstore      => { :name => "hstore" }
294 295
      }

296
      # Returns 'PostgreSQL' as adapter name for identification purposes.
297
      def adapter_name
298
        ADAPTER_NAME
299 300
      end

301 302
      # Returns +true+, since this connection adapter supports prepared statement
      # caching.
303 304 305 306
      def supports_statement_cache?
        true
      end

307 308 309 310
      def supports_index_sort_order?
        true
      end

311 312 313 314
      class StatementPool < ConnectionAdapters::StatementPool
        def initialize(connection, max)
          super
          @counter = 0
315
          @cache   = Hash.new { |h,pid| h[pid] = {} }
316 317
        end

318 319 320 321
        def each(&block); cache.each(&block); end
        def key?(key);    cache.key?(key); end
        def [](key);      cache[key]; end
        def length;       cache.length; end
322 323 324 325 326 327

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

        def []=(sql, key)
328 329
          while @max <= cache.size
            dealloc(cache.shift.last)
330 331
          end
          @counter += 1
332
          cache[sql] = key
333 334 335
        end

        def clear
336
          cache.each_value do |stmt_key|
337 338
            dealloc stmt_key
          end
339
          cache.clear
340 341
        end

342 343 344 345 346
        def delete(sql_key)
          dealloc cache[sql_key]
          cache.delete sql_key
        end

347
        private
348 349 350 351
        def cache
          @cache[$$]
        end

352
        def dealloc(key)
353 354 355 356 357 358 359
          @connection.query "DEALLOCATE #{key}" if connection_active?
        end

        def connection_active?
          @connection.status == PGconn::CONNECTION_OK
        rescue PGError
          false
360 361 362
        end
      end

363 364
      # Initializes and connects a PostgreSQL adapter.
      def initialize(connection, logger, connection_parameters, config)
365
        super(connection, logger)
366
        @connection_parameters, @config = connection_parameters, config
367
        @visitor = Arel::Visitors::PostgreSQL.new self
368

369 370
        # @local_tz is initialized as nil to avoid warnings when connect tries to use it
        @local_tz = nil
371 372
        @table_alias_length = nil

373
        connect
374 375
        @statements = StatementPool.new @connection,
                                        config.fetch(:statement_limit) { 1000 }
376 377 378 379 380

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

381
        @local_tz = execute('SHOW TIME ZONE', 'SCHEMA').first["TimeZone"]
382 383
      end

X
Xavier Noria 已提交
384
      # Clears the prepared statements cache.
385 386 387 388
      def clear_cache!
        @statements.clear
      end

389 390
      # Is this connection alive and ready for queries?
      def active?
391 392
        @connection.status == PGconn::CONNECTION_OK
      rescue PGError
393
        false
394 395 396 397
      end

      # Close then reopen the connection.
      def reconnect!
398 399 400
        clear_cache!
        @connection.reset
        configure_connection
401
      end
402

403 404 405 406 407
      def reset!
        clear_cache!
        super
      end

408 409
      # Disconnects from the database if already connected. Otherwise, this
      # method does nothing.
410
      def disconnect!
411
        clear_cache!
412 413
        @connection.close rescue nil
      end
414

415
      def native_database_types #:nodoc:
416
        NATIVE_DATABASE_TYPES
417
      end
418

419
      # Returns true, since this connection adapter supports migrations.
420 421
      def supports_migrations?
        true
422 423
      end

424
      # Does PostgreSQL support finding primary key on non-Active Record tables?
425 426 427 428
      def supports_primary_key? #:nodoc:
        true
      end

429 430 431
      # Enable standard-conforming strings if available.
      def set_standard_conforming_strings
        old, self.client_min_messages = client_min_messages, 'panic'
432
        execute('SET standard_conforming_strings = on', 'SCHEMA') rescue nil
433 434
      ensure
        self.client_min_messages = old
435 436
      end

437
      def supports_insert_with_returning?
438
        true
439 440
      end

441 442 443
      def supports_ddl_transactions?
        true
      end
444

445
      # Returns true, since this connection adapter supports savepoints.
446 447 448
      def supports_savepoints?
        true
      end
449

450 451 452 453 454
      # Returns true.
      def supports_explain?
        true
      end

455
      # Returns the configured supported identifier length supported by PostgreSQL
456
      def table_alias_length
457
        @table_alias_length ||= query('SHOW max_identifier_length')[0][0].to_i
458
      end
459

460 461
      # QUOTING ==================================================

462
      # Escapes binary strings for bytea input to the database.
463
      def escape_bytea(value)
464
        PGconn.escape_bytea(value) if value
465 466 467 468 469
      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.
470
      def unescape_bytea(value)
471
        PGconn.unescape_bytea(value) if value
472 473
      end

474 475
      # Quotes PostgreSQL-specific data types for SQL input.
      def quote(value, column = nil) #:nodoc:
476 477
        return super unless column

A
Aaron Patterson 已提交
478
        case value
479 480 481
        when Float
          return super unless value.infinite? && column.type == :datetime
          "'#{value.to_s.downcase}'"
A
Aaron Patterson 已提交
482 483
        when Numeric
          return super unless column.sql_type == 'money'
484
          # Not truly string input, so doesn't require (or allow) escape string syntax.
485
          "'#{value}'"
A
Aaron Patterson 已提交
486 487 488 489 490 491 492 493 494 495 496
        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
497
          end
498 499 500 501 502
        else
          super
        end
      end

503 504 505 506 507 508
      def type_cast(value, column)
        return super unless column

        case value
        when String
          return super unless 'bytea' == column.sql_type
509
          { :value => value, :format => 1 }
510 511 512
        when Hash
          return super unless 'hstore' == column.sql_type
          PostgreSQLColumn.hstore_to_string(value)
513 514 515 516 517
        else
          super
        end
      end

518 519 520
      # Quotes strings for use in SQL input.
      def quote_string(s) #:nodoc:
        @connection.escape(s)
521 522
      end

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
      # 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

542 543
      # Quotes column names for use in SQL queries.
      def quote_column_name(name) #:nodoc:
544
        PGconn.quote_ident(name.to_s)
545 546
      end

547 548 549
      # 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:
550 551 552 553 554
        if value.acts_like?(:time) && value.respond_to?(:usec)
          "#{super}.#{sprintf("%06d", value.usec)}"
        else
          super
        end
555 556
      end

557 558
      # Set the authorized user for this session
      def session_auth=(user)
559
        clear_cache!
A
Aaron Patterson 已提交
560
        exec_query "SET SESSION AUTHORIZATION #{user}"
561 562
      end

563 564
      # REFERENTIAL INTEGRITY ====================================

565
      def supports_disable_referential_integrity? #:nodoc:
566
        true
567 568
      end

569
      def disable_referential_integrity #:nodoc:
570
        if supports_disable_referential_integrity? then
571 572
          execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} DISABLE TRIGGER ALL" }.join(";"))
        end
573 574
        yield
      ensure
575
        if supports_disable_referential_integrity? then
576 577
          execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} ENABLE TRIGGER ALL" }.join(";"))
        end
578
      end
579 580 581

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

582
      def explain(arel, binds = [])
X
Xavier Noria 已提交
583
        sql = "EXPLAIN #{to_sql(arel)}"
584
        ExplainPrettyPrinter.new.pp(exec_query(sql, 'EXPLAIN', binds))
X
Xavier Noria 已提交
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
      end

      class ExplainPrettyPrinter # :nodoc:
        # Pretty prints the result of a EXPLAIN in a way that resembles the output of the
        # PostgreSQL shell:
        #
        #                                     QUERY PLAN
        #   ------------------------------------------------------------------------------
        #    Nested Loop Left Join  (cost=0.00..37.24 rows=8 width=0)
        #      Join Filter: (posts.user_id = users.id)
        #      ->  Index Scan using users_pkey on users  (cost=0.00..8.27 rows=1 width=4)
        #            Index Cond: (id = 1)
        #      ->  Seq Scan on posts  (cost=0.00..28.88 rows=8 width=4)
        #            Filter: (posts.user_id = 1)
        #   (6 rows)
        #
        def pp(result)
          header = result.columns.first
          lines  = result.rows.map(&:first)

          # We add 2 because there's one char of padding at both sides, note
          # the extra hyphens in the example above.
          width = [header, *lines].map(&:length).max + 2

          pp = []

          pp << header.center(width).rstrip
          pp << '-' * width

          pp += lines.map {|line| " #{line}"}

          nrows = result.rows.length
          rows_label = nrows == 1 ? 'row' : 'rows'
          pp << "(#{nrows} #{rows_label})"

          pp.join("\n") + "\n"
        end
      end

624 625 626 627 628 629
      # 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

630
      # Executes an INSERT query and returns the new record's ID
631
      def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
632 633 634 635 636
        unless pk
          # Extract the table from the insert sql. Yuck.
          table_ref = extract_table_ref_from_insert_sql(sql)
          pk = primary_key(table_ref) if table_ref
        end
637

638
        if pk
639 640 641
          select_value("#{sql} RETURNING #{quote_column_name(pk)}")
        else
          super
642
        end
643
      end
644
      alias :create :insert
645

646 647
      # create a 2D array representing the result set
      def result_as_array(res) #:nodoc:
648
        # check if we have any binary column and if they need escaping
649 650
        ftypes = Array.new(res.nfields) do |i|
          [i, res.ftype(i)]
651 652
        end

653 654 655 656 657 658
        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 }
659 660
        binaries = typehash[BYTEA_COLUMN_TYPE_OID] || []
        monies   = typehash[MONEY_COLUMN_TYPE_OID] || []
661 662 663

        rows.each do |row|
          # unescape string passed BYTEA field (OID == 17)
664 665
          binaries.each do |index, _|
            row[index] = unescape_bytea(row[index])
666 667 668 669 670 671
          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.
672
          monies.each do |index, _|
673 674 675 676 677 678 679 680 681 682
            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!(/,/, '.')
683
            end
684 685 686 687 688 689
          end
        end
      end


      # Queries the database and returns the results in an Array-like object
690
      def query(sql, name = nil) #:nodoc:
691
        log(sql, name) do
692
          result_as_array @connection.async_exec(sql)
693
        end
694 695
      end

696
      # Executes an SQL statement, returning a PGresult object on success
697 698
      # or raising a PGError exception otherwise.
      def execute(sql, name = nil)
699
        log(sql, name) do
700
          @connection.async_exec(sql)
701
        end
702 703
      end

704 705
      def substitute_at(column, index)
        Arel.sql("$#{index + 1}")
706 707
      end

A
Aaron Patterson 已提交
708
      def exec_query(sql, name = 'SQL', binds = [])
709
        log(sql, name, binds) do
710 711
          result = binds.empty? ? exec_no_cache(sql, binds) :
                                  exec_cache(sql, binds)
712

713 714 715
          ret = ActiveRecord::Result.new(result.fields, result_as_array(result))
          result.clear
          return ret
716 717 718
        end
      end

719 720 721 722 723 724 725 726 727
      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
728
      alias :exec_update :exec_delete
729

730 731
      def sql_for_insert(sql, pk, id_value, sequence_name, binds)
        unless pk
732 733 734
          # Extract the table from the insert sql. Yuck.
          table_ref = extract_table_ref_from_insert_sql(sql)
          pk = primary_key(table_ref) if table_ref
735 736 737 738 739 740 741
        end

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

        [sql, binds]
      end

742
      # Executes an UPDATE query and returns the number of affected tuples.
743
      def update_sql(sql, name = nil)
744
        super.cmd_tuples
745 746
      end

747 748
      # Begins a transaction.
      def begin_db_transaction
749 750 751
        execute "BEGIN"
      end

752 753
      # Commits a transaction.
      def commit_db_transaction
754 755
        execute "COMMIT"
      end
756

757 758
      # Aborts a transaction.
      def rollback_db_transaction
759 760
        execute "ROLLBACK"
      end
761

762 763
      def outside_transaction?
        @connection.transaction_status == PGconn::PQTRANS_IDLE
764
      end
765

J
Jonathan Viney 已提交
766 767 768 769 770 771 772 773
      def create_savepoint
        execute("SAVEPOINT #{current_savepoint_name}")
      end

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

774
      def release_savepoint
J
Jonathan Viney 已提交
775 776
        execute("RELEASE SAVEPOINT #{current_savepoint_name}")
      end
777

778 779
      # SCHEMA STATEMENTS ========================================

780 781 782
      # Drops the database specified on the +name+ attribute
      # and creates it again using the provided +options+.
      def recreate_database(name, options = {}) #:nodoc:
783
        drop_database(name)
784
        create_database(name, options)
785 786
      end

787
      # Create a new PostgreSQL database. Options include <tt>:owner</tt>, <tt>:template</tt>,
788 789
      # <tt>:encoding</tt>, <tt>:tablespace</tt>, and <tt>:connection_limit</tt> (note that MySQL uses
      # <tt>:charset</tt> while PostgreSQL uses <tt>:encoding</tt>).
790 791 792 793 794 795 796 797 798 799
      #
      # 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
800
            " OWNER = \"#{value}\""
801
          when :template
802
            " TEMPLATE = \"#{value}\""
803 804 805
          when :encoding
            " ENCODING = '#{value}'"
          when :tablespace
806
            " TABLESPACE = \"#{value}\""
807 808 809 810 811 812 813
          when :connection_limit
            " CONNECTION LIMIT = #{value}"
          else
            ""
          end
        end

814
        execute "CREATE DATABASE #{quote_table_name(name)}#{option_string}"
815 816
      end

817
      # Drops a PostgreSQL database.
818 819 820 821
      #
      # Example:
      #   drop_database 'matt_development'
      def drop_database(name) #:nodoc:
822
        execute "DROP DATABASE IF EXISTS #{quote_table_name(name)}"
823 824
      end

825 826
      # Returns the list of all tables in the schema search path or a specified schema.
      def tables(name = nil)
827
        query(<<-SQL, 'SCHEMA').map { |row| row[0] }
828
          SELECT tablename
829 830 831 832 833
          FROM pg_tables
          WHERE schemaname = ANY (current_schemas(false))
        SQL
      end

834
      # Returns true if table exists.
835 836
      # If the schema is not specified as part of +name+ then it will only find tables within
      # the current schema search path (regardless of permissions to access tables in other schemas)
837
      def table_exists?(name)
838
        schema, table = Utils.extract_schema_and_table(name.to_s)
839
        return false unless table
840

841 842
        binds = [[nil, table]]
        binds << [nil, schema] if schema
843 844

        exec_query(<<-SQL, 'SCHEMA', binds).rows.first[0].to_i > 0
845
            SELECT COUNT(*)
A
Aaron Patterson 已提交
846 847 848 849 850
            FROM pg_class c
            LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
            WHERE c.relkind in ('v','r')
            AND c.relname = $1
            AND n.nspname = #{schema ? '$2' : 'ANY (current_schemas(false))'}
851 852 853
        SQL
      end

854 855 856 857 858 859 860 861
      # Returns true if schema exists.
      def schema_exists?(name)
        exec_query(<<-SQL, 'SCHEMA', [[nil, name]]).rows.first[0].to_i > 0
          SELECT COUNT(*)
          FROM pg_namespace
          WHERE nspname = $1
        SQL
      end
862

863
      # Returns an array of indexes for the given table.
864
      def indexes(table_name, name = nil)
865
         result = query(<<-SQL, name)
866
           SELECT distinct i.relname, d.indisunique, d.indkey, pg_get_indexdef(d.indexrelid), t.oid
867 868 869
           FROM pg_class t
           INNER JOIN pg_index d ON t.oid = d.indrelid
           INNER JOIN pg_class i ON d.indexrelid = i.oid
870 871 872
           WHERE i.relkind = 'i'
             AND d.indisprimary = 'f'
             AND t.relname = '#{table_name}'
873
             AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname = ANY (current_schemas(false)) )
874 875 876
          ORDER BY i.relname
        SQL

877

878
        result.map do |row|
879 880 881
          index_name = row[0]
          unique = row[1] == 't'
          indkey = row[2].split(" ")
882 883
          inddef = row[3]
          oid = row[4]
884

885 886
          columns = Hash[query(<<-SQL, "Columns for index #{row[0]} on #{table_name}")]
          SELECT a.attnum, a.attname
887 888 889 890 891
          FROM pg_attribute a
          WHERE a.attrelid = #{oid}
          AND a.attnum IN (#{indkey.join(",")})
          SQL

892
          column_names = columns.values_at(*indkey).compact
893 894 895 896

          # add info on sort order for columns (only desc order is explicitly specified, asc is the default)
          desc_order_columns = inddef.scan(/(\w+) DESC/).flatten
          orders = desc_order_columns.any? ? Hash[desc_order_columns.map {|order_column| [order_column, :desc]}] : {}
J
Jon Leighton 已提交
897

898
          column_names.empty? ? nil : IndexDefinition.new(table_name, index_name, unique, column_names, [], orders)
899
        end.compact
900 901
      end

902
      # Returns the list of all column definitions for a table.
903
      def columns(table_name)
904
        # Limit, precision, and scale are all handled by the superclass.
905 906
        column_definitions(table_name).collect do |column_name, type, default, notnull|
          PostgreSQLColumn.new(column_name, default, type, notnull == 'f')
D
Initial  
David Heinemeier Hansson 已提交
907 908 909
        end
      end

910 911 912 913 914
      # Returns the current database name.
      def current_database
        query('select current_database()')[0][0]
      end

915 916 917 918 919
      # Returns the current schema name.
      def current_schema
        query('SELECT current_schema', 'SCHEMA')[0][0]
      end

920 921 922 923 924 925 926 927
      # 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

928 929 930 931 932 933
      # 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)
934 935
        if schema_csv
          execute "SET search_path TO #{schema_csv}"
936
          @schema_search_path = schema_csv
937
        end
D
Initial  
David Heinemeier Hansson 已提交
938 939
      end

940 941
      # Returns the active schema search path.
      def schema_search_path
X
Xavier Noria 已提交
942
        @schema_search_path ||= query('SHOW search_path', 'SCHEMA')[0][0]
943
      end
944

945 946
      # Returns the current client message level.
      def client_min_messages
947
        query('SHOW client_min_messages', 'SCHEMA')[0][0]
948 949 950 951
      end

      # Set the client message level.
      def client_min_messages=(level)
952
        execute("SET client_min_messages TO '#{level}'", 'SCHEMA')
953 954 955 956
      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:
957 958 959 960 961 962 963 964 965 966
        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
967 968
      end

969 970
      # Resets the sequence of a table's primary key to the maximum value.
      def reset_pk_sequence!(table, pk = nil, sequence = nil) #:nodoc:
971 972
        unless pk and sequence
          default_pk, default_sequence = pk_and_sequence_for(table)
973

974 975 976
          pk ||= default_pk
          sequence ||= default_sequence
        end
977

978 979 980 981 982
        if @logger && pk && !sequence
          @logger.warn "#{table} has primary key #{pk} with no default sequence"
        end

        if pk && sequence
983
          quoted_sequence = quote_table_name(sequence)
G
Guillermo Iguaran 已提交
984

985 986 987
          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
988 989 990
        end
      end

991 992
      # Returns a table's primary key and belonging sequence.
      def pk_and_sequence_for(table) #:nodoc:
993 994
        # First try looking for a sequence with a dependency on the
        # given table's primary key.
995
        result = exec_query(<<-end_sql, 'SCHEMA').rows.first
996
          SELECT attr.attname, ns.nspname, seq.relname
997
          FROM pg_class seq
A
Akira Matsuda 已提交
998
          INNER JOIN pg_depend dep ON seq.oid = dep.objid
999 1000
          INNER JOIN pg_attribute attr ON attr.attrelid = dep.refobjid AND attr.attnum = dep.refobjsubid
          INNER JOIN pg_constraint cons ON attr.attrelid = cons.conrelid AND attr.attnum = cons.conkey[1]
1001
          INNER JOIN pg_namespace ns ON seq.relnamespace = ns.oid
1002 1003 1004
          WHERE seq.relkind  = 'S'
            AND cons.contype = 'p'
            AND dep.refobjid = '#{quote_table_name(table)}'::regclass
1005
        end_sql
1006

1007
        # [primary_key, sequence]
1008 1009 1010 1011 1012
        if result.second ==  'public' then
          sequence = result.last
        else
          sequence = result.second+'.'+result.last
        end
G
Guillermo Iguaran 已提交
1013

1014
        [result.first, sequence]
1015 1016
      rescue
        nil
1017 1018
      end

1019 1020
      # Returns just a table's primary key
      def primary_key(table)
1021
        row = exec_query(<<-end_sql, 'SCHEMA', [[nil, table]]).rows.first
1022
          SELECT DISTINCT(attr.attname)
1023 1024 1025 1026 1027
          FROM pg_attribute attr
          INNER JOIN pg_depend dep ON attr.attrelid = dep.refobjid AND attr.attnum = dep.refobjsubid
          INNER JOIN pg_constraint cons ON attr.attrelid = cons.conrelid AND attr.attnum = cons.conkey[1]
          WHERE cons.contype = 'p'
            AND dep.refobjid = $1::regclass
1028 1029 1030
        end_sql

        row && row.first
1031 1032
      end

1033
      # Renames a table.
1034 1035 1036
      #
      # Example:
      #   rename_table('octopuses', 'octopi')
1037
      def rename_table(name, new_name)
1038
        clear_cache!
1039
        execute "ALTER TABLE #{quote_table_name(name)} RENAME TO #{quote_table_name(new_name)}"
1040
      end
1041

1042 1043
      # Adds a new column to the named table.
      # See TableDefinition#column for details of the options you can use.
S
Scott Barron 已提交
1044
      def add_column(table_name, column_name, type, options = {})
1045
        clear_cache!
1046 1047
        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)
1048

1049
        execute add_column_sql
S
Scott Barron 已提交
1050
      end
D
Initial  
David Heinemeier Hansson 已提交
1051

1052 1053
      # Changes the column of a table.
      def change_column(table_name, column_name, type, options = {})
1054
        clear_cache!
1055 1056
        quoted_table_name = quote_table_name(table_name)

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

1059 1060
        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)
1061
      end
1062

1063 1064
      # Changes the default value of a table column.
      def change_column_default(table_name, column_name, default)
1065
        clear_cache!
1066
        execute "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} SET DEFAULT #{quote(default)}"
1067
      end
1068

1069
      def change_column_null(table_name, column_name, null, default = nil)
1070
        clear_cache!
1071
        unless null || default.nil?
1072
          execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL")
1073
        end
1074
        execute("ALTER TABLE #{quote_table_name(table_name)} ALTER #{quote_column_name(column_name)} #{null ? 'DROP' : 'SET'} NOT NULL")
1075 1076
      end

1077 1078
      # Renames a column in a table.
      def rename_column(table_name, column_name, new_column_name)
1079
        clear_cache!
1080
        execute "ALTER TABLE #{quote_table_name(table_name)} RENAME COLUMN #{quote_column_name(column_name)} TO #{quote_column_name(new_column_name)}"
1081
      end
1082

1083 1084 1085 1086
      def remove_index!(table_name, index_name) #:nodoc:
        execute "DROP INDEX #{quote_table_name(index_name)}"
      end

1087 1088 1089 1090
      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

1091 1092
      def index_name_length
        63
1093
      end
1094

1095 1096
      # Maps logical Rails types to PostgreSQL-specific data types.
      def type_to_sql(type, limit = nil, precision = nil, scale = nil)
1097
        return super unless type.to_s == 'integer'
1098
        return 'integer' unless limit
1099

1100
        case limit
1101 1102 1103
          when 1, 2; 'smallint'
          when 3, 4; 'integer'
          when 5..8; 'bigint'
1104
          else raise(ActiveRecordError, "No integer type has byte size #{limit}. Use a numeric with precision 0 instead.")
1105 1106
        end
      end
1107

1108
      # Returns a SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
1109 1110 1111
      #
      # PostgreSQL requires the ORDER BY columns in the select list for distinct queries, and
      # requires that the ORDER BY include the distinct column.
1112
      #
1113
      #   distinct("posts.id", "posts.created_at desc")
1114 1115
      def distinct(columns, orders) #:nodoc:
        return "DISTINCT #{columns}" if orders.empty?
1116

1117 1118
        # Construct a clean list of column names from the ORDER BY clause, removing
        # any ASC/DESC modifiers
1119
        order_columns = orders.collect { |s| s.gsub(/\s+(ASC|DESC)\s*/i, '') }
1120
        order_columns.delete_if { |c| c.blank? }
1121
        order_columns = order_columns.zip((0...order_columns.size).to_a).map { |s,i| "#{s} AS alias_#{i}" }
1122

1123
        "DISTINCT #{columns}, #{order_columns * ', '}"
1124
      end
1125

1126
      module Utils
1127 1128
        extend self

1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
        # Returns an array of <tt>[schema_name, table_name]</tt> extracted from +name+.
        # +schema_name+ is nil if not specified in +name+.
        # +schema_name+ and +table_name+ exclude surrounding quotes (regardless of whether provided in +name+)
        # +name+ supports the range of schema/table references understood by PostgreSQL, for example:
        #
        # * <tt>table_name</tt>
        # * <tt>"table.name"</tt>
        # * <tt>schema_name.table_name</tt>
        # * <tt>schema_name."table.name"</tt>
        # * <tt>"schema.name"."table name"</tt>
1139
        def extract_schema_and_table(name)
1140 1141 1142 1143 1144
          table, schema = name.scan(/[^".\s]+|"[^"]*"/)[0..1].collect{|m| m.gsub(/(^"|"$)/,'') }.reverse
          [schema, table]
        end
      end

1145
      protected
1146
        # Returns the version of the connected PostgreSQL server.
1147
        def postgresql_version
1148
          @connection.server_version
1149 1150
        end

1151 1152 1153
        def translate_exception(exception, message)
          case exception.message
          when /duplicate key value violates unique constraint/
1154
            RecordNotUnique.new(message, exception)
1155
          when /violates foreign key constraint/
1156
            InvalidForeignKey.new(message, exception)
1157 1158 1159 1160 1161
          else
            super
          end
        end

D
Initial  
David Heinemeier Hansson 已提交
1162
      private
1163 1164
        FEATURE_NOT_SUPPORTED = "0A000" # :nodoc:

1165 1166
        def exec_no_cache(sql, binds)
          @connection.async_exec(sql)
1167
        end
1168

1169
        def exec_cache(sql, binds)
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
          begin
            stmt_key = prepare_statement sql

            # Clear the queue
            @connection.get_last_result
            @connection.send_query_prepared(stmt_key, binds.map { |col, val|
              type_cast(val, col)
            })
            @connection.block
            @connection.get_last_result
          rescue PGError => e
            # Get the PG code for the failure.  Annoyingly, the code for
            # prepared statements whose return value may have changed is
            # FEATURE_NOT_SUPPORTED.  Check here for more details:
            # http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/cache/plancache.c#l573
            code = e.result.result_error_field(PGresult::PG_DIAG_SQLSTATE)
            if FEATURE_NOT_SUPPORTED == code
              @statements.delete sql_key(sql)
              retry
            else
              raise e
            end
          end
        end

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

        # Prepare the statement if it hasn't been prepared, return
        # the statement key.
        def prepare_statement(sql)
          sql_key = sql_key(sql)
1205
          unless @statements.key? sql_key
1206
            nextkey = @statements.next_key
1207
            @connection.prepare nextkey, sql
1208
            @statements[sql_key] = nextkey
1209
          end
1210
          @statements[sql_key]
1211
        end
1212

P
Pratik Naik 已提交
1213
        # The internal PostgreSQL identifier of the money data type.
1214
        MONEY_COLUMN_TYPE_OID = 790 #:nodoc:
1215 1216
        # The internal PostgreSQL identifier of the BYTEA data type.
        BYTEA_COLUMN_TYPE_OID = 17 #:nodoc:
1217 1218 1219 1220

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

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

1228 1229 1230
          configure_connection
        end

1231
        # Configures the encoding, verbosity, schema search path, and time zone of the connection.
1232
        # This is called by #connect and should not be called manually.
1233 1234
        def configure_connection
          if @config[:encoding]
1235
            @connection.set_client_encoding(@config[:encoding])
1236
          end
1237 1238
          self.client_min_messages = @config[:min_messages] if @config[:min_messages]
          self.schema_search_path = @config[:schema_search_path] || @config[:schema_order]
1239 1240 1241 1242

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

1243
          # If using Active Record's time zone support configure the connection to return
1244
          # TIMESTAMP WITH ZONE types in UTC.
1245
          if ActiveRecord::Base.default_timezone == :utc
1246
            execute("SET time zone 'UTC'", 'SCHEMA')
1247
          elsif @local_tz
1248
            execute("SET time zone '#{@local_tz}'", 'SCHEMA')
1249
          end
1250 1251
        end

1252
        # Returns the current ID of a table's sequence.
1253 1254 1255
        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 已提交
1256 1257
        end

1258
        # Executes a SELECT query and returns the results, performing any data type
1259
        # conversions that are required to be performed here instead of in PostgreSQLColumn.
1260
        def select(sql, name = nil, binds = [])
1261
          exec_query(sql, name, binds)
1262 1263 1264
        end

        def select_raw(sql, name = nil)
1265
          res = execute(sql, name)
1266
          results = result_as_array(res)
1267
          fields = res.fields
1268
          res.clear
1269
          return fields, results
M
Marcel Molina 已提交
1270 1271
        end

1272
        # Returns the list of a table's column names, data types, and default values.
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
        #
        # 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
1290
        def column_definitions(table_name) #:nodoc:
1291
          exec_query(<<-end_sql, 'SCHEMA').rows
1292
            SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull
1293 1294
              FROM pg_attribute a LEFT JOIN pg_attrdef d
                ON a.attrelid = d.adrelid AND a.attnum = d.adnum
1295
             WHERE a.attrelid = '#{quote_table_name(table_name)}'::regclass
1296 1297 1298
               AND a.attnum > 0 AND NOT a.attisdropped
             ORDER BY a.attnum
          end_sql
D
Initial  
David Heinemeier Hansson 已提交
1299
        end
1300 1301

        def extract_pg_identifier_from_name(name)
1302
          match_data = name.start_with?('"') ? name.match(/\"([^\"]+)\"/) : name.match(/([^\.]+)/)
1303 1304

          if match_data
1305 1306
            rest = name[match_data[0].length, name.length]
            rest = rest[1, rest.length] if rest.start_with? "."
J
José Valim 已提交
1307
            [match_data[1], (rest.length > 0 ? rest : nil)]
1308 1309
          end
        end
1310

1311 1312 1313 1314 1315
        def extract_table_ref_from_insert_sql(sql)
          sql[/into\s+([^\(]*).*values\s*\(/i]
          $1.strip if $1
        end

1316 1317 1318
        def table_definition
          TableDefinition.new(self)
        end
D
Initial  
David Heinemeier Hansson 已提交
1319 1320 1321
    end
  end
end