Class: ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter

Inherits:
AbstractAdapter
  • Object
show all
Defined in:
lib/active_record/connection_adapters/abstract_mysql_adapter.rb

Direct Known Subclasses

Mysql2Adapter, MysqlAdapter

Defined Under Namespace

Classes: Column

Constant Summary collapse

LOST_CONNECTION_ERROR_MESSAGES =
[
"Server shutdown in progress",
"Broken pipe",
"Lost connection to MySQL server during query",
"MySQL server has gone away" ]
NATIVE_DATABASE_TYPES =
{
  :primary_key => "int(11) DEFAULT NULL auto_increment PRIMARY KEY",
  :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 }
}

Instance Attribute Summary

Attributes inherited from AbstractAdapter

#in_use, #last_use, #open_transactions, #pool, #schema_cache, #visitor

Attributes included from QueryCache

#query_cache, #query_cache_enabled

Instance Method Summary collapse

Methods inherited from AbstractAdapter

#active?, #clear_cache!, #close, #current_savepoint_name, #decrement_open_transactions, #disconnect!, #expire, #increment_open_transactions, #lease, #prefetch_primary_key?, #raw_connection, #reconnect!, #requires_reloading?, #reset!, #substitute_at, #supports_count_distinct?, #supports_ddl_transactions?, #supports_explain?, #transaction_joinable=, #verify!

Methods included from QueryCache

#cache, #clear_query_cache, dirties_query_cache, #disable_query_cache!, #enable_query_cache!, included, #select_all, #uncached

Methods included from DatabaseLimits

#column_name_length, #columns_per_multicolumn_index, #columns_per_table, #in_clause_length, #index_name_length, #indexes_per_table, #joins_per_query, #sql_query_length, #table_alias_length, #table_name_length

Methods included from Quoting

#quote_string, #quoted_date, #type_cast

Methods included from DatabaseStatements

#add_transaction_record, #case_sensitive_equality_operator, #default_sequence_name, #delete, #empty_insert_statement_value, #exec_delete, #exec_insert, #exec_query, #exec_update, #insert, #insert_fixture, #outside_transaction?, #reset_sequence!, #sanitize_limit, #select_all, #select_one, #select_rows, #select_value, #select_values, #supports_statement_cache?, #to_sql, #transaction, #update

Methods included from SchemaStatements

#add_column_options!, #add_index, #add_timestamps, #assume_migrated_upto_version, #change_table, #column_exists?, #distinct, #drop_table, #dump_schema_information, #index_exists?, #index_name, #index_name_exists?, #initialize_schema_migrations_table, #remove_column, #remove_index, #remove_index!, #remove_timestamps, #rename_index, #table_alias_for

Constructor Details

#initialize(connection, logger, connection_options, config) ⇒ AbstractMysqlAdapter

FIXME: Make the first parameter more similar for the two adapters



126
127
128
129
130
131
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 126

def initialize(connection, logger, connection_options, config)
  super(connection, logger)
  @connection_options, @config = connection_options, config
  @quoted_column_names, @quoted_table_names = {}, {}
  @visitor = Arel::Visitors::MySQL.new self
end

Instance Method Details

#adapter_nameObject

:nodoc:



133
134
135
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 133

def adapter_name #:nodoc:
  self.class::ADAPTER_NAME
end

#add_column(table_name, column_name, type, options = {}) ⇒ Object



448
449
450
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 448

def add_column(table_name, column_name, type, options = {})
  execute("ALTER TABLE #{quote_table_name(table_name)} #{add_column_sql(table_name, column_name, type, options)}")
end

#add_column_position!(sql, options) ⇒ Object



489
490
491
492
493
494
495
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 489

def add_column_position!(sql, options)
  if options[:first]
    sql << " FIRST"
  elsif options[:after]
    sql << " AFTER #{quote_column_name(options[:after])}"
  end
end

#begin_db_transactionObject



255
256
257
258
259
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 255

def begin_db_transaction
  execute "BEGIN"
rescue Exception
  # Transactions aren't supported
end

#bulk_change_table(table_name, operations) ⇒ Object

:nodoc:



425
426
427
428
429
430
431
432
433
434
435
436
437
438
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 425

