Class: ActiveRecord::ConnectionAdapters::MysqlAdapter

Inherits:
AbstractAdapter show all
Defined in:
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.

  • :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

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"
]

Instance Method Summary collapse

Methods inherited from AbstractAdapter

#clear_query_cache

Constructor Details

#initialize(connection, logger, connection_options = nil) ⇒ MysqlAdapter

Returns a new instance of MysqlAdapter.



87
88
89
90
# File 'lib/active_record/connection_adapters/mysql_adapter.rb', line 87

def initialize(connection, logger, connection_options=nil)
  super(connection, logger)
  @connection_options = connection_options
end

Instance Method Details

#adapter_nameObject



92
93
94
# File 'lib/active_record/connection_adapters/mysql_adapter.rb', line 92

def adapter_name
  'MySQL'
end

#add_limit_offset!(sql, options) ⇒ Object



179
180
181
182
183
184
185
186
187
# File 'lib/active_record/connection_adapters/mysql_adapter.rb', line 179

def add_limit_offset!(sql, options)
  if options[:limit]
    if options[:offset].blank?
      sql << " LIMIT #{options[:limit]}"
    else
      sql << " LIMIT #{options[:offset]}, #{options[:limit]}"
    end
  end
end

#begin_db_transactionObject



145
146
147
148
149
# File 'lib/active_record/connection_adapters/mysql_adapter.rb', line 145

def begin_db_transaction
  execute "BEGIN"
rescue Exception
  # Transactions aren't supported
end

#change_column(table_name, column_name, type, options = {}) ⇒ Object



208
209
210
211
212
213
214
# File 'lib/active_record/connection_adapters/mysql_adapter.rb', line 208

def change_column(table_name, column_name, type, options = {})
  options[:default] ||= select_one("SHOW COLUMNS FROM #{table_name} LIKE '#{column_name}'")["Default"]
  
  change_column_sql = "ALTER TABLE #{table_name} CHANGE #{column_name} #{column_name} #{type_to_sql(type, options[:limit])}"
  add_column_options!(change_column_sql, options)
  execute(change_column_sql)
end

#change_column_default(table_name, column_name, default) ⇒ Object



202
203
204
205
206
# File 'lib/active_record/connection_adapters/mysql_adapter.rb', line 202

def change_column_default(table_name, column_name, default)
  current_type = select_one("SHOW COLUMNS FROM #{table_name} LIKE '#{column_name}'")["Type"]

  change_column(table_name, column_name, current_type, { :default => default })
end

#columns(table_name, name = nil) ⇒ Object



105
106
107
108
109
110
# File 'lib/active_record/connection_adapters/mysql_adapter.rb', line 105

def columns(table_name, name = nil)
  sql = "SHOW FIELDS FROM #{table_name}"
  columns = []
  execute(sql, name).each { |field| columns << Column.new(field[0], field[4], field[1]) }
  columns
end

#commit_db_transactionObject



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

def commit_db_transaction
  execute "COMMIT"
rescue Exception
  # Transactions aren't supported
end

#create_database(name) ⇒ Object



198
199
200
# File 'lib/active_record/connection_adapters/mysql_adapter.rb', line 198

def create_database(name)
  execute "CREATE DATABASE #{name}"
end

#create_table(name, options = {}) ⇒ Object



221
222
223
# File 'lib/active_record/connection_adapters/mysql_adapter.rb', line 221

def create_table(name, options = {})
  super(name, {:options => "ENGINE=InnoDB"}.merge(options))
end

#drop_database(name) ⇒ Object



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

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

#execute(sql, name = nil, retries = 2) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/active_record/connection_adapters/mysql_adapter.rb', line 117

def execute(sql, name = nil, retries = 2)
  unless @logger
    @connection.query(sql)
  else
    log(sql, name) { @connection.query(sql) }
  end
rescue ActiveRecord::StatementInvalid => exception
  if LOST_CONNECTION_ERROR_MESSAGES.any? { |msg| exception.message.split(":").first =~ /^#{msg}/ }
    @connection.real_connect(*@connection_options)
    unless @logger
      @connection.query(sql)
    else
      @logger.info "Retrying invalid statement with reopened connection"
      log(sql, name) { @connection.query(sql) }
    end
  else
    raise
  end
end

#insert(sql, name = nil, pk = nil, id_value = nil) ⇒ Object



112
113
114
115
# File 'lib/active_record/connection_adapters/mysql_adapter.rb', line 112

def insert(sql, name = nil, pk = nil, id_value = nil)
  execute(sql, name = nil)
  id_value || @connection.insert_id
end

#native_database_typesObject



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/active_record/connection_adapters/mysql_adapter.rb', line 71

def native_database_types
  {
    :primary_key => "int(11) DEFAULT NULL auto_increment PRIMARY KEY",
    :string      => { :name => "varchar", :limit => 255 },
    :text        => { :name => "text" },
    :integer     => { :name => "int", :limit => 11 },
    :float       => { :name => "float" },
    :datetime    => { :name => "datetime" },
    :timestamp   => { :name => "datetime" },
    :time        => { :name => "datetime" },
    :date        => { :name => "date" },
    :binary      => { :name => "blob" },
    :boolean     => { :name => "tinyint", :limit => 1 }
  }
end

#quote_column_name(name) ⇒ Object



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

def quote_column_name(name)
  "`#{name}`"
end

#quote_string(string) ⇒ Object



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

def quote_string(string)
  Mysql::quote(string)
end

#recreate_database(name) ⇒ Object



189
190
191
192
# File 'lib/active_record/connection_adapters/mysql_adapter.rb', line 189

def recreate_database(name)
  drop_database(name)
  create_database(name)
end

#rename_column(table_name, column_name, new_column_name) ⇒ Object



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

def rename_column(table_name, column_name, new_column_name)
  current_type = select_one("SHOW COLUMNS FROM #{table_name} LIKE '#{column_name}'")["Type"]
  execute "ALTER TABLE #{table_name} CHANGE #{column_name} #{new_column_name} #{current_type}"
end

#rollback_db_transactionObject



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

def rollback_db_transaction
  execute "ROLLBACK"
rescue Exception
  # Transactions aren't supported
end

#select_all(sql, name = nil) ⇒ Object



96
97
98
# File 'lib/active_record/connection_adapters/mysql_adapter.rb', line 96

def select_all(sql, name = nil)
  select(sql, name)
end

#select_one(sql, name = nil) ⇒ Object



100
101
102
103
# File 'lib/active_record/connection_adapters/mysql_adapter.rb', line 100

def select_one(sql, name = nil)
  result = select(sql, name)
  result.nil? ? nil : result.first
end

#structure_dumpObject



173
174
175
176
177
# File 'lib/active_record/connection_adapters/mysql_adapter.rb', line 173

def structure_dump
  select_all("SHOW TABLES").inject("") do |structure, table|
    structure += select_one("SHOW CREATE TABLE #{table.to_a.first.last}")["Create Table"] + ";\n\n"
  end
end

#supports_migrations?Boolean

Returns:

  • (Boolean)


67
68
69
# File 'lib/active_record/connection_adapters/mysql_adapter.rb', line 67

def supports_migrations?
  true
end

#update(sql, name = nil) ⇒ Object Also known as: delete



137
138
139
140
# File 'lib/active_record/connection_adapters/mysql_adapter.rb', line 137

def update(sql, name = nil)
  execute(sql, name)
  @connection.affected_rows
end