Class: ActiveRecord::ConnectionAdapters::MysqlAdapter

Inherits:
AbstractMysqlAdapter show all
Defined in:
activerecord/lib/active_record/connection_adapters/mysql_adapter.rb

Overview

The MySQL adapter will work with both Ruby/MySQL, which is a Ruby-based MySQL adapter that comes bundled with Active Record, and with the faster C-based MySQL/Ruby adapter (available both as a gem and from www.tmtm.org/en/mysql/ruby/).

Options:

  • :host - Defaults to “localhost”.

  • :port - Defaults to 3306.

  • :socket - Defaults to “/tmp/mysql.sock”.

  • :username - Defaults to “root”

  • :password - Defaults to nothing.

  • :database - The name of the database. No default, must be provided.

  • :encoding - (Optional) Sets the client encoding by executing “SET NAMES <encoding>” after connection.

  • :reconnect - Defaults to false (See MySQL documentation: dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html).

  • :sslca - Necessary to use MySQL with an SSL connection.

  • :sslkey - Necessary to use MySQL with an SSL connection.

  • :sslcert - Necessary to use MySQL with an SSL connection.

  • :sslcapath - Necessary to use MySQL with an SSL connection.

  • :sslcipher - Necessary to use MySQL with an SSL connection.

Defined Under Namespace

Classes: Column, StatementPool

Constant Summary collapse

ADAPTER_NAME =
'MySQL'
ENCODINGS =

Taken from here:

https://github.com/tmtm/ruby-mysql/blob/master/lib/mysql/charset.rb

Author: TOMITA Masahiro <[email protected]>

Hash.new { |h,k| h[k] = k }

Constants inherited from AbstractMysqlAdapter

AbstractMysqlAdapter::LOST_CONNECTION_ERROR_MESSAGES, AbstractMysqlAdapter::NATIVE_DATABASE_TYPES

Instance Attribute Summary

Attributes inherited from AbstractAdapter

#in_use, #last_use, #logger, #open_transactions, #pool, #schema_cache, #visitor

Attributes included from QueryCache

#query_cache, #query_cache_enabled

Instance Method Summary collapse

Methods inherited from AbstractMysqlAdapter

#adapter_name, #add_column, #add_column_position!, #bulk_change_table, #case_insensitive_comparison, #case_sensitive_modifier, #change_column, #change_column_default, #change_column_null, #charset, #collation, #columns, #commit_db_transaction, #create_database, #create_savepoint, #create_table, #current_database, #disable_referential_integrity, #drop_database, #emulate_booleans, #execute, #indexes, #join_to_update, #limited_update_conditions, #native_database_types, #pk_and_sequence_for, #primary_key, #quote, #quote_column_name, #quote_table_name, #quoted_false, #quoted_true, #recreate_database, #release_savepoint, #rename_column, #rename_table, #rollback_db_transaction, #rollback_to_savepoint, #show_variable, #structure_dump, #supports_bulk_alter?, #supports_index_sort_order?, #supports_migrations?, #supports_primary_key?, #supports_savepoints?, #table_exists?, #tables, #type_to_sql, #update_sql

Methods inherited from AbstractAdapter

#adapter_name, #case_insensitive_comparison, #case_sensitive_modifier, #close, #create_savepoint, #current_savepoint_name, #decrement_open_transactions, #disable_referential_integrity, #expire, #increment_open_transactions, #lease, #prefetch_primary_key?, #quote_table_name, #raw_connection, #release_savepoint, #requires_reloading?, #rollback_to_savepoint, #substitute_at, #supports_bulk_alter?, #supports_count_distinct?, #supports_ddl_transactions?, #supports_explain?, #supports_index_sort_order?, #supports_migrations?, #supports_primary_key?, #supports_savepoints?, #transaction_joinable=, #verify!

Methods included from ActiveSupport::Callbacks

#run_callbacks

Methods included from ActiveSupport::Concern

#append_features, extended, #included

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

#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_column_name, #quote_table_name, #quoted_date, #quoted_false, #quoted_true

Methods included from DatabaseStatements

