Class: ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter

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

Direct Known Subclasses

Mysql2Adapter, MysqlAdapter

Defined Under Namespace

Classes: BindSubstitution, Column, SchemaCreation

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 }
}
INDEX_TYPES =
[:fulltext, :spatial]
INDEX_USINGS =
[:btree, :hash]

Constants inherited from AbstractAdapter

ActiveRecord::ConnectionAdapters::AbstractAdapter::SIMPLE_INT

Constants included from ActiveSupport::Callbacks

ActiveSupport::Callbacks::CALLBACK_FILTER_TYPES

Instance Attribute Summary

Attributes inherited from AbstractAdapter

#in_use, #last_use, #logger, #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, #disconnect!, #expire, #extensions, #lease, #open_transactions, #prefetch_primary_key?, #raw_connection, #reconnect!, #requires_reloading?, #reset!, #substitute_at, #supports_count_distinct?, #supports_ddl_transactions?, #supports_explain?, #supports_extensions?, #supports_partial_index?, type_cast_config_to_boolean, type_cast_config_to_integer, #unprepared_statement, #unprepared_visitor, #verify!

Methods included from ColumnDumper

#column_spec, #migration_keys, #prepare_column_options

Methods included from ActiveSupport::Callbacks

#run_callbacks

Methods included from ActiveSupport::Concern

#append_features, extended, #included

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

#allowed_index_name_length, #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, #quote_table_name_for_assignment, #quoted_date, #type_cast

Methods included from DatabaseStatements

#add_transaction_record, #begin_transaction, #case_sensitive_equality_operator, #commit_transaction, #current_transaction, #default_sequence_name, #delete, #exec_delete, #exec_insert, #exec_query, #exec_update, #insert, #insert_fixture, #join_to_delete, #reset_sequence!, #reset_transaction, #rollback_transaction, #sanitize_limit, #select_all, #select_one, #select_rows, #select_value, #select_values, #supports_statement_cache?, #to_sql, #transaction, #transaction_isolation_levels, #transaction_open?, #update, #within_new_transaction

Methods included from SchemaStatements

#add_column, #add_reference, #add_timestamps, #assume_migrated_upto_version, #change_table, #column_exists?, #columns_for_distinct, #create_join_table, #drop_join_table, #drop_table, #dump_schema_information, #index_exists?, #index_name, #index_name_exists?, #initialize_schema_migrations_table, #remove_column, #remove_columns, #remove_index, #remove_index!, #remove_reference, #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



171
172
173
174
175
176
177
178
179
180
181
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 171

def initialize(connection, logger, connection_options, config)
  super(connection, logger)
  @connection_options, @config = connection_options, config
  @quoted_column_names, @quoted_table_names = {}, {}

  if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true })
    @visitor = Arel::Visitors::MySQL.new self
  else
    @visitor = unprepared_visitor
  end
end

Instance Method Details

#adapter_nameObject

:nodoc:



183
184
185
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 183

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

#add_column_position!(sql, options) ⇒ Object



566
567
568
569
570
571
572
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 566

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

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

:nodoc:



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

def add_index(table_name, column_name, options = {}) #:nodoc:
  index_name, index_type, index_columns, index_options, index_algorithm, index_using = add_index_options(table_name, column_name, options)
  execute "CREATE #{index_type} INDEX #{quote_column_name(index_name)} #{index_using} ON #{quote_table_name(table_name)} (#{index_columns})#{index_options} #{index_algorithm}"
end

#begin_db_transactionObject



317
318
319
320
321
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 317

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

#begin_isolated_db_transaction(isolation) ⇒ Object



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

def begin_isolated_db_transaction(isolation)
  execute "SET TRANSACTION ISOLATION LEVEL #{transaction_isolation_levels.fetch(isolation)}"
  begin_db_transaction
rescue
  # Transactions aren't supported
end

#bulk_change_table(table_name, operations) ⇒ Object

:nodoc:



481
482
483
484
485
486
487
488
489
490
491
492
493
494
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 481

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, true)
      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



603
604
605
606
607
608
609
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 603

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



599
600
601
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 599

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

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

:nodoc:



520
521
522
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 520

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



505
506
507
508
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 505

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



510
511
512
513
514
515
516
517
518
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 510

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.



409
410
411
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 409

def charset
  show_variable 'character_set_database'
end

#collationObject

Returns the database collation strategy.



414
415
416
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 414

def collation
  show_variable 'collation_database'
end

#columns(table_name) ⇒ Object

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



468
469
470
471
472
473
474
475
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 468

def columns(table_name)#: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], field[:Extra])
    end
  end
end

#commit_db_transactionObject

:nodoc:



330
331
332
333
334
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 330

def commit_db_transaction #:nodoc:
  execute "COMMIT"
rescue
  # 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


388
389
390
391
392
393
394
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 388

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



342
343
344
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 342

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

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

:nodoc:



477
478
479
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 477

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

#current_databaseObject



404
405
406
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 404

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

#disable_referential_integrity(&block) ⇒ Object

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



277
278
279
280
281
282
283
284
285
286
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 277

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')


400
401
402
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 400

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)


231
232
233
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 231

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

#empty_insert_statement_valueObject



366
367
368
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 366

def empty_insert_statement_value
  "VALUES ()"
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


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

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)


242
243
244
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 242

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

#execute(sql, name = nil) ⇒ Object

Executes the SQL statement in the context of this connection.



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

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.new("'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.", exception.original_exception)
  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 an abstract way without concerning ourselves about whether it needs to be explicitly freed or not.

