123456789_123456789_123456789_123456789_123456789_

Class: ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter

Constant Summary

::ActiveSupport::Callbacks - Included

CALLBACK_FILTER_TYPES

DatabaseStatements - Included

DEFAULT_INSERT_VALUE, HIGH_PRECISION_CURRENT_TIMESTAMP

AbstractAdapter - Inherited

ADAPTER_NAME, COMMENT_REGEX, DEFAULT_READ_QUERY, EXCEPTION_IMMEDIATE, EXCEPTION_NEVER, EXTENDED_TYPE_MAPS, SIMPLE_INT, TYPE_MAP

MySQL::DatabaseStatements - Included

HIGH_PRECISION_CURRENT_TIMESTAMP, READ_QUERY

MySQL::Quoting - Included

QUOTED_COLUMN_NAMES, QUOTED_TABLE_NAMES

MySQL::SchemaStatements - Included

CHARSETS_OF_4BYTES_MAXLEN

Class Attribute Summary

Class Method Summary

Instance Attribute Summary

MySQL::SchemaStatements - Included

MySQL::DatabaseStatements - Included

AbstractAdapter - Inherited

#__callbacks,
#active?

Checks whether the connection to the database is still active.

#connected?

Checks whether the connection to the database was established.

#database_exists?,
#in_use?
#lock, #logger, #owner, #pool, #pool=,
#prepared_statements
#preventing_writes?

Determines whether writes are currently being prevented.

#replica?,
#requires_reloading?

Returns true if its required to reload the connection between requests for development mode.

#savepoint_errors_invalidate_transactions?

Do TransactionRollbackErrors on savepoints affect the parent transaction?

#supports_advisory_locks?

Does this adapter support application-enforced advisory locking?

#supports_bulk_alter?,
#supports_check_constraints?

Does this adapter support creating check constraints?

#supports_comments?

Does this adapter support metadata comments on database objects (tables, columns, indexes)?

#supports_comments_in_create?

Can comments for tables, columns, and indexes be specified in create/alter table statements?

#supports_common_table_expressions?, #supports_concurrent_connections?,
#supports_datetime_with_precision?

Does this adapter support datetime with precision?

#supports_ddl_transactions?

Does this adapter support DDL rollbacks in transactions? That is, would CREATE TABLE or ALTER TABLE get rolled back by a transaction?

#supports_deferrable_constraints?

Does this adapter support creating deferrable constraints?

#supports_exclusion_constraints?

Does this adapter support creating exclusion constraints?

#supports_explain?

Does this adapter support explain?

#supports_expression_index?

Does this adapter support expression indices?

#supports_extensions?

Does this adapter support database extensions?

#supports_foreign_keys?

Does this adapter support creating foreign key constraints?

#supports_foreign_tables?

Does this adapter support foreign/external tables?

#supports_index_include?

Does this adapter support including non-key columns?

#supports_index_sort_order?

Does this adapter support index sort order?

#supports_indexes_in_create?

Does this adapter support creating indexes in the same statement as creating the table?

#supports_insert_conflict_target?, #supports_insert_on_duplicate_skip?, #supports_insert_on_duplicate_update?, #supports_insert_returning?,
#supports_json?

Does this adapter support JSON data type?

#supports_lazy_transactions?,
#supports_materialized_views?

Does this adapter support materialized views?

#supports_nulls_not_distinct?,
#supports_optimizer_hints?

Does this adapter support optimizer hints?

#supports_partial_index?

Does this adapter support partial indices?

#supports_partitioned_indexes?, #supports_restart_db_transaction?,
#supports_savepoints?

Does this adapter support savepoints?

#supports_transaction_isolation?

Does this adapter support setting the isolation level for a transaction?

#supports_unique_constraints?

Does this adapter support creating unique constraints?

#supports_validate_constraints?

Does this adapter support creating invalid constraints?

#supports_views?

Does this adapter support views?

#supports_virtual_columns?

Does this adapter support virtual columns?

#visitor, #reconnect_can_restore_state?, #advisory_locks_enabled?, #async_enabled?, #lock_thread=

DatabaseStatements - Included

SchemaStatements - Included

Instance Method Summary

MySQL::SchemaStatements - Included

MySQL::Quoting - Included

#cast_bound_value, #quoted_binary,
#type_cast

Override type_cast we pass to mysql2 ::Date and ::Time objects instead of Strings since MySQL adapters are able to handle those classes more efficiently.

#unquote_identifier, #unquoted_false, #unquoted_true

MySQL::DatabaseStatements - Included

AbstractAdapter - Inherited

#adapter_name

Returns the human-readable name of the adapter.

#check_all_foreign_keys_valid!

Override to check all foreign key constraints in a database.

#clear_cache!

Clear any caching the database adapter may be doing.

#close

Check the connection back in to the connection pool.

#connect!, #connection_retries, #default_timezone,
#disable_extension

This is meant to be implemented by the adapters that support extensions.

#disable_referential_integrity

Override to turn off referential integrity while executing &block.

#discard!

Immediately forget this connection ever existed.

#disconnect!

Disconnects from the database if already connected.

#enable_extension

This is meant to be implemented by the adapters that support extensions.

#expire

this method must only be called while holding connection pool’s mutex.

#extensions

A list of extensions, to be filled in by adapters that support them.

#index_algorithms

A list of index algorithms, to be filled by adapters that support them.

#lease

this method must only be called while holding connection pool’s mutex.

#prefetch_primary_key?

Should primary key values be selected from their corresponding sequence before the insert statement? If true, next_sequence_value is called before each insert to set the record’s primary key.

#prepared_statements?,
#raw_connection

Provides access to the underlying database driver for this adapter.

#reconnect!

Disconnects from the database if already connected, and establishes a new connection with the database.

#reset!

Reset the state of this connection, directing the DBMS to clear transactions and other connection-related server-side state.

#retry_deadline,
#role

The role (e.g. :writing) for the current connection.

#schema_cache,
#schema_version

Returns the version identifier of the schema currently available in the database.

#shard

The shard (e.g. :default) for the current connection.

#throw_away!

Removes the connection from the pool and disconnect it.

#unprepared_statement,
#verify!

Checks whether the connection to the database is still active (i.e. not stale).

#any_raw_connection

Returns a raw connection for internal use with methods that are known to both be thread-safe and not rely upon actual server communication.

#arel_visitor, #backoff,
#build_result

Builds the result object.

#build_statement_pool, #can_perform_case_insensitive_comparison_for?, #collector, #column_for, #column_for_attribute,
#configure_connection

Perform any necessary initialization upon the newly-established connection settings, run queries to configure any application-global “session” variables, etc.

#default_prepared_statements, #extended_type_map_key, #invalidate_transaction, #log, #reconnect, #retryable_connection_error?, #retryable_query_error?, #translate_exception, #translate_exception_class, #type_map,
#valid_raw_connection

