Class: ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter

Inherits:
AbstractAdapter show all
Includes:
MySQL::ColumnDumper, MySQL::Quoting
Defined in:
activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb

Direct Known Subclasses

Mysql2Adapter

Defined Under Namespace

Classes: MysqlJson, MysqlString, StatementPool

Constant Summary collapse

NATIVE_DATABASE_TYPES =
{
  primary_key: "int 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" },
  time:        { name: "time" },
  date:        { name: "date" },
  binary:      { name: "blob" },
  boolean:     { name: "tinyint", limit: 1 },
  json:        { name: "json" },
}
INDEX_TYPES =
[:fulltext, :spatial]
INDEX_USINGS =
[:btree, :hash]
CHARSETS_OF_4BYTES_MAXLEN =
['utf8mb4', 'utf16', 'utf16le', 'utf32']

Constants inherited from AbstractAdapter

ActiveRecord::ConnectionAdapters::AbstractAdapter::ADAPTER_NAME, ActiveRecord::ConnectionAdapters::AbstractAdapter::SIMPLE_INT

Constants included from ActiveSupport::Callbacks

ActiveSupport::Callbacks::CALLBACK_FILTER_TYPES

Instance Attribute Summary

Attributes inherited from AbstractAdapter

#logger, #owner, #pool, #prepared_statements, #schema_cache, #visitor

Attributes included from QueryCache

#query_cache, #query_cache_enabled

Attributes included from DatabaseStatements

#transaction_manager

Instance Method Summary collapse

Methods included from MySQL::ColumnDumper

#column_spec_for_primary_key, #migration_keys, #prepare_column_options

Methods included from MySQL::Quoting

#quote_column_name, #quote_table_name, #quoted_date, #quoted_false, #quoted_true, #unquoted_false, #unquoted_true

Methods inherited from AbstractAdapter

#active?, #adapter_name, #case_insensitive_comparison, #close, #collector, #column_name_for_operation, #combine_bind_parameters, #disable_extension, #disconnect!, #enable_extension, #expire, #extensions, #lease, #lookup_cast_type, #prefetch_primary_key?, #raw_connection, #reconnect!, #requires_reloading?, #reset!, #steal!, #supports_comments?, #supports_comments_in_create?, #supports_ddl_transactions?, #supports_expression_index?, #supports_extensions?, #supports_json?, #supports_multi_insert?, #supports_partial_index?, #supports_savepoints?, type_cast_config_to_boolean, type_cast_config_to_integer, #type_map, #unprepared_statement, #verify!

Methods included from Savepoints

#create_savepoint, #current_savepoint_name, #exec_rollback_to_savepoint, #release_savepoint

Methods included from ColumnDumper

#column_spec, #column_spec_for_primary_key, #migration_keys, #prepare_column_options

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

#lookup_cast_type_from_column, #prepare_binds_for_database, #quote, #quote_column_name, #quote_default_expression, #quote_string, #quote_table_name, #quote_table_name_for_assignment, #quoted_date, #quoted_false, #quoted_time, #quoted_true, #type_cast, #type_cast_from_column, #unquoted_false, #unquoted_true

Methods included from DatabaseStatements

#add_transaction_record, #cacheable_query, #default_sequence_name, #delete, #exec_delete, #exec_insert, #exec_query, #exec_update, #insert, #insert_fixture, #reset_sequence!, #reset_transaction, #rollback_db_transaction, #rollback_to_savepoint, #sanitize_limit, #select_all, #select_one, #select_rows, #select_value, #select_values, #to_sql, #transaction, #transaction_isolation_levels, #transaction_open?, #transaction_state, #update

Methods included from SchemaStatements

#add_column, #add_foreign_key, #add_index_options, #add_reference, #add_timestamps, #assume_migrated_upto_version, #change_column_comment, #change_table, #change_table_comment, #column_exists?, #create_join_table, #drop_join_table, #dump_schema_information, #foreign_key_column_for, #foreign_key_exists?, #foreign_key_for, #foreign_key_for!, #foreign_key_options, #index_exists?, #index_name, #index_name_exists?, #initialize_internal_metadata_table, #initialize_schema_migrations_table, #insert_versions_sql, #options_include_default?, #primary_key, #remove_column, #remove_columns, #remove_foreign_key, #remove_index, #remove_reference, #remove_timestamps, #table_alias_for

Methods included from ActiveSupport::Callbacks

#run_callbacks

Methods included from ActiveSupport::Concern

#append_features, #class_methods, extended, #included

Constructor Details

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

Returns a new instance of AbstractMysqlAdapter.