def bulk_change_table(table_name, operations) #:nodoc:
  sqls = operations.map do |command, args|
    table, arguments = args.shift, args
    method = :"#{command}_sql"

    if respond_to?(method)
      send(method, table, *arguments)
    else
      raise "Unknown method called : #{method}(#{arguments.inspect})"
    end
  end.flatten.join(", ")

  execute("ALTER TABLE #{quote_table_name(table_name)} #{sqls}")
end

#case_insensitive_comparison(table, attribute, column, value) ⇒ Object



526
527
528
529
530
531
532
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 526

def case_insensitive_comparison(table, attribute, column, value)
  if column.case_sensitive?
    super
  else
    table[attribute].eq(value)
  end
end

#case_sensitive_modifier(node) ⇒ Object



522
523
524
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 522

def case_sensitive_modifier(node)
  Arel::Nodes::Bin.new(node)
end

#change_column(table_name, column_name, type, options = {}) ⇒ Object

:nodoc:



467
468
469
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 467

def change_column(table_name, column_name, type, options = {}) #:nodoc:
  execute("ALTER TABLE #{quote_table_name(table_name)} #{change_column_sql(table_name, column_name, type, options)}")
end

#change_column_default(table_name, column_name, default) ⇒ Object



452
453
454
455
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 452

def change_column_default(table_name, column_name, default)
  column = column_for(table_name, column_name)
  change_column table_name, column_name, column.sql_type, :default => default
end

#change_column_null(table_name, column_name, null, default = nil) ⇒ Object



457
458
459
460
461
462
463
464
465
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 457

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

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

#charsetObject

Returns the database character set.



357
358
359
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 357

def charset
  show_variable 'character_set_database'
end

#collationObject

Returns the database collation strategy.



362
363
364
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 362

def collation
  show_variable 'collation_database'
end

#columns(table_name, name = nil) ⇒ Object

Returns an array of Column objects for the table specified by table_name.



412
413
414
415
416
417
418
419
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 412

def columns(table_name, name = nil)#:nodoc:
  sql = "SHOW FULL FIELDS FROM #{quote_table_name(table_name)}"
  execute_and_free(sql, 'SCHEMA') do |result|
    each_hash(result).map do |field|
      new_column(field[:Field], field[:Default], field[:Type], field[:Null] == "YES", field[:Collation])
    end
  end
end

#commit_db_transactionObject

:nodoc:



261
262
263
264
265
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 261

def commit_db_transaction #:nodoc:
  execute "COMMIT"
rescue Exception
  # Transactions aren't supported
end

#create_database(name, options = {}) ⇒ Object

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


336
337
338
339
340
341
342
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 336

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
end

#create_savepointObject



273
274
275
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 273

def create_savepoint
  execute("SAVEPOINT #{current_savepoint_name}")
end

#create_table(table_name, options = {}) ⇒ Object

:nodoc:



421
422
423
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 421

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

#current_databaseObject



352
353
354
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 352

def current_database
  select_value 'SELECT DATABASE() as db'
end

#disable_referential_integrity(&block) ⇒ Object

REFERENTIAL INTEGRITY ====================================



215
216
217
218
219
220
221
222
223
224
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 215

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

#drop_database(name) ⇒ Object

Drops a MySQL database.

Example:

drop_database('sebastian_development')


348
349
350
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 348

def drop_database(name) #:nodoc:
  execute "DROP DATABASE IF EXISTS `#{name}`"
end

#each_hash(result) ⇒ Object

The two drivers have slightly different ways of yielding hashes of results, so this method must be implemented to provide a uniform interface.

Raises:

  • (NotImplementedError)


169
170
171
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 169

def each_hash(result) # :nodoc:
  raise NotImplementedError
end

#emulate_booleansObject

:singleton-method: 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::Mysql[2]Adapter.emulate_booleans = false


99
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 99

class_attribute :emulate_booleans

#error_number(exception) ⇒ Object

Must return the Mysql error number from the exception, if the exception has an error number.

Raises:

  • (NotImplementedError)


180
181
182
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 180

def error_number(exception) # :nodoc:
  raise NotImplementedError
end

#execute(sql, name = nil) ⇒ Object

Executes the SQL statement in the context of this connection.



229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 229

