Class: ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter
- Inherits:
-
AbstractAdapter
- Object
- AbstractAdapter
- ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter
- Includes:
- Savepoints
- Defined in:
- lib/active_record/connection_adapters/abstract_mysql_adapter.rb
Direct Known Subclasses
Defined Under Namespace
Classes: Column, MysqlDateTime, MysqlString, SchemaCreation
Constant Summary collapse
- LOST_CONNECTION_ERROR_MESSAGES =
[ "Server shutdown in progress", "Broken pipe", "Lost connection to MySQL server during query", "MySQL server has gone away" ]
- NATIVE_DATABASE_TYPES =
{ :primary_key => "int(11) auto_increment PRIMARY KEY", :string => { :name => "varchar", :limit => 255 }, :text => { :name => "text" }, :integer => { :name => "int", :limit => 4 }, :float => { :name => "float" }, :decimal => { :name => "decimal" }, :datetime => { :name => "datetime" }, :time => { :name => "time" }, :date => { :name => "date" }, :binary => { :name => "blob" }, :boolean => { :name => "tinyint", :limit => 1 } }
- INDEX_TYPES =
[:fulltext, :spatial]
- INDEX_USINGS =
[:btree, :hash]
Constants inherited from AbstractAdapter
ActiveRecord::ConnectionAdapters::AbstractAdapter::ADAPTER_NAME, ActiveRecord::ConnectionAdapters::AbstractAdapter::SIMPLE_INT
Instance Attribute Summary
Attributes inherited from AbstractAdapter
#logger, #owner, #pool, #prepared_statements, #schema_cache, #visitor
Attributes included from QueryCache
#query_cache, #query_cache_enabled
Attributes included from DatabaseStatements
Instance Method Summary collapse
-
#_quote(value) ⇒ Object
QUOTING ==================================================.
-
#add_index(table_name, column_name, options = {}) ⇒ Object
:nodoc:.
- #begin_db_transaction ⇒ Object
- #begin_isolated_db_transaction(isolation) ⇒ Object
-
#bulk_change_table(table_name, operations) ⇒ Object
:nodoc:.
- #case_insensitive_comparison(table, attribute, column, value) ⇒ Object
- #case_sensitive_comparison(table, attribute, column, value) ⇒ Object
- #case_sensitive_modifier(node, table_attribute) ⇒ Object
-
#change_column(table_name, column_name, type, options = {}) ⇒ Object
:nodoc:.
-
#change_column_default(table_name, column_name, default) ⇒ Object
:nodoc:.
- #change_column_null(table_name, column_name, null, default = nil) ⇒ Object
-
#charset ⇒ Object
Returns the database character set.
-
#clear_cache! ⇒ Object
– DATABASE STATEMENTS ====================================== ++.
-
#collation ⇒ Object
Returns the database collation strategy.
-
#columns(table_name) ⇒ Object
Returns an array of
Column
objects for the table specified bytable_name
. -
#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_table(table_name, options = {}) ⇒ Object
:nodoc:.
- #current_database ⇒ Object
-
#disable_referential_integrity ⇒ Object
REFERENTIAL INTEGRITY ====================================.
-
#drop_database(name) ⇒ Object
Drops a MySQL database.
- #drop_table(table_name, options = {}) ⇒ Object
-
#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 ⇒ Object
-
#emulate_booleans ⇒ Object
:singleton-method: By default, the MysqlAdapter 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
MysqlAdapter has to free a result after using it, so we use this method to write stuff in an abstract way without concerning ourselves about whether it needs to be explicitly freed or not.
- #foreign_keys(table_name) ⇒ Object
- #index_algorithms ⇒ Object
-
#indexes(table_name, name = nil) ⇒ Object
Returns an array of indexes for the given table.
-
#initialize(connection, logger, connection_options, config) ⇒ AbstractMysqlAdapter
constructor
FIXME: Make the first parameter more similar for the two adapters.
-
#join_to_update(update, select) ⇒ Object
In the simple case, MySQL allows us to place JOINs directly into the UPDATE query.
- #native_database_types ⇒ Object
-
#new_column(field, default, cast_type, sql_type = nil, null = true, collation = "", extra = "") ⇒ Object
:nodoc:.
-
#pk_and_sequence_for(table) ⇒ Object
Returns a table’s primary key and belonging sequence.
-
#prepare_column_options(column, types) ⇒ Object
:nodoc:.
-
#primary_key(table) ⇒ Object
Returns just a table’s primary key.
-
#quote_column_name(name) ⇒ Object
:nodoc:.
-
#quote_table_name(name) ⇒ Object
:nodoc:.
- #quoted_false ⇒ Object
- #quoted_true ⇒ Object
-
#recreate_database(name, options = {}) ⇒ Object
Drops the database specified on the
name
attribute and creates it again using the providedoptions
. -
#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.
- #schema_creation ⇒ Object
-
#show_variable(name) ⇒ Object
SHOW VARIABLES LIKE ‘name’.
- #strict_mode? ⇒ Boolean
-
#supports_bulk_alter? ⇒ Boolean
:nodoc:.
- #supports_datetime_with_precision? ⇒ Boolean
- #supports_foreign_keys? ⇒ Boolean
-
#supports_index_sort_order? ⇒ Boolean
Technically MySQL allows to create indexes with the sort order syntax but at the moment (5.5) it doesn’t yet implement them.
- #supports_indexes_in_create? ⇒ Boolean
-
#supports_migrations? ⇒ Boolean
Returns true, since this connection adapter supports migrations.
- #supports_primary_key? ⇒ Boolean
-
#supports_transaction_isolation? ⇒ Boolean
MySQL 4 technically support transaction isolation, but it is affected by a bug where the transaction level gets persisted for the whole session:.
- #supports_views? ⇒ Boolean
- #table_exists?(name) ⇒ Boolean (also: #data_source_exists?)
-
#tables(name = nil, database = nil, like = nil) ⇒ Object
(also: #data_sources)
:nodoc:.
- #truncate(table_name, name = nil) ⇒ Object
-
#type_to_sql(type, limit = nil, precision = nil, scale = nil) ⇒ Object
Maps logical Rails types to MySQL-specific data types.
- #unquoted_false ⇒ Object
- #unquoted_true ⇒ Object
-
#update_sql(sql, name = nil) ⇒ Object
:nodoc:.
- #valid_type?(type) ⇒ Boolean
Methods included from Savepoints
#create_savepoint, #exec_rollback_to_savepoint, #release_savepoint, #supports_savepoints?
Methods inherited from AbstractAdapter
#active?, #adapter_name, #close, #collector, #column_name_for_operation, #create_savepoint, #current_savepoint_name, #disable_extension, #disconnect!, #enable_extension, #expire, #extensions, #lease, #lookup_cast_type, #prefetch_primary_key?, #raw_connection, #reconnect!, #release_savepoint, #requires_reloading?, #reset!, #substitute_at, #supports_ddl_transactions?, #supports_explain?, #supports_extensions?, #supports_partial_index?, #supports_savepoints?, type_cast_config_to_boolean, type_cast_config_to_integer, #type_map, #unprepared_statement, #verify!
Methods included from ColumnDumper
Methods included from QueryCache
#cache, #clear_query_cache, dirties_query_cache, #disable_query_cache!, #enable_query_cache!, included, #select_all, #uncached
Methods included from DatabaseLimits
#allowed_index_name_length, #column_name_length, #columns_per_multicolumn_index, #columns_per_table, #in_clause_length, #index_name_length, #indexes_per_table, #joins_per_query, #sql_query_length, #table_alias_length, #table_name_length
Methods included from Quoting
#quote, #quote_string, #quote_table_name_for_assignment, #quoted_date, #type_cast
Methods included from DatabaseStatements
#add_transaction_record, #cacheable_query, #default_sequence_name, #delete, #exec_delete, #exec_insert, #exec_query, #exec_rollback_to_savepoint, #exec_update, #insert, #insert_fixture, #join_to_delete, #reset_sequence!, #reset_transaction, #rollback_db_transaction, #rollback_to_savepoint, #sanitize_limit, #select_all, #select_one, #select_rows, #select_value, #select_values, #supports_statement_cache?, #to_sql, #transaction, #transaction_isolation_levels, #transaction_open?, #transaction_state, #update
Methods included from SchemaStatements
#add_column, #add_foreign_key, #add_index_options, #add_reference, #add_timestamps, #assume_migrated_upto_version, #change_table, #column_exists?, #create_join_table, #drop_join_table, #dump_schema_information, #foreign_key_column_for, #index_exists?, #index_name, #index_name_exists?, #initialize_schema_migrations_table, #remove_column, #remove_columns, #remove_foreign_key, #remove_index, #remove_index!, #remove_reference, #remove_timestamps, #table_alias_for, #update_table_definition
Methods included from TimestampDefaultDeprecation
#emit_warning_if_null_unspecified
Constructor Details
#initialize(connection, logger, connection_options, config) ⇒ AbstractMysqlAdapter
FIXME: Make the first parameter more similar for the two adapters
168 169 170 171 172 173 174 175 176 177 178 179 180 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 168 def initialize(connection, logger, , config) super(connection, logger) , @config = , config @quoted_column_names, @quoted_table_names = {}, {} @visitor = Arel::Visitors::MySQL.new self if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true }) @prepared_statements = true else @prepared_statements = false end end |
Instance Method Details
#_quote(value) ⇒ Object
QUOTING ==================================================
253 254 255 256 257 258 259 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 253 def _quote(value) # :nodoc: if value.is_a?(Type::Binary::Data) "x'#{value.hex}'" else super end end |
#add_index(table_name, column_name, options = {}) ⇒ Object
:nodoc:
539 540 541 542 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 539 def add_index(table_name, column_name, = {}) #:nodoc: index_name, index_type, index_columns, , index_algorithm, index_using = (table_name, column_name, ) execute "CREATE #{index_type} INDEX #{quote_column_name(index_name)} #{index_using} ON #{quote_table_name(table_name)} (#{index_columns})#{index_options} #{index_algorithm}" end |
#begin_db_transaction ⇒ Object
324 325 326 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 324 def begin_db_transaction execute "BEGIN" end |
#begin_isolated_db_transaction(isolation) ⇒ Object
328 329 330 331 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 328 def begin_isolated_db_transaction(isolation) execute "SET TRANSACTION ISOLATION LEVEL #{transaction_isolation_levels.fetch(isolation)}" begin_db_transaction end |
#bulk_change_table(table_name, operations) ⇒ Object
:nodoc:
477 478 479 480 481 482 483 484 485 486 487 488 489 490 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 477 def bulk_change_table(table_name, operations) #:nodoc: sqls = operations.flat_map do |command, args| table, arguments = args.shift, args method = :"#{command}_sql" if respond_to?(method, true) send(method, table, *arguments) else raise "Unknown method called : #{method}(#{arguments.inspect})" end end.join(", ") execute("ALTER TABLE #{quote_table_name(table_name)} #{sqls}") end |
#case_insensitive_comparison(table, attribute, column, value) ⇒ Object
651 652 653 654 655 656 657 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 651 def case_insensitive_comparison(table, attribute, column, value) if column.case_sensitive? super else table[attribute].eq(value) end end |
#case_sensitive_comparison(table, attribute, column, value) ⇒ Object
643 644 645 646 647 648 649 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 643 def case_sensitive_comparison(table, attribute, column, value) if column.case_sensitive? table[attribute].eq(value) else super end end |
#case_sensitive_modifier(node, table_attribute) ⇒ Object
638 639 640 641 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 638 def case_sensitive_modifier(node, table_attribute) node = Arel::Nodes.build_quoted node, table_attribute Arel::Nodes::Bin.new(node) end |
#change_column(table_name, column_name, type, options = {}) ⇒ Object
:nodoc:
530 531 532 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 530 def change_column(table_name, column_name, type, = {}) #:nodoc: execute("ALTER TABLE #{quote_table_name(table_name)} #{change_column_sql(table_name, column_name, type, options)}") end |
#change_column_default(table_name, column_name, default) ⇒ Object
:nodoc:
515 516 517 518 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 515 def change_column_default(table_name, column_name, default) #:nodoc: column = column_for(table_name, column_name) change_column table_name, column_name, column.sql_type, :default => default end |
#change_column_null(table_name, column_name, null, default = nil) ⇒ Object
520 521 522 523 524 525 526 527 528 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 520 def change_column_null(table_name, column_name, null, default = nil) column = column_for(table_name, column_name) unless null || default.nil? execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL") end change_column table_name, column_name, column.sql_type, :null => null end |
#charset ⇒ Object
Returns the database character set.
396 397 398 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 396 def charset show_variable 'character_set_database' end |
#clear_cache! ⇒ Object
– DATABASE STATEMENTS ====================================== ++
302 303 304 305 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 302 def clear_cache! super reload_type_map end |
#collation ⇒ Object
Returns the database collation strategy.
401 402 403 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 401 def collation show_variable 'collation_database' end |
#columns(table_name) ⇒ Object
Returns an array of Column
objects for the table specified by table_name
.
461 462 463 464 465 466 467 468 469 470 471 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 461 def columns(table_name)#:nodoc: sql = "SHOW FULL FIELDS FROM #{quote_table_name(table_name)}" execute_and_free(sql, 'SCHEMA') do |result| each_hash(result).map do |field| field_name = set_field_encoding(field[:Field]) sql_type = field[:Type] cast_type = lookup_cast_type(sql_type) new_column(field_name, field[:Default], cast_type, sql_type, field[:Null] == "YES", field[:Collation], field[:Extra]) end end end |
#columns_for_distinct(columns, orders) ⇒ Object
In MySQL 5.7.5 and up, ONLY_FULL_GROUP_BY affects handling of queries that use DISTINCT and ORDER BY. It requires the ORDER BY columns in the select list for distinct queries, and requires that the ORDER BY include the distinct column. See dev.mysql.com/doc/refman/5.7/en/group-by-handling.html
663 664 665 666 667 668 669 670 671 672 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 663 def columns_for_distinct(columns, orders) # :nodoc: order_columns = orders.reject(&:blank?).map { |s| # Convert Arel node to string s = s.to_sql unless s.is_a?(String) # Remove any ASC/DESC modifiers s.gsub(/\s+(?:ASC|DESC)\b/i, '') }.reject(&:blank?).map.with_index { |column, i| "#{column} AS alias_#{i}" } [super, *order_columns].join(', ') end |
#commit_db_transaction ⇒ Object
:nodoc:
333 334 335 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 333 def commit_db_transaction #:nodoc: execute "COMMIT" end |
#create_database(name, options = {}) ⇒ Object
Create a new MySQL database with optional :charset
and :collation
. Charset defaults to utf8.
Example:
create_database 'charset_test', charset: 'latin1', collation: 'latin1_bin'
create_database 'matt_development'
create_database 'matt_development', charset: :big5
375 376 377 378 379 380 381 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 375 def create_database(name, = {}) if [:collation] execute "CREATE DATABASE `#{name}` DEFAULT CHARACTER SET `#{options[:charset] || 'utf8'}` COLLATE `#{options[:collation]}`" else execute "CREATE DATABASE `#{name}` DEFAULT CHARACTER SET `#{options[:charset] || 'utf8'}`" end end |
#create_table(table_name, options = {}) ⇒ Object
:nodoc:
473 474 475 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 473 def create_table(table_name, = {}) #:nodoc: super(table_name, .reverse_merge(:options => "ENGINE=InnoDB")) end |
#current_database ⇒ Object
391 392 393 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 391 def current_database select_value 'SELECT DATABASE() as db' end |
#disable_referential_integrity ⇒ Object
REFERENTIAL INTEGRITY ====================================
287 288 289 290 291 292 293 294 295 296 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 287 def disable_referential_integrity #:nodoc: old = select_value("SELECT @@FOREIGN_KEY_CHECKS") begin update("SET FOREIGN_KEY_CHECKS = 0") yield ensure update("SET FOREIGN_KEY_CHECKS = #{old}") end end |
#drop_database(name) ⇒ Object
Drops a MySQL database.
Example:
drop_database('sebastian_development')
387 388 389 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 387 def drop_database(name) #:nodoc: execute "DROP DATABASE IF EXISTS `#{name}`" end |
#drop_table(table_name, options = {}) ⇒ Object
501 502 503 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 501 def drop_table(table_name, = {}) execute "DROP#{' TEMPORARY' if options[:temporary]} TABLE #{quote_table_name(table_name)}#{' CASCADE' if options[:force] == :cascade}" end |
#each_hash(result) ⇒ Object
The two drivers have slightly different ways of yielding hashes of results, so this method must be implemented to provide a uniform interface.
237 238 239 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 237 def each_hash(result) # :nodoc: raise NotImplementedError end |
#empty_insert_statement_value ⇒ Object
353 354 355 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 353 def empty_insert_statement_value "VALUES ()" end |
#emulate_booleans ⇒ Object
:singleton-method: By default, the MysqlAdapter will consider all columns of type tinyint(1)
as boolean. If you wish to disable this emulation (which was the default behavior in versions 0.13.1 and earlier) you can add the following line to your application.rb file:
ActiveRecord::ConnectionAdapters::Mysql[2]Adapter.emulate_booleans = false
139 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 139 class_attribute :emulate_booleans |
#error_number(exception) ⇒ Object
Must return the MySQL error number from the exception, if the exception has an error number.
247 248 249 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 247 def error_number(exception) # :nodoc: raise NotImplementedError end |
#exec_rollback_db_transaction ⇒ Object
:nodoc:
337 338 339 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 337 def exec_rollback_db_transaction #:nodoc: execute "ROLLBACK" end |
#execute(sql, name = nil) ⇒ Object
Executes the SQL statement in the context of this connection.
308 309 310 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 308 def execute(sql, name = nil) log(sql, name) { @connection.query(sql) } end |
#execute_and_free(sql, name = nil) {|execute(sql, name)| ... } ⇒ Object
MysqlAdapter has to free a result after using it, so we use this method to write stuff in an abstract way without concerning ourselves about whether it needs to be explicitly freed or not.
315 316 317 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 315 def execute_and_free(sql, name = nil) #:nodoc: yield execute(sql, name) end |
#foreign_keys(table_name) ⇒ Object
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 544 def foreign_keys(table_name) fk_info = select_all "SELECT fk.referenced_table_name as 'to_table'\n,fk.referenced_column_name as 'primary_key'\n,fk.column_name as 'column'\n,fk.constraint_name as 'name'\nFROM information_schema.key_column_usage fk\nWHERE fk.referenced_column_name is not null\nAND fk.table_schema = '\#{@config[:database]}'\nAND fk.table_name = '\#{table_name}'\n".strip_heredoc create_table_info = select_one("SHOW CREATE TABLE #{quote_table_name(table_name)}")["Create Table"] fk_info.map do |row| = { column: row['column'], name: row['name'], primary_key: row['primary_key'] } [:on_update] = extract_foreign_key_action(create_table_info, row['name'], "UPDATE") [:on_delete] = extract_foreign_key_action(create_table_info, row['name'], "DELETE") ForeignKeyDefinition.new(table_name, row['to_table'], ) end end |
#index_algorithms ⇒ Object
229 230 231 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 229 def index_algorithms { default: 'ALGORITHM = DEFAULT', copy: 'ALGORITHM = COPY', inplace: 'ALGORITHM = INPLACE' } end |
#indexes(table_name, name = nil) ⇒ Object
Returns an array of indexes for the given table.
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 437 def indexes(table_name, name = nil) #:nodoc: indexes = [] current_index = nil execute_and_free("SHOW KEYS FROM #{quote_table_name(table_name)}", 'SCHEMA') do |result| each_hash(result) do |row| if current_index != row[:Key_name] next if row[:Key_name] == 'PRIMARY' # skip the primary key current_index = row[:Key_name] mysql_index_type = row[:Index_type].downcase.to_sym index_type = INDEX_TYPES.include?(mysql_index_type) ? mysql_index_type : nil index_using = INDEX_USINGS.include?(mysql_index_type) ? mysql_index_type : nil indexes << IndexDefinition.new(row[:Table], row[:Key_name], row[:Non_unique].to_i == 0, [], [], nil, nil, index_type, index_using) end indexes.last.columns << row[:Column_name] indexes.last.lengths << row[:Sub_part] end end indexes end |
#join_to_update(update, select) ⇒ Object
In the simple case, MySQL allows us to place JOINs directly into the UPDATE query. However, this does not allow for LIMIT, OFFSET and ORDER. To support these, we must use a subquery.
344 345 346 347 348 349 350 351 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 344 def join_to_update(update, select) #:nodoc: if select.limit || select.offset || select.orders.any? super else update.table select.source update.wheres = select.constraints end end |
#native_database_types ⇒ Object
225 226 227 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 225 def native_database_types NATIVE_DATABASE_TYPES end |
#new_column(field, default, cast_type, sql_type = nil, null = true, collation = "", extra = "") ⇒ Object
:nodoc:
241 242 243 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 241 def new_column(field, default, cast_type, sql_type = nil, null = true, collation = "", extra = "") # :nodoc: Column.new(field, default, cast_type, sql_type, null, collation, strict_mode?, extra) end |
#pk_and_sequence_for(table) ⇒ Object
Returns a table’s primary key and belonging sequence.
620 621 622 623 624 625 626 627 628 629 630 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 620 def pk_and_sequence_for(table) execute_and_free("SHOW CREATE TABLE #{quote_table_name(table)}", 'SCHEMA') do |result| create_table = each_hash(result).first[:"Create Table"] if create_table.to_s =~ /PRIMARY KEY\s+(?:USING\s+\w+\s+)?\((.+)\)/ keys = $1.split(",").map { |key| key.delete('`"') } keys.length == 1 ? [keys.first, nil] : nil else nil end end end |
#prepare_column_options(column, types) ⇒ Object
:nodoc:
61 62 63 64 65 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 61 def (column, types) # :nodoc: spec = super spec.delete(:limit) if :boolean === column.type spec end |
#primary_key(table) ⇒ Object
Returns just a table’s primary key
633 634 635 636 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 633 def primary_key(table) pk_and_sequence = pk_and_sequence_for(table) pk_and_sequence && pk_and_sequence.first end |
#quote_column_name(name) ⇒ Object
:nodoc:
261 262 263 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 261 def quote_column_name(name) #:nodoc: @quoted_column_names[name] ||= "`#{name.to_s.gsub('`', '``')}`" end |
#quote_table_name(name) ⇒ Object
:nodoc:
265 266 267 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 265 def quote_table_name(name) #:nodoc: @quoted_table_names[name] ||= quote_column_name(name).gsub('.', '`.`') end |
#quoted_false ⇒ Object
277 278 279 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 277 def quoted_false QUOTED_FALSE end |
#quoted_true ⇒ Object
269 270 271 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 269 def quoted_true QUOTED_TRUE end |
#recreate_database(name, options = {}) ⇒ Object
Drops the database specified on the name
attribute and creates it again using the provided options
.
361 362 363 364 365 366 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 361 def recreate_database(name, = {}) drop_database(name) sql = create_database(name, ) reconnect! sql end |
#rename_column(table_name, column_name, new_column_name) ⇒ Object
:nodoc:
534 535 536 537 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 534 def rename_column(table_name, column_name, new_column_name) #:nodoc: execute("ALTER TABLE #{quote_table_name(table_name)} #{rename_column_sql(table_name, column_name, new_column_name)}") rename_column_indexes(table_name, column_name, new_column_name) end |
#rename_index(table_name, old_name, new_name) ⇒ Object
505 506 507 508 509 510 511 512 513 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 505 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')
496 497 498 499 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 496 def rename_table(table_name, new_name) execute "RENAME TABLE #{quote_table_name(table_name)} TO #{quote_table_name(new_name)}" rename_table_indexes(table_name, new_name) end |
#schema_creation ⇒ Object
57 58 59 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 57 def schema_creation SchemaCreation.new self end |
#show_variable(name) ⇒ Object
SHOW VARIABLES LIKE ‘name’
612 613 614 615 616 617 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 612 def show_variable(name) variables = select_all("select @@#{name} as 'Value'", 'SCHEMA') variables.first['Value'] unless variables.empty? rescue ActiveRecord::StatementInvalid nil end |
#strict_mode? ⇒ Boolean
674 675 676 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 674 def strict_mode? self.class.type_cast_config_to_boolean(@config.fetch(:strict, true)) end |
#supports_bulk_alter? ⇒ Boolean
:nodoc:
191 192 193 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 191 def supports_bulk_alter? #:nodoc: true end |
#supports_datetime_with_precision? ⇒ Boolean
221 222 223 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 221 def supports_datetime_with_precision? version >= '5.6.4' end |
#supports_foreign_keys? ⇒ Boolean
213 214 215 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 213 def supports_foreign_keys? true end |
#supports_index_sort_order? ⇒ Boolean
Technically MySQL allows to create indexes with the sort order syntax but at the moment (5.5) it doesn’t yet implement them
197 198 199 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 197 def supports_index_sort_order? true end |
#supports_indexes_in_create? ⇒ Boolean
209 210 211 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 209 def supports_indexes_in_create? true end |
#supports_migrations? ⇒ Boolean
Returns true, since this connection adapter supports migrations.
183 184 185 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 183 def supports_migrations? true end |
#supports_primary_key? ⇒ Boolean
187 188 189 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 187 def supports_primary_key? true end |
#supports_transaction_isolation? ⇒ Boolean
MySQL 4 technically support transaction isolation, but it is affected by a bug where the transaction level gets persisted for the whole session:
205 206 207 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 205 def supports_transaction_isolation? version >= '5.0.0' end |
#supports_views? ⇒ Boolean
217 218 219 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 217 def supports_views? version >= '5.0.0' end |
#table_exists?(name) ⇒ Boolean Also known as: data_source_exists?
420 421 422 423 424 425 426 427 428 429 430 431 432 433 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 420 def table_exists?(name) return false unless name.present? return true if tables(nil, nil, name).any? name = name.to_s schema, table = name.split('.', 2) unless table # A table was provided without a schema table = schema schema = nil end tables(nil, schema, table).any? end |
#tables(name = nil, database = nil, like = nil) ⇒ Object Also known as: data_sources
:nodoc:
405 406 407 408 409 410 411 412 413 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 405 def tables(name = nil, database = nil, like = nil) #:nodoc: sql = "SHOW TABLES " sql << "IN #{quote_table_name(database)} " if database sql << "LIKE #{quote(like)}" if like execute_and_free(sql, 'SCHEMA') do |result| result.collect { |field| field.first } end end |
#truncate(table_name, name = nil) ⇒ Object
416 417 418 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 416 def truncate(table_name, name = nil) execute "TRUNCATE TABLE #{quote_table_name(table_name)}", name end |
#type_to_sql(type, limit = nil, precision = nil, scale = nil) ⇒ Object
Maps logical Rails types to MySQL-specific data types.
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 603 604 605 606 607 608 609 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 573 def type_to_sql(type, limit = nil, precision = nil, scale = nil) case type.to_s when 'binary' case limit when 0..0xfff; "varbinary(#{limit})" when nil; "blob" when 0x1000..0xffffffff; "blob(#{limit})" else raise(ActiveRecordError, "No binary type has character length #{limit}") end when 'integer' case limit when 1; 'tinyint' when 2; 'smallint' when 3; 'mediumint' when nil, 4, 11; 'int(11)' # compatibility with MySQL default when 5..8; 'bigint' else raise(ActiveRecordError, "No integer type has byte size #{limit}") end when 'text' case limit when 0..0xff; 'tinytext' when nil, 0x100..0xffff; 'text' when 0x10000..0xffffff; 'mediumtext' when 0x1000000..0xffffffff; 'longtext' else raise(ActiveRecordError, "No text type has character length #{limit}") end when 'datetime' return super unless precision case precision when 0..6; "datetime(#{precision})" else raise(ActiveRecordError, "No datetime type has precision of #{precision}. The allowed range of precision is from 0 to 6.") end else super end end |
#unquoted_false ⇒ Object
281 282 283 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 281 def unquoted_false 0 end |
#unquoted_true ⇒ Object
273 274 275 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 273 def unquoted_true 1 end |
#update_sql(sql, name = nil) ⇒ Object
:nodoc:
319 320 321 322 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 319 def update_sql(sql, name = nil) #:nodoc: super @connection.affected_rows end |
#valid_type?(type) ⇒ Boolean
678 679 680 |
# File 'lib/active_record/connection_adapters/abstract_mysql_adapter.rb', line 678 def valid_type?(type) !native_database_types[type].nil? end |