# File lib/sequel/adapters/shared/mysql.rb 493 def primary_key_from_schema(table) 494 schema(table).select{|a| a[1][:primary_key]}.map{|a| a[0]} 495 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
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 345 def auto_increment_sql 346 'AUTO_INCREMENT' 347 end
MySQL
needs to set transaction isolation before begining a transaction
# File lib/sequel/adapters/shared/mysql.rb 350 def begin_new_transaction(conn, opts) 351 set_transaction_isolation(conn, opts) 352 log_connection_execute(conn, begin_transaction_sql) 353 end
Use XA START to start a new prepared transaction if the :prepare option is given.
# File lib/sequel/adapters/shared/mysql.rb 357 def begin_transaction(conn, opts=OPTS) 358 if (s = opts[:prepare]) && savepoint_level(conn) == 1 359 log_connection_execute(conn, "XA START #{literal(s)}") 360 else 361 super 362 end 363 end
Support :on_update_current_timestamp option.
# File lib/sequel/adapters/shared/mysql.rb 366 def column_definition_default_sql(sql, column) 367 super 368 sql << " ON UPDATE CURRENT_TIMESTAMP" if column[:on_update_current_timestamp] 369 end
Add generation clause SQL
fragment to column creation SQL
.
# File lib/sequel/adapters/shared/mysql.rb 372 def column_definition_generated_sql(sql, column) 373 if (generated_expression = column[:generated_always_as]) 374 sql << " GENERATED ALWAYS AS (#{literal(generated_expression)})" 375 case (type = column[:generated_type]) 376 when nil 377 # none, database default 378 when :virtual 379 sql << " VIRTUAL" 380 when :stored 381 sql << (mariadb? ? " PERSISTENT" : " STORED") 382 else 383 raise Error, "unsupported :generated_type option: #{type.inspect}" 384 end 385 end 386 end
# File lib/sequel/adapters/shared/mysql.rb 388 def column_definition_order 389 COLUMN_DEFINITION_ORDER 390 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 394 def column_definition_sql(column) 395 column.delete(:default) if column[:type] == File || (column[:type] == String && column[:text] == true) 396 super 397 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 401 def commit_transaction(conn, opts=OPTS) 402 if (s = opts[:prepare]) && savepoint_level(conn) <= 1 403 log_connection_execute(conn, "XA END #{literal(s)}") 404 log_connection_execute(conn, "XA PREPARE #{literal(s)}") 405 else 406 super 407 end 408 end
Use MySQL
specific syntax for engine type and character encoding
# File lib/sequel/adapters/shared/mysql.rb 411 def create_table_sql(name, generator, options = OPTS) 412 engine = options.fetch(:engine, default_engine) 413 charset = options.fetch(:charset, default_charset) 414 collate = options.fetch(:collate, default_collate) 415 generator.constraints.sort_by{|c| (c[:type] == :primary_key) ? -1 : 1} 416 417 # Proc for figuring out the primary key for a given table. 418 key_proc = lambda do |t| 419 if t == name 420 if pk = generator.primary_key_name 421 [pk] 422 elsif !(pkc = generator.constraints.select{|con| con[:type] == :primary_key}).empty? 423 pkc.first[:columns] 424 elsif !(pkc = generator.columns.select{|con| con[:primary_key] == true}).empty? 425 pkc.map{|c| c[:name]} 426 end 427 else 428 primary_key_from_schema(t) 429 end 430 end 431 432 # Manually set the keys, since MySQL requires one, it doesn't use the primary 433 # key if none are specified. 434 generator.constraints.each do |c| 435 if c[:type] == :foreign_key 436 c[:key] ||= key_proc.call(c[:table]) 437 end 438 end 439 440 # Split column constraints into table constraints in some cases: 441 # foreign key - Always 442 # unique, primary_key - Only if constraint has a name 443 generator.columns.each do |c| 444 if t = c.delete(:table) 445 same_table = t == name 446 key = c[:key] || key_proc.call(t) 447 448 if same_table && !key.nil? 449 generator.constraints.unshift(:type=>:unique, :columns=>Array(key)) 450 end 451 452 generator.foreign_key([c[:name]], t, c.merge(:name=>c[:foreign_key_constraint_name], :type=>:foreign_key, :key=>key)) 453 end 454 end 455 456 "#{super}#{" ENGINE=#{engine}" if engine}#{" DEFAULT CHARSET=#{charset}" if charset}#{" DEFAULT COLLATE=#{collate}" if collate}" 457 end
# File lib/sequel/adapters/shared/mysql.rb 467 def database_error_regexps 468 DATABASE_ERROR_REGEXPS 469 end
Backbone of the tables and views support using SHOW FULL TABLES.
# File lib/sequel/adapters/shared/mysql.rb 472 def full_tables(type, opts) 473 m = output_identifier_meth 474 metadata_dataset.with_sql('SHOW FULL TABLES').server(opts[:server]).map{|r| m.call(r.values.first) if r.delete(:Table_type) == type}.compact 475 end
# File lib/sequel/adapters/shared/mysql.rb 477 def index_definition_sql(table_name, index) 478 index_name = quote_identifier(index[:name] || default_index_name(table_name, index[:columns])) 479 raise Error, "Partial indexes are not supported for this database" if index[:where] && !supports_partial_indexes? 480 index_type = case index[:type] 481 when :full_text 482 "FULLTEXT " 483 when :spatial 484 "SPATIAL " 485 else 486 using = " USING #{index[:type]}" unless index[:type] == nil 487 "UNIQUE " if index[:unique] 488 end 489 "CREATE #{index_type}INDEX #{index_name}#{using} ON #{quote_schema_table(table_name)} #{literal(index[:columns])}" 490 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 # Disable the use of split_materialized in the optimizer. This is 337 # needed to pass association tests on MariaDB 10.5+. 338 if opts[:disable_split_materialized] && typecast_value_boolean(opts[:disable_split_materialized]) 339 sqls << "SET SESSION optimizer_switch='split_materialized=off'" 340 end 341 342 sqls 343 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 498 def rename_tables_sql(renames) 499 rename_tos = renames.map do |from, to| 500 "#{quote_schema_table(from)} TO #{quote_schema_table(to)}" 501 end.join(', ') 502 "RENAME TABLE #{rename_tos}" 503 end
Rollback the currently open XA transaction
# File lib/sequel/adapters/shared/mysql.rb 506 def rollback_transaction(conn, opts=OPTS) 507 if (s = opts[:prepare]) && savepoint_level(conn) <= 1 508 log_connection_execute(conn, "XA END #{literal(s)}") 509 log_connection_execute(conn, "XA PREPARE #{literal(s)}") 510 log_connection_execute(conn, "XA ROLLBACK #{literal(s)}") 511 else 512 super 513 end 514 end
# File lib/sequel/adapters/shared/mysql.rb 516 def schema_column_type(db_type) 517 case db_type 518 when /\Aset/io 519 :set 520 when /\Amediumint/io 521 :integer 522 when /\Amediumtext/io 523 :string 524 else 525 super 526 end 527 end
Use the MySQL
specific DESCRIBE syntax to get a table description.
# File lib/sequel/adapters/shared/mysql.rb 530 def schema_parse_table(table_name, opts) 531 m = output_identifier_meth(opts[:dataset]) 532 im = input_identifier_meth(opts[:dataset]) 533 table = SQL::Identifier.new(im.call(table_name)) 534 table = SQL::QualifiedIdentifier.new(im.call(opts[:schema]), table) if opts[:schema] 535 metadata_dataset.with_sql("DESCRIBE ?", table).map do |row| 536 extra = row.delete(:Extra) 537 if row[:primary_key] = row.delete(:Key) == 'PRI' 538 row[:auto_increment] = !!(extra.to_s =~ /auto_increment/i) 539 end 540 if supports_generated_columns? 541 # Extra field contains VIRTUAL or PERSISTENT for generated columns 542 row[:generated] = !!(extra.to_s =~ /VIRTUAL|STORED|PERSISTENT/i) 543 end 544 row[:allow_null] = row.delete(:Null) == 'YES' 545 row[:default] = row.delete(:Default) 546 row[:db_type] = row.delete(:Type) 547 row[:type] = schema_column_type(row[:db_type]) 548 row[:extra] = extra 549 [m.call(row.delete(:Field)), row] 550 end 551 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 555 def split_alter_table_op?(op) 556 server_version >= 50600 && (op[:op] == :drop_index || (op[:op] == :drop_constraint && op[:type] == :unique)) 557 end
MySQL
can combine multiple alter table ops into a single query.
# File lib/sequel/adapters/shared/mysql.rb 566 def supports_combining_alter_table_ops? 567 true 568 end
MySQL
supports CREATE OR REPLACE VIEW.
# File lib/sequel/adapters/shared/mysql.rb 571 def supports_create_or_replace_view? 572 true 573 end
MySQL
does not support named column constraints.
# File lib/sequel/adapters/shared/mysql.rb 576 def supports_named_column_constraints? 577 false 578 end
MySQL
has both datetime and timestamp classes, most people are going to want datetime
# File lib/sequel/adapters/shared/mysql.rb 598 def type_literal_generic_datetime(column) 599 if supports_timestamp_usecs? 600 :'datetime(6)' 601 elsif column[:default] == Sequel::CURRENT_TIMESTAMP 602 :timestamp 603 else 604 :datetime 605 end 606 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 583 def type_literal_generic_file(column) 584 case column[:size] 585 when :tiny # < 2^8 bytes 586 :tinyblob 587 when :medium # < 2^24 bytes 588 :mediumblob 589 when :long # < 2^32 bytes 590 :longblob 591 else # 2^16 bytes 592 :blob 593 end 594 end
MySQL
has both datetime and timestamp classes, most people are going to want datetime.
# File lib/sequel/adapters/shared/mysql.rb 610 def type_literal_generic_only_time(column) 611 if supports_timestamp_usecs? 612 :'time(6)' 613 else 614 :time 615 end 616 end
MySQL
doesn’t have a true boolean class, so it uses tinyint(1)
# File lib/sequel/adapters/shared/mysql.rb 619 def type_literal_generic_trueclass(column) 620 :'tinyint(1)' 621 end
MySQL
5.0.2+ supports views with check option.
# File lib/sequel/adapters/shared/mysql.rb 624 def view_with_check_option_support 625 :local if server_version >= 50002 626 end