Similar to any_raw_connection, but ensures it is validated and connected.

#verified!

Mark the connection as verified.

#warning_ignored?,
#with_raw_connection

Lock the monitor, ensure we’re properly connected and transactions are materialized, and then yield the underlying raw connection object.

#add_enum_value

This is meant to be implemented by the adapters that support custom enum types.

#build_insert_sql

Called by ::ActiveRecord::InsertAll, Passed an instance of ::ActiveRecord::InsertAll::Builder, This method implements standard bulk inserts for all databases, but should be overridden by adapters to implement common features with non-standard syntax like handling duplicates or returning values.

#case_insensitive_comparison, #case_sensitive_comparison, #check_if_write_query, #check_version, #clean!, #connection_class,
#create_enum

This is meant to be implemented by the adapters that support custom enum types.

#create_virtual_table

This is meant to be implemented by the adapters that support virtual tables.

#database_version, #default_index_type?, #default_uniqueness_comparison,
#drop_enum

This is meant to be implemented by the adapters that support custom enum types.

#drop_virtual_table

This is meant to be implemented by the adapters that support virtual tables.

#get_advisory_lock

This is meant to be implemented by the adapters that support advisory locks.

#get_database_version, #inspect, #prepared_statements_disabled_cache,
#release_advisory_lock

This is meant to be implemented by the adapters that support advisory locks.

#rename_enum

This is meant to be implemented by the adapters that support custom enum types.

#rename_enum_value

This is meant to be implemented by the adapters that support custom enum types.

#return_value_after_insert?,
#seconds_idle

Seconds since this connection was returned to the pool.

#steal!

this method must only be called while holding connection pool’s mutex (and a desire for segfaults).

#valid_type?, #with_instrumenter

Savepoints - Included

DatabaseLimits - Included

#index_name_length

Returns the maximum length of an index name.

#table_alias_length

Returns the maximum length of a table alias.

#table_name_length

Returns the maximum length of a table name.

#bind_params_length, #max_identifier_length

Quoting - Included

#quote

Quotes the column value to help prevent SQL injection attacks.

#quote_column_name

Quotes the column name.

#quote_string

Quotes a string, escaping any ‘ (single quote) and \ (backslash) characters.

#quote_table_name

Quotes the table name.

#quote_table_name_for_assignment

Override to return the quoted table name for assignment.

#quoted_date

Quote date/time values for use in SQL input.

#quoted_false, #quoted_true,
#type_cast

Cast a value to a type that the database understands.

#unquoted_false, #unquoted_true, #lookup_cast_type, #type_casted_binds,
#cast_bound_value

Cast a value to be used as a bound parameter of unknown type.

#lookup_cast_type_from_column

If you are having to call this function, you are likely doing something wrong.

#quote_default_expression, #quoted_binary, #quoted_time, #sanitize_as_sql_comment

DatabaseStatements - Included

#add_transaction_record

Register a record with the current transaction so that its after_commit and after_rollback callbacks can be called.

#begin_db_transaction

Begins the transaction (and turns off auto-committing).

#begin_isolated_db_transaction

Begins the transaction with the isolation level set.

#commit_db_transaction

Commits the transaction (and turns on auto-committing).

#create
#default_sequence_name,
#delete

Executes the delete statement and returns the number of rows affected.

#disable_lazy_transactions!, #empty_insert_statement_value, #enable_lazy_transactions!,
#exec_delete

Executes delete sql statement in the context of this connection using binds as the bind substitutes.

#exec_insert

Executes insert sql statement in the context of this connection using binds as the bind substitutes.

#exec_query

Executes sql statement in the context of this connection using binds as the bind substitutes.

#exec_update

Executes update sql statement in the context of this connection using binds as the bind substitutes.

#execute

Executes the SQL statement in the context of this connection and returns the raw result from the connection adapter.

#high_precision_current_timestamp

Returns an ::Arel SQL literal for the CURRENT_TIMESTAMP for usage with arbitrary precision date/time columns.

#initialize,
#insert

Executes an INSERT query and returns the new record’s ID.

#insert_fixture

Inserts the given fixture into the table.

#insert_fixtures_set,
#reset_isolation_level

Hook point called after an isolated DB transaction is committed or rolled back.

#reset_sequence!

Set the sequence to the max value of the table’s column.

#restart_db_transaction,
#rollback_db_transaction

Rolls back the transaction (and turns on auto-committing).

#rollback_to_savepoint,
#sanitize_limit

Sanitizes the given LIMIT parameter in order to prevent SQL injection.

#select_all

Returns an ::ActiveRecord::Result instance.

#select_one

Returns a record hash with the column names as keys and column values as values.

#select_rows

Returns an array of arrays containing the field values.

#select_value

Returns a single value from a record.

#select_values

Returns an array of the values of the first column in a select:

#to_sql

Converts an arel AST to SQL.

#transaction

Runs the given block in a database transaction, and returns the result of the block.

#transaction_isolation_levels,
#truncate

Executes the truncate statement.

#update

Executes the update statement and returns the number of rows affected.

#write_query?

Determines whether the SQL statement is a write query.

#affected_rows, #arel_from_relation, #build_fixture_sql, #build_fixture_statements, #build_truncate_statement, #build_truncate_statements,
#cast_result

Receive a native adapter result object and returns an ::ActiveRecord::Result object.

#combine_multi_statements, #default_insert_value, #execute_batch, #extract_table_ref_from_insert_sql,
#internal_execute

Same as #internal_exec_query, but yields a native adapter result.

#last_inserted_id, #perform_query, #preprocess_query,
#raw_execute

Lowest level way to execute a query.

#returning_column_values,
#select

Returns an ::ActiveRecord::Result instance.

#single_value_from_rows, #begin_deferred_transaction,
#cacheable_query

This is used in the ::ActiveRecord::StatementCache object.

#exec_insert_all, #exec_restart_db_transaction, #exec_rollback_db_transaction, #explain,
#internal_exec_query

Execute a query and returns an ::ActiveRecord::Result

#mark_transaction_written_if_write, #query, #query_value, #query_values,
#raw_exec_query

Same as raw_execute but returns an ::ActiveRecord::Result object.

#reset_transaction, #truncate_tables,
#with_yaml_fallback

::ActiveRecord::Fixture value is quoted by ::Arel, however scalar values are not quotable.

#sql_for_insert, #to_sql_and_binds

SchemaStatements - Included

#add_belongs_to
#add_check_constraint

Adds a new check constraint to the table.

#add_column

Add a new type column named column_name to table_name.

#add_foreign_key

Adds a new foreign key.

#add_index

Adds a new index to the table.

#add_reference

Adds a reference.

#add_timestamps

Adds timestamps (created_at and updated_at) columns to table_name.

