Class: ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter
- Inherits:
-
AbstractAdapter
- Object
- AbstractAdapter
- ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter
- Includes:
- MySQL::Quoting, MySQL::SchemaStatements
- Defined in:
- lib/active_record/connection_adapters/abstract_mysql_adapter.rb
Direct Known Subclasses
Defined Under Namespace
Classes: MysqlString, StatementPool
Constant Summary collapse
- NATIVE_DATABASE_TYPES =
{ primary_key: "bigint auto_increment PRIMARY KEY", string: { name: "varchar", limit: 255 }, text: { name: "text" }, integer: { name: "int", limit: 4 }, float: { name: "float", limit: 24 }, decimal: { name: "decimal" }, datetime: { name: "datetime" }, timestamp: { name: "timestamp" }, time: { name: "time" }, date: { name: "date" }, binary: { name: "blob" }, blob: { name: "blob" }, boolean: { name: "tinyint", limit: 1 }, json: { name: "json" }, }
Constants inherited from AbstractAdapter
ActiveRecord::ConnectionAdapters::AbstractAdapter::ADAPTER_NAME, ActiveRecord::ConnectionAdapters::AbstractAdapter::COMMENT_REGEX, ActiveRecord::ConnectionAdapters::AbstractAdapter::SIMPLE_INT
Instance Attribute Summary
Attributes inherited from AbstractAdapter
#lock, #logger, #owner, #pool, #visitor
Attributes included from QueryCache
#query_cache, #query_cache_enabled
Attributes included from DatabaseStatements
Instance Method Summary collapse
-
#add_index(table_name, column_name, options = {}) ⇒ Object
:nodoc:.
-
#add_sql_comment!(sql, comment) ⇒ Object
:nodoc:.
- #begin_db_transaction ⇒ Object
- #begin_isolated_db_transaction(isolation) ⇒ Object
-
#build_insert_sql(insert) ⇒ Object
:nodoc:.
-
#case_sensitive_comparison(attribute, value) ⇒ Object
:nodoc:.
-
#change_column(table_name, column_name, type, options = {}) ⇒ Object
:nodoc:.
-
#change_column_comment(table_name, column_name, comment_or_changes) ⇒ Object
:nodoc:.
-
#change_column_default(table_name, column_name, default_or_changes) ⇒ Object
:nodoc:.
-
#change_column_null(table_name, column_name, null, default = nil) ⇒ Object
:nodoc:.
-
#change_table_comment(table_name, comment_or_changes) ⇒ Object
:nodoc:.
-
#charset ⇒ Object
Returns the database character set.
-
#check_version ⇒ Object
:nodoc:.
-
#clear_cache! ⇒ Object
CONNECTION MANAGEMENT ====================================.
-
#collation ⇒ Object
Returns the database collation strategy.
-
#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.
-
#commit_db_transaction ⇒ Object
:nodoc:.
-
#create_database(name, options = {}) ⇒ Object
Create a new MySQL database with optional
:charset
and:collation
. - #current_database ⇒ Object
-
#default_index_type?(index) ⇒ Boolean
:nodoc:.
-
#default_uniqueness_comparison(attribute, value, klass) ⇒ Object
:nodoc:.
-
#disable_referential_integrity ⇒ Object
REFERENTIAL INTEGRITY ====================================.
-
#drop_database(name) ⇒ Object
Drops a MySQL database.
-
#drop_table(table_name, options = {}) ⇒ Object
Drops a table from the database.
-
#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.
- #empty_insert_statement_value(primary_key = nil) ⇒ Object
-
#emulate_booleans ⇒ Object
:singleton-method: By default, the Mysql2Adapter will consider all columns of type
tinyint(1)
as boolean. -
#error_number(exception) ⇒ Object
Must return the MySQL error number from the exception, if the exception has an error number.
-
#exec_rollback_db_transaction ⇒ Object
:nodoc:.
-
#execute(sql, name = nil) ⇒ Object
Executes the SQL statement in the context of this connection.
-
#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.
-
#explain(arel, binds = []) ⇒ Object
– DATABASE STATEMENTS ====================================== ++.
- #foreign_keys(table_name) ⇒ Object
-
#get_advisory_lock(lock_name, timeout = 0) ⇒ Object
:nodoc:.
-
#get_database_version ⇒ Object
:nodoc:.
- #index_algorithms ⇒ Object
-
#initialize(connection, logger, connection_options, config) ⇒ AbstractMysqlAdapter
constructor
A new instance of AbstractMysqlAdapter.
-
#mariadb? ⇒ Boolean
:nodoc:.
- #native_database_types ⇒ Object
-
#primary_keys(table_name) ⇒ Object
:nodoc:.
-
#recreate_database(name, options = {}) ⇒ Object
Drops the database specified on the
name
attribute and creates it again using the providedoptions
. -
#release_advisory_lock(lock_name) ⇒ Object
:nodoc:.
-
#rename_column(table_name, column_name, new_column_name) ⇒ Object
:nodoc:.
- #rename_index(table_name, old_name, new_name) ⇒ Object
-
#rename_table(table_name, new_name) ⇒ Object
Renames a table.
-
#show_variable(name) ⇒ Object
SHOW VARIABLES LIKE ‘name’.
- #strict_mode? ⇒ Boolean
- #supports_advisory_locks? ⇒ Boolean
- #supports_bulk_alter? ⇒ Boolean
- #supports_common_table_expressions? ⇒ Boolean
- #supports_datetime_with_precision? ⇒ Boolean
- #supports_explain? ⇒ Boolean
- #supports_expression_index? ⇒ Boolean
- #supports_foreign_keys? ⇒ Boolean
- #supports_index_sort_order? ⇒ Boolean
- #supports_indexes_in_create? ⇒ Boolean
- #supports_insert_on_duplicate_skip? ⇒ Boolean
- #supports_insert_on_duplicate_update? ⇒ Boolean
-
#supports_optimizer_hints? ⇒ Boolean
See dev.mysql.com/doc/refman/8.0/en/optimizer-hints.html for more details.
- #supports_transaction_isolation? ⇒ Boolean
- #supports_views? ⇒ Boolean
- #supports_virtual_columns? ⇒ Boolean
-
#table_comment(table_name) ⇒ Object
:nodoc:.
-
#table_options(table_name) ⇒ Object
:nodoc:.
Methods included from MySQL::SchemaStatements
#create_schema_dumper, #create_table, #indexes, #internal_string_options_for_primary_key, #remove_column, #table_alias_length, #type_to_sql, #update_table_definition
Methods included from MySQL::Quoting
#column_name_matcher, #column_name_with_order_matcher, #quote_column_name, #quote_table_name, #quoted_binary, #quoted_date, #unquoted_false, #unquoted_true
Methods inherited from AbstractAdapter
#active?, #adapter_name, #advisory_locks_enabled?, build_read_query_regexp, #case_insensitive_comparison, #close, #column_name_for_operation, database_exists?, #database_version, #disable_extension, #discard!, #disconnect!, #enable_extension, #expire, #extensions, #lease, #migration_context, #migrations_paths, #prefetch_primary_key?, #prepared_statements, #prepared_statements_disabled_cache, #preventing_writes?, quoted_column_names, quoted_table_names, #raw_connection, #reconnect!, #replica?, #requires_reloading?, #reset!, #schema_cache, #schema_cache=, #schema_migration, #seconds_idle, #steal!, #supports_comments?, #supports_comments_in_create?, #supports_ddl_transactions?, #supports_extensions?, #supports_foreign_keys_in_create?, #supports_foreign_tables?, #supports_insert_conflict_target?, #supports_insert_returning?, #supports_json?, #supports_lazy_transactions?, #supports_materialized_views?, #supports_multi_insert?, #supports_partial_index?, #supports_partitioned_indexes?, #supports_savepoints?, #supports_validate_constraints?, type_cast_config_to_boolean, type_cast_config_to_integer, #unprepared_statement, #valid_type?, #verify!
Methods included from Savepoints
#create_savepoint, #current_savepoint_name, #exec_rollback_to_savepoint, #release_savepoint
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, #max_identifier_length, #sql_query_length, #table_alias_length, #table_name_length
Methods included from Quoting
#column_name_matcher, #column_name_with_order_matcher, #lookup_cast_type_from_column, #quote, #quote_column_name, #quote_default_expression, #quote_string, #quote_table_name, #quote_table_name_for_assignment, #quoted_binary, #quoted_date, #quoted_false, #quoted_time, #quoted_true, #sanitize_as_sql_comment, #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_insert_all, #exec_query, #exec_update, #insert, #insert_fixture, #insert_fixtures_set, #query, #query_value, #query_values, #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, #truncate, #truncate_tables, #update, #with_yaml_fallback, #write_query?
Methods included from SchemaStatements
#add_column, #add_foreign_key, #add_index_options, #add_reference, #add_timestamps, #assume_migrated_upto_version, #change_table, #column_exists?, #columns, #create_join_table, #create_schema_dumper, #create_table, #data_source_exists?, #data_sources, #drop_join_table, #dump_schema_information, #foreign_key_column_for, #foreign_key_exists?, #foreign_key_options, #index_exists?, #index_name, #index_name_exists?, #indexes, #internal_string_options_for_primary_key, #options_include_default?, #primary_key, #remove_column, #remove_columns, #remove_foreign_key, #remove_index, #remove_reference, #remove_timestamps, #table_alias_for, #table_exists?, #tables, #type_to_sql, #update_table_definition, #view_exists?, #views
Constructor Details
#initialize(connection, logger, connection_options, config) ⇒ AbstractMysqlAdapter
Returns a new instance of AbstractMysqlAdapter.
53 54 55 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 53 def initialize(connection, logger, , config) super(connection, logger, config) end |
Instance Method Details
#add_index(table_name, column_name, options = {}) ⇒ Object
:nodoc:
368 369 370 371 372 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 368 def add_index(table_name, column_name, = {}) #:nodoc: index_name, index_type, index_columns, _, index_algorithm, index_using, comment = (table_name, column_name, **) 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:
374 375 376 377 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 374 def add_sql_comment!(sql, comment) # :nodoc: sql << " COMMENT #{quote(comment)}" if comment.present? sql end |
#begin_db_transaction ⇒ Object
213 214 215 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 213 def begin_db_transaction execute "BEGIN" end |
#begin_isolated_db_transaction(isolation) ⇒ Object
217 218 219 220 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 217 def begin_isolated_db_transaction(isolation) execute "SET TRANSACTION ISOLATION LEVEL #{transaction_isolation_levels.fetch(isolation)}" begin_db_transaction end |
#build_insert_sql(insert) ⇒ Object
:nodoc:
512 513 514 515 516 517 518 519 520 521 522 523 524 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 512 def build_insert_sql(insert) # :nodoc: sql = +"INSERT #{insert.into} #{insert.values_list}" if insert.skip_duplicates? no_op_column = quote_column_name(insert.keys.first) sql << " ON DUPLICATE KEY UPDATE #{no_op_column}=#{no_op_column}" elsif insert.update_duplicates? sql << " ON DUPLICATE KEY UPDATE " sql << insert.updatable_columns.map { |column| "#{column}=VALUES(#{column})" }.join(",") end sql end |
#case_sensitive_comparison(attribute, value) ⇒ Object
:nodoc:
474 475 476 477 478 479 480 481 482 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 474 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 = {}) ⇒ Object
:nodoc:
359 360 361 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 359 def change_column(table_name, column_name, type, = {}) #:nodoc: execute("ALTER TABLE #{quote_table_name(table_name)} #{change_column_for_alter(table_name, column_name, type, )}") end |
#change_column_comment(table_name, column_name, comment_or_changes) ⇒ Object
:nodoc:
354 355 356 357 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 354 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) ⇒ Object
:nodoc:
341 342 343 344 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 341 def change_column_default(table_name, column_name, default_or_changes) #:nodoc: default = extract_new_default_value(default_or_changes) change_column table_name, column_name, nil, default: default end |
#change_column_null(table_name, column_name, null, default = nil) ⇒ Object
:nodoc:
346 347 348 349 350 351 352 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 346 def change_column_null(table_name, column_name, null, default = nil) #:nodoc: 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) ⇒ Object
:nodoc:
297 298 299 300 301 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 297 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 ⇒ Object
Returns the database character set.
277 278 279 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 277 def charset show_variable "character_set_database" end |
#check_version ⇒ Object
:nodoc:
526 527 528 529 530 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 526 def check_version # :nodoc: if database_version < "5.5.8" raise "Your version of MySQL (#{database_version}) is too old. Active Record supports MySQL >= 5.5.8." end end |
#clear_cache! ⇒ Object
CONNECTION MANAGEMENT ====================================
177 178 179 180 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 177 def clear_cache! # :nodoc: reload_type_map super end |
#collation ⇒ Object
Returns the database collation strategy.
282 283 284 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 282 def collation show_variable "collation_database" 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
493 494 495 496 497 498 499 500 501 502 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 493 def columns_for_distinct(columns, orders) # :nodoc: order_columns = orders.reject(&: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, "") }.reject(&:blank?).map.with_index { |column, i| "#{column} AS alias_#{i}" } (order_columns << super).join(", ") end |
#commit_db_transaction ⇒ Object
:nodoc:
222 223 224 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 222 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 utf8mb4.
Example:
create_database 'charset_test', charset: 'latin1', collation: 'latin1_bin'
create_database 'matt_development'
create_database 'matt_development', charset: :big5
252 253 254 255 256 257 258 259 260 261 262 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 252 def create_database(name, = {}) if [:collation] execute "CREATE DATABASE #{quote_table_name(name)} DEFAULT COLLATE #{quote_table_name([:collation])}" elsif [:charset] execute "CREATE DATABASE #{quote_table_name(name)} DEFAULT CHARACTER SET #{quote_table_name([: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 |
#current_database ⇒ Object
272 273 274 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 272 def current_database query_value("SELECT database()", "SCHEMA") end |
#default_index_type?(index) ⇒ Boolean
:nodoc:
508 509 510 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 508 def default_index_type?(index) # :nodoc: index.using == :btree || super end |
#default_uniqueness_comparison(attribute, value, klass) ⇒ Object
:nodoc:
459 460 461 462 463 464 465 466 467 468 469 470 471 472 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 459 def default_uniqueness_comparison(attribute, value, klass) # :nodoc: column = column_for_attribute(attribute) if column.collation && !column.case_sensitive? && !value.nil? ActiveSupport::Deprecation.warn(<<~MSG.squish) Uniqueness validator will no longer enforce case sensitive comparison in Rails 6.1. To continue case sensitive comparison on the :#{attribute.name} attribute in #{klass} model, pass `case_sensitive: true` option explicitly to the uniqueness validator. MSG attribute.eq(Arel::Nodes::Bin.new(value)) else super end end |
#disable_referential_integrity ⇒ Object
REFERENTIAL INTEGRITY ====================================
164 165 166 167 168 169 170 171 172 173 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 164 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}") end end |
#drop_database(name) ⇒ Object
Drops a MySQL database.
Example:
drop_database('sebastian_development')
268 269 270 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 268 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.
327 328 329 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 327 def drop_table(table_name, = {}) execute "DROP#{' TEMPORARY' if [:temporary]} TABLE#{' IF EXISTS' if [:if_exists]} #{quote_table_name(table_name)}#{' CASCADE' if [: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.
152 153 154 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 152 def each_hash(result) # :nodoc: raise NotImplementedError end |
#empty_insert_statement_value(primary_key = nil) ⇒ Object
230 231 232 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 230 def empty_insert_statement_value(primary_key = nil) "VALUES ()" end |
#emulate_booleans ⇒ Object
: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
27 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 27 class_attribute :emulate_booleans, default: true |
#error_number(exception) ⇒ Object
Must return the MySQL error number from the exception, if the exception has an error number.
158 159 160 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 158 def error_number(exception) # :nodoc: raise NotImplementedError end |
#exec_rollback_db_transaction ⇒ Object
:nodoc:
226 227 228 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 226 def exec_rollback_db_transaction #:nodoc: execute "ROLLBACK" end |
#execute(sql, name = nil) ⇒ Object
Executes the SQL statement in the context of this connection.
196 197 198 199 200 201 202 203 204 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 196 def execute(sql, name = nil) materialize_transactions log(sql, name) do ActiveSupport::Dependencies.interlock.permit_concurrent_loads do @connection.query(sql) end end 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.
209 210 211 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 209 def execute_and_free(sql, name = nil) # :nodoc: yield execute(sql, name) end |
#explain(arel, binds = []) ⇒ Object
– DATABASE STATEMENTS ====================================== ++
186 187 188 189 190 191 192 193 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 186 def explain(arel, binds = []) sql = "EXPLAIN #{to_sql(arel, binds)}" start = Concurrent.monotonic_time result = exec_query(sql, "EXPLAIN", binds) elapsed = Concurrent.monotonic_time - start MySQL::ExplainPrettyPrinter.new.pp(result, elapsed) end |
#foreign_keys(table_name) ⇒ Object
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 379 def foreign_keys(table_name) raise ArgumentError unless table_name.present? scope = quoted_scope(table_name) fk_info = 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', 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 fk_info.map do |row| = { column: row["column"], name: row["name"], primary_key: row["primary_key"] } [:on_update] = extract_foreign_key_action(row["on_update"]) [:on_delete] = extract_foreign_key_action(row["on_delete"]) ForeignKeyDefinition.new(table_name, row["to_table"], ) end end |
#get_advisory_lock(lock_name, timeout = 0) ⇒ Object
:nodoc:
132 133 134 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 132 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 ⇒ Object
:nodoc:
57 58 59 60 61 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 57 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 |
#index_algorithms ⇒ Object
144 145 146 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 144 def index_algorithms { default: +"ALGORITHM = DEFAULT", copy: +"ALGORITHM = COPY", inplace: +"ALGORITHM = INPLACE" } end |
#mariadb? ⇒ Boolean
:nodoc:
63 64 65 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 63 def mariadb? # :nodoc: /mariadb/i.match?(full_version) end |
#native_database_types ⇒ Object
140 141 142 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 140 def native_database_types NATIVE_DATABASE_TYPES end |
#primary_keys(table_name) ⇒ Object
:nodoc:
444 445 446 447 448 449 450 451 452 453 454 455 456 457 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 444 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 |
#recreate_database(name, options = {}) ⇒ Object
Drops the database specified on the name
attribute and creates it again using the provided options
.
238 239 240 241 242 243 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 238 def recreate_database(name, = {}) drop_database(name) sql = create_database(name, ) reconnect! sql end |
#release_advisory_lock(lock_name) ⇒ Object
:nodoc:
136 137 138 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 136 def release_advisory_lock(lock_name) # :nodoc: query_value("SELECT RELEASE_LOCK(#{quote(lock_name.to_s)})") == 1 end |
#rename_column(table_name, column_name, new_column_name) ⇒ Object
:nodoc:
363 364 365 366 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 363 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_index(table_name, old_name, new_name) ⇒ Object
331 332 333 334 335 336 337 338 339 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 331 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')
307 308 309 310 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 307 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 |
#show_variable(name) ⇒ Object
SHOW VARIABLES LIKE ‘name’
438 439 440 441 442 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 438 def show_variable(name) query_value("SELECT @@#{name}", "SCHEMA") rescue ActiveRecord::StatementInvalid nil end |
#strict_mode? ⇒ Boolean
504 505 506 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 504 def strict_mode? self.class.type_cast_config_to_boolean(@config.fetch(:strict, true)) end |
#supports_advisory_locks? ⇒ Boolean
120 121 122 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 120 def supports_advisory_locks? true end |
#supports_bulk_alter? ⇒ Boolean
67 68 69 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 67 def supports_bulk_alter? true end |
#supports_common_table_expressions? ⇒ Boolean
112 113 114 115 116 117 118 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 112 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
99 100 101 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 99 def supports_datetime_with_precision? mariadb? || database_version >= "5.6.4" end |
#supports_explain? ⇒ Boolean
83 84 85 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 83 def supports_explain? true end |
#supports_expression_index? ⇒ Boolean
75 76 77 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 75 def supports_expression_index? !mariadb? && database_version >= "8.0.13" end |
#supports_foreign_keys? ⇒ Boolean
91 92 93 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 91 def supports_foreign_keys? true end |
#supports_index_sort_order? ⇒ Boolean
71 72 73 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 71 def supports_index_sort_order? !mariadb? && database_version >= "8.0.1" end |
#supports_indexes_in_create? ⇒ Boolean
87 88 89 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 87 def supports_indexes_in_create? true end |
#supports_insert_on_duplicate_skip? ⇒ Boolean
124 125 126 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 124 def supports_insert_on_duplicate_skip? true end |
#supports_insert_on_duplicate_update? ⇒ Boolean
128 129 130 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 128 def supports_insert_on_duplicate_update? true end |
#supports_optimizer_hints? ⇒ Boolean
See dev.mysql.com/doc/refman/8.0/en/optimizer-hints.html for more details.
108 109 110 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 108 def supports_optimizer_hints? !mariadb? && database_version >= "5.7.7" end |
#supports_transaction_isolation? ⇒ Boolean
79 80 81 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 79 def supports_transaction_isolation? true end |
#supports_views? ⇒ Boolean
95 96 97 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 95 def supports_views? true end |
#supports_virtual_columns? ⇒ Boolean
103 104 105 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 103 def supports_virtual_columns? mariadb? || database_version >= "5.7.5" end |
#table_comment(table_name) ⇒ Object
:nodoc:
286 287 288 289 290 291 292 293 294 295 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 286 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) ⇒ Object
:nodoc:
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 415 def (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. = create_table_info.sub(/\A.*\n\) ?/m, "").sub(/\n\/\*!.*\*\/\n\z/m, "").strip # strip AUTO_INCREMENT .sub!(/(ENGINE=\w+)(?: AUTO_INCREMENT=\d+)/, '\1') [:options] = unless .blank? # strip COMMENT if .sub!(/ COMMENT='.+'/, "") [:comment] = table_comment(table_name) end end |