#add_transaction_record, #case_sensitive_equality_operator, #commit_db_transaction, #default_sequence_name, #delete, #empty_insert_statement_value, #exec_insert, #execute, #insert, #insert_fixture, #join_to_update, #limited_update_conditions, #outside_transaction?, #reset_sequence!, #rollback_db_transaction, #sanitize_limit, #select_all, #select_one, #select_value, #select_values, #to_sql, #transaction, #update

Methods included from SchemaStatements

#add_column, #add_column_options!, #add_index, #add_timestamps, #assume_migrated_upto_version, #change_column, #change_column_default, #change_table, #column_exists?, #columns, #create_table, #distinct, #drop_table, #dump_schema_information, #index_exists?, #index_name, #index_name_exists?, #initialize_schema_migrations_table, #native_database_types, #remove_column, #remove_index, #remove_index!, #remove_timestamps, #rename_column, #rename_index, #rename_table, #structure_dump, #table_alias_for, #table_exists?, #type_to_sql

Constructor Details

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

Returns a new instance of MysqlAdapter.



126
127
128
129
130
131
132
# File 'activerecord/lib/active_record/connection_adapters/mysql_adapter.rb', line 126

def initialize(connection, logger, connection_options, config)
  super
  @statements = StatementPool.new(@connection,
                                  config.fetch(:statement_limit) { 1000 })
  @client_encoding = nil
  connect
end

Instance Method Details

#active?Boolean

CONNECTION MANAGEMENT ====================================

Returns:

  • (Boolean)


175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'activerecord/lib/active_record/connection_adapters/mysql_adapter.rb', line 175

def active?
  if @connection.respond_to?(:stat)
    @connection.stat
  else
    @connection.query 'select 1'
  end

  # mysql-ruby doesn't raise an exception when stat fails.
  if @connection.respond_to?(:errno)
    @connection.errno.zero?
  else
    true
  end
rescue Mysql::Error
  false
end

#begin_db_transactionObject

:nodoc:



347
348
349
350
351
# File 'activerecord/lib/active_record/connection_adapters/mysql_adapter.rb', line 347

def begin_db_transaction #:nodoc:
  exec_query "BEGIN"
rescue Mysql::Error
  # Transactions aren't supported
end

#clear_cache!Object

Clears the prepared statements cache.



223
224
225
# File 'activerecord/lib/active_record/connection_adapters/mysql_adapter.rb', line 223

def clear_cache!
  @statements.clear
end

#client_encodingObject

Get the client encoding for this database



275
276
277
278
279
280
281
282
# File 'activerecord/lib/active_record/connection_adapters/mysql_adapter.rb', line 275

def client_encoding
  return @client_encoding if @client_encoding

  result = exec_query(
    "SHOW VARIABLES WHERE Variable_name = 'character_set_client'",
    'SCHEMA')
  @client_encoding = ENCODINGS[result.rows.last.last]
end

#disconnect!Object

Disconnects from the database if already connected. Otherwise, this method does nothing.



200
201
202
# File 'activerecord/lib/active_record/connection_adapters/mysql_adapter.rb', line 200

def disconnect!
  @connection.close rescue nil
end

#each_hash(result) ⇒ Object

HELPER METHODS ===========================================



142
143
144
145
146
147
148
149
150
151
# File 'activerecord/lib/active_record/connection_adapters/mysql_adapter.rb', line 142

def each_hash(result) # :nodoc:
  if block_given?
    result.each_hash do |row|
      row.symbolize_keys!
      yield row
    end
  else
    to_enum(:each_hash, result)
  end
end

#error_number(exception) ⇒ Object

:nodoc:



157
158
159
# File 'activerecord/lib/active_record/connection_adapters/mysql_adapter.rb', line 157

def error_number(exception) # :nodoc:
  exception.errno if exception.respond_to?(:errno)
end

#exec_delete(sql, name, binds) ⇒ Object Also known as: exec_update



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

def exec_delete(sql, name, binds)
  affected_rows = 0

  exec_query(sql, name, binds) do |n|
    affected_rows = n
  end

  affected_rows
end

#exec_query(sql, name = 'SQL', binds = []) {|affected_rows| ... } ⇒ Object

Yields:

  • (affected_rows)


284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'activerecord/lib/active_record/connection_adapters/mysql_adapter.rb', line 284