#assume_migrated_upto_version,
#build_create_table_definition

Returns a TableDefinition object containing information about the table that would be created if the same arguments were passed to #create_table.

#change_column

Changes the column’s definition according to the new options.

#change_column_comment

Changes the comment for a column or removes it if nil.

#change_column_default

Sets a new default value for a column:

#change_column_null

Sets or removes a NOT NULL constraint on a column.

#change_table

A block for changing columns in table.

#change_table_comment

Changes the comment for a table or removes it if nil.

#check_constraint_exists?

Checks to see if a check constraint exists on a table for a given check constraint definition.

#check_constraints

Returns an array of check constraints for the given table.

#column_exists?

Checks to see if a column exists in a given table.

#columns

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

#create_join_table

Creates a new join table with the name created using the lexical order of the first two arguments.

#create_table

Creates a new table with the name table_name.

#data_source_exists?

Checks to see if the data source name exists on the database.

#data_sources

Returns the relation names usable to back Active Record models.

#drop_join_table

Drops the join table specified by the given arguments.

#drop_table

Drops a table or tables from the database.

#foreign_key_exists?

Checks to see if a foreign key exists on a table for a given foreign key definition.

#foreign_keys

Returns an array of foreign keys for the given table.

#index_exists?

Checks to see if an index exists on a table for a given index definition.

#index_name_exists?

Verifies the existence of an index with a given name.

#indexes

Returns an array of indexes for the given table.

#max_index_name_size

Returns the maximum length of an index name in bytes.

#native_database_types

Returns a hash of mappings from the abstract data types to the native database types.

#options_include_default?,
#primary_key

Returns just a table’s primary key.

#remove_belongs_to
#remove_check_constraint

Removes the given check constraint from the table.

#remove_column

Removes the column from the table definition.

#remove_columns

Removes the given columns from the table definition.

#remove_foreign_key

Removes the given foreign key from the table.

#remove_index

Removes the given index from the table.

#remove_reference

Removes the reference(s).

#remove_timestamps

Removes the timestamp columns (created_at and updated_at) from the table definition.

#rename_column

Renames a column.

#rename_index

Renames an index.

#rename_table

Renames a table.

#table_alias_for

Truncates a table alias according to the limits of the current adapter.

#table_comment

Returns the table comment that’s stored in database metadata.

#table_exists?

Checks to see if the table table_name exists on the database.

#table_options,
#tables

Returns an array of table names defined in the database.

#view_exists?

Checks to see if the view view_name exists on the database.

#views

Returns an array of view names defined in the database.

#add_column_for_alter, #add_index_sort_order,
#add_options_for_index_columns

Overridden by the MySQL adapter for supporting index lengths and by the PostgreSQL adapter for supporting operator classes.

#add_timestamps_for_alter, #can_remove_index_by_name?, #change_column_default_for_alter, #check_constraint_for, #check_constraint_for!, #check_constraint_name, #column_options_keys, #create_alter_table, #create_table_definition, #data_source_sql,
#expression_column_name?

Try to identify whether the given column name is an expression.

#extract_foreign_key_action,
#extract_new_comment_value
#extract_new_default_value, #fetch_type_metadata, #foreign_key_for, #foreign_key_for!, #foreign_key_name, #generate_index_name, #index_column_names, #index_name_for_remove, #index_name_options, #insert_versions_sql, #options_for_index_columns, #quoted_scope, #reference_name_for_table, #remove_column_for_alter, #remove_columns_for_alter, #remove_timestamps_for_alter, #rename_column_indexes, #rename_column_sql, #rename_table_indexes, #strip_table_name_prefix_and_suffix, #validate_change_column_null_argument!, #validate_create_table_options!, #validate_index_length!, #validate_table_length!, #add_columns, #add_index_options,
#build_add_column_definition

Builds an AlterTable object for adding a column to a table.

#build_change_column_default_definition
#build_create_index_definition

Builds a CreateIndexDefinition object.

#build_create_join_table_definition

Builds a TableDefinition object for a join table.

#bulk_change_table, #check_constraint_options,
#columns_for_distinct

Given a set of columns and an ORDER BY clause, returns the columns for a SELECT DISTINCT.

#create_schema_dumper, #distinct_relation_for_primary_key, #dump_schema_information, #foreign_key_column_for, #foreign_key_options, #index_algorithm, #index_name, #internal_string_options_for_primary_key, #quoted_columns_for_index, #remove_constraint,
#schema_creation

Returns an instance of SchemaCreation, which can be used to visit a schema definition object and return DDL.

#type_to_sql, #update_table_definition, #valid_column_definition_options, #valid_primary_key_options, #valid_table_definition_options

::ActiveRecord::Migration::JoinTable - Included

::ActiveSupport::Callbacks - Included

#run_callbacks

Runs the callbacks for the given event.

#halted_callback_hook

A hook invoked every time a before callback is halted.

Constructor Details

This class inherits a constructor from ActiveRecord::ConnectionAdapters::AbstractAdapter

Class Attribute Details

.emulate_booleans (rw)

[ GitHub ]

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

class_attribute :emulate_booleans, default: true

.emulate_booleans?Boolean (rw)

[ GitHub ]

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

class_attribute :emulate_booleans, default: true

Class Method Details

.dbconsole(config, options = {})

[ GitHub ]

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

def dbconsole(config, options = {})
  mysql_config = config.configuration_hash

  args = {
    host: "--host",
    port: "--port",
    socket: "--socket",
    username: "--user",
    encoding: "--default-character-set",
    sslca: "--ssl-ca",
    sslcert: "--ssl-cert",
    sslcapath: "--ssl-capath",
    sslcipher: "--ssl-cipher",
    sslkey: "--ssl-key",
    ssl_mode: "--ssl-mode"
  }.filter_map { |opt, arg| "#{arg}=#{mysql_config[opt]}" if mysql_config[opt] }

  if mysql_config[:password] && options[:include_password]
    args << "--password=#{mysql_config[:password]}"
  elsif mysql_config[:password] && !mysql_config[:password].to_s.empty?
    args << "-p"
  end

  args << config.database

  find_cmd_and_exec(ActiveRecord.database_cli[:mysql], *args)
end

.extended_type_map(default_timezone: nil, emulate_booleans:)

This method is for internal use only.
[ GitHub ]

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

def extended_type_map(default_timezone: nil, emulate_booleans:) # :nodoc:
  super(default_timezone: default_timezone).tap do |m|
    if emulate_booleans
      m.register_type %r(^tinyint\(1\))i, Type::Boolean.new
    end
  end
end

.extract_precision(sql_type) (private)

[ GitHub ]

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

def extract_precision(sql_type)
  if /\A(?:date)?time(?:stamp)?\b/.match?(sql_type)
    super || 0
  else
    super
  end
end

.initialize_type_map(m) (private)

[ GitHub ]

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