def execute(sql, name = nil)
  if name == :skip_logging
    @connection.query(sql)
  else
    log(sql, name) { @connection.query(sql) }
  end
rescue ActiveRecord::StatementInvalid => exception
  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."
  else
    raise
  end
end

#execute_and_free(sql, name = nil) {|execute(sql, name)| ... } ⇒ Object

MysqlAdapter has to free a result after using it, so we use this method to write stuff in a abstract way without concerning ourselves about whether it needs to be explicitly freed or not.

Yields:



246
247
248
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 246

def execute_and_free(sql, name = nil) #:nodoc:
  yield execute(sql, name)
end

#indexes(table_name, name = nil) ⇒ Object

Returns an array of indexes for the given table.



392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 392

def indexes(table_name, name = nil) #:nodoc:
  indexes = []
  current_index = nil
  execute_and_free("SHOW KEYS FROM #{quote_table_name(table_name)}", 'SCHEMA') do |result|
    each_hash(result) do |row|
      if current_index != row[:Key_name]
        next if row[:Key_name] == 'PRIMARY' # skip the primary key
        current_index = row[:Key_name]
        indexes << IndexDefinition.new(row[:Table], row[:Key_name], row[:Non_unique].to_i == 0, [], [])
      end

      indexes.last.columns << row[:Column_name]
      indexes.last.lengths << row[:Sub_part]
    end
  end

  indexes
end

#join_to_update(update, select) ⇒ Object

In the simple case, MySQL allows us to place JOINs directly into the UPDATE query. However, this does not allow for LIMIT, OFFSET and ORDER. To support these, we must use a subquery. However, MySQL is too stupid to create a temporary table for this automatically, so we have to give it some prompting in the form of a subsubquery. Ugh!



290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 290

def join_to_update(update, select) #:nodoc:
  if select.limit || select.offset || select.orders.any?
    subsubselect = select.clone
    subsubselect.projections = [update.key]

    subselect = Arel::SelectManager.new(select.engine)
    subselect.project Arel.sql(update.key.name)
    subselect.from subsubselect.as('__active_record_temp')

    update.where update.key.in(subselect)
  else
    update.table select.source
    update.wheres = select.constraints
  end
end

#limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key) ⇒ Object



534
535
536
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 534

def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key)
  where_sql
end

#native_database_typesObject



161
162
163
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 161

def native_database_types
  NATIVE_DATABASE_TYPES
end

#new_column(field, default, type, null, collation) ⇒ Object

Overridden by the adapters to instantiate their specific Column type.



174
175
176
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 174

def new_column(field, default, type, null, collation) # :nodoc:
  Column.new(field, default, type, null, collation)
end

#pk_and_sequence_for(table) ⇒ Object

Returns a table’s primary key and belonging sequence.



504
505
506
507
508
509
510
511
512
513
514
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 504