65
66
67
68
69
70
71
72
73
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 65

def initialize(connection, logger, connection_options, config)
  super(connection, logger, config)

  @statements = StatementPool.new(self.class.type_cast_config_to_integer(config[:statement_limit]))

  if version < '5.0.0'
    raise "Your version of MySQL (#{full_version.match(/^\d+\.\d+\.\d+/)[0]}) is too old. Active Record supports MySQL >= 5.0."
  end
end

Instance Method Details

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

:nodoc:


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

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

#add_sql_comment!(sql, comment) ⇒ Object

:nodoc:


510
511
512
513
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 510

def add_sql_comment!(sql, comment) # :nodoc:
  sql << " COMMENT #{quote(comment)}" if comment.present?
  sql
end

#arel_visitorObject

:nodoc:


27
28
29
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 27

def arel_visitor # :nodoc:
  Arel::Visitors::MySQL.new(self)
end

#begin_db_transactionObject


228
229
230
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 228

def begin_db_transaction
  execute "BEGIN"
end

#begin_isolated_db_transaction(isolation) ⇒ Object


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

def begin_isolated_db_transaction(isolation)
  execute "SET TRANSACTION ISOLATION LEVEL #{transaction_isolation_levels.fetch(isolation)}"
  begin_db_transaction
end

#bulk_change_table(table_name, operations) ⇒ Object

:nodoc:


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

def bulk_change_table(table_name, operations) #:nodoc:
  sqls = operations.flat_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.join(", ")

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

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


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

def case_sensitive_comparison(table, attribute, column, value)
  if !value.nil? && column.collation && !column.case_sensitive?
    table[attribute].eq(Arel::Nodes::Bin.new(Arel::Nodes::BindParam.new))
  else
    super
  end
end

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

:nodoc:


495
496
497
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 495

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_or_changes) ⇒ Object

:nodoc:


479
480
481
482
483
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 479

def change_column_default(table_name, column_name, default_or_changes) #:nodoc:
  default = extract_new_default_value(default_or_changes)
  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

:nodoc:


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

def change_column_null(table_name, column_name, null, default = nil) #:nodoc:
  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.


300
301
302
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 300

def charset
  show_variable 'character_set_database'
end

#clear_cache!Object

Clears the prepared statements cache.


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

def clear_cache!
  reload_type_map
  @statements.clear
end

#collationObject

Returns the database collation strategy.


305
306
307
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 305

def collation
  show_variable 'collation_database'
end

#columns(table_name) ⇒ Object

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


398
399
400
401
402
403
404
405
406
407
408
409
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 398

def columns(table_name) # :nodoc:
  table_name = table_name.to_s
  column_definitions(table_name).map do |field|
     = (field[:Type], field[:Extra])
    if .type == :datetime && field[:Default] == "CURRENT_TIMESTAMP"
      default, default_function = nil, field[:Default]
    else
      default, default_function = field[:Default], nil
    end
    new_column(field[:Field], default, , field[:Null] == "YES", table_name, default_function, field[:Collation], comment: field[:Comment].presence)
  end
end

#columns_for_distinct(columns, orders) ⇒ Object

In MySQL 5.7.5 and up, ONLY_FULL_GROUP_BY affects handling of queries that use DISTINCT and ORDER BY. It requires the ORDER BY columns in the select list for distinct queries, and requires that the ORDER BY include the distinct column. See dev.mysql.com/doc/refman/5.7/en/group-by-handling.html


632
633
634
635
636
637
638
639
640
641
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 632

def columns_for_distinct(columns, orders) # :nodoc:
  order_columns = orders.reject(&:blank?).map { |s|
    # Convert Arel node to string
    s = s.to_sql unless s.is_a?(String)
    # Remove any ASC/DESC modifiers
    s.gsub(/\s+(?:ASC|DESC)\b/i, '')
  }.reject(&:blank?).map.with_index { |column, i| "#{column} AS alias_#{i}" }

  [super, *order_columns].join(', ')
end

#commit_db_transactionObject

:nodoc:


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

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

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

def create_database(name, options = {})
  if options[:collation]
    execute "CREATE DATABASE #{quote_table_name(name)} DEFAULT CHARACTER SET #{quote_table_name(options[:charset] || 'utf8')} COLLATE #{quote_table_name(options[:collation])}"
  else
    execute "CREATE DATABASE #{quote_table_name(name)} DEFAULT CHARACTER SET #{quote_table_name(options[:charset] || 'utf8')}"
  end
end

#create_table(table_name, **options) ⇒ Object

:nodoc:


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