def initialize_type_map(m)
  super

  m.register_type %r(tinytext)i,   Type::Text.new(limit: 2**8 - 1)
  m.register_type %r(tinyblob)i,   Type::Binary.new(limit: 2**8 - 1)
  m.register_type %r(text)i,       Type::Text.new(limit: 2**16 - 1)
  m.register_type %r(blob)i,       Type::Binary.new(limit: 2**16 - 1)
  m.register_type %r(mediumtext)i, Type::Text.new(limit: 2**24 - 1)
  m.register_type %r(mediumblob)i, Type::Binary.new(limit: 2**24 - 1)
  m.register_type %r(longtext)i,   Type::Text.new(limit: 2**32 - 1)
  m.register_type %r(longblob)i,   Type::Binary.new(limit: 2**32 - 1)
  m.register_type %r(^float)i,     Type::Float.new(limit: 24)
  m.register_type %r(^double)i,    Type::Float.new(limit: 53)

  register_integer_type m, %r(^bigint)i,    limit: 8
  register_integer_type m, %r(^int)i,       limit: 4
  register_integer_type m, %r(^mediumint)i, limit: 3
  register_integer_type m, %r(^smallint)i,  limit: 2
  register_integer_type m, %r(^tinyint)i,   limit: 1

  m.alias_type %r(year)i, "integer"
  m.alias_type %r(bit)i,  "binary"
end

.register_integer_type(mapping, key, **options) (private)

[ GitHub ]

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

def register_integer_type(mapping, key, **options)
  mapping.register_type(key) do |sql_type|
    if /\bunsigned\b/.match?(sql_type)
      Type::UnsignedInteger.new(**options)
    else
      Type::Integer.new(**options)
    end
  end
end

Instance Attribute Details

#emulate_booleans (rw)

[ GitHub ]

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

class_attribute :emulate_booleans, default: true

#emulate_booleans?Boolean (rw)

[ GitHub ]

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

class_attribute :emulate_booleans, default: true

#mariadb?Boolean (readonly)

This method is for internal use only.
[ GitHub ]

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

def mariadb? # :nodoc:
  /mariadb/i.match?(full_version)
end

#strict_mode?Boolean (readonly)

[ GitHub ]

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

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

#supports_advisory_locks?Boolean (readonly)

[ GitHub ]

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

def supports_advisory_locks?
  true
end

#supports_bulk_alter?Boolean (readonly)

[ GitHub ]

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

def supports_bulk_alter?
  true
end

#supports_check_constraints?Boolean (readonly)

[ GitHub ]

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

def supports_check_constraints?
  if mariadb?
    database_version >= "10.3.10" || (database_version < "10.3" && database_version >= "10.2.22")
  else
    database_version >= "8.0.16"
  end
end

#supports_common_table_expressions?Boolean (readonly)

[ GitHub ]

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

def supports_common_table_expressions?
  if mariadb?
    database_version >= "10.2.1"
  else
    database_version >= "8.0.1"
  end
end

#supports_datetime_with_precision?Boolean (readonly)

[ GitHub ]

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

def supports_datetime_with_precision?
  true
end

#supports_explain?Boolean (readonly)

[ GitHub ]

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

def supports_explain?
  true
end

#supports_expression_index?Boolean (readonly)

[ GitHub ]

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

def supports_expression_index?
  !mariadb? && database_version >= "8.0.13"
end

#supports_foreign_keys?Boolean (readonly)

[ GitHub ]

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

def supports_foreign_keys?
  true
end

#supports_index_sort_order?Boolean (readonly)

[ GitHub ]

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

def supports_index_sort_order?
  mariadb? ? database_version >= "10.8.1" : database_version >= "8.0.1"
end

#supports_indexes_in_create?Boolean (readonly)

[ GitHub ]

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

def supports_indexes_in_create?
  true
end

#supports_insert_on_duplicate_skip?Boolean (readonly)

[ GitHub ]

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

def supports_insert_on_duplicate_skip?
  true
end

#supports_insert_on_duplicate_update?Boolean (readonly)

[ GitHub ]

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

def supports_insert_on_duplicate_update?
  true
end

#supports_insert_raw_alias_syntax?Boolean (readonly, private)

[ GitHub ]

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

def supports_insert_raw_alias_syntax?
  !mariadb? && database_version >= "8.0.19"
end

#supports_insert_returning?Boolean (readonly)

[ GitHub ]

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

def supports_insert_returning?
  mariadb? && database_version >= "10.5.0"
end

#supports_optimizer_hints?Boolean (readonly)

[ GitHub ]

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

def supports_optimizer_hints?
  !mariadb? && database_version >= "5.7.7"
end

#supports_rename_column?Boolean (readonly, private)

[ GitHub ]

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

def supports_rename_column?
  if mariadb?
    database_version >= "10.5.2"
  else
    database_version >= "8.0.3"
  end
end

#supports_rename_index?Boolean (readonly, private)

[ GitHub ]

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

def supports_rename_index?
  if mariadb?
    database_version >= "10.5.2"
  else
    database_version >= "5.7.6"
  end
end

#supports_restart_db_transaction?Boolean (readonly)

[ GitHub ]

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

def supports_restart_db_transaction?
  true
end

#supports_transaction_isolation?Boolean (readonly)

[ GitHub ]

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

def supports_transaction_isolation?
  true
end

#supports_views?Boolean (readonly)

[ GitHub ]

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

def supports_views?
  true
end

#supports_virtual_columns?Boolean (readonly)

[ GitHub ]

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

def supports_virtual_columns?
  mariadb? || database_version >= "5.7.5"
end

Instance Method Details

#add_index(table_name, column_name, **options)

This method is for internal use only.
[ GitHub ]

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

def add_index(table_name, column_name, **options) # :nodoc:
  create_index = build_create_index_definition(table_name, column_name, **options)
  return unless create_index

  execute schema_creation.accept(create_index)
end

#add_index_for_alter(table_name, column_name, **options) (private)

[ GitHub ]

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

def add_index_for_alter(table_name, column_name, **options)
  index, algorithm, _ = add_index_options(table_name, column_name, **options)
  algorithm = ", #{algorithm}" if algorithm

  "ADD #{schema_creation.accept(index)}#{algorithm}"
end

#add_sql_comment!(sql, comment)

This method is for internal use only.
[ GitHub ]

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

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

#arel_visitor (private)

[ GitHub ]

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

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

#begin_db_transaction

This method is for internal use only.
[ GitHub ]

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

def begin_db_transaction # :nodoc:
  internal_execute("BEGIN", "TRANSACTION", allow_retry: true, materialize_transactions: false)
end

#begin_isolated_db_transaction(isolation)

This method is for internal use only.
[ GitHub ]

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

