mysql_adapter.rb 21.3 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 'set'
4

5
module MysqlCompat #:nodoc:
6 7
  # add all_hashes method to standard mysql-c bindings or pure ruby version
  def self.define_all_hashes_method!
8 9
    raise 'Mysql not loaded' unless defined?(::Mysql)

10 11
    target = defined?(Mysql::Result) ? Mysql::Result : MysqlRes
    return if target.instance_methods.include?('all_hashes')
12 13 14

    # Ruby driver has a version string and returns null values in each_hash
    # C driver >= 2.7 returns null values in each_hash
15 16
    if Mysql.const_defined?(:VERSION) && (Mysql::VERSION.is_a?(String) || Mysql::VERSION >= 20700)
      target.class_eval <<-'end_eval'
17 18 19 20 21
      def all_hashes                     # def all_hashes
        rows = []                        #   rows = []
        each_hash { |row| rows << row }  #   each_hash { |row| rows << row }
        rows                             #   rows
      end                                # end
22
      end_eval
23 24 25 26

    # adapters before 2.7 don't have a version constant
    # and don't return null values in each_hash
    else
27
      target.class_eval <<-'end_eval'
28 29 30 31 32 33 34 35
      def all_hashes                                            # def all_hashes
        rows = []                                               #   rows = []
        all_fields = fetch_fields.inject({}) { |fields, f|      #   all_fields = fetch_fields.inject({}) { |fields, f|
          fields[f.name] = nil; fields                          #     fields[f.name] = nil; fields
        }                                                       #   }
        each_hash { |row| rows << all_fields.dup.update(row) }  #   each_hash { |row| rows << all_fields.dup.update(row) }
        rows                                                    #   rows
      end                                                       # end
36 37
      end_eval
    end
38

39 40
    unless target.instance_methods.include?('all_hashes') ||
           target.instance_methods.include?(:all_hashes)
41 42
      raise "Failed to defined #{target.name}#all_hashes method. Mysql::VERSION = #{Mysql::VERSION.inspect}"
    end
43 44 45
  end
end

D
Initial  
David Heinemeier Hansson 已提交
46 47
module ActiveRecord
  class Base
48 49
    # Establishes a connection to the database that's used by all Active Record objects.
    def self.mysql_connection(config) # :nodoc:
50
      config = config.symbolize_keys
D
Initial  
David Heinemeier Hansson 已提交
51 52 53 54 55
      host     = config[:host]
      port     = config[:port]
      socket   = config[:socket]
      username = config[:username] ? config[:username].to_s : 'root'
      password = config[:password].to_s
56

D
Initial  
David Heinemeier Hansson 已提交
57 58 59 60 61
      if config.has_key?(:database)
        database = config[:database]
      else
        raise ArgumentError, "No database specified. Missing argument: database."
      end
62

63
      # Require the MySQL driver and define Mysql::Result.all_hashes
64 65 66 67 68 69 70 71
      unless defined? Mysql
        begin
          require_library_or_gem('mysql')
        rescue LoadError
          $stderr.puts '!!! The bundled mysql.rb driver has been removed from Rails 2.2. Please install the mysql gem and try again: gem install mysql.'
          raise
        end
      end
72 73
      MysqlCompat.define_all_hashes_method!

74
      mysql = Mysql.init
75
      mysql.ssl_set(config[:sslkey], config[:sslcert], config[:sslca], config[:sslcapath], config[:sslcipher]) if config[:sslca] || config[:sslkey]
76

77
      ConnectionAdapters::MysqlAdapter.new(mysql, logger, [host, username, password, database, port, socket], config)
D
Initial  
David Heinemeier Hansson 已提交
78 79
    end
  end
80

D
Initial  
David Heinemeier Hansson 已提交
81
  module ConnectionAdapters
82
    class MysqlColumn < Column #:nodoc:
83 84 85
      def extract_default(default)
        if type == :binary || type == :text
          if default.blank?
86
            return null ? nil : ''