def create_table(table_name, **options) #:nodoc:
  super(table_name, options: 'ENGINE=InnoDB', **options)
end

#current_databaseObject


295
296
297
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 295

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

#data_source_exists?(table_name) ⇒ Boolean

Returns:

  • (Boolean)

347
348
349
350
351
352
353
354
355
356
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 347

def data_source_exists?(table_name)
  return false unless table_name.present?

  schema, name = extract_schema_qualified_name(table_name)

  sql = "SELECT table_name FROM information_schema.tables "
  sql << "WHERE table_schema = #{quote(schema)} AND table_name = #{quote(name)}"

  select_values(sql, 'SCHEMA').any?
end

#data_sourcesObject


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

def data_sources
  sql = "SELECT table_name FROM information_schema.tables "
  sql << "WHERE table_schema = #{quote(@config[:database])}"

  select_values(sql, 'SCHEMA')
end

#disable_referential_integrityObject

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


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

def disable_referential_integrity #: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')

291
292
293
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 291

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

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

Drops a table from the database.

:force

Set to :cascade to drop dependent objects as well. Defaults to false.

:if_exists

Set to true to only drop the table if it exists. Defaults to false.

:temporary

Set to true to drop temporary table. Defaults to false.

Although this command ignores most options and the block if one is given, it can be helpful to provide these in a migration's change method so it can be reverted. In that case, options and the block will be used by create_table.


465
466
467
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 465

def drop_table(table_name, options = {})
  execute "DROP#{' TEMPORARY' if options[:temporary]} TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_table_name(table_name)}#{' CASCADE' if options[:force] == :cascade}"
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)

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

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

#empty_insert_statement_valueObject


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

def empty_insert_statement_value
  "VALUES ()"
end

#emulate_booleansObject

:singleton-method: By default, the Mysql2Adapter will consider all columns of type tinyint(1) as boolean. If you wish to disable this emulation you can add the following line to your application.rb file:

ActiveRecord::ConnectionAdapters::Mysql2Adapter.emulate_booleans = false

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

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)

178
179
180
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 178

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

#exec_rollback_db_transactionObject

:nodoc:


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

def exec_rollback_db_transaction #:nodoc:
  execute "ROLLBACK"
end

#execute(sql, name = nil) ⇒ Object

Executes the SQL statement in the context of this connection.


217
218
219
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 217

def execute(sql, name = nil)
  log(sql, name) { @connection.query(sql) }
end

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

Mysql2Adapter doesn't have to free a result after using it, but 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:


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

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

#explain(arel, binds = []) ⇒ Object

– DATABASE STATEMENTS ====================================== ++


207
208
209
210
211
212
213
214
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 207

def explain(arel, binds = [])
  sql     = "EXPLAIN #{to_sql(arel, binds)}"
  start   = Time.now
  result  = exec_query(sql, 'EXPLAIN', binds)
  elapsed = Time.now - start

  MySQL::ExplainPrettyPrinter.new.pp(result, elapsed)
end

#foreign_keys(table_name) ⇒ Object

Raises:

  • (ArgumentError)

515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 515

def foreign_keys(table_name)
  raise ArgumentError unless table_name.present?

  schema, name = extract_schema_qualified_name(table_name)

  fk_info = select_all(<<-SQL.strip_heredoc, 'SCHEMA')
    SELECT fk.referenced_table_name AS 'to_table',
           fk.referenced_column_name AS 'primary_key',
           fk.column_name AS 'column',
           fk.constraint_name AS 'name',
           rc.update_rule AS 'on_update',
           rc.delete_rule AS 'on_delete'
    FROM information_schema.key_column_usage fk
    JOIN information_schema.referential_constraints rc
    USING (constraint_schema, constraint_name)
    WHERE fk.referenced_column_name IS NOT NULL
      AND fk.table_schema = #{quote(schema)}
      AND fk.table_name = #{quote(name)}
  SQL

  fk_info.map do |row|
    options = {
      column: row['column'],
      name: row['name'],
      primary_key: row['primary_key']
    }

    options[:on_update] = extract_foreign_key_action(row['on_update'])
    options[:on_delete] = extract_foreign_key_action(row['on_delete'])

    ForeignKeyDefinition.new(table_name, row['to_table'], options)
  end
end

#get_advisory_lock(lock_name, timeout = 0) ⇒ Object

:nodoc:


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

def get_advisory_lock(lock_name, timeout = 0) # :nodoc:
  select_value("SELECT GET_LOCK('#{lock_name}', #{timeout});").to_s == '1'
end

#index_algorithmsObject


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

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.