def begin_isolated_db_transaction(isolation) # :nodoc:
  # From MySQL manual: The [SET TRANSACTION] statement applies only to the next single transaction performed within the session.
  # So we don't need to implement #reset_isolation_level
  execute_batch(
    ["SET TRANSACTION ISOLATION LEVEL #{transaction_isolation_levels.fetch(isolation)}", "BEGIN"],
    "TRANSACTION",
    allow_retry: true,
    materialize_transactions: false,
  )
end

#build_change_column_default_definition(table_name, column_name, default_or_changes)

This method is for internal use only.
[ GitHub ]

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

def build_change_column_default_definition(table_name, column_name, default_or_changes) # :nodoc:
  column = column_for(table_name, column_name)
  return unless column

  default = extract_new_default_value(default_or_changes)
  ChangeColumnDefaultDefinition.new(column, default)
end

#build_change_column_definition(table_name, column_name, type, **options)

This method is for internal use only.

Builds a ChangeColumnDefinition object.

This definition object contains information about the column change that would occur if the same arguments were passed to #change_column. See #change_column for information about passing a table_name, column_name, type and other options that can be passed.

[ GitHub ]

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

def build_change_column_definition(table_name, column_name, type, **options) # :nodoc:
  column = column_for(table_name, column_name)
  type ||= column.sql_type

  unless options.key?(:default)
    options[:default] = column.default
  end

  unless options.key?(:null)
    options[:null] = column.null
  end

  unless options.key?(:comment)
    options[:comment] = column.comment
  end

  if options[:collation] == :no_collation
    options.delete(:collation)
  else
    options[:collation] ||= column.collation if text_type?(type)
  end

  unless options.key?(:auto_increment)
    options[:auto_increment] = column.auto_increment?
  end

  td = create_table_definition(table_name)
  cd = td.new_column_definition(column.name, type, **options)
  ChangeColumnDefinition.new(cd, column.name)
end

#build_create_index_definition(table_name, column_name, **options)

This method is for internal use only.
[ GitHub ]

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

def build_create_index_definition(table_name, column_name, **options) # :nodoc:
  index, algorithm, if_not_exists = add_index_options(table_name, column_name, **options)

  return if if_not_exists && index_exists?(table_name, column_name, name: index.name)

  CreateIndexDefinition.new(index, algorithm)
end

#build_insert_sql(insert)

This method is for internal use only.
[ GitHub ]

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

def build_insert_sql(insert) # :nodoc:
  no_op_column = quote_column_name(insert.keys.first) if insert.keys.first

  # MySQL 8.0.19 replaces `VALUES(<expression>)` clauses with row and column alias names, see https://dev.mysql.com/worklog/task/?id=6312 .
  # then MySQL 8.0.20 deprecates the `VALUES(<expression>)` see https://dev.mysql.com/worklog/task/?id=13325 .
  if supports_insert_raw_alias_syntax?
    values_alias = quote_table_name("#{insert.model.table_name.parameterize}_values")
    sql = +"INSERT #{insert.into} #{insert.values_list} AS #{values_alias}"

    if insert.skip_duplicates?
      if no_op_column
        sql << " ON DUPLICATE KEY UPDATE #{no_op_column}=#{values_alias}.#{no_op_column}"
      end
    elsif insert.update_duplicates?
      if insert.raw_update_sql?
        sql = +"INSERT #{insert.into} #{insert.values_list} ON DUPLICATE KEY UPDATE #{insert.raw_update_sql}"
      else
        sql << " ON DUPLICATE KEY UPDATE "
        sql << insert.touch_model_timestamps_unless { |column| "#{insert.model.quoted_table_name}.#{column}<=>#{values_alias}.#{column}" }
        sql << insert.updatable_columns.map { |column| "#{column}=#{values_alias}.#{column}" }.join(",")
      end
    end
  else
    sql = +"INSERT #{insert.into} #{insert.values_list}"

    if insert.skip_duplicates?
      if no_op_column
        sql << " ON DUPLICATE KEY UPDATE #{no_op_column}=#{no_op_column}"
      end
    elsif insert.update_duplicates?
      sql << " ON DUPLICATE KEY UPDATE "
      if insert.raw_update_sql?
        sql << insert.raw_update_sql
      else
        sql << insert.touch_model_timestamps_unless { |column| "#{column}<=>VALUES(#{column})" }
        sql << insert.updatable_columns.map { |column| "#{column}=VALUES(#{column})" }.join(",")
      end
    end
  end

  sql << " RETURNING #{insert.returning}" if insert.returning
  sql
end

#build_statement_pool (private)

[ GitHub ]

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

def build_statement_pool
  StatementPool.new(self.class.type_cast_config_to_integer(@config[:statement_limit]))
end

#can_perform_case_insensitive_comparison_for?(column) ⇒ Boolean (private)

[ GitHub ]

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

def can_perform_case_insensitive_comparison_for?(column)
  column.case_sensitive?
end

#case_sensitive_comparison(attribute, value)

This method is for internal use only.
[ GitHub ]

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

def case_sensitive_comparison(attribute, value) # :nodoc:
  column = column_for_attribute(attribute)

  if column.collation && !column.case_sensitive?
    attribute.eq(Arel::Nodes::Bin.new(value))
  else
    super
  end
end

#change_column(table_name, column_name, type, **options)

This method is for internal use only.
[ GitHub ]

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

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

#change_column_comment(table_name, column_name, comment_or_changes)

This method is for internal use only.
[ GitHub ]

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

def change_column_comment(table_name, column_name, comment_or_changes) # :nodoc:
  comment = extract_new_comment_value(comment_or_changes)
  change_column table_name, column_name, nil, comment: comment
end

#change_column_default(table_name, column_name, default_or_changes)

This method is for internal use only.
[ GitHub ]

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

def change_column_default(table_name, column_name, default_or_changes) # :nodoc:
  execute "ALTER TABLE #{quote_table_name(table_name)} #{change_column_default_for_alter(table_name, column_name, default_or_changes)}"
end

#change_column_for_alter(table_name, column_name, type, **options) (private)

[ GitHub ]

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

def change_column_for_alter(table_name, column_name, type, **options)
  cd = build_change_column_definition(table_name, column_name, type, **options)
  schema_creation.accept(cd)
end

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

This method is for internal use only.
[ GitHub ]

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

def change_column_null(table_name, column_name, null, default = nil) # :nodoc:
  validate_change_column_null_argument!(null)

  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, nil, null: null
end

#change_table_comment(table_name, comment_or_changes)

This method is for internal use only.
[ GitHub ]

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

def change_table_comment(table_name, comment_or_changes) # :nodoc:
  comment = extract_new_comment_value(comment_or_changes)
  comment = "" if comment.nil?
  execute("ALTER TABLE #{quote_table_name(table_name)} COMMENT #{quote(comment)}")
end

#charset

Returns the database character set.

[ GitHub ]

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