def exec_query(sql, name = 'SQL', binds = [])
  # If the configuration sets prepared_statements:false, binds will
  # always be empty, since the bind variables will have been already
  # substituted and removed from binds by BindVisitor, so this will
  # effectively disable prepared statement usage completely.
  if binds.empty?
    result_set, affected_rows = exec_without_stmt(sql, name)
  else
    result_set, affected_rows = exec_stmt(sql, name, binds)
  end

  yield affected_rows if block_given?

  result_set
end

#exec_without_stmt(sql, name = 'SQL') ⇒ Object

:nodoc:



304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'activerecord/lib/active_record/connection_adapters/mysql_adapter.rb', line 304

def exec_without_stmt(sql, name = 'SQL') # :nodoc:
  # Some queries, like SHOW CREATE TABLE don't work through the prepared
  # statement API. For those queries, we need to use this method. :'(
  log(sql, name) do
    result = @connection.query(sql)
    affected_rows = @connection.affected_rows

    if result
      cols = result.fetch_fields.map { |field| field.name }
      result_set = ActiveRecord::Result.new(cols, result.to_a)
      result.free
    else
      result_set = ActiveRecord::Result.new([], [])
    end

    [result_set, affected_rows]
  end
end

#execute_and_free(sql, name = nil) ⇒ Object



323
324
325
326
327
328
# File 'activerecord/lib/active_record/connection_adapters/mysql_adapter.rb', line 323

def execute_and_free(sql, name = nil)
  result = execute(sql, name)
  ret = yield result
  result.free
  ret
end

#insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) ⇒ Object Also known as: create

:nodoc:



330
331
332
333
# File 'activerecord/lib/active_record/connection_adapters/mysql_adapter.rb', line 330

def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #:nodoc:
  super sql, name
  id_value || @connection.insert_id
end

#last_inserted_id(result) ⇒ Object



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

def last_inserted_id(result)
  @connection.insert_id
end

#new_column(field, default, type, null, collation) ⇒ Object

:nodoc:



153
154
155
# File 'activerecord/lib/active_record/connection_adapters/mysql_adapter.rb', line 153

def new_column(field, default, type, null, collation) # :nodoc:
  Column.new(field, default, type, null, collation)
end

#quote_string(string) ⇒ Object

:nodoc:



169
170
171
# File 'activerecord/lib/active_record/connection_adapters/mysql_adapter.rb', line 169

def quote_string(string) #:nodoc:
  @connection.quote(string)
end

#reconnect!Object



192
193
194
195
196
# File 'activerecord/lib/active_record/connection_adapters/mysql_adapter.rb', line 192

def reconnect!
  disconnect!
  clear_cache!
  connect
end

#reset!Object



204
205
206
207
208
209
210
211
# File 'activerecord/lib/active_record/connection_adapters/mysql_adapter.rb', line 204

def reset!
  if @connection.respond_to?(:change_user)
    # See http://bugs.mysql.com/bug.php?id=33540 -- the workaround way to
    # reset the connection is to change the user to the same user.
    @connection.change_user(@config[:username], @config[:password], @config[:database])
    configure_connection
  end
end

#select_rows(sql, name = nil) ⇒ Object

DATABASE STATEMENTS ======================================



215
216
217
218
219
220
# File 'activerecord/lib/active_record/connection_adapters/mysql_adapter.rb', line 215

def select_rows(sql, name = nil)
  @connection.query_with_result = true
  rows = exec_query(sql, name).rows
  @connection.more_results && @connection.next_result    # invoking stored procedures with CLIENT_MULTI_RESULTS requires this to tidy up else connection will be dropped
  rows
end

#supports_statement_cache?Boolean

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

Returns:

  • (Boolean)


136
137
138
# File 'activerecord/lib/active_record/connection_adapters/mysql_adapter.rb', line 136

def supports_statement_cache?
  true
end

#type_cast(value, column) ⇒ Object

QUOTING ==================================================



163
164
165
166
167
# File 'activerecord/lib/active_record/connection_adapters/mysql_adapter.rb', line 163

def type_cast(value, column)
  return super unless value == true || value == false

  value ? 1 : 0
end