87 88 89 90 91 92 93 94
          else
            raise ArgumentError, "#{type} columns cannot have a default value: #{default.inspect}"
          end
        elsif missing_default_forged_as_empty_string?(default)
          nil
        else
          super
        end
95 96
      end

97 98 99 100 101
      def has_default?
        return false if type == :binary || type == :text #mysql forbids defaults on blob and text columns
        super
      end

102 103
      private
        def simplified_type(field_type)
104
          return :boolean if MysqlAdapter.emulate_booleans && field_type.downcase.index("tinyint(1)")
105
          return :string  if field_type =~ /enum/i
106 107
          super
        end
108

109
        def extract_limit(sql_type)
110 111
          case sql_type
          when /blob|text/i
112 113 114 115 116 117 118 119 120 121
            case sql_type
            when /tiny/i
              255
            when /medium/i
              16777215
            when /long/i
              2147483647 # mysql only allows 2^31-1, not 2^32-1, somewhat inconsistently with the tiny/medium/normal cases
            else
              super # we could return 65535 here, but we leave it undecorated by default
            end
122
          when /^bigint/i;    8
J
Jeremy Kemper 已提交
123
          when /^int/i;       4
124
          when /^mediumint/i; 3
J
Jeremy Kemper 已提交
125 126
          when /^smallint/i;  2
          when /^tinyint/i;   1
127 128 129 130 131
          else
            super
          end
        end

132 133
        # MySQL misreports NOT NULL column default when none is given.
        # We can't detect this for columns which may have a legitimate ''
134 135
        # default (string) but we can for others (integer, datetime, boolean,
        # and the rest).
136 137 138
        #
        # Test whether the column has default '', is not null, and is not
        # a type allowing default ''.
139 140
        def missing_default_forged_as_empty_string?(default)
          type != :string && !null && default == ''
141
        end
142 143
    end

144 145 146 147 148
    # The MySQL adapter will work with both Ruby/MySQL, which is a Ruby-based MySQL adapter that comes bundled with Active Record, and with
    # the faster C-based MySQL/Ruby adapter (available both as a gem and from http://www.tmtm.org/en/mysql/ruby/).
    #
    # Options:
    #
P
Pratik Naik 已提交
149 150 151 152 153 154 155
    # * <tt>:host</tt> - Defaults to "localhost".
    # * <tt>:port</tt> - Defaults to 3306.
    # * <tt>:socket</tt> - Defaults to "/tmp/mysql.sock".
    # * <tt>:username</tt> - Defaults to "root"
    # * <tt>:password</tt> - Defaults to nothing.
    # * <tt>:database</tt> - The name of the database. No default, must be provided.
    # * <tt>:encoding</tt> - (Optional) Sets the client encoding by executing "SET NAMES <encoding>" after connection.
156
    # * <tt>:reconnect</tt> - Defaults to false (See MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html).
157
    # * <tt>:sslca</tt> - Necessary to use MySQL with an SSL connection.
P
Pratik Naik 已提交
158 159 160 161
    # * <tt>:sslkey</tt> - Necessary to use MySQL with an SSL connection.
    # * <tt>:sslcert</tt> - Necessary to use MySQL with an SSL connection.
    # * <tt>:sslcapath</tt> - Necessary to use MySQL with an SSL connection.
    # * <tt>:sslcipher</tt> - Necessary to use MySQL with an SSL connection.
162
    #
163
    class MysqlAdapter < AbstractAdapter
P
Pratik Naik 已提交
164 165 166 167 168 169 170 171 172

      ##
      # :singleton-method:
      # By default, the MysqlAdapter will consider all columns of type <tt>tinyint(1)</tt>
      # as boolean. If you wish to disable this emulation (which was the default
      # behavior in versions 0.13.1 and earlier) you can add the following line
      # to your environment.rb file:
      #
      #   ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans = false
173
      cattr_accessor :emulate_booleans
174
      self.emulate_booleans = true
175

176 177
      ADAPTER_NAME = 'MySQL'.freeze

