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 www.tmtm.org/en/mysql/ruby/).

Options:

  • :host - Defaults to “localhost”.

  • :port - Defaults to 3306.

  • :socket - Defaults to “/tmp/mysql.sock“.

  • :username - Defaults to “root“

  • :password - Defaults to nothing.

  • :database - The name of the database. No default, must be provided.

  • :encoding - (Optional) Sets the client encoding by executing “SET NAMES ” after connection.

  • :reconnect - Defaults to false (See MySQL documentation: dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html).

  • :sslca - Necessary to use MySQL with an SSL connection.

  • :sslkey - Necessary to use MySQL with an SSL connection.

  • :sslcert - Necessary to use MySQL with an SSL connection.

  • :sslcapath - Necessary to use MySQL with an SSL connection.

  • :sslcipher - Necessary to use MySQL with an SSL connection.

Methods
Constants
ADAPTER_NAME = 'MySQL'.freeze
LOST_CONNECTION_ERROR_MESSAGES = [ "Server shutdown in progress", "Broken pipe", "Lost connection to MySQL server during query", "MySQL server has gone away" ]
QUOTED_FALSE = '1'.freeze, '0'.freeze
NATIVE_DATABASE_TYPES = { :primary_key => "int(11) DEFAULT NULL auto_increment PRIMARY KEY".freeze, :string => { :name => "varchar", :limit => 255 }, :text => { :name => "text" }, :integer => { :name => "int", :limit => 4 }, :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 } }
Public Class methods
emulate_booleans

By default, the MysqlAdapter will consider all columns of type tinyint(1) 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 application.rb file:

  ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans = false
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 132
132:       cattr_accessor :emulate_booleans
new(connection, logger, connection_options, config)
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 160
160:       def initialize(connection, logger, connection_options, config)
161:         super(connection, logger)
162:         @connection_options, @config = connection_options, config
163:         @quoted_column_names, @quoted_table_names = {}, {}
164:         connect
165:       end
Public Instance methods
active?()

CONNECTION MANAGEMENT ====================================

       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 236
236:       def active?
237:         if @connection.respond_to?(:stat)
238:           @connection.stat
239:         else
240:           @connection.query 'select 1'
241:         end
242: 
243:         # mysql-ruby doesn't raise an exception when stat fails.
244:         if @connection.respond_to?(:errno)
245:           @connection.errno.zero?
246:         else
247:           true
248:         end
249:       rescue Mysql::Error
250:         false
251:       end
add_column(table_name, column_name, type, options = {})
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 452
452:       def add_column(table_name, column_name, type, options = {})
453:         add_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
454:         add_column_options!(add_column_sql, options)
455:         add_column_position!(add_column_sql, options)
456:         execute(add_column_sql)
457:       end
add_column_position!(sql, options)
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 519
519:       def add_column_position!(sql, options)
520:         if options[:first]
521:           sql << " FIRST"
522:         elsif options[:after]
523:           sql << " AFTER #{quote_column_name(options[:after])}"
524:         end
525:       end
case_sensitive_equality_operator()
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 550
550:       def case_sensitive_equality_operator
551:         "= BINARY"
552:       end
change_column_null(table_name, column_name, null, default = nil)
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 464
464:       def change_column_null(table_name, column_name, null, default = nil)
465:         column = column_for(table_name, column_name)
466: 
467:         unless null || default.nil?
468:           execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL")
469:         end
470: 
471:         change_column table_name, column_name, column.sql_type, :null => null
472:       end
charset()

Returns the database character set.

       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 396
396:       def charset
397:         show_variable 'character_set_database'
398:       end
collation()

Returns the database collation strategy.

       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 401
401:       def collation
402:         show_variable 'collation_database'
403:       end
create_database(name, options = {})

Create a new MySQL database with optional :charset and :collation. Charset defaults to utf8.

