# File lib/sequel/adapters/shared/mysql.rb 481 def primary_key_from_schema(table) 482 schema(table).select{|a| a[1][:primary_key]}.map{|a| a[0]} 483 end
module Sequel::MySQL::DatabaseMethods
Constants
- CAST_TYPES
- COLUMN_DEFINITION_ORDER
- DATABASE_ERROR_REGEXPS
Attributes
Set the default charset used for CREATE TABLE. You can pass the :charset option to create_table to override this setting.
Set the default collation used for CREATE TABLE. You can pass the :collate option to create_table to override this setting.
Set the default engine used for CREATE TABLE. You can pass the :engine option to create_table to override this setting.
Public Instance Methods
MySQL's cast rules are restrictive in that you can't just cast to any possible database type.
# File lib/sequel/adapters/shared/mysql.rb 38 def cast_type_literal(type) 39 CAST_TYPES[type] || super 40 end
# File lib/sequel/adapters/shared/mysql.rb 42 def commit_prepared_transaction(transaction_id, opts=OPTS) 43 run("XA COMMIT #{literal(transaction_id)}", opts) 44 end
# File lib/sequel/adapters/shared/mysql.rb 46 def database_type 47 :mysql 48 end
Use the Information Schema's KEY_COLUMN_USAGE table to get basic information on foreign key columns, but include the constraint name.
# File lib/sequel/adapters/shared/mysql.rb 53 def foreign_key_list(table, opts=OPTS) 54 m = output_identifier_meth 55 im = input_identifier_meth 56 ds = metadata_dataset. 57 from(Sequel[:INFORMATION_SCHEMA][:KEY_COLUMN_USAGE]). 58 where(:TABLE_NAME=>im.call(table), :TABLE_SCHEMA=>Sequel.function(:DATABASE)). 59 exclude(:CONSTRAINT_NAME=>'PRIMARY'). 60 exclude(:REFERENCED_TABLE_NAME=>nil). 61 order(:CONSTRAINT_NAME, :POSITION_IN_UNIQUE_CONSTRAINT). 62 select(Sequel[:CONSTRAINT_NAME].as(:name), Sequel[:COLUMN_NAME].as(:column), Sequel[:REFERENCED_TABLE_NAME].as(:table), Sequel[:REFERENCED_COLUMN_NAME].as(:key)) 63 64 h = {} 65 ds.each do |row| 66 if r = h[row[:name]] 67 r[:columns] << m.call(row[:column]) 68 r[:key] << m.call(row[:key]) 69 else 70 h[row[:name]] = {:name=>m.call(row[:name]), :columns=>[m.call(row[:column])], :table=>m.call(row[:table]), :key=>[m.call(row[:key])]} 71 end 72 end 73 h.values 74 end
# File lib/sequel/adapters/shared/mysql.rb 76 def freeze 77 server_version 78 mariadb? 79 supports_timestamp_usecs? 80 super 81 end
MySQL
namespaces indexes per table.
# File lib/sequel/adapters/shared/mysql.rb 84 def global_index_namespace? 85 false 86 end
Use SHOW INDEX FROM to get the index information for the table.
By default partial indexes are not included, you can use the option :partial to override this.
# File lib/sequel/adapters/shared/mysql.rb 93 def indexes(table, opts=OPTS) 94 indexes = {} 95 remove_indexes = [] 96 m = output_identifier_meth 97 schema, table = schema_and_table(table) 98 99 table = Sequel::SQL::Identifier.new(table) 100 sql = "SHOW INDEX FROM #{literal(table)}" 101 if schema 102 schema = Sequel::SQL::Identifier.new(schema) 103 sql += " FROM #{literal(schema)}" 104 end 105 106 metadata_dataset.with_sql(sql).each do |r| 107 name = r[:Key_name] 108 next if name == 'PRIMARY' 109 name = m.call(name) 110 remove_indexes << name if r[:Sub_part] && ! opts[:partial] 111 i = indexes[name] ||= {:columns=>[], :unique=>r[:Non_unique] != 1} 112 i[:columns] << m.call(r[:Column_name]) 113 end 114 indexes.reject{|k,v| remove_indexes.include?(k)} 115 end
Whether the database is MariaDB and not MySQL
# File lib/sequel/adapters/shared/mysql.rb 122 def mariadb? 123 return @is_mariadb if defined?(@is_mariadb) 124 @is_mariadb = !(fetch('SELECT version()').single_value! !~ /mariadb/i) 125 end
Renames multiple tables in a single call.
DB.rename_tables [:items, :old_items], [:other_items, :old_other_items] # RENAME TABLE items TO old_items, other_items TO old_other_items
# File lib/sequel/adapters/shared/mysql.rb 195 def rename_tables(*renames) 196 execute_ddl(rename_tables_sql(renames)) 197 renames.each{|from,| remove_cached_schema(from)} 198 end
# File lib/sequel/adapters/shared/mysql.rb 117 def rollback_prepared_transaction(transaction_id, opts=OPTS) 118 run("XA ROLLBACK #{literal(transaction_id)}", opts) 119 end
Get version of MySQL
server, used for determined capabilities.
# File lib/sequel/adapters/shared/mysql.rb 128 def server_version 129 @server_version ||= begin 130 m = /(\d+)\.(\d+)\.(\d+)/.match(fetch('SELECT version()').single_value!) 131 (m[1].to_i * 10000) + (m[2].to_i * 100) + m[3].to_i 132 end 133 end
MySQL
supports CREATE TABLE IF NOT EXISTS syntax.
# File lib/sequel/adapters/shared/mysql.rb 136 def supports_create_table_if_not_exists? 137 true 138 end
Generated columns are supported in MariaDB 5.2.0+ and MySQL
5.7.6+.
# File lib/sequel/adapters/shared/mysql.rb 141 def supports_generated_columns? 142 server_version >= (mariadb? ? 50200 : 50706) 143 end
MySQL
5+ supports prepared transactions (two-phase commit) using XA
# File lib/sequel/adapters/shared/mysql.rb 146 def supports_prepared_transactions? 147 server_version >= 50000 148 end
MySQL
5+ supports savepoints
# File lib/sequel/adapters/shared/mysql.rb 151 def supports_savepoints? 152 server_version >= 50000 153 end
MySQL
doesn't support savepoints inside prepared transactions in from 5.5.12 to 5.5.23, see bugs.mysql.com/bug.php?id=64374
# File lib/sequel/adapters/shared/mysql.rb 157 def supports_savepoints_in_prepared_transactions? 158 super && (server_version <= 50512 || server_version >= 50523) 159 end
Support fractional timestamps on MySQL
5.6.5+ if the :fractional_seconds Database
option is used. Technically, MySQL
5.6.4+ supports them, but automatic initialization of datetime values wasn't supported to 5.6.5+, and this is related to that.
# File lib/sequel/adapters/shared/mysql.rb 165 def supports_timestamp_usecs? 166 return @supports_timestamp_usecs if defined?(@supports_timestamp_usecs) 167 @supports_timestamp_usecs = server_version >= 50605 && typecast_value_boolean(opts[:fractional_seconds]) 168 end
MySQL
supports transaction isolation levels
# File lib/sequel/adapters/shared/mysql.rb 171 def supports_transaction_isolation_levels? 172 true 173 end
Return an array of symbols specifying table names in the current database.
Options:
- :server
-
Set the server to use
# File lib/sequel/adapters/shared/mysql.rb 179 def tables(opts=OPTS) 180 full_tables('BASE TABLE', opts) 181 end
Return an array of symbols specifying view names in the current database.
Options:
- :server
-
Set the server to use
# File lib/sequel/adapters/shared/mysql.rb 187 def views(opts=OPTS) 188 full_tables('VIEW', opts) 189 end
Private Instance Methods
# File lib/sequel/adapters/shared/mysql.rb 202 def alter_table_add_column_sql(table, op) 203 pos = if after_col = op[:after] 204 " AFTER #{quote_identifier(after_col)}" 205 elsif op[:first] 206 " FIRST" 207 end 208 209 sql = if related = op.delete(:table) 210 sql = super + "#{pos}, ADD " 211 op[:table] = related 212 op[:key] ||= primary_key_from_schema(related) 213 if constraint_name = op.delete(:foreign_key_constraint_name) 214 sql << "CONSTRAINT #{quote_identifier(constraint_name)} " 215 end 216 sql << "FOREIGN KEY (#{quote_identifier(op[:name])})#{column_references_sql(op)}" 217 else 218 "#{super}#{pos}" 219 end 220 end
# File lib/sequel/adapters/shared/mysql.rb 257 def alter_table_add_constraint_sql(table, op) 258 if op[:type] == :foreign_key 259 op[:key] ||= primary_key_from_schema(op[:table]) 260 end 261 super 262 end
# File lib/sequel/adapters/shared/mysql.rb 222 def alter_table_change_column_sql(table, op) 223 o = op[:op] 224 opts = schema(table).find{|x| x.first == op[:name]} 225 opts = opts ? opts.last.dup : {} 226 opts[:name] = o == :rename_column ? op[:new_name] : op[:name] 227 opts[:type] = o == :set_column_type ? op[:type] : opts[:db_type] 228 opts[:null] = o == :set_column_null ? op[:null] : opts[:allow_null] 229 opts[:default] = o == :set_column_default ? op[:default] : opts[:ruby_default] 230 opts.delete(:default) if opts[:default] == nil 231 opts.delete(:primary_key) 232 unless op[:type] || opts[:type] 233 raise Error, "cannot determine database type to use for CHANGE COLUMN operation" 234 end 235 opts = op.merge(opts) 236 if op.has_key?(:auto_increment) 237 opts[:auto_increment] = op[:auto_increment] 238 end 239 "CHANGE COLUMN #{quote_identifier(op[:name])} #{column_definition_sql(opts)}" 240 end
# File lib/sequel/adapters/shared/mysql.rb 264 def alter_table_drop_constraint_sql(table, op) 265 case op[:type] 266 when :primary_key 267 "DROP PRIMARY KEY" 268 when :foreign_key 269 name = op[:name] || foreign_key_name(table, op[:columns]) 270 "DROP FOREIGN KEY #{quote_identifier(name)}" 271 when :unique 272 "DROP INDEX #{quote_identifier(op[:name])}" 273 when :check, nil 274 if supports_check_constraints? 275 "DROP CONSTRAINT #{quote_identifier(op[:name])}" 276 end 277 end 278 end
# File lib/sequel/adapters/shared/mysql.rb 245 def alter_table_set_column_default_sql(table, op) 246 return super unless op[:default].nil? 247 248 opts = schema(table).find{|x| x[0] == op[:name]} 249 250 if opts && opts[1][:allow_null] == false 251 "ALTER COLUMN #{quote_identifier(op[:name])} DROP DEFAULT" 252 else 253 super 254 end 255 end
# File lib/sequel/adapters/shared/mysql.rb 280 def alter_table_sql(table, op) 281 case op[:op] 282 when :drop_index 283 "#{drop_index_sql(table, op)} ON #{quote_schema_table(table)}" 284 when :drop_constraint 285 if op[:type] == :primary_key 286 if (pk = primary_key_from_schema(table)).length == 1 287 return [alter_table_sql(table, {:op=>:rename_column, :name=>pk.first, :new_name=>pk.first, :auto_increment=>false}), super] 288 end 289 end 290 super 291 else 292 super 293 end 294 end
# File lib/sequel/adapters/shared/mysql.rb 339 def auto_increment_sql 340 'AUTO_INCREMENT' 341 end
MySQL
needs to set transaction isolation before begining a transaction
# File lib/sequel/adapters/shared/mysql.rb 344 def begin_new_transaction(conn, opts) 345 set_transaction_isolation(conn, opts) 346 log_connection_execute(conn, begin_transaction_sql) 347 end
Use XA START to start a new prepared transaction if the :prepare option is given.
# File lib/sequel/adapters/shared/mysql.rb 351 def begin_transaction(conn, opts=OPTS) 352 if (s = opts[:prepare]) && savepoint_level(conn) == 1 353 log_connection_execute(conn, "XA START #{literal(s)}") 354 else 355 super 356 end 357 end
Add generation clause SQL
fragment to column creation SQL
.
# File lib/sequel/adapters/shared/mysql.rb 360 def column_definition_generated_sql(sql, column) 361 if (generated_expression = column[:generated_always_as]) 362 sql << " GENERATED ALWAYS AS (#{literal(generated_expression)})" 363 case (type = column[:generated_type]) 364 when nil 365 # none, database default 366 when :virtual 367 sql << " VIRTUAL" 368 when :stored 369 sql << (mariadb? ? " PERSISTENT" : " STORED") 370 else 371 raise Error, "unsupported :generated_type option: #{type.inspect}" 372 end 373 end 374 end
# File lib/sequel/adapters/shared/mysql.rb 376 def column_definition_order 377 COLUMN_DEFINITION_ORDER 378 end
MySQL
doesn't allow default values on text columns, so ignore if it the generic text type is used
# File lib/sequel/adapters/shared/mysql.rb 382 def column_definition_sql(column) 383 column.delete(:default) if column[:type] == File || (column[:type] == String && column[:text] == true) 384 super 385 end
Handle MySQL
specific default format.
# File lib/sequel/adapters/shared/mysql.rb 297 def column_schema_normalize_default(default, type) 298 if column_schema_default_string_type?(type) 299 return if [:date, :datetime, :time].include?(type) && /\ACURRENT_(?:DATE|TIMESTAMP)?\z/.match(default) 300 default = "'#{default.gsub("'", "''").gsub('\\', '\\\\')}'" 301 end 302 super(default, type) 303 end
# File lib/sequel/adapters/shared/mysql.rb 305 def column_schema_to_ruby_default(default, type) 306 return Sequel::CURRENT_DATE if mariadb? && server_version >= 100200 && default == 'curdate()' 307 super 308 end
Don't allow combining adding foreign key operations with other operations, since in some cases adding a foreign key constraint in the same query as other operations results in MySQL
error 150.
# File lib/sequel/adapters/shared/mysql.rb 313 def combinable_alter_table_op?(op) 314 super && !(op[:op] == :add_constraint && op[:type] == :foreign_key) && !(op[:op] == :drop_constraint && op[:type] == :primary_key) 315 end
Prepare the XA transaction for a two-phase commit if the :prepare option is given.
# File lib/sequel/adapters/shared/mysql.rb 389 def commit_transaction(conn, opts=OPTS) 390 if (s = opts[:prepare]) && savepoint_level(conn) <= 1 391 log_connection_execute(conn, "XA END #{literal(s)}") 392 log_connection_execute(conn, "XA PREPARE #{literal(s)}") 393 else 394 super 395 end 396 end
Use MySQL
specific syntax for engine type and character encoding
# File lib/sequel/adapters/shared/mysql.rb 399 def create_table_sql(name, generator, options = OPTS) 400 engine = options.fetch(:engine, default_engine) 401 charset = options.fetch(:charset, default_charset) 402 collate = options.fetch(:collate, default_collate) 403 generator.constraints.sort_by{|c| (c[:type] == :primary_key) ? -1 : 1} 404 405 # Proc for figuring out the primary key for a given table. 406 key_proc = lambda do |t| 407 if t == name 408 if pk = generator.primary_key_name 409 [pk] 410 elsif !(pkc = generator.constraints.select{|con| con[:type] == :primary_key}).empty? 411 pkc.first[:columns] 412 elsif !(pkc = generator.columns.select{|con| con[:primary_key] == true}).empty? 413 pkc.map{|c| c[:name]} 414 end 415 else 416 primary_key_from_schema(t) 417 end 418 end 419 420 # Manually set the keys, since MySQL requires one, it doesn't use the primary 421 # key if none are specified. 422 generator.constraints.each do |c| 423 if c[:type] == :foreign_key 424 c[:key] ||= key_proc.call(c[:table]) 425 end 426 end 427 428 # Split column constraints into table constraints in some cases: 429 # foreign key - Always 430 # unique, primary_key - Only if constraint has a name 431 generator.columns.each do |c| 432 if t = c.delete(:table) 433 same_table = t == name 434 key = c[:key] || key_proc.call(t) 435 436 if same_table && !key.nil? 437 generator.constraints.unshift(:type=>:unique, :columns=>Array(key)) 438 end 439 440 generator.foreign_key([c[:name]], t, c.merge(:name=>c[:foreign_key_constraint_name], :type=>:foreign_key, :key=>key)) 441 end 442 end 443 444 "#{super}#{" ENGINE=#{engine}" if engine}#{" DEFAULT CHARSET=#{charset}" if charset}#{" DEFAULT COLLATE=#{collate}" if collate}" 445 end
# File lib/sequel/adapters/shared/mysql.rb 455 def database_error_regexps 456 DATABASE_ERROR_REGEXPS 457 end
Backbone of the tables and views support using SHOW FULL TABLES.
# File lib/sequel/adapters/shared/mysql.rb 460 def full_tables(type, opts) 461 m = output_identifier_meth 462 metadata_dataset.with_sql('SHOW FULL TABLES').server(opts[:server]).map{|r| m.call(r.values.first) if r.delete(:Table_type) == type}.compact 463 end
# File lib/sequel/adapters/shared/mysql.rb 465 def index_definition_sql(table_name, index) 466 index_name = quote_identifier(index[:name] || default_index_name(table_name, index[:columns])) 467 raise Error, "Partial indexes are not supported for this database" if index[:where] && !supports_partial_indexes? 468 index_type = case index[:type] 469 when :full_text 470 "FULLTEXT " 471 when :spatial 472 "SPATIAL " 473 else 474 using = " USING #{index[:type]}" unless index[:type] == nil 475 "UNIQUE " if index[:unique] 476 end 477 "CREATE #{index_type}INDEX #{index_name}#{using} ON #{quote_schema_table(table_name)} #{literal(index[:columns])}" 478 end
The SQL
queries to execute on initial connection
# File lib/sequel/adapters/shared/mysql.rb 318 def mysql_connection_setting_sqls 319 sqls = [] 320 321 if wait_timeout = opts.fetch(:timeout, 2147483) 322 # Increase timeout so mysql server doesn't disconnect us 323 # Value used by default is maximum allowed value on Windows. 324 sqls << "SET @@wait_timeout = #{wait_timeout}" 325 end 326 327 # By default, MySQL 'where id is null' selects the last inserted id 328 sqls << "SET SQL_AUTO_IS_NULL=0" unless opts[:auto_is_null] 329 330 # If the user has specified one or more sql modes, enable them 331 if sql_mode = opts[:sql_mode] 332 sql_mode = Array(sql_mode).join(',').upcase 333 sqls << "SET sql_mode = '#{sql_mode}'" 334 end 335 336 sqls 337 end
Parse the schema for the given table to get an array of primary key columns
SQL
statement for renaming multiple tables.
# File lib/sequel/adapters/shared/mysql.rb 486 def rename_tables_sql(renames) 487 rename_tos = renames.map do |from, to| 488 "#{quote_schema_table(from)} TO #{quote_schema_table(to)}" 489 end.join(', ') 490 "RENAME TABLE #{rename_tos}" 491 end
Rollback the currently open XA transaction
# File lib/sequel/adapters/shared/mysql.rb 494 def rollback_transaction(conn, opts=OPTS) 495 if (s = opts[:prepare]) && savepoint_level(conn) <= 1 496 log_connection_execute(conn, "XA END #{literal(s)}") 497 log_connection_execute(conn, "XA PREPARE #{literal(s)}") 498 log_connection_execute(conn, "XA ROLLBACK #{literal(s)}") 499 else 500 super 501 end 502 end
# File lib/sequel/adapters/shared/mysql.rb 504 def schema_column_type(db_type) 505 case db_type 506 when /\Aset/io 507 :set 508 when /\Amediumint/io 509 :integer 510 when /\Amediumtext/io 511 :string 512 else 513 super 514 end 515 end
Use the MySQL
specific DESCRIBE syntax to get a table description.
# File lib/sequel/adapters/shared/mysql.rb 518 def schema_parse_table(table_name, opts) 519 m = output_identifier_meth(opts[:dataset]) 520 im = input_identifier_meth(opts[:dataset]) 521 table = SQL::Identifier.new(im.call(table_name)) 522 table = SQL::QualifiedIdentifier.new(im.call(opts[:schema]), table) if opts[:schema] 523 metadata_dataset.with_sql("DESCRIBE ?", table).map do |row| 524 extra = row.delete(:Extra) 525 if row[:primary_key] = row.delete(:Key) == 'PRI' 526 row[:auto_increment] = !!(extra.to_s =~ /auto_increment/i) 527 end 528 if supports_generated_columns? 529 # Extra field contains VIRTUAL or PERSISTENT for generated columns 530 row[:generated] = !!(extra.to_s =~ /VIRTUAL|STORED|PERSISTENT/i) 531 end 532 row[:allow_null] = row.delete(:Null) == 'YES' 533 row[:default] = row.delete(:Default) 534 row[:db_type] = row.delete(:Type) 535 row[:type] = schema_column_type(row[:db_type]) 536 [m.call(row.delete(:Field)), row] 537 end 538 end
Split DROP INDEX ops on MySQL
5.6+, as dropping them in the same statement as dropping a related foreign key causes an error.
# File lib/sequel/adapters/shared/mysql.rb 542 def split_alter_table_op?(op) 543 server_version >= 50600 && (op[:op] == :drop_index || (op[:op] == :drop_constraint && op[:type] == :unique)) 544 end
Whether the database supports CHECK constraints
# File lib/sequel/adapters/shared/mysql.rb 547 def supports_check_constraints? 548 mariadb? && server_version >= 100200 549 end
MySQL
can combine multiple alter table ops into a single query.
# File lib/sequel/adapters/shared/mysql.rb 552 def supports_combining_alter_table_ops? 553 true 554 end
MySQL
supports CREATE OR REPLACE VIEW.
# File lib/sequel/adapters/shared/mysql.rb 557 def supports_create_or_replace_view? 558 true 559 end
MySQL
does not support named column constraints.
# File lib/sequel/adapters/shared/mysql.rb 562 def supports_named_column_constraints? 563 false 564 end
MySQL
has both datetime and timestamp classes, most people are going to want datetime
# File lib/sequel/adapters/shared/mysql.rb 584 def type_literal_generic_datetime(column) 585 if supports_timestamp_usecs? 586 :'datetime(6)' 587 elsif column[:default] == Sequel::CURRENT_TIMESTAMP 588 :timestamp 589 else 590 :datetime 591 end 592 end
Respect the :size option if given to produce tinyblob, mediumblob, and longblob if :tiny, :medium, or :long is given.
# File lib/sequel/adapters/shared/mysql.rb 569 def type_literal_generic_file(column) 570 case column[:size] 571 when :tiny # < 2^8 bytes 572 :tinyblob 573 when :medium # < 2^24 bytes 574 :mediumblob 575 when :long # < 2^32 bytes 576 :longblob 577 else # 2^16 bytes 578 :blob 579 end 580 end
MySQL
has both datetime and timestamp classes, most people are going to want datetime.
# File lib/sequel/adapters/shared/mysql.rb 596 def type_literal_generic_only_time(column) 597 if supports_timestamp_usecs? 598 :'time(6)' 599 else 600 :time 601 end 602 end
MySQL
doesn't have a true boolean class, so it uses tinyint(1)
# File lib/sequel/adapters/shared/mysql.rb 605 def type_literal_generic_trueclass(column) 606 :'tinyint(1)' 607 end
MySQL
5.0.2+ supports views with check option.
# File lib/sequel/adapters/shared/mysql.rb 610 def view_with_check_option_support 611 :local if server_version >= 50002 612 end