178
      LOST_CONNECTION_ERROR_MESSAGES = [
179
        "Server shutdown in progress",
180 181
        "Broken pipe",
        "Lost connection to MySQL server during query",
182 183
        "MySQL server has gone away" ]

184
      QUOTED_TRUE, QUOTED_FALSE = '1'.freeze, '0'.freeze
185

186 187 188 189
      NATIVE_DATABASE_TYPES = {
        :primary_key => "int(11) DEFAULT NULL auto_increment PRIMARY KEY".freeze,
        :string      => { :name => "varchar", :limit => 255 },
        :text        => { :name => "text" },
190
        :integer     => { :name => "int", :limit => 4 },
191 192 193 194 195 196 197 198 199 200
        :float       => { :name => "float" },
        :decimal     => { :name => "decimal" },
        :datetime    => { :name => "datetime" },
        :timestamp   => { :name => "datetime" },
        :time        => { :name => "time" },
        :date        => { :name => "date" },
        :binary      => { :name => "blob" },
        :boolean     => { :name => "tinyint", :limit => 1 }
      }

J
Jeremy Kemper 已提交
201
      def initialize(connection, logger, connection_options, config)
202
        super(connection, logger)
J
Jeremy Kemper 已提交
203
        @connection_options, @config = connection_options, config
204
        @quoted_column_names, @quoted_table_names = {}, {}
205
        connect
206 207 208
      end

      def adapter_name #:nodoc:
209
        ADAPTER_NAME
210 211 212
      end

      def supports_migrations? #:nodoc:
213 214
        true
      end
215 216 217 218
      
      def supports_savepoints? #:nodoc:
        true
      end
219

220
      def native_database_types #:nodoc:
221
        NATIVE_DATABASE_TYPES
222 223
      end

224

225 226
      # QUOTING ==================================================

227
      def quote(value, column = nil)
228
        if value.kind_of?(String) && column && column.type == :binary && column.class.respond_to?(:string_to_binary)
229 230
          s = column.class.string_to_binary(value).unpack("H*")[0]
          "x'#{s}'"
231
        elsif value.kind_of?(BigDecimal)
232
          value.to_s("F")
233 234 235 236 237
        else
          super
        end
      end

238
      def quote_column_name(name) #:nodoc:
239
        @quoted_column_names[name] ||= "`#{name}`"
240 241
      end

242
      def quote_table_name(name) #:nodoc:
243
        @quoted_table_names[name] ||= quote_column_name(name).gsub('.', '`.`')
244 245
      end

246
      def quote_string(string) #:nodoc:
247
        @connection.quote(string)
D
Initial  
David Heinemeier Hansson 已提交
248
      end
249

250
      def quoted_true
251
        QUOTED_TRUE
252
      end
253

254
      def quoted_false
255
        QUOTED_FALSE
D
Initial  
David Heinemeier Hansson 已提交
256
      end
257

258 259 260 261 262 263 264 265 266 267 268 269
      # REFERENTIAL INTEGRITY ====================================

      def disable_referential_integrity(&block) #:nodoc:
        old = select_value("SELECT @@FOREIGN_KEY_CHECKS")

        begin
          update("SET FOREIGN_KEY_CHECKS = 0")
          yield
        ensure
          update("SET FOREIGN_KEY_CHECKS = #{old}")
        end
      end
270

271 272 273
      # CONNECTION MANAGEMENT ====================================

      def active?
274 275 276 277 278
        if @connection.respond_to?(:stat)
          @connection.stat
        else
          @connection.query 'select 1'
        end
279 280 281 282 283 284 285

        # mysql-ruby doesn't raise an exception when stat fails.
        if @connection.respond_to?(:errno)
          @connection.errno.zero?
        else
          true
        end
286 287 288 289 290
      rescue Mysql::Error
        false
      end

      def reconnect!
291
        disconnect!
292
        connect
293
      end
294

295 296 297
      def disconnect!
        @connection.close rescue nil
      end
298

