# File lib/sequel/adapters/shared/mysql.rb 461 def primary_key_from_schema(table) 462 schema(table).select{|a| a[1][:primary_key]}.map{|a| a[0]} 463 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
# 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 193 def alter_table_add_column_sql(table, op) 194 pos = if after_col = op[:after] 195 " AFTER #{quote_identifier(after_col)}" 196 elsif op[:first] 197 " FIRST" 198 end 199 200 sql = if related = op.delete(:table) 201 sql = super + "#{pos}, ADD " 202 op[:table] = related 203 op[:key] ||= primary_key_from_schema(related) 204 if constraint_name = op.delete(:foreign_key_constraint_name) 205 sql << "CONSTRAINT #{quote_identifier(constraint_name)} " 206 end 207 sql << "FOREIGN KEY (#{quote_identifier(op[:name])})#{column_references_sql(op)}" 208 else 209 "#{super}#{pos}" 210 end 211 end
# File lib/sequel/adapters/shared/mysql.rb 237 def alter_table_add_constraint_sql(table, op) 238 if op[:type] == :foreign_key 239 op[:key] ||= primary_key_from_schema(op[:table]) 240 end 241 super 242 end
# File lib/sequel/adapters/shared/mysql.rb 213 def alter_table_change_column_sql(table, op) 214 o = op[:op] 215 opts = schema(table).find{|x| x.first == op[:name]} 216 opts = opts ? opts.last.dup : {} 217 opts[:name] = o == :rename_column ? op[:new_name] : op[:name] 218 opts[:type] = o == :set_column_type ? op[:type] : opts[:db_type] 219 opts[:null] = o == :set_column_null ? op[:null] : opts[:allow_null] 220 opts[:default] = o == :set_column_default ? op[:default] : opts[:ruby_default] 221 opts.delete(:default) if opts[:default] == nil 222 opts.delete(:primary_key) 223 unless op[:type] || opts[:type] 224 raise Error, "cannot determine database type to use for CHANGE COLUMN operation" 225 end 226 opts = op.merge(opts) 227 if op.has_key?(:auto_increment) 228 opts[:auto_increment] = op[:auto_increment] 229 end 230 "CHANGE COLUMN #{quote_identifier(op[:name])} #{column_definition_sql(opts)}" 231 end
# File lib/sequel/adapters/shared/mysql.rb 244 def alter_table_drop_constraint_sql(table, op) 245 case op[:type] 246 when :primary_key 247 "DROP PRIMARY KEY" 248 when :foreign_key 249 name = op[:name] || foreign_key_name(table, op[:columns]) 250 "DROP FOREIGN KEY #{quote_identifier(name)}" 251 when :unique 252 "DROP INDEX #{quote_identifier(op[:name])}" 253 when :check, nil 254 if supports_check_constraints? 255 "DROP CONSTRAINT #{quote_identifier(op[:name])}" 256 end 257 end 258 end
# File lib/sequel/adapters/shared/mysql.rb 260 def alter_table_sql(table, op) 261 case op[:op] 262 when :drop_index 263 "#{drop_index_sql(table, op)} ON #{quote_schema_table(table)}" 264 when :drop_constraint 265 if op[:type] == :primary_key 266 if (pk = primary_key_from_schema(table)).length == 1 267 return [alter_table_sql(table, {:op=>:rename_column, :name=>pk.first, :new_name=>pk.first, :auto_increment=>false}), super] 268 end 269 end 270 super 271 else 272 super 273 end 274 end
# File lib/sequel/adapters/shared/mysql.rb 319 def auto_increment_sql 320 'AUTO_INCREMENT' 321 end
MySQL
needs to set transaction isolation before begining a transaction
# File lib/sequel/adapters/shared/mysql.rb 324 def begin_new_transaction(conn, opts) 325 set_transaction_isolation(conn, opts) 326 log_connection_execute(conn, begin_transaction_sql) 327 end
Use XA START to start a new prepared transaction if the :prepare option is given.
# File lib/sequel/adapters/shared/mysql.rb 331 def begin_transaction(conn, opts=OPTS) 332 if (s = opts[:prepare]) && savepoint_level(conn) == 1 333 log_connection_execute(conn, "XA START #{literal(s)}") 334 else 335 super 336 end 337 end
Add generation clause SQL
fragment to column creation SQL
.
# File lib/sequel/adapters/shared/mysql.rb 340 def column_definition_generated_sql(sql, column) 341 if (generated_expression = column[:generated_always_as]) 342 sql << " GENERATED ALWAYS AS (#{literal(generated_expression)})" 343 case (type = column[:generated_type]) 344 when nil 345 # none, database default 346 when :virtual 347 sql << " VIRTUAL" 348 when :stored 349 sql << (mariadb? ? " PERSISTENT" : " STORED") 350 else 351 raise Error, "unsupported :generated_type option: #{type.inspect}" 352 end 353 end 354 end
# File lib/sequel/adapters/shared/mysql.rb 356 def column_definition_order 357 COLUMN_DEFINITION_ORDER 358 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 362 def column_definition_sql(column) 363 column.delete(:default) if column[:type] == File || (column[:type] == String && column[:text] == true) 364 super 365 end
Handle MySQL
specific default format.
# File lib/sequel/adapters/shared/mysql.rb 277 def column_schema_normalize_default(default, type) 278 if column_schema_default_string_type?(type) 279 return if [:date, :datetime, :time].include?(type) && /\ACURRENT_(?:DATE|TIMESTAMP)?\z/.match(default) 280 default = "'#{default.gsub("'", "''").gsub('\\', '\\\\')}'" 281 end 282 super(default, type) 283 end
# File lib/sequel/adapters/shared/mysql.rb 285 def column_schema_to_ruby_default(default, type) 286 return Sequel::CURRENT_DATE if mariadb? && server_version >= 100200 && default == 'curdate()' 287 super 288 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 293 def combinable_alter_table_op?(op) 294 super && !(op[:op] == :add_constraint && op[:type] == :foreign_key) && !(op[:op] == :drop_constraint && op[:type] == :primary_key) 295 end
Prepare the XA transaction for a two-phase commit if the :prepare option is given.
# File lib/sequel/adapters/shared/mysql.rb 369 def commit_transaction(conn, opts=OPTS) 370 if (s = opts[:prepare]) && savepoint_level(conn) <= 1 371 log_connection_execute(conn, "XA END #{literal(s)}") 372 log_connection_execute(conn, "XA PREPARE #{literal(s)}") 373 else 374 super 375 end 376 end
Use MySQL
specific syntax for engine type and character encoding
# File lib/sequel/adapters/shared/mysql.rb 379 def create_table_sql(name, generator, options = OPTS) 380 engine = options.fetch(:engine, default_engine) 381 charset = options.fetch(:charset, default_charset) 382 collate = options.fetch(:collate, default_collate) 383 generator.constraints.sort_by{|c| (c[:type] == :primary_key) ? -1 : 1} 384 385 # Proc for figuring out the primary key for a given table. 386 key_proc = lambda do |t| 387 if t == name 388 if pk = generator.primary_key_name 389 [pk] 390 elsif !(pkc = generator.constraints.select{|con| con[:type] == :primary_key}).empty? 391 pkc.first[:columns] 392 elsif !(pkc = generator.columns.select{|con| con[:primary_key] == true}).empty? 393 pkc.map{|c| c[:name]} 394 end 395 else 396 primary_key_from_schema(t) 397 end 398 end 399 400 # Manually set the keys, since MySQL requires one, it doesn't use the primary 401 # key if none are specified. 402 generator.constraints.each do |c| 403 if c[:type] == :foreign_key 404 c[:key] ||= key_proc.call(c[:table]) 405 end 406 end 407 408 # Split column constraints into table constraints in some cases: 409 # foreign key - Always 410 # unique, primary_key - Only if constraint has a name 411 generator.columns.each do |c| 412 if t = c.delete(:table) 413 same_table = t == name 414 key = c[:key] || key_proc.call(t) 415 416 if same_table && !key.nil? 417 generator.constraints.unshift(:type=>:unique, :columns=>Array(key)) 418 end 419 420 generator.foreign_key([c[:name]], t, c.merge(:name=>c[:foreign_key_constraint_name], :type=>:foreign_key, :key=>key)) 421 end 422 end 423 424 "#{super}#{" ENGINE=#{engine}" if engine}#{" DEFAULT CHARSET=#{charset}" if charset}#{" DEFAULT COLLATE=#{collate}" if collate}" 425 end
# File lib/sequel/adapters/shared/mysql.rb 435 def database_error_regexps 436 DATABASE_ERROR_REGEXPS 437 end
Backbone of the tables and views support using SHOW FULL TABLES.
# File lib/sequel/adapters/shared/mysql.rb 440 def full_tables(type, opts) 441 m = output_identifier_meth 442 metadata_dataset.with_sql('SHOW FULL TABLES').server(opts[:server]).map{|r| m.call(r.values.first) if r.delete(:Table_type) == type}.compact 443 end
# File lib/sequel/adapters/shared/mysql.rb 445 def index_definition_sql(table_name, index) 446 index_name = quote_identifier(index[:name] || default_index_name(table_name, index[:columns])) 447 raise Error, "Partial indexes are not supported for this database" if index[:where] && !supports_partial_indexes? 448 index_type = case index[:type] 449 when :full_text 450 "FULLTEXT " 451 when :spatial 452 "SPATIAL " 453 else 454 using = " USING #{index[:type]}" unless index[:type] == nil 455 "UNIQUE " if index[:unique] 456 end 457 "CREATE #{index_type}INDEX #{index_name}#{using} ON #{quote_schema_table(table_name)} #{literal(index[:columns])}" 458 end
The SQL
queries to execute on initial connection
# File lib/sequel/adapters/shared/mysql.rb 298 def mysql_connection_setting_sqls 299 sqls = [] 300 301 if wait_timeout = opts.fetch(:timeout, 2147483) 302 # Increase timeout so mysql server doesn't disconnect us 303 # Value used by default is maximum allowed value on Windows. 304 sqls << "SET @@wait_timeout = #{wait_timeout}" 305 end 306 307 # By default, MySQL 'where id is null' selects the last inserted id 308 sqls << "SET SQL_AUTO_IS_NULL=0" unless opts[:auto_is_null] 309 310 # If the user has specified one or more sql modes, enable them 311 if sql_mode = opts[:sql_mode] 312 sql_mode = Array(sql_mode).join(',').upcase 313 sqls << "SET sql_mode = '#{sql_mode}'" 314 end 315 316 sqls 317 end
Parse the schema for the given table to get an array of primary key columns
Rollback the currently open XA transaction
# File lib/sequel/adapters/shared/mysql.rb 466 def rollback_transaction(conn, opts=OPTS) 467 if (s = opts[:prepare]) && savepoint_level(conn) <= 1 468 log_connection_execute(conn, "XA END #{literal(s)}") 469 log_connection_execute(conn, "XA PREPARE #{literal(s)}") 470 log_connection_execute(conn, "XA ROLLBACK #{literal(s)}") 471 else 472 super 473 end 474 end
# File lib/sequel/adapters/shared/mysql.rb 476 def schema_column_type(db_type) 477 case db_type 478 when /\Aset/io 479 :set 480 when /\Amediumint/io 481 :integer 482 when /\Amediumtext/io 483 :string 484 else 485 super 486 end 487 end
Use the MySQL
specific DESCRIBE syntax to get a table description.
# File lib/sequel/adapters/shared/mysql.rb 490 def schema_parse_table(table_name, opts) 491 m = output_identifier_meth(opts[:dataset]) 492 im = input_identifier_meth(opts[:dataset]) 493 table = SQL::Identifier.new(im.call(table_name)) 494 table = SQL::QualifiedIdentifier.new(im.call(opts[:schema]), table) if opts[:schema] 495 metadata_dataset.with_sql("DESCRIBE ?", table).map do |row| 496 extra = row.delete(:Extra) 497 if row[:primary_key] = row.delete(:Key) == 'PRI' 498 row[:auto_increment] = !!(extra.to_s =~ /auto_increment/i) 499 end 500 if supports_generated_columns? 501 # Extra field contains VIRTUAL or PERSISTENT for generated columns 502 row[:generated] = !!(extra.to_s =~ /VIRTUAL|STORED|PERSISTENT/i) 503 end 504 row[:allow_null] = row.delete(:Null) == 'YES' 505 row[:default] = row.delete(:Default) 506 row[:db_type] = row.delete(:Type) 507 row[:type] = schema_column_type(row[:db_type]) 508 [m.call(row.delete(:Field)), row] 509 end 510 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 514 def split_alter_table_op?(op) 515 server_version >= 50600 && (op[:op] == :drop_index || (op[:op] == :drop_constraint && op[:type] == :unique)) 516 end
Whether the database supports CHECK constraints
# File lib/sequel/adapters/shared/mysql.rb 519 def supports_check_constraints? 520 mariadb? && server_version >= 100200 521 end
MySQL
can combine multiple alter table ops into a single query.
# File lib/sequel/adapters/shared/mysql.rb 524 def supports_combining_alter_table_ops? 525 true 526 end
MySQL
supports CREATE OR REPLACE VIEW.
# File lib/sequel/adapters/shared/mysql.rb 529 def supports_create_or_replace_view? 530 true 531 end
MySQL
does not support named column constraints.
# File lib/sequel/adapters/shared/mysql.rb 534 def supports_named_column_constraints? 535 false 536 end
MySQL
has both datetime and timestamp classes, most people are going to want datetime
# File lib/sequel/adapters/shared/mysql.rb 556 def type_literal_generic_datetime(column) 557 if supports_timestamp_usecs? 558 :'datetime(6)' 559 elsif column[:default] == Sequel::CURRENT_TIMESTAMP 560 :timestamp 561 else 562 :datetime 563 end 564 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 541 def type_literal_generic_file(column) 542 case column[:size] 543 when :tiny # < 2^8 bytes 544 :tinyblob 545 when :medium # < 2^24 bytes 546 :mediumblob 547 when :long # < 2^32 bytes 548 :longblob 549 else # 2^16 bytes 550 :blob 551 end 552 end
MySQL
has both datetime and timestamp classes, most people are going to want datetime.
# File lib/sequel/adapters/shared/mysql.rb 568 def type_literal_generic_only_time(column) 569 if supports_timestamp_usecs? 570 :'time(6)' 571 else 572 :time 573 end 574 end
MySQL
doesn't have a true boolean class, so it uses tinyint(1)
# File lib/sequel/adapters/shared/mysql.rb 577 def type_literal_generic_trueclass(column) 578 :'tinyint(1)' 579 end
MySQL
5.0.2+ supports views with check option.
# File lib/sequel/adapters/shared/mysql.rb 582 def view_with_check_option_support 583 :local if server_version >= 50002 584 end