Example:

  create_database 'charset_test', :charset => 'latin1', :collation => 'latin1_bin'
  create_database 'matt_development'
  create_database 'matt_development', :charset => :big5
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 379
379:       def create_database(name, options = {})
380:         if options[:collation]
381:           execute "CREATE DATABASE `#{name}` DEFAULT CHARACTER SET `#{options[:charset] || 'utf8'}` COLLATE `#{options[:collation]}`"
382:         else
383:           execute "CREATE DATABASE `#{name}` DEFAULT CHARACTER SET `#{options[:charset] || 'utf8'}`"
384:         end
385:       end
create_savepoint()
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 328
328:       def create_savepoint
329:         execute("SAVEPOINT #{current_savepoint_name}")
330:       end
current_database()
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 391
391:       def current_database
392:         select_value 'SELECT DATABASE() as db'
393:       end
disconnect!()
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 258
258:       def disconnect!
259:         @connection.close rescue nil
260:       end
drop_table(table_name, options = {})
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 413
413:       def drop_table(table_name, options = {})
414:         super(table_name, options)
415:       end
limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key)
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 554
554:       def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key)
555:         where_sql
556:       end
primary_key(table)

Returns just a table’s primary key

       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 545
545:       def primary_key(table)
546:         pk_and_sequence = pk_and_sequence_for(table)
547:         pk_and_sequence && pk_and_sequence.first
548:       end
quote(value, column = nil)

QUOTING ==================================================

       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 190
190:       def quote(value, column = nil)
191:         if value.kind_of?(String) && column && column.type == :binary && column.class.respond_to?(:string_to_binary)
192:           s = column.class.string_to_binary(value).unpack("H*")[0]
193:           "x'#{s}'"
194:         elsif value.kind_of?(BigDecimal)
195:           value.to_s("F")
196:         else
197:           super
198:         end
199:       end
quoted_false()
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 217
217:       def quoted_false
218:         QUOTED_FALSE
219:       end
quoted_true()
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 213
213:       def quoted_true
214:         QUOTED_TRUE
215:       end
reconnect!()
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 253
253:       def reconnect!
254:         disconnect!
255:         connect
256:       end
release_savepoint()
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 336
336:       def release_savepoint
337:         execute("RELEASE SAVEPOINT #{current_savepoint_name}")
338:       end
rename_table(table_name, new_name)
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 448
448:       def rename_table(table_name, new_name)
449:         execute "RENAME TABLE #{quote_table_name(table_name)} TO #{quote_table_name(new_name)}"
450:       end
reset!()
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 262
262:       def reset!
263:         if @connection.respond_to?(:change_user)
264:           # See http://bugs.mysql.com/bug.php?id=33540 -- the workaround way to
265:           # reset the connection is to change the user to the same user.
266:           @connection.change_user(@config[:username], @config[:password], @config[:database])
267:           configure_connection
268:         end
269:       end
rollback_to_savepoint()
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 332
332:       def rollback_to_savepoint
333:         execute("ROLLBACK TO SAVEPOINT #{current_savepoint_name}")
334:       end
select_rows(sql, name = nil)

DATABASE STATEMENTS ======================================

       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 273
273:       def select_rows(sql, name = nil)
274:         @connection.query_with_result = true
275:         result = execute(sql, name)
276:         rows = []
277:         result.each { |row| rows << row }
278:         result.free
279:         @connection.more_results && @connection.next_result    # invoking stored procedures with CLIENT_MULTI_RESULTS requires this to tidy up else connection will be dropped 
280:         rows
281:       end
show_variable(name)

SHOW VARIABLES LIKE ‘name’

       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 528
528:       def show_variable(name)
529:         variables = select_all("SHOW VARIABLES LIKE '#{name}'")
530:         variables.first['Value'] unless variables.empty?
531:       end
type_to_sql(type, limit = nil, precision = nil, scale = nil)

Maps logical Rails types to MySQL-specific data types.

       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 506