374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 374

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, row[:Index_comment].presence)
      end

      indexes.last.columns << row[:Column_name]
      indexes.last.lengths.merge!(row[:Column_name] => row[:Sub_part].to_i) if row[:Sub_part]
    end
  end

  indexes
end

#internal_string_options_for_primary_keyObject

:nodoc:


77
78
79
80
81
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 77

def internal_string_options_for_primary_key # :nodoc:
  super.tap { |options|
    options[:collation] = collation.sub(/\A[^_]+/, 'utf8') if CHARSETS_OF_4BYTES_MAXLEN.include?(charset)
  }
end

#join_to_update(update, select, key) ⇒ 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.


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

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

#mariadb?Boolean

:nodoc:

Returns:

  • (Boolean)

87
88
89
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 87

def mariadb? # :nodoc:
  full_version =~ /mariadb/i
end

#native_database_typesObject


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

def native_database_types
  NATIVE_DATABASE_TYPES
end

#new_column(*args) ⇒ Object

:nodoc:


172
173
174
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 172

def new_column(*args) #:nodoc:
  MySQL::Column.new(*args)
end

#primary_keys(table_name) ⇒ Object

:nodoc:

Raises:

  • (ArgumentError)

600
601
602
603
604
605
606
607
608
609
610
611
612
613
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 600

def primary_keys(table_name) # :nodoc:
  raise ArgumentError unless table_name.present?

  schema, name = extract_schema_qualified_name(table_name)

  select_values(<<-SQL.strip_heredoc, 'SCHEMA')
    SELECT column_name
    FROM information_schema.key_column_usage
    WHERE constraint_name = 'PRIMARY'
      AND table_schema = #{quote(schema)}
      AND table_name = #{quote(name)}
    ORDER BY ordinal_position
  SQL
end

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

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


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

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

#release_advisory_lock(lock_name) ⇒ Object

:nodoc:


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

def release_advisory_lock(lock_name) # :nodoc:
  select_value("SELECT RELEASE_LOCK('#{lock_name}')").to_s == '1'
end

#rename_column(table_name, column_name, new_column_name) ⇒ Object

:nodoc:


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

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_index(table_name, old_name, new_name) ⇒ Object


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

def rename_index(table_name, old_name, new_name)
  if supports_rename_index?
    validate_index_length!(table_name, new_name)

    execute "ALTER TABLE #{quote_table_name(table_name)} RENAME INDEX #{quote_table_name(old_name)} TO #{quote_table_name(new_name)}"
  else
    super
  end
end

#rename_table(table_name, new_name) ⇒ Object

Renames a table.

Example:

rename_table('octopuses', 'octopi')

445
446
447
448
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 445

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

#schema_creationObject

:nodoc:


23
24
25
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 23

def schema_creation # :nodoc:
  MySQL::SchemaCreation.new(self)
end

#show_variable(name) ⇒ Object

SHOW VARIABLES LIKE 'name'


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

def show_variable(name)
  select_value("SELECT @@#{name}", 'SCHEMA')
rescue ActiveRecord::StatementInvalid
  nil
end

#strict_mode?Boolean

Returns:

  • (Boolean)

643
644
645
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 643

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

#supports_advisory_locks?Boolean

Returns:

  • (Boolean)

144
145
146
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 144

def supports_advisory_locks?
  true
end

#supports_bulk_alter?Boolean

:nodoc:

Returns:

  • (Boolean)

100
101
102
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 100

def supports_bulk_alter? #:nodoc:
  true
end

#supports_datetime_with_precision?Boolean

Returns:

  • (Boolean)

136
137
138
139
140
141
142
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 136

def supports_datetime_with_precision?
  if mariadb?
    version >= '5.3.0'
  else
    version >= '5.6.4'
  end
end

#supports_explain?Boolean

Returns:

  • (Boolean)

120
121
122
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 120

def supports_explain?
  true
end

#supports_foreign_keys?Boolean

Returns:

  • (Boolean)

128
129
130
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 128

def supports_foreign_keys?
  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)

112
113
114
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 112

def supports_index_sort_order?
  true
end

#supports_indexes_in_create?Boolean

Returns:

  • (Boolean)

124
125
126
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 124

def supports_indexes_in_create?
  true
end

#supports_migrations?Boolean

Returns true, since this connection adapter supports migrations.

Returns:

  • (Boolean)

92
93
94
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 92

def supports_migrations?
  true
end

#supports_primary_key?Boolean

Returns:

  • (Boolean)

96
97
98
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 96

def supports_primary_key?
  true
end

#supports_statement_cache?Boolean