def charset
  show_variable "character_set_database"
end

#check_constraints(table_name)

[ GitHub ]

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

def check_constraints(table_name)
  if supports_check_constraints?
    scope = quoted_scope(table_name)

    sql = <<~SQL
      SELECT cc.constraint_name AS 'name',
            cc.check_clause AS 'expression'
      FROM information_schema.check_constraints cc
      JOIN information_schema.table_constraints tc
      USING (constraint_schema, constraint_name)
      WHERE tc.table_schema = #{scope[:schema]}
        AND tc.table_name = #{scope[:name]}
        AND cc.constraint_schema = #{scope[:schema]}
    SQL
    sql += " AND cc.table_name = #{scope[:name]}" if mariadb?

    chk_info = internal_exec_query(sql, "SCHEMA")

    chk_info.map do |row|
      options = {
        name: row["name"]
      }
      expression = row["expression"]
      expression = expression[1..-2] if expression.start_with?("(") && expression.end_with?(")")
      expression = strip_whitespace_characters(expression)

      unless mariadb?
        # MySQL returns check constraints expression in an already escaped form.
        # This leads to duplicate escaping later (e.g. when the expression is used in the SchemaDumper).
        expression = expression.gsub("\\'", "'")
      end

      CheckConstraintDefinition.new(table_name, expression, options)
    end
  else
    raise NotImplementedError
  end
end

#check_version

This method is for internal use only.
[ GitHub ]

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

def check_version # :nodoc:
  if database_version < "5.6.4"
    raise DatabaseVersionError, "Your version of MySQL (#{database_version}) is too old. Active Record supports MySQL >= 5.6.4."
  end
end

#collation

Returns the database collation strategy.

[ GitHub ]

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

def collation
  show_variable "collation_database"
end

#column_definitions(table_name) (private)

This method is for internal use only.
[ GitHub ]

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

def column_definitions(table_name) # :nodoc:
  internal_exec_query("SHOW FULL FIELDS FROM #{quote_table_name(table_name)}", "SCHEMA")
end

#columns_for_distinct(columns, orders)

This method is for internal use only.

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/en/group-by-handling.html

[ GitHub ]

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

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

  (order_columns << super).join(", ")
end

#commit_db_transaction

This method is for internal use only.
[ GitHub ]

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

def commit_db_transaction # :nodoc:
  internal_execute("COMMIT", "TRANSACTION", allow_retry: false, materialize_transactions: true)
end

#configure_connection (private)

[ GitHub ]

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

def configure_connection
  super
  variables = @config.fetch(:variables, {}).stringify_keys

  # Increase timeout so the server doesn't disconnect us.
  wait_timeout = self.class.type_cast_config_to_integer(@config[:wait_timeout])
  wait_timeout = 2147483 unless wait_timeout.is_a?(Integer)
  variables["wait_timeout"] = wait_timeout

  defaults = [":default", :default].to_set

  # Make MySQL reject illegal values rather than truncating or blanking them, see
  # https://dev.mysql.com/doc/refman/en/sql-mode.html#sqlmode_strict_all_tables
  # If the user has provided another value for sql_mode, don't replace it.
  if sql_mode = variables.delete("sql_mode")
    sql_mode = quote(sql_mode)
  elsif !defaults.include?(strict_mode?)
    if strict_mode?
      sql_mode = "CONCAT(@@sql_mode, ',STRICT_ALL_TABLES')"
    else
      sql_mode = "REPLACE(@@sql_mode, 'STRICT_TRANS_TABLES', '')"
      sql_mode = "REPLACE(#{sql_mode}, 'STRICT_ALL_TABLES', '')"
      sql_mode = "REPLACE(#{sql_mode}, 'TRADITIONAL', '')"
    end
    sql_mode = "CONCAT(#{sql_mode}, ',NO_AUTO_VALUE_ON_ZERO')"
  end
  sql_mode_assignment = "@@SESSION.sql_mode = #{sql_mode}, " if sql_mode

  # NAMES does not have an equals sign, see
  # https://dev.mysql.com/doc/refman/en/set-names.html
  # (trailing comma because variable_assignments will always have content)
  if @config[:encoding]
    encoding = +"NAMES #{@config[:encoding]}"
    encoding << " COLLATE #{@config[:collation]}" if @config[:collation]
    encoding << ", "
  end

  # Gather up all of the SET variables...
  variable_assignments = variables.filter_map do |k, v|
    if defaults.include?(v)
      "@@SESSION.#{k} = DEFAULT" # Sets the value to the global or compile default
    elsif !v.nil?
      "@@SESSION.#{k} = #{quote(v)}"
    end
  end.join(", ")

  # ...and send them all in one query
  raw_execute("SET #{encoding} #{sql_mode_assignment} #{variable_assignments}", "SCHEMA")
end

#create_database(name, options = {})

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

Example:

create_database 'charset_test', charset: 'latin1', collation: 'latin1_bin'
create_database 'matt_development'
create_database 'matt_development', charset: :big5
[ GitHub ]

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

def create_database(name, options = {})
  if options[:collation]
    execute "CREATE DATABASE #{quote_table_name(name)} DEFAULT COLLATE #{quote_table_name(options[:collation])}"
  elsif options[:charset]
    execute "CREATE DATABASE #{quote_table_name(name)} DEFAULT CHARACTER SET #{quote_table_name(options[:charset])}"
  elsif row_format_dynamic_by_default?
    execute "CREATE DATABASE #{quote_table_name(name)} DEFAULT CHARACTER SET `utf8mb4`"
  else
    raise "Configure a supported :charset and ensure innodb_large_prefix is enabled to support indexes on varchar(255) string columns."
  end
end

#create_table_info(table_name) (private)

This method is for internal use only.
[ GitHub ]

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

def create_table_info(table_name) # :nodoc:
  internal_exec_query("SHOW CREATE TABLE #{quote_table_name(table_name)}", "SCHEMA").first["Create Table"]
end

#current_database

[ GitHub ]

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

def current_database
  query_value("SELECT database()", "SCHEMA")
end

#default_index_type?(index) ⇒ Boolean

This method is for internal use only.
[ GitHub ]

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

def default_index_type?(index) # :nodoc:
  index.using == :btree || super
end

#disable_referential_integrity

This method is for internal use only.

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

[ GitHub ]

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

def disable_referential_integrity # :nodoc:
  old = query_value("SELECT @@FOREIGN_KEY_CHECKS")

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

#drop_database(name)

This method is for internal use only.

Drops a MySQL database.

Example:

drop_database('sebastian_development')
[ GitHub ]

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

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

#drop_table(*table_names, **options)

Drops a table or tables 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 except if you provide more than one table which is not supported.

[ GitHub ]

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