506:       def type_to_sql(type, limit = nil, precision = nil, scale = nil)
507:         return super unless type.to_s == 'integer'
508: 
509:         case limit
510:         when 1; 'tinyint'
511:         when 2; 'smallint'
512:         when 3; 'mediumint'
513:         when nil, 4, 11; 'int(11)'  # compatibility with MySQL default
514:         when 5..8; 'bigint'
515:         else raise(ActiveRecordError, "No integer type has byte size #{limit}")
516:         end
517:       end
Protected Instance methods
quoted_columns_for_index(column_names, options = {})
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 559
559:         def quoted_columns_for_index(column_names, options = {})
560:           length = options[:length] if options.is_a?(Hash)
561: 
562:           quoted_column_names = case length
563:           when Hash
564:             column_names.map {|name| length[name] ? "#{quote_column_name(name)}(#{length[name]})" : quote_column_name(name) }
565:           when Fixnum
566:             column_names.map {|name| "#{quote_column_name(name)}(#{length})"}
567:           else
568:             column_names.map {|name| quote_column_name(name) }
569:           end
570:         end
translate_exception(exception, message)
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 572
572:         def translate_exception(exception, message)
573:           return super unless exception.respond_to?(:errno)
574: 
575:           case exception.errno
576:           when 1062
577:             RecordNotUnique.new(message, exception)
578:           when 1452
579:             InvalidForeignKey.new(message, exception)
580:           else
581:             super
582:           end
583:         end
Private Instance methods
column_for(table_name, column_name)
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 635
635:         def column_for(table_name, column_name)
636:           unless column = columns(table_name).find { |c| c.name == column_name.to_s }
637:             raise "No such column: #{table_name}.#{column_name}"
638:           end
639:           column
640:         end
configure_connection()
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 608
608:         def configure_connection
609:           encoding = @config[:encoding]
610:           execute("SET NAMES '#{encoding}'", :skip_logging) if encoding
611: 
612:           # By default, MySQL 'where id is null' selects the last inserted id.
613:           # Turn this off. http://dev.rubyonrails.org/ticket/6778
614:           execute("SET SQL_AUTO_IS_NULL=0", :skip_logging)
615:         end
connect()
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 586
586:         def connect
587:           encoding = @config[:encoding]
588:           if encoding
589:             @connection.options(Mysql::SET_CHARSET_NAME, encoding) rescue nil
590:           end
591: 
592:           if @config[:sslca] || @config[:sslkey]
593:             @connection.ssl_set(@config[:sslkey], @config[:sslcert], @config[:sslca], @config[:sslcapath], @config[:sslcipher])
594:           end
595: 
596:           @connection.options(Mysql::OPT_CONNECT_TIMEOUT, @config[:connect_timeout]) if @config[:connect_timeout]
597:           @connection.options(Mysql::OPT_READ_TIMEOUT, @config[:read_timeout]) if @config[:read_timeout]
598:           @connection.options(Mysql::OPT_WRITE_TIMEOUT, @config[:write_timeout]) if @config[:write_timeout]
599: 
600:           @connection.real_connect(*@connection_options)
601: 
602:           # reconnect must be set after real_connect is called, because real_connect sets it to false internally
603:           @connection.reconnect = !!@config[:reconnect] if @connection.respond_to?(:reconnect=)
604: 
605:           configure_connection
606:         end
select(sql, name = nil)
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 617
617:         def select(sql, name = nil)
618:           @connection.query_with_result = true
619:           result = execute(sql, name)
620:           rows = []
621:           result.each_hash { |row| rows << row }
622:           result.free
623:           @connection.more_results && @connection.next_result    # invoking stored procedures with CLIENT_MULTI_RESULTS requires this to tidy up else connection will be dropped 
624:           rows
625:         end
supports_views?()
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 627
627:         def supports_views?
628:           version[0] >= 5
629:         end
version()
       # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line 631
631:         def version
632:           @version ||= @connection.server_info.scan(/^(\d+)\.(\d+)\.(\d+)/).flatten.map { |v| v.to_i }
633:         end