def pk_and_sequence_for(table)
  execute_and_free("SHOW CREATE TABLE #{quote_table_name(table)}", 'SCHEMA') do |result|
    create_table = each_hash(result).first[:"Create Table"]
    if create_table.to_s =~ /PRIMARY KEY\s+\((.+)\)/
      keys = $1.split(",").map { |key| key.gsub(/[`"]/, "") }
      keys.length == 1 ? [keys.first, nil] : nil
    else
      nil
    end
  end
end

#primary_key(table) ⇒ Object

Returns just a table’s primary key



517
518
519
520
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 517

def primary_key(table)
  pk_and_sequence = pk_and_sequence_for(table)
  pk_and_sequence && pk_and_sequence.first
end

#quote(value, column = nil) ⇒ Object

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



186
187
188
189
190
191
192
193
194
195
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 186

def quote(value, column = nil)
  if value.kind_of?(String) && column && column.type == :binary && column.class.respond_to?(:string_to_binary)
    s = column.class.string_to_binary(value).unpack("H*")[0]
    "x'#{s}'"
  elsif value.kind_of?(BigDecimal)
    value.to_s("F")
  else
    super
  end
end

#quote_column_name(name) ⇒ Object

:nodoc:



197
198
199
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 197

def quote_column_name(name) #:nodoc:
  @quoted_column_names[name] ||= "`#{name.to_s.gsub('`', '``')}`"
end

#quote_table_name(name) ⇒ Object

:nodoc:



201
202
203
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 201

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

#quoted_falseObject



209
210
211
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 209

def quoted_false
  QUOTED_FALSE
end

#quoted_trueObject



205
206
207
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 205

def quoted_true
  QUOTED_TRUE
end

#recreate_database(name, options = {}) ⇒ Object

Drops the database specified on the name attribute and creates it again using the provided options.



324
325
326
327
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 324

def recreate_database(name, options = {})
  drop_database(name)
  create_database(name, options)
end

#release_savepointObject



281
282
283
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 281

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

#rename_column(table_name, column_name, new_column_name) ⇒ Object

:nodoc:



471
472
473
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 471

def rename_column(table_name, column_name, new_column_name) #:nodoc:
  execute("ALTER TABLE #{quote_table_name(table_name)} #{rename_column_sql(table_name, column_name, new_column_name)}")
end

#rename_table(table_name, new_name) ⇒ Object

Renames a table.

Example:

rename_table('octopuses', 'octopi')


444
445
446
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 444

def rename_table(table_name, new_name)
  execute "RENAME TABLE #{quote_table_name(table_name)} TO #{quote_table_name(new_name)}"
end

#rollback_db_transactionObject

:nodoc:



267
268
269
270
271
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 267

def rollback_db_transaction #:nodoc:
  execute "ROLLBACK"
rescue Exception
  # Transactions aren't supported
end

#rollback_to_savepointObject



277
278
279
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 277

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

#show_variable(name) ⇒ Object

SHOW VARIABLES LIKE ‘name’



498
499
500
501
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 498

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

#structure_dumpObject

SCHEMA STATEMENTS ========================================



308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 308

def structure_dump #:nodoc:
  if supports_views?
    sql = "SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'"
  else
    sql = "SHOW TABLES"
  end

  select_all(sql).map { |table|
    table.delete('Table_type')
    sql = "SHOW CREATE TABLE #{quote_table_name(table.to_a.first.last)}"
    exec_without_stmt(sql).first['Create Table'] + ";\n\n"
  }.join
end

#supports_bulk_alter?Boolean

:nodoc:

Returns:

  • (Boolean)


151
152
153
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 151

def supports_bulk_alter? #:nodoc:
  true
end

#supports_index_sort_order?Boolean

Technically MySQL allows to create indexes with the sort order syntax but at the moment (5.5) it doesn’t yet implement them

Returns:

  • (Boolean)


157
158
159
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 157

def supports_index_sort_order?
  true
end

#supports_migrations?Boolean

Returns true, since this connection adapter supports migrations.

Returns:

  • (Boolean)


138
139
140
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 138

def supports_migrations?
  true
end

#supports_primary_key?Boolean

Returns:

  • (Boolean)


142
143
144
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 142

def supports_primary_key?
  true
end

#supports_savepoints?Boolean

Returns true, since this connection adapter supports savepoints.

Returns:

  • (Boolean)


147
148
149
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 147

def supports_savepoints?
  true
end

#table_exists?(name) ⇒ Boolean

Returns:

  • (Boolean)


376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 376

def table_exists?(name)
  return false unless name
  return true if tables(nil, nil, name).any?

  name          = name.to_s
  schema, table = name.split('.', 2)

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

  tables(nil, schema, table).any?
end

#tables(name = nil, database = nil, like = nil) ⇒ Object

:nodoc:



366
367
368
369
370
371
372
373
374
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 366

def tables(name = nil, database = nil, like = nil) #:nodoc:
  sql = "SHOW TABLES "
  sql << "IN #{database} " if database
  sql << "LIKE #{quote(like)}" if like

  execute_and_free(sql, 'SCHEMA') do |result|
    result.collect { |field| field.first }
  end
end

#type_to_sql(type, limit = nil, precision = nil, scale = nil) ⇒ Object

Maps logical Rails types to MySQL-specific data types.



476
477
478
479
480
481
482
483
484
485
486
487
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 476

def type_to_sql(type, limit = nil, precision = nil, scale = nil)
  return super unless type.to_s == 'integer'

  case limit
  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}")
  end
end

#update_sql(sql, name = nil) ⇒ Object

:nodoc:



250
251
252
253
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 250

def update_sql(sql, name = nil) #:nodoc:
  super
  @connection.affected_rows
end