Returns true, since this connection adapter supports prepared statement caching.

Returns:

  • (Boolean)

106
107
108
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 106

def supports_statement_cache?
  true
end

#supports_transaction_isolation?Boolean

Returns:

  • (Boolean)

116
117
118
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 116

def supports_transaction_isolation?
  true
end

#supports_views?Boolean

Returns:

  • (Boolean)

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

def supports_views?
  true
end

#table_comment(table_name) ⇒ Object

:nodoc:


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

def table_comment(table_name) # :nodoc:
  schema, name = extract_schema_qualified_name(table_name)

  select_value(<<-SQL.strip_heredoc, 'SCHEMA')
    SELECT table_comment
    FROM information_schema.tables
    WHERE table_schema = #{quote(schema)}
      AND table_name = #{quote(name)}
  SQL
end

#table_exists?(table_name) ⇒ Boolean

Returns:

  • (Boolean)

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

def table_exists?(table_name)
  # Update lib/active_record/internal_metadata.rb when this gets removed
  ActiveSupport::Deprecation.warn(<<-MSG.squish)
    #table_exists? currently checks both tables and views.
    This behavior is deprecated and will be changed with Rails 5.1 to only check tables.
    Use #data_source_exists? instead.
  MSG

  data_source_exists?(table_name)
end

#table_options(table_name) ⇒ Object

:nodoc:


549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 549

def table_options(table_name) # :nodoc:
  table_options = {}

  create_table_info = create_table_info(table_name)

  # strip create_definitions and partition_options
  raw_table_options = create_table_info.sub(/\A.*\n\) /m, '').sub(/\n\/\*!.*\*\/\n\z/m, '').strip

  # strip AUTO_INCREMENT
  raw_table_options.sub!(/(ENGINE=\w+)(?: AUTO_INCREMENT=\d+)/, '\1')

  table_options[:options] = raw_table_options

  # strip COMMENT
  if raw_table_options.sub!(/ COMMENT='.+'/, '')
    table_options[:comment] = table_comment(table_name)
  end

  table_options
end

#tables(name = nil) ⇒ Object

:nodoc:


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

def tables(name = nil) # :nodoc:
  ActiveSupport::Deprecation.warn(<<-MSG.squish)
    #tables currently returns both tables and views.
    This behavior is deprecated and will be changed with Rails 5.1 to only return tables.
    Use #data_sources instead.
  MSG

  if name
    ActiveSupport::Deprecation.warn(<<-MSG.squish)
      Passing arguments to #tables is deprecated without replacement.
    MSG
  end

  data_sources
end

#truncate(table_name, name = nil) ⇒ Object


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

def truncate(table_name, name = nil)
  execute "TRUNCATE TABLE #{quote_table_name(table_name)}", name
end

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

Maps logical Rails types to MySQL-specific data types.


571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 571

def type_to_sql(type, limit = nil, precision = nil, scale = nil, unsigned = nil)
  sql = case type.to_s
  when 'integer'
    integer_to_sql(limit)
  when 'text'
    text_to_sql(limit)
  when 'blob'
    binary_to_sql(limit)
  when 'binary'
    if (0..0xfff) === limit
      "varbinary(#{limit})"
    else
      binary_to_sql(limit)
    end
  else
    super(type, limit, precision, scale)
  end

  sql << ' unsigned' if unsigned && type != :primary_key
  sql
end

#update_table_definition(table_name, base) ⇒ Object

:nodoc:


19
20
21
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 19

def update_table_definition(table_name, base) # :nodoc:
  MySQL::Table.new(table_name, base)
end

#valid_type?(type) ⇒ Boolean

Returns:

  • (Boolean)

647
648
649
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 647

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

#versionObject

:nodoc:


83
84
85
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 83

def version #:nodoc:
  @version ||= Version.new(full_version.match(/^\d+\.\d+\.\d+/)[0])
end

#view_exists?(view_name) ⇒ Boolean

:nodoc:

Returns:

  • (Boolean)

362
363
364
365
366
367
368
369
370
371
# File 'activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 362

def view_exists?(view_name) # :nodoc:
  return false unless view_name.present?

  schema, name = extract_schema_qualified_name(view_name)

  sql = "SELECT table_name FROM information_schema.tables WHERE table_type = 'VIEW'"
  sql << " AND table_schema = #{quote(schema)} AND table_name = #{quote(name)}"

  select_values(sql, 'SCHEMA').any?
end

#viewsObject

:nodoc:


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

def views # :nodoc:
  select_values("SHOW FULL TABLES WHERE table_type = 'VIEW'", 'SCHEMA')
end