299 300 301 302 303
      def reset!
        if @connection.respond_to?(:change_user)
          # See http://bugs.mysql.com/bug.php?id=33540 -- the workaround way to
          # reset the connection is to change the user to the same user.
          @connection.change_user(@config[:username], @config[:password], @config[:database])
304
          configure_connection
305 306
        end
      end
307

308
      # DATABASE STATEMENTS ======================================
309

310 311 312 313 314 315 316 317 318
      def select_rows(sql, name = nil)
        @connection.query_with_result = true
        result = execute(sql, name)
        rows = []
        result.each { |row| rows << row }
        result.free
        rows
      end

319
      # Executes a SQL query and returns a MySQL::Result object. Note that you have to free the Result object after you're done using it.
320
      def execute(sql, name = nil) #:nodoc:
321
        log(sql, name) { @connection.query(sql) }
322
      rescue ActiveRecord::StatementInvalid => exception
323 324
        if exception.message.split(":").first =~ /Packets out of order/
          raise ActiveRecord::StatementInvalid, "'Packets out of order' error was received from the database. Please update your mysql bindings (gem install mysql) and read http://dev.mysql.com/doc/mysql/en/password-hashing.html for more information.  If you're on Windows, use the Instant Rails installer to get the updated mysql bindings."
325 326
        else
          raise
327
        end
D
Initial  
David Heinemeier Hansson 已提交
328
      end
329

330 331
      def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #:nodoc:
        super sql, name
332 333 334
        id_value || @connection.insert_id
      end

335 336
      def update_sql(sql, name = nil) #:nodoc:
        super
337 338
        @connection.affected_rows
      end
339

340
      def begin_db_transaction #:nodoc:
341 342 343
        execute "BEGIN"
      rescue Exception
        # Transactions aren't supported
D
Initial  
David Heinemeier Hansson 已提交
344
      end
345

346
      def commit_db_transaction #:nodoc:
347 348 349
        execute "COMMIT"
      rescue Exception
        # Transactions aren't supported
D
Initial  
David Heinemeier Hansson 已提交
350
      end
351

352
      def rollback_db_transaction #:nodoc:
353 354 355
        execute "ROLLBACK"
      rescue Exception
        # Transactions aren't supported
D
Initial  
David Heinemeier Hansson 已提交
356
      end
357

J
Jonathan Viney 已提交
358 359 360 361 362 363 364 365 366 367 368
      def create_savepoint
        execute("SAVEPOINT #{current_savepoint_name}")
      end

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

      def release_savepoint
        execute("RELEASE SAVEPOINT #{current_savepoint_name}")
      end
369

370
      def add_limit_offset!(sql, options) #:nodoc:
371
        if limit = options[:limit]
372
          limit = sanitize_limit(limit)
373 374
          unless offset = options[:offset]
            sql << " LIMIT #{limit}"
375
          else
376
            sql << " LIMIT #{offset.to_i}, #{limit}"
377
          end
378
        end
379
      end
380

381 382 383 384

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

      def structure_dump #:nodoc:
385 386 387 388 389
        if supports_views?
          sql = "SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'"
        else
          sql = "SHOW TABLES"
        end
390

391 392
        select_all(sql).inject("") do |structure, table|
          table.delete('Table_type')
393
          structure += select_one("SHOW CREATE TABLE #{quote_table_name(table.to_a.first.last)}")["Create Table"] + ";\n\n"
394 395 396
        end
      end

397
      def recreate_database(name, options = {}) #:nodoc:
D
Initial  
David Heinemeier Hansson 已提交
398
        drop_database(name)
399
        create_database(name, options)
D
Initial  
David Heinemeier Hansson 已提交
400
      end
401

402
      # Create a new MySQL database with optional <tt>:charset</tt> and <tt>:collation</tt>.
403 404 405 406 407 408 409 410 411 412 413 414
      # Charset defaults to utf8.
      #
      # Example:
      #   create_database 'charset_test', :charset => 'latin1', :collation => 'latin1_bin'
      #   create_database 'matt_development'
      #   create_database 'matt_development', :charset => :big5
      def create_database(name, options = {})
        if options[:collation]
          execute "CREATE DATABASE `#{name}` DEFAULT CHARACTER SET `#{options[:charset] || 'utf8'}` COLLATE `#{options[:collation]}`"
        else
          execute "CREATE DATABASE `#{name}` DEFAULT CHARACTER SET `#{options[:charset] || 'utf8'}`"
        end