def drop_table(*table_names, **options)
  table_names.each { |table_name| schema_cache.clear_data_source_cache!(table_name.to_s) }
  execute "DROP#{' TEMPORARY' if options[:temporary]} TABLE#{' IF EXISTS' if options[:if_exists]} #{table_names.map { |table_name| quote_table_name(table_name) }.join(', ')}#{' CASCADE' if options[:force] == :cascade}"
end

#empty_insert_statement_value(primary_key = nil)

This method is for internal use only.
[ GitHub ]

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

def empty_insert_statement_value(primary_key = nil) # :nodoc:
  "VALUES ()"
end

#error_number(exception)

This method is for internal use only.

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

Raises:

  • (NotImplementedError)
[ GitHub ]

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

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

#exec_restart_db_transaction

This method is for internal use only.
[ GitHub ]

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

def exec_restart_db_transaction # :nodoc:
  internal_execute("ROLLBACK AND CHAIN", "TRANSACTION", allow_retry: false, materialize_transactions: true)
end

#exec_rollback_db_transaction

This method is for internal use only.
[ GitHub ]

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

def exec_rollback_db_transaction # :nodoc:
  internal_execute("ROLLBACK", "TRANSACTION", allow_retry: false, materialize_transactions: true)
end

#extended_type_map_key (private)

[ GitHub ]

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

def extended_type_map_key
  if @default_timezone
    { default_timezone: @default_timezone, emulate_booleans: emulate_booleans }
  elsif emulate_booleans
    EMULATE_BOOLEANS_TRUE
  end
end

#foreign_keys(table_name)

Raises:

  • (ArgumentError)
[ GitHub ]

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

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

  scope = quoted_scope(table_name)

  # MySQL returns 1 row for each column of composite foreign keys.
  fk_info = internal_exec_query(<<~SQL, "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',
           fk.ordinal_position AS 'position',
           rc.update_rule AS 'on_update',
           rc.delete_rule AS 'on_delete'
    FROM information_schema.referential_constraints rc
    JOIN information_schema.key_column_usage fk
    USING (constraint_schema, constraint_name)
    WHERE fk.referenced_column_name IS NOT NULL
      AND fk.table_schema = #{scope[:schema]}
      AND fk.table_name = #{scope[:name]}
      AND rc.constraint_schema = #{scope[:schema]}
      AND rc.table_name = #{scope[:name]}
  SQL

  grouped_fk = fk_info.group_by { |row| row["name"] }.values.each { |group| group.sort_by! { |row| row["position"] } }
  grouped_fk.map do |group|
    row = group.first
    options = {
      name: row["name"],
      on_update: extract_foreign_key_action(row["on_update"]),
      on_delete: extract_foreign_key_action(row["on_delete"])
    }

    if group.one?
      options[:column] = unquote_identifier(row["column"])
      options[:primary_key] = row["primary_key"]
    else
      options[:column] = group.map { |row| unquote_identifier(row["column"]) }
      options[:primary_key] = group.map { |row| row["primary_key"] }
    end

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

#get_advisory_lock(lock_name, timeout = 0)

This method is for internal use only.
[ GitHub ]

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

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

#get_database_version

This method is for internal use only.
[ GitHub ]

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

def get_database_version # :nodoc:
  full_version_string = get_full_version
  version_string = version_string(full_version_string)
  Version.new(version_string, full_version_string)
end

#handle_warnings(sql) (private)

[ GitHub ]

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

def handle_warnings(sql)
  return if ActiveRecord.db_warnings_action.nil? || @raw_connection.warning_count == 0

  @affected_rows_before_warnings = @raw_connection.affected_rows
  warning_count = @raw_connection.warning_count
  result = @raw_connection.query("SHOW WARNINGS")
  result = [
    ["Warning", nil, "Query had warning_count=#{warning_count} but ‘SHOW WARNINGS’ did not return the warnings. Check MySQL logs or database configuration."],
  ] if result.count == 0
  result.each do |level, code, message|
    warning = SQLWarning.new(message, code, level, sql, @pool)
    next if warning_ignored?(warning)

    ActiveRecord.db_warnings_action.call(warning)
  end
end

#index_algorithms

[ GitHub ]

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

def index_algorithms
  {
    default: "ALGORITHM = DEFAULT",
    copy:    "ALGORITHM = COPY",
    inplace: "ALGORITHM = INPLACE",
    instant: "ALGORITHM = INSTANT",
  }
end

#mismatched_foreign_key(message, sql:, binds:, connection_pool:) (private)

[ GitHub ]

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

def mismatched_foreign_key(message, sql:, binds:, connection_pool:)
  options = {
    message: message,
    sql: sql,
    binds: binds,
    connection_pool: connection_pool
  }

  if sql
    options.update mismatched_foreign_key_details(message: message, sql: sql)
  else
    options[:query_parser] = ->(sql) { mismatched_foreign_key_details(message: message, sql: sql) }
  end

  MismatchedForeignKey.new(**options)
end

#mismatched_foreign_key_details(message:, sql:) (private)

[ GitHub ]

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

def mismatched_foreign_key_details(message:, sql:)
  foreign_key_pat =
    /Referencing column '(\w+)' and referenced/i =~ message ? $1 : '\w+'

  match = %r/
    (?:CREATE|ALTER)\sTABLE\s*(?:`?\w`?\.)?`?(?<table>\w)`?.?
    FOREIGN\s+KEY\s*\(`?(?<foreign_key>#{foreign_key_pat})`?\)\s*
    REFERENCES\s*(`?(?<target_table>\w)`?)\s*\(`?(?<primary_key>\w)`?\)
  /xmi.match(sql)

  options = {}

  if match
    options[:table] = match[:table]
    options[:foreign_key] = match[:foreign_key]
    options[:target_table] = match[:target_table]
    options[:primary_key] = match[:primary_key]
    options[:primary_key_column] = column_for(match[:target_table], match[:primary_key])
  end

  options
end

#native_database_types

[ GitHub ]

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

def native_database_types
  NATIVE_DATABASE_TYPES
end

#primary_keys(table_name)

This method is for internal use only.

Raises:

  • (ArgumentError)
[ GitHub ]

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

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

  scope = quoted_scope(table_name)

  query_values(<<~SQL, "SCHEMA")
    SELECT column_name
    FROM information_schema.statistics
    WHERE index_name = 'PRIMARY'
      AND table_schema = #{scope[:schema]}
      AND table_name = #{scope[:name]}
    ORDER BY seq_in_index
  SQL
end

#quote_string(string)

Quotes strings for use in SQL input.

[ GitHub ]

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

def quote_string(string)
  with_raw_connection(allow_retry: true, materialize_transactions: false) do |connection|
    connection.escape(string)
  end
end

#recreate_database(name, options = {})

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

[ GitHub ]

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

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

#release_advisory_lock(lock_name)

This method is for internal use only.
[ GitHub ]

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

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

#remove_index_for_alter(table_name, column_name = nil, **options) (private)

[ GitHub ]

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

def remove_index_for_alter(table_name, column_name = nil, **options)
  index_name = index_name_for_remove(table_name, column_name, options)
  "DROP INDEX #{quote_column_name(index_name)}"
end

#rename_column(table_name, column_name, new_column_name)

This method is for internal use only.
[ GitHub ]

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

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

#rename_column_for_alter(table_name, column_name, new_column_name) (private)

[ GitHub ]

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

def rename_column_for_alter(table_name, column_name, new_column_name)
  return rename_column_sql(table_name, column_name, new_column_name) if supports_rename_column?

  column  = column_for(table_name, column_name)
  options = {
    default: column.default,
    null: column.null,
    auto_increment: column.auto_increment?,
    comment: column.comment
  }

  current_type = internal_exec_query("SHOW COLUMNS FROM #{quote_table_name(table_name)} LIKE #{quote(column_name)}", "SCHEMA").first["Type"]
  td = create_table_definition(table_name)
  cd = td.new_column_definition(new_column_name, current_type, **options)
  schema_creation.accept(ChangeColumnDefinition.new(cd, column.name))
end

#rename_index(table_name, old_name, new_name)

[ GitHub ]

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

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, **options)

