Class: ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter
- Inherits:
-
AbstractAdapter
- Object
- AbstractAdapter
- ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter
- Defined in:
- lib/active_record/connection_adapters/abstract_mysql_adapter.rb
Direct Known Subclasses
Defined Under Namespace
Classes: 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 }, bigint: { name: "bigint" }, 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: "boolean" }, json: { name: "json" }, }
- EXTENDED_TYPE_MAPS =
Concurrent::Map.new
- EMULATE_BOOLEANS_TRUE =
{ emulate_booleans: true }.freeze
Constants included from MySQL::Quoting
MySQL::Quoting::QUOTED_COLUMN_NAMES, MySQL::Quoting::QUOTED_TABLE_NAMES
Constants inherited from AbstractAdapter
ActiveRecord::ConnectionAdapters::AbstractAdapter::ADAPTER_NAME, ActiveRecord::ConnectionAdapters::AbstractAdapter::COMMENT_REGEX, ActiveRecord::ConnectionAdapters::AbstractAdapter::MAX_JITTER, ActiveRecord::ConnectionAdapters::AbstractAdapter::SIMPLE_INT, ActiveRecord::ConnectionAdapters::AbstractAdapter::TYPE_MAP
Constants included from QueryCache
Instance Attribute Summary
Attributes inherited from AbstractAdapter
#allow_preconnect, #lock, #logger, #owner, #pinned, #pool, #visitor
Attributes included from QueryCache
Attributes included from DatabaseStatements
Class Method Summary collapse
-
.cli_args(config) ⇒ Object
:nodoc:.
- .dbconsole(config, options = {}) ⇒ Object
-
.extended_type_map(default_timezone: nil, emulate_booleans:) ⇒ Object
:nodoc:.
-
.native_database_types ⇒ Object
:nodoc:.
Instance Method Summary collapse
-
#add_index(table_name, column_name, **options) ⇒ Object
:nodoc:.
-
#add_sql_comment!(sql, comment) ⇒ Object
:nodoc:.
-
#begin_db_transaction ⇒ Object
-- DATABASE STATEMENTS ====================================== ++.
-
#begin_isolated_db_transaction(isolation) ⇒ Object
:nodoc:.
-
#build_change_column_default_definition(table_name, column_name, default_or_changes) ⇒ Object
:nodoc:.
-
#build_change_column_definition(table_name, column_name, type, **options) ⇒ Object
Builds a ChangeColumnDefinition object.
-
#build_create_index_definition(table_name, column_name, **options) ⇒ Object
:nodoc:.
-
#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_constraints(table_name) ⇒ Object
-
#check_version ⇒ Object
:nodoc:.
-
#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.
-
#create_or_find_by_lock ⇒ Object
:nodoc:.
- #current_database ⇒ Object
-
#default_index_type?(index) ⇒ Boolean
:nodoc:.
-
#disable_index(table_name, index_name) ⇒ Object
:nodoc:.
-
#disable_referential_integrity ⇒ Object
REFERENTIAL INTEGRITY ====================================.
-
#drop_database(name) ⇒ Object
Drops a MySQL database.
-
#drop_table(*table_names, **options) ⇒ Object
Drops a table or tables from the database.
-
#empty_insert_statement_value(primary_key = nil) ⇒ Object
:nodoc:.
-
#emulate_booleans ⇒ Object
:singleton-method: By default, the Mysql2Adapter will consider all columns of type tinyint(1) as boolean.
-
#enable_index(table_name, index_name) ⇒ Object
:nodoc:.
-
#error_number(exception) ⇒ Object
Must return the MySQL error number from the exception, if the exception has an error number.
-
#exec_restart_db_transaction ⇒ Object
:nodoc:.
-
#exec_rollback_db_transaction ⇒ Object
:nodoc:.
- #foreign_keys(table_name) ⇒ Object
-
#get_advisory_lock(lock_name, timeout = 0) ⇒ Object
:nodoc:.
-
#get_database_version ⇒ Object
:nodoc:.
- #index_algorithms ⇒ Object
-
#mariadb? ⇒ Boolean
:nodoc:.
-
#primary_keys(table_name) ⇒ Object
:nodoc:.
-
#quote_string(string) ⇒ Object
Quotes strings for use in SQL input.
-
#recreate_database(name, options = {}) ⇒ Object
Drops the database specified on the
nameattribute 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, **options) ⇒ Object
Renames a table.
-
#return_value_after_insert?(column) ⇒ Boolean
:nodoc:.
-
#show_variable(name) ⇒ Object
SHOW VARIABLES LIKE 'name'.
- #strict_mode? ⇒ Boolean
- #supports_advisory_locks? ⇒ Boolean
- #supports_bulk_alter? ⇒ Boolean
- #supports_check_constraints? ⇒ Boolean
- #supports_common_table_expressions? ⇒ Boolean
- #supports_datetime_with_precision? ⇒ Boolean
-
#supports_disabling_indexes? ⇒ Boolean
See https://dev.mysql.com/doc/refman/8.0/en/invisible-indexes.html for more details on MySQL feature.
- #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_insert_returning? ⇒ Boolean
-
#supports_optimizer_hints? ⇒ Boolean
See https://dev.mysql.com/doc/refman/en/optimizer-hints.html for more details.
- #supports_restart_db_transaction? ⇒ Boolean
- #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
#add_index_options, #create_index_definition, #create_schema_dumper, #create_table, #indexes, #internal_string_options_for_primary_key, #remove_column, #remove_foreign_key, #schema_creation, #table_alias_length, #type_to_sql, #update_table_definition
Methods included from MySQL::Quoting
#cast_bound_value, #quoted_binary, #type_cast, #unquote_identifier, #unquoted_false, #unquoted_true
Methods included from MySQL::DatabaseStatements
#build_explain_clause, #default_insert_value, #explain, #high_precision_current_timestamp, #write_query?
Methods inherited from AbstractAdapter
#active?, #adapter_name, #add_enum_value, #advisory_locks_enabled?, #async_enabled?, build_read_query_regexp, #case_insensitive_comparison, #check_all_foreign_keys_valid!, #clean!, #clear_cache!, #close, #connect!, #connected?, #connection_age, #connection_descriptor, #connection_retries, #create_enum, #create_virtual_table, database_exists?, #database_exists?, #database_version, #default_timezone, #default_uniqueness_comparison, #disable_extension, #discard!, #disconnect!, #drop_enum, #drop_virtual_table, #enable_extension, #ensure_writes_are_allowed, #expire, #extensions, find_cmd_and_exec, #force_retirement, #initialize, #inspect, #lease, #lock_thread=, #max_jitter, #native_database_types, #pool_jitter, #prefetch_primary_key?, #prepared_statements?, #prepared_statements_disabled_cache, #preventing_writes?, #raw_connection, #reconnect!, register_class_with_precision, #rename_enum, #rename_enum_value, #replica?, #requires_reloading?, #reset!, #retry_deadline, #role, #savepoint_errors_invalidate_transactions?, #schema_cache, #schema_version, #seconds_idle, #seconds_since_last_activity, #shard, #steal!, #supports_comments?, #supports_comments_in_create?, #supports_concurrent_connections?, #supports_ddl_transactions?, #supports_deferrable_constraints?, #supports_exclusion_constraints?, #supports_extensions?, #supports_foreign_tables?, #supports_index_include?, #supports_insert_conflict_target?, #supports_json?, #supports_lazy_transactions?, #supports_materialized_views?, #supports_nulls_not_distinct?, #supports_partial_index?, #supports_partitioned_indexes?, #supports_savepoints?, #supports_unique_constraints?, #supports_validate_constraints?, #throw_away!, type_cast_config_to_boolean, type_cast_config_to_integer, #unprepared_statement, #valid_type?, valid_type?, validate_default_timezone, #verified?, #verify!, #verify_timeout
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, #initialize, #query_cache_enabled, #select_all, #uncached
Methods included from DatabaseLimits
#index_name_length, #max_identifier_length, #table_alias_length, #table_name_length
Methods included from Quoting
#cast_bound_value, #lookup_cast_type, #quote, #quote_column_name, #quote_default_expression, #quote_table_name, #quote_table_name_for_assignment, #quoted_binary, #quoted_date, #quoted_false, #quoted_time, #quoted_true, #sanitize_as_sql_comment, #type_cast, #unquoted_false, #unquoted_true
Methods included from DatabaseStatements
#add_transaction_record, #begin_deferred_transaction, #cacheable_query, #default_insert_value, #default_sequence_name, #delete, #exec_delete, #exec_insert, #exec_insert_all, #exec_query, #exec_update, #execute, #explain, #high_precision_current_timestamp, #initialize, #insert, #insert_fixture, #insert_fixtures_set, #internal_exec_query, #mark_transaction_written, #query, #query_value, #query_values, #raw_exec_query, #reset_isolation_level, #reset_sequence!, #reset_transaction, #restart_db_transaction, #rollback_db_transaction, #rollback_to_savepoint, #select_all, #select_one, #select_rows, #select_value, #select_values, #to_sql, #transaction, #transaction_isolation_levels, #transaction_open?, #truncate, #truncate_tables, #update, #with_yaml_fallback, #write_query?
Methods included from SchemaStatements
#add_check_constraint, #add_column, #add_columns, #add_foreign_key, #add_index_options, #add_reference, #add_timestamps, #assume_migrated_upto_version, #build_add_column_definition, #build_create_join_table_definition, #build_create_table_definition, #bulk_change_table, #change_table, #check_constraint_exists?, #check_constraint_options, #column_exists?, #columns, #create_join_table, #create_schema_dumper, #create_table, #data_source_exists?, #data_sources, #distinct_relation_for_primary_key, #drop_join_table, #dump_schema_versions, #foreign_key_column_for, #foreign_key_exists?, #foreign_key_options, #index_algorithm, #index_exists?, #index_name, #index_name_exists?, #indexes, #internal_string_options_for_primary_key, #max_index_name_size, #native_database_types, #options_include_default?, #primary_key, #quoted_columns_for_index, #remove_check_constraint, #remove_column, #remove_columns, #remove_constraint, #remove_foreign_key, #remove_index, #remove_reference, #remove_timestamps, #schema_creation, #table_alias_for, #table_exists?, #tables, #type_to_sql, #update_table_definition, #use_foreign_keys?, #valid_column_definition_options, #valid_primary_key_options, #valid_table_definition_options, #view_exists?, #views
Constructor Details
This class inherits a constructor from ActiveRecord::ConnectionAdapters::AbstractAdapter
Class Method Details
.cli_args(config) ⇒ Object
:nodoc:
72 73 74 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 72 def cli_args(config) # :nodoc: cli_arg_map.filter_map { |opt, arg| "#{arg}=#{config[opt]}" if config[opt] } end |
.dbconsole(config, options = {}) ⇒ Object
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 76 def dbconsole(config, = {}) mysql_config = config.configuration_hash args = cli_args(mysql_config.except(:password)) if mysql_config[:password] && [: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:) ⇒ Object
:nodoc:
757 758 759 760 761 762 763 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 757 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 |
.native_database_types ⇒ Object
:nodoc:
92 93 94 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 92 def native_database_types # :nodoc: NATIVE_DATABASE_TYPES end |
Instance Method Details
#add_index(table_name, column_name, **options) ⇒ Object
:nodoc:
482 483 484 485 486 487 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 482 def add_index(table_name, column_name, **) # :nodoc: create_index = build_create_index_definition(table_name, column_name, **) return unless create_index execute schema_creation.accept(create_index) end |
#add_sql_comment!(sql, comment) ⇒ Object
:nodoc:
515 516 517 518 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 515 def add_sql_comment!(sql, comment) # :nodoc: sql << " COMMENT #{quote(comment)}" if comment.present? sql end |
#begin_db_transaction ⇒ Object
-- DATABASE STATEMENTS ====================================== ++
252 253 254 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 252 def begin_db_transaction # :nodoc: internal_execute("BEGIN", "TRANSACTION", allow_retry: true, materialize_transactions: false) end |
#begin_isolated_db_transaction(isolation) ⇒ Object
:nodoc:
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 256 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 if multi_statements_enabled? execute_batch( ["SET TRANSACTION ISOLATION LEVEL #{transaction_isolation_levels.fetch(isolation)}", "BEGIN"], "TRANSACTION", allow_retry: true, materialize_transactions: false, ) else with_raw_connection(allow_retry: true, materialize_transactions: false) do internal_execute( "SET TRANSACTION ISOLATION LEVEL #{transaction_isolation_levels.fetch(isolation)}", "TRANSACTION", allow_retry: false, materialize_transactions: false, ) internal_execute("BEGIN", "TRANSACTION", allow_retry: false, materialize_transactions: false) end end end |
#build_change_column_default_definition(table_name, column_name, default_or_changes) ⇒ Object
:nodoc:
410 411 412 413 414 415 416 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 410 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) ⇒ Object
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.
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 442 def build_change_column_definition(table_name, column_name, type, **) # :nodoc: column = column_for(table_name, column_name) type ||= column.sql_type unless .key?(:default) [:default] = if column.default_function -> { column.default_function } else column.default end end unless .key?(:null) [:null] = column.null end unless .key?(:comment) [:comment] = column.comment end if [:collation] == :no_collation .delete(:collation) else [:collation] ||= column.collation if text_type?(type) end unless .key?(:auto_increment) [:auto_increment] = column.auto_increment? end td = create_table_definition(table_name) cd = td.new_column_definition(column.name, type, **) ChangeColumnDefinition.new(cd, column.name) end |
#build_create_index_definition(table_name, column_name, **options) ⇒ Object
:nodoc:
489 490 491 492 493 494 495 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 489 def build_create_index_definition(table_name, column_name, **) # :nodoc: index, algorithm, if_not_exists = (table_name, column_name, **) return if if_not_exists && index_exists?(table_name, column_name, name: index.name) CreateIndexDefinition.new(index, algorithm) end |
#build_insert_sql(insert) ⇒ Object
:nodoc:
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 693 def build_insert_sql(insert) # :nodoc: # Can use any column as it will be assigned to itself. 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? quoted_table_name = insert.model.quoted_table_name 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}=#{quoted_table_name}.#{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. { |column| "#{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. { |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 |
#case_sensitive_comparison(attribute, value) ⇒ Object
:nodoc:
655 656 657 658 659 660 661 662 663 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 655 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:
433 434 435 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 433 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:
428 429 430 431 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 428 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:
406 407 408 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 406 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_null(table_name, column_name, null, default = nil) ⇒ Object
:nodoc:
418 419 420 421 422 423 424 425 426 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 418 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) ⇒ Object
:nodoc:
358 359 360 361 362 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 358 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.
338 339 340 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 338 def charset show_variable "character_set_database" end |
#check_constraints(table_name) ⇒ Object
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 565 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| = { 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, ) end else raise NotImplementedError end end |
#check_version ⇒ Object
:nodoc:
739 740 741 742 743 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 739 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 ⇒ Object
Returns the database collation strategy.
343 344 345 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 343 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 https://dev.mysql.com/doc/refman/en/group-by-handling.html
674 675 676 677 678 679 680 681 682 683 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 674 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 ⇒ Object
:nodoc:
279 280 281 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 279 def commit_db_transaction # :nodoc: internal_execute("COMMIT", "TRANSACTION", allow_retry: false, materialize_transactions: true) 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
313 314 315 316 317 318 319 320 321 322 323 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 313 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 |
#create_or_find_by_lock ⇒ Object
:nodoc:
202 203 204 205 206 207 208 209 210 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 202 def create_or_find_by_lock # :nodoc: # A shared lock provides a current read under REPEATABLE READ without # upgrading the shared record lock acquired by a duplicate INSERT. if mariadb? || database_version < "8.0.1" "LOCK IN SHARE MODE" else "FOR SHARE" end end |
#current_database ⇒ Object
333 334 335 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 333 def current_database query_value("SELECT database()", "SCHEMA") end |
#default_index_type?(index) ⇒ Boolean
:nodoc:
689 690 691 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 689 def default_index_type?(index) # :nodoc: index.using == :btree || super end |
#disable_index(table_name, index_name) ⇒ Object
:nodoc:
506 507 508 509 510 511 512 513 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 506 def disable_index(table_name, index_name) # :nodoc: raise NotImplementedError unless supports_disabling_indexes? query = <<~SQL ALTER TABLE #{quote_table_name(table_name)} ALTER INDEX #{quote_column_name(index_name)} #{mariadb? ? "IGNORED" : "INVISIBLE"} SQL execute(query) end |
#disable_referential_integrity ⇒ Object
REFERENTIAL INTEGRITY ====================================
237 238 239 240 241 242 243 244 245 246 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 237 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) ⇒ Object
Drops a MySQL database.
Example:
drop_database('sebastian_development')
329 330 331 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 329 def drop_database(name) # :nodoc: execute "DROP DATABASE IF EXISTS #{quote_table_name(name)}" end |
#drop_table(*table_names, **options) ⇒ Object
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.
391 392 393 394 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 391 def drop_table(*table_names, **) table_names.each { |table_name| schema_cache.clear_data_source_cache!(table_name.to_s) } execute "DROP#{' TEMPORARY' if [:temporary]} TABLE#{' IF EXISTS' if [:if_exists]} #{table_names.map { |table_name| quote_table_name(table_name) }.join(', ')}#{' CASCADE' if [:force] == :cascade}" end |
#empty_insert_statement_value(primary_key = nil) ⇒ Object
:nodoc:
291 292 293 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 291 def empty_insert_statement_value(primary_key = nil) # :nodoc: "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
29 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 29 class_attribute :emulate_booleans, default: true |
#enable_index(table_name, index_name) ⇒ Object
:nodoc:
497 498 499 500 501 502 503 504 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 497 def enable_index(table_name, index_name) # :nodoc: raise NotImplementedError unless supports_disabling_indexes? query = <<~SQL ALTER TABLE #{quote_table_name(table_name)} ALTER INDEX #{quote_column_name(index_name)} #{mariadb? ? "NOT IGNORED" : "VISIBLE"} SQL execute(query) end |
#error_number(exception) ⇒ Object
Must return the MySQL error number from the exception, if the exception has an error number.
231 232 233 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 231 def error_number(exception) # :nodoc: raise NotImplementedError end |
#exec_restart_db_transaction ⇒ Object
:nodoc:
287 288 289 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 287 def exec_restart_db_transaction # :nodoc: internal_execute("ROLLBACK AND CHAIN", "TRANSACTION", allow_retry: false, materialize_transactions: true) end |
#exec_rollback_db_transaction ⇒ Object
:nodoc:
283 284 285 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 283 def exec_rollback_db_transaction # :nodoc: internal_execute("ROLLBACK", "TRANSACTION", allow_retry: false, materialize_transactions: true) end |
#foreign_keys(table_name) ⇒ Object
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 520 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 = { name: row["name"], on_update: extract_foreign_key_action(row["on_update"]), on_delete: extract_foreign_key_action(row["on_delete"]) } if group.one? [:column] = unquote_identifier(row["column"]) [:primary_key] = row["primary_key"] else [:column] = group.map { |row| unquote_identifier(row["column"]) } [:primary_key] = group.map { |row| row["primary_key"] } end ForeignKeyDefinition.new(table_name, unquote_identifier(row["to_table"]), ) end end |
#get_advisory_lock(lock_name, timeout = 0) ⇒ Object
:nodoc:
212 213 214 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 212 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:
97 98 99 100 101 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 97 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
220 221 222 223 224 225 226 227 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 220 def index_algorithms { default: "ALGORITHM = DEFAULT", copy: "ALGORITHM = COPY", inplace: "ALGORITHM = INPLACE", instant: "ALGORITHM = INSTANT", } end |
#mariadb? ⇒ Boolean
:nodoc:
103 104 105 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 103 def mariadb? # :nodoc: /mariadb/i.match?(full_version) end |
#primary_keys(table_name) ⇒ Object
:nodoc:
640 641 642 643 644 645 646 647 648 649 650 651 652 653 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 640 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) ⇒ Object
Quotes strings for use in SQL input.
750 751 752 753 754 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 750 def quote_string(string) with_raw_connection(allow_retry: true, materialize_transactions: false) do |connection| connection.escape(string) end end |
#recreate_database(name, options = {}) ⇒ Object
Drops the database specified on the name attribute
and creates it again using the provided options.
299 300 301 302 303 304 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 299 def recreate_database(name, = {}) drop_database(name) sql = create_database(name, ) reconnect! sql end |
#release_advisory_lock(lock_name) ⇒ Object
:nodoc:
216 217 218 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 216 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:
477 478 479 480 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 477 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
396 397 398 399 400 401 402 403 404 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 396 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) ⇒ Object
Renames a table.
Example:
rename_table('octopuses', 'octopi')
368 369 370 371 372 373 374 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 368 def rename_table(table_name, new_name, **) validate_table_length!(new_name) unless [:_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, **) end |
#return_value_after_insert?(column) ⇒ Boolean
:nodoc:
188 189 190 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 188 def return_value_after_insert?(column) # :nodoc: supports_insert_returning? ? column.auto_populated? : column.auto_increment? end |
#show_variable(name) ⇒ Object
SHOW VARIABLES LIKE 'name'
634 635 636 637 638 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 634 def show_variable(name) query_value("SELECT @@#{name}", "SCHEMA", materialize_transactions: false, allow_retry: true) rescue ActiveRecord::StatementInvalid nil end |
#strict_mode? ⇒ Boolean
685 686 687 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 685 def strict_mode? self.class.type_cast_config_to_boolean(@config.fetch(:strict, true)) end |
#supports_advisory_locks? ⇒ Boolean
172 173 174 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 172 def supports_advisory_locks? true end |
#supports_bulk_alter? ⇒ Boolean
107 108 109 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 107 def supports_bulk_alter? true end |
#supports_check_constraints? ⇒ Boolean
139 140 141 142 143 144 145 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 139 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
164 165 166 167 168 169 170 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 164 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
151 152 153 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 151 def supports_datetime_with_precision? true end |
#supports_disabling_indexes? ⇒ Boolean
See https://dev.mysql.com/doc/refman/8.0/en/invisible-indexes.html for more details on MySQL feature. See https://mariadb.com/kb/en/ignored-indexes/ for more details on the MariaDB feature.
194 195 196 197 198 199 200 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 194 def supports_disabling_indexes? if mariadb? database_version >= "10.6.0" else database_version >= "8.0.0" end end |
#supports_explain? ⇒ Boolean
127 128 129 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 127 def supports_explain? true end |
#supports_expression_index? ⇒ Boolean
115 116 117 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 115 def supports_expression_index? !mariadb? && database_version >= "8.0.13" end |
#supports_foreign_keys? ⇒ Boolean
135 136 137 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 135 def supports_foreign_keys? true end |
#supports_index_sort_order? ⇒ Boolean
111 112 113 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 111 def supports_index_sort_order? mariadb? ? database_version >= "10.8.1" : database_version >= "8.0.1" end |
#supports_indexes_in_create? ⇒ Boolean
131 132 133 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 131 def supports_indexes_in_create? true end |
#supports_insert_on_duplicate_skip? ⇒ Boolean
176 177 178 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 176 def supports_insert_on_duplicate_skip? true end |
#supports_insert_on_duplicate_update? ⇒ Boolean
180 181 182 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 180 def supports_insert_on_duplicate_update? true end |
#supports_insert_returning? ⇒ Boolean
184 185 186 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 184 def supports_insert_returning? mariadb? && database_version >= "10.5.0" end |
#supports_optimizer_hints? ⇒ Boolean
See https://dev.mysql.com/doc/refman/en/optimizer-hints.html for more details.
160 161 162 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 160 def supports_optimizer_hints? !mariadb? && database_version >= "5.7.7" end |
#supports_restart_db_transaction? ⇒ Boolean
123 124 125 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 123 def supports_restart_db_transaction? true end |
#supports_transaction_isolation? ⇒ Boolean
119 120 121 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 119 def supports_transaction_isolation? true end |
#supports_views? ⇒ Boolean
147 148 149 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 147 def supports_views? true end |
#supports_virtual_columns? ⇒ Boolean
155 156 157 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 155 def supports_virtual_columns? mariadb? || database_version >= "5.7.5" end |
#table_comment(table_name) ⇒ Object
:nodoc:
347 348 349 350 351 352 353 354 355 356 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 347 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:
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 604 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 return if .empty? = {} if / DEFAULT CHARSET=(?<charset>\w+)(?: COLLATE=(?<collation>\w+))?/ =~ = $` + $' # before part + after part [:charset] = charset [:collation] = collation if collation end # strip AUTO_INCREMENT .sub!(/(ENGINE=\w+)(?: AUTO_INCREMENT=\d+)/, '\1') # strip COMMENT if .sub!(/ COMMENT='.+'/, "") [:comment] = table_comment(table_name) end [:options] = unless == "ENGINE=InnoDB" end |