415
      end
416

417
      def drop_database(name) #:nodoc:
418
        execute "DROP DATABASE IF EXISTS `#{name}`"
D
Initial  
David Heinemeier Hansson 已提交
419
      end
420

421
      def current_database
422 423 424 425 426 427 428 429 430 431 432
        select_value 'SELECT DATABASE() as db'
      end

      # Returns the database character set.
      def charset
        show_variable 'character_set_database'
      end

      # Returns the database collation strategy.
      def collation
        show_variable 'collation_database'
433
      end
434 435 436

      def tables(name = nil) #:nodoc:
        tables = []
437 438 439
        result = execute("SHOW TABLES", name)
        result.each { |field| tables << field[0] }
        result.free
440
        tables
D
Initial  
David Heinemeier Hansson 已提交
441
      end
442

443 444 445 446
      def drop_table(table_name, options = {})
        super(table_name, options)
      end

447 448 449
      def indexes(table_name, name = nil)#:nodoc:
        indexes = []
        current_index = nil
450 451
        result = execute("SHOW KEYS FROM #{quote_table_name(table_name)}", name)
        result.each do |row|
452 453 454 455 456 457 458 459
          if current_index != row[2]
            next if row[2] == "PRIMARY" # skip the primary key
            current_index = row[2]
            indexes << IndexDefinition.new(row[0], row[2], row[1] == "0", [])
          end

          indexes.last.columns << row[4]
        end
460
        result.free
461 462 463 464
        indexes
      end

      def columns(table_name, name = nil)#:nodoc:
465
        sql = "SHOW FIELDS FROM #{quote_table_name(table_name)}"
466
        columns = []
467 468 469
        result = execute(sql, name)
        result.each { |field| columns << MysqlColumn.new(field[0], field[4], field[1], field[2] == "YES") }
        result.free
470 471 472
        columns
      end

473 474
      def create_table(table_name, options = {}) #:nodoc:
        super(table_name, options.reverse_merge(:options => "ENGINE=InnoDB"))
475
      end
476

477 478
      def rename_table(table_name, new_name)
        execute "RENAME TABLE #{quote_table_name(table_name)} TO #{quote_table_name(new_name)}"
479
      end
480 481

      def change_column_default(table_name, column_name, default) #:nodoc:
482 483 484 485 486 487 488 489 490 491
        column = column_for(table_name, column_name)
        change_column table_name, column_name, column.sql_type, :default => default
      end

      def change_column_null(table_name, column_name, null, default = nil)
        column = column_for(table_name, column_name)

        unless null || default.nil?
          execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL")
        end
492

493
        change_column table_name, column_name, column.sql_type, :null => null
494
      end
495

496
      def change_column(table_name, column_name, type, options = {}) #:nodoc:
497 498
        column = column_for(table_name, column_name)

499
        unless options_include_default?(options)
500 501 502 503 504
          options[:default] = column.default
        end

        unless options.has_key?(:null)
          options[:null] = column.null
505
        end
506

507
        change_column_sql = "ALTER TABLE #{quote_table_name(table_name)} CHANGE #{quote_column_name(column_name)} #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
508 509 510 511
        add_column_options!(change_column_sql, options)
        execute(change_column_sql)
      end

512
      def rename_column(table_name, column_name, new_column_name) #:nodoc:
513 514 515
        options = {}
        if column = columns(table_name).find { |c| c.name == column_name.to_s }
          options[:default] = column.default
516
          options[:null] = column.null
517 518 519
        else
          raise ActiveRecordError, "No such column: #{table_name}.#{column_name}"
        end
520
        current_type = select_one("SHOW COLUMNS FROM #{quote_table_name(table_name)} LIKE '#{column_name}'")["Type"]