Renames a table.

Example:

rename_table('octopuses', 'octopi')
[ GitHub ]

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

def rename_table(table_name, new_name, **options)
  validate_table_length!(new_name) unless options[:_uses_legacy_table_name]
  schema_cache.clear_data_source_cache!(table_name.to_s)
  schema_cache.clear_data_source_cache!(new_name.to_s)
  execute "RENAME TABLE #{quote_table_name(table_name)} TO #{quote_table_name(new_name)}"
  rename_table_indexes(table_name, new_name, **options)
end

#show_variable(name)

SHOW VARIABLES LIKE ‘name’

[ GitHub ]

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

def show_variable(name)
  query_value("SELECT @@#{name}", "SCHEMA", materialize_transactions: false, allow_retry: true)
rescue ActiveRecord::StatementInvalid
  nil
end

#strip_whitespace_characters(expression) (private)

[ GitHub ]

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

def strip_whitespace_characters(expression)
  expression = expression.gsub(/\\n|\\\\/, "")
  expression = expression.gsub(/\s{2,}/, " ")
  expression
end

#table_comment(table_name)

This method is for internal use only.
[ GitHub ]

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

def table_comment(table_name) # :nodoc:
  scope = quoted_scope(table_name)

  query_value(<<~SQL, "SCHEMA").presence
    SELECT table_comment
    FROM information_schema.tables
    WHERE table_schema = #{scope[:schema]}
      AND table_name = #{scope[:name]}
  SQL
end

#table_options(table_name)

This method is for internal use only.
[ GitHub ]

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

def table_options(table_name) # :nodoc:
  create_table_info = create_table_info(table_name)

  # strip create_definitions and partition_options
  # Be aware that `create_table_info` might not include any table options due to `NO_TABLE_OPTIONS` sql mode.
  raw_table_options = create_table_info.sub(/\A.*\n\) ?/m, "").sub(/\n\/\*!.*\*\/\n\z/m, "").strip

  return if raw_table_options.empty?

  table_options = {}

  if / DEFAULT CHARSET=(?<charset>\w+)(?: COLLATE=(?<collation>\w+))?/ =~ raw_table_options
    raw_table_options = $` + $' # before part + after part
    table_options[:charset] = charset
    table_options[:collation] = collation if collation
  end

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

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

  table_options[:options] = raw_table_options unless raw_table_options == "ENGINE=InnoDB"
  table_options
end

#translate_exception(exception, message:, sql:, binds:) (private)

[ GitHub ]

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

def translate_exception(exception, message:, sql:, binds:)
  case error_number(exception)
  when nil
    if exception.message.match?(/MySQL client is not connected/i)
      ConnectionNotEstablished.new(exception, connection_pool: @pool)
    else
      super
    end
  when ER_CONNECTION_KILLED, ER_SERVER_SHUTDOWN, CR_SERVER_GONE_ERROR, CR_SERVER_LOST, ER_CLIENT_INTERACTION_TIMEOUT
    ConnectionFailed.new(message, sql: sql, binds: binds, connection_pool: @pool)
  when ER_DB_CREATE_EXISTS
    DatabaseAlreadyExists.new(message, sql: sql, binds: binds, connection_pool: @pool)
  when ER_DUP_ENTRY
    RecordNotUnique.new(message, sql: sql, binds: binds, connection_pool: @pool)
  when ER_NO_REFERENCED_ROW, ER_ROW_IS_REFERENCED, ER_ROW_IS_REFERENCED_2, ER_NO_REFERENCED_ROW_2
    InvalidForeignKey.new(message, sql: sql, binds: binds, connection_pool: @pool)
  when ER_CANNOT_ADD_FOREIGN, ER_FK_INCOMPATIBLE_COLUMNS
    mismatched_foreign_key(message, sql: sql, binds: binds, connection_pool: @pool)
  when ER_CANNOT_CREATE_TABLE
    if message.include?("errno: 150")
      mismatched_foreign_key(message, sql: sql, binds: binds, connection_pool: @pool)
    else
      super
    end
  when ER_DATA_TOO_LONG
    ValueTooLong.new(message, sql: sql, binds: binds, connection_pool: @pool)
  when ER_OUT_OF_RANGE
    RangeError.new(message, sql: sql, binds: binds, connection_pool: @pool)
  when ER_NOT_NULL_VIOLATION, ER_DO_NOT_HAVE_DEFAULT
    NotNullViolation.new(message, sql: sql, binds: binds, connection_pool: @pool)
  when ER_LOCK_DEADLOCK
    Deadlocked.new(message, sql: sql, binds: binds, connection_pool: @pool)
  when ER_LOCK_WAIT_TIMEOUT
    LockWaitTimeout.new(message, sql: sql, binds: binds, connection_pool: @pool)
  when ER_QUERY_TIMEOUT, ER_FILSORT_ABORT
    StatementTimeout.new(message, sql: sql, binds: binds, connection_pool: @pool)
  when ER_QUERY_INTERRUPTED
    QueryCanceled.new(message, sql: sql, binds: binds, connection_pool: @pool)
  else
    super
  end
end

#version_string(full_version_string) (private)

[ GitHub ]

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

def version_string(full_version_string)
  if full_version_string && matches = full_version_string.match(/^(?:5\.5\.5-)?(\d\.\d\.\d+)/)
    matches[1]
  else
    raise DatabaseVersionError, "Unable to parse MySQL version from #{full_version_string.inspect}"
  end
end

#warning_ignored?(warning) ⇒ Boolean (private)

[ GitHub ]

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

def warning_ignored?(warning)
  warning.level == "Note" || super
end