Yields:



308
309
310
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 308

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

#index_algorithmsObject



223
224
225
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 223

def index_algorithms
  { default: 'ALGORITHM = DEFAULT', copy: 'ALGORITHM = COPY', inplace: 'ALGORITHM = INPLACE' }
end

#indexes(table_name, name = nil) ⇒ Object

Returns an array of indexes for the given table.



444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 444

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]

        mysql_index_type = row[:Index_type].downcase.to_sym
        index_type  = INDEX_TYPES.include?(mysql_index_type)  ? mysql_index_type : nil
        index_using = INDEX_USINGS.include?(mysql_index_type) ? mysql_index_type : nil
        indexes << IndexDefinition.new(row[:Table], row[:Key_name], row[:Non_unique].to_i == 0, [], [], nil, nil, index_type, index_using)
      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.



357
358
359
360
361
362
363
364
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 357

def join_to_update(update, select) #:nodoc:
  if select.limit || select.offset || select.orders.any?
    super
  else
    update.table select.source
    update.wheres = select.constraints
  end
end

#limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key) ⇒ Object



611
612
613
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 611

def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key)
  where_sql
end

#native_database_typesObject



219
220
221
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 219

def native_database_types
  NATIVE_DATABASE_TYPES
end

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

Overridden by the adapters to instantiate their specific Column type.



236
237
238
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 236

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

#pk_and_sequence_for(table) ⇒ Object

Returns a table’s primary key and belonging sequence.



581
582
583
584
585
586
587
588
589
590
591
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 581

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+(?:USING\s+\w+\s+)?\((.+)\)/
      keys = $1.split(",").map { |key| key.delete('`"') }
      keys.length == 1 ? [keys.first, nil] : nil
    else
      nil
    end
  end
end

#primary_key(table) ⇒ Object

Returns just a table’s primary key



594
595
596
597
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 594

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 ==================================================



248
249
250
251
252
253
254
255
256
257
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 248

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:



259
260
261
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 259

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

#quote_table_name(name) ⇒ Object

:nodoc:



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

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

#quoted_falseObject



271
272
273
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 271

def quoted_false
  QUOTED_FALSE
end

#quoted_trueObject



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

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.



374
375
376
377
378
379
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 374

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

#release_savepointObject



350
351
352
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 350

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

#rename_column(table_name, column_name, new_column_name) ⇒ Object

:nodoc:



524
525
526
527
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 524

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)}")
  rename_column_indexes(table_name, column_name, new_column_name)
end

#rename_table(table_name, new_name) ⇒ Object

Renames a table.

Example:

rename_table('octopuses', 'octopi')


500
501
502
503
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 500

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

#rollback_db_transactionObject

:nodoc:



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

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

#rollback_to_savepointObject



346
347
348
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 346

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

#schema_creationObject



32
33
34
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 32

def schema_creation
  SchemaCreation.new self
end

#show_variable(name) ⇒ Object

SHOW VARIABLES LIKE ‘name’



575
576
577
578
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 575

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

#strict_mode?Boolean

Returns:

  • (Boolean)


615
616
617
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 615

def strict_mode?
  self.class.type_cast_config_to_boolean(@config.fetch(:strict, true))
end

#supports_bulk_alter?Boolean

:nodoc:

Returns:

  • (Boolean)


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

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)


207
208
209
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 207

def supports_index_sort_order?
  true
end

#supports_migrations?Boolean

Returns true, since this connection adapter supports migrations.

Returns:

  • (Boolean)


188
189
190
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 188

def supports_migrations?
  true
end

#supports_primary_key?Boolean

Returns:

  • (Boolean)


192
193
194
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 192

def supports_primary_key?
  true
end

#supports_savepoints?Boolean

Returns true, since this connection adapter supports savepoints.

Returns:

  • (Boolean)


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

def supports_savepoints?
  true
end

#supports_transaction_isolation?Boolean

MySQL 4 technically support transaction isolation, but it is affected by a bug where the transaction level gets persisted for the whole session:

bugs.mysql.com/bug.php?id=39170

Returns:

  • (Boolean)


215
216
217
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 215

def supports_transaction_isolation?
  version[0] >= 5
end

#table_exists?(name) ⇒ Boolean

Returns:

  • (Boolean)


428
429
430
431
432
433
434
435
436
437
438
439
440
441
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 428

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:



418
419
420
421
422
423
424
425
426
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 418

def tables(name = nil, database = nil, like = nil) #:nodoc:
  sql = "SHOW TABLES "
  sql << "IN #{quote_table_name(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.



535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 535

def type_to_sql(type, limit = nil, precision = nil, scale = nil)
  case type.to_s
  when 'binary'
    case limit
    when 0..0xfff;           "varbinary(#{limit})"
    when nil;                "blob"
    when 0x1000..0xffffffff; "blob(#{limit})"
    else raise(ActiveRecordError, "No binary type has character length #{limit}")
    end
  when '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
  when 'text'
    case limit
    when 0..0xff;               'tinytext'
    when nil, 0x100..0xffff;    'text'
    when 0x10000..0xffffff;     'mediumtext'
    when 0x1000000..0xffffffff; 'longtext'
    else raise(ActiveRecordError, "No text type has character length #{limit}")
    end
  else
    super
  end
end

#update_sql(sql, name = nil) ⇒ Object

:nodoc:



312
313
314
315
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 312

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

#valid_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


619
620
621
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 619

def valid_type?(type)
  !native_database_types[type].nil?
end