521 522 523
        rename_column_sql = "ALTER TABLE #{quote_table_name(table_name)} CHANGE #{quote_column_name(column_name)} #{quote_column_name(new_column_name)} #{current_type}"
        add_column_options!(rename_column_sql, options)
        execute(rename_column_sql)
524 525
      end

526 527 528 529 530
      # Maps logical Rails types to MySQL-specific data types.
      def type_to_sql(type, limit = nil, precision = nil, scale = nil)
        return super unless type.to_s == 'integer'

        case limit
531 532 533 534 535 536
        when 1; 'tinyint'
        when 2; 'smallint'
        when 3; 'mediumint'
        when nil, 4, 11; 'int(11)'  # compatibility with MySQL default
        when 5..8; 'bigint'
        else raise(ActiveRecordError, "No integer type has byte size #{limit}")
537 538 539
        end
      end

540

541 542
      # SHOW VARIABLES LIKE 'name'
      def show_variable(name)
543 544
        variables = select_all("SHOW VARIABLES LIKE '#{name}'")
        variables.first['Value'] unless variables.empty?
545 546
      end

547 548 549
      # Returns a table's primary key and belonging sequence.
      def pk_and_sequence_for(table) #:nodoc:
        keys = []
550 551
        result = execute("describe #{quote_table_name(table)}")
        result.each_hash do |h|
552 553
          keys << h["Field"]if h["Key"] == "PRI"
        end
554
        result.free
555 556 557
        keys.length == 1 ? [keys.first, nil] : nil
      end

558 559 560 561
      def case_sensitive_equality_operator
        "= BINARY"
      end

562 563 564 565
      def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key)
        where_sql
      end

566 567 568 569 570
      protected

        def translate_exception(exception, message)
          case exception.errno
          when 1062
571
            RecordNotUnique.new(message, exception)
572
          when 1452
573
            InvalidForeignKey.new(message, exception)
574 575 576 577 578
          else
            super
          end
        end

D
Initial  
David Heinemeier Hansson 已提交
579
      private
580 581 582
        def connect
          encoding = @config[:encoding]
          if encoding
583
            @connection.options(Mysql::SET_CHARSET_NAME, encoding) rescue nil
584
          end
585

586 587 588
          if @config[:sslca] || @config[:sslkey]
            @connection.ssl_set(@config[:sslkey], @config[:sslcert], @config[:sslca], @config[:sslcapath], @config[:sslcipher])
          end
589

590
          @connection.real_connect(*@connection_options)
591 592 593 594

          # reconnect must be set after real_connect is called, because real_connect sets it to false internally
          @connection.reconnect = !!@config[:reconnect] if @connection.respond_to?(:reconnect=)

595 596
          configure_connection
        end
597

598 599
        def configure_connection
          encoding = @config[:encoding]
600
          execute("SET NAMES '#{encoding}'") if encoding
601 602 603 604

          # By default, MySQL 'where id is null' selects the last inserted id.
          # Turn this off. http://dev.rubyonrails.org/ticket/6778
          execute("SET SQL_AUTO_IS_NULL=0")
605 606
        end

D
Initial  
David Heinemeier Hansson 已提交
607
        def select(sql, name = nil)
608 609
          @connection.query_with_result = true
          result = execute(sql, name)
610
          rows = result.all_hashes
611
          result.free
D
Initial  
David Heinemeier Hansson 已提交
612 613
          rows
        end
614

615 616 617
        def supports_views?
          version[0] >= 5
        end
618

619 620 621
        def version
          @version ||= @connection.server_info.scan(/^(\d+)\.(\d+)\.(\d+)/).flatten.map { |v| v.to_i }
        end
622 623 624 625 626 627 628

        def column_for(table_name, column_name)
          unless column = columns(table_name).find { |c| c.name == column_name.to_s }
            raise "No such column: #{table_name}.#{column_name}"
          end
          column
        end
D
Initial  
David Heinemeier Hansson 已提交
629 630
    end
  end
631
end