# File lib/sequel/adapters/shared/mysql.rb 472 def primary_key_from_schema(table) 473 schema(table).select{|a| a[1][:primary_key]}.map{|a| a[0]} 474 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 248 def alter_table_add_constraint_sql(table, op) 249 if op[:type] == :foreign_key 250 op[:key] ||= primary_key_from_schema(op[:table]) 251 end 252 super 253 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 255 def alter_table_drop_constraint_sql(table, op) 256 case op[:type] 257 when :primary_key 258 "DROP PRIMARY KEY" 259 when :foreign_key 260 name = op[:name] || foreign_key_name(table, op[:columns]) 261 "DROP FOREIGN KEY #{quote_identifier(name)}" 262 when :unique 263 "DROP INDEX #{quote_identifier(op[:name])}" 264 when :check, nil 265 if supports_check_constraints? 266 "DROP CONSTRAINT #{quote_identifier(op[:name])}" 267 end 268 end 269 end
# File lib/sequel/adapters/shared/mysql.rb 236 def alter_table_set_column_default_sql(table, op) 237 return super unless op[:default].nil? 238 239 opts = schema(table).find{|x| x[0] == op[:name]} 240 241 if opts && opts[1][:allow_null] == false 242 "ALTER COLUMN #{quote_identifier(op[:name])} DROP DEFAULT" 243 else 244 super 245 end 246 end
# File lib/sequel/adapters/shared/mysql.rb 271 def alter_table_sql(table, op) 272 case op[:op] 273 when :drop_index 274 "#{drop_index_sql(table, op)} ON #{quote_schema_table(table)}" 275 when :drop_constraint 276 if op[:type] == :primary_key 277 if (pk = primary_key_from_schema(table)).length == 1 278 return [alter_table_sql(table, {:op=>:rename_column, :name=>pk.first, :new_name=>pk.first, :auto_increment=>false}), super] 279 end 280 end 281 super 282 else 283 super 284 end 285 end
# File lib/sequel/adapters/shared/mysql.rb 330 def auto_increment_sql 331 'AUTO_INCREMENT' 332 end
MySQL
needs to set transaction isolation before begining a transaction
# File lib/sequel/adapters/shared/mysql.rb 335 def begin_new_transaction(conn, opts) 336 set_transaction_isolation(conn, opts) 337 log_connection_execute(conn, begin_transaction_sql) 338 end
Use XA START to start a new prepared transaction if the :prepare option is given.
# File lib/sequel/adapters/shared/mysql.rb 342 def begin_transaction(conn, opts=OPTS) 343 if (s = opts[:prepare]) && savepoint_level(conn) == 1 344 log_connection_execute(conn, "XA START #{literal(s)}") 345 else 346 super 347 end 348 end
Add generation clause SQL
fragment to column creation SQL
.
# File lib/sequel/adapters/shared/mysql.rb 351 def column_definition_generated_sql(sql, column) 352 if (generated_expression = column[:generated_always_as]) 353 sql << " GENERATED ALWAYS AS (#{literal(generated_expression)})" 354 case (type = column[:generated_type]) 355 when nil 356 # none, database default 357 when :virtual 358 sql << " VIRTUAL" 359 when :stored 360 sql << (mariadb? ? " PERSISTENT" : " STORED") 361 else 362 raise Error, "unsupported :generated_type option: #{type.inspect}" 363 end 364 end 365 end
# File lib/sequel/adapters/shared/mysql.rb 367 def column_definition_order 368 COLUMN_DEFINITION_ORDER 369 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 373 def column_definition_sql(column) 374 column.delete(:default) if column[:type] == File || (column[:type] == String && column[:text] == true) 375 super 376 end
Handle MySQL
specific default format.
# File lib/sequel/adapters/shared/mysql.rb 288 def column_schema_normalize_default(default, type) 289 if column_schema_default_string_type?(type) 290 return if [:date, :datetime, :time].include?(type) && /\ACURRENT_(?:DATE|TIMESTAMP)?\z/.match(default) 291 default = "'#{default.gsub("'", "''").gsub('\\', '\\\\')}'" 292 end 293 super(default, type) 294 end
# File lib/sequel/adapters/shared/mysql.rb 296 def column_schema_to_ruby_default(default, type) 297 return Sequel::CURRENT_DATE if mariadb? && server_version >= 100200 && default == 'curdate()' 298 super 299 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 304 def combinable_alter_table_op?(op) 305 super && !(op[:op] == :add_constraint && op[:type] == :foreign_key) && !(op[:op] == :drop_constraint && op[:type] == :primary_key) 306 end
Prepare the XA transaction for a two-phase commit if the :prepare option is given.
# File lib/sequel/adapters/shared/mysql.rb 380 def commit_transaction(conn, opts=OPTS) 381 if (s = opts[:prepare]) && savepoint_level(conn) <= 1 382 log_connection_execute(conn, "XA END #{literal(s)}") 383 log_connection_execute(conn, "XA PREPARE #{literal(s)}") 384 else 385 super 386 end 387 end
Use MySQL
specific syntax for engine type and character encoding
# File lib/sequel/adapters/shared/mysql.rb 390 def create_table_sql(name, generator, options = OPTS) 391 engine = options.fetch(:engine, default_engine) 392 charset = options.fetch(:charset, default_charset) 393 collate = options.fetch(:collate, default_collate) 394 generator.constraints.sort_by{|c| (c[:type] == :primary_key) ? -1 : 1} 395 396 # Proc for figuring out the primary key for a given table. 397 key_proc = lambda do |t| 398 if t == name 399 if pk = generator.primary_key_name 400 [pk] 401 elsif !(pkc = generator.constraints.select{|con| con[:type] == :primary_key}).empty? 402 pkc.first[:columns] 403 elsif !(pkc = generator.columns.select{|con| con[:primary_key] == true}).empty? 404 pkc.map{|c| c[:name]} 405 end 406 else 407 primary_key_from_schema(t) 408 end 409 end 410 411 # Manually set the keys, since MySQL requires one, it doesn't use the primary 412 # key if none are specified. 413 generator.constraints.each do |c| 414 if c[:type] == :foreign_key 415 c[:key] ||= key_proc.call(c[:table]) 416 end 417 end 418 419 # Split column constraints into table constraints in some cases: 420 # foreign key - Always 421 # unique, primary_key - Only if constraint has a name 422 generator.columns.each do |c| 423 if t = c.delete(:table) 424 same_table = t == name 425 key = c[:key] || key_proc.call(t) 426 427 if same_table && !key.nil? 428 generator.constraints.unshift(:type=>:unique, :columns=>Array(key)) 429 end 430 431 generator.foreign_key([c[:name]], t, c.merge(:name=>c[:foreign_key_constraint_name], :type=>:foreign_key, :key=>key)) 432 end 433 end 434 435 "#{super}#{" ENGINE=#{engine}" if engine}#{" DEFAULT CHARSET=#{charset}" if charset}#{" DEFAULT COLLATE=#{collate}" if collate}" 436 end
# File lib/sequel/adapters/shared/mysql.rb 446 def database_error_regexps 447 DATABASE_ERROR_REGEXPS 448 end
Backbone of the tables and views support using SHOW FULL TABLES.
# File lib/sequel/adapters/shared/mysql.rb 451 def full_tables(type, opts) 452 m = output_identifier_meth 453 metadata_dataset.with_sql('SHOW FULL TABLES').server(opts[:server]).map{|r| m.call(r.values.first) if r.delete(:Table_type) == type}.compact 454 end
# File lib/sequel/adapters/shared/mysql.rb 456 def index_definition_sql(table_name, index) 457 index_name = quote_identifier(index[:name] || default_index_name(table_name, index[:columns])) 458 raise Error, "Partial indexes are not supported for this database" if index[:where] && !supports_partial_indexes? 459 index_type = case index[:type] 460 when :full_text 461 "FULLTEXT " 462 when :spatial 463 "SPATIAL " 464 else 465 using = " USING #{index[:type]}" unless index[:type] == nil 466 "UNIQUE " if index[:unique] 467 end 468 "CREATE #{index_type}INDEX #{index_name}#{using} ON #{quote_schema_table(table_name)} #{literal(index[:columns])}" 469 end
The SQL
queries to execute on initial connection
# File lib/sequel/adapters/shared/mysql.rb 309 def mysql_connection_setting_sqls 310 sqls = [] 311 312 if wait_timeout = opts.fetch(:timeout, 2147483) 313 # Increase timeout so mysql server doesn't disconnect us 314 # Value used by default is maximum allowed value on Windows. 315 sqls << "SET @@wait_timeout = #{wait_timeout}" 316 end 317 318 # By default, MySQL 'where id is null' selects the last inserted id 319 sqls << "SET SQL_AUTO_IS_NULL=0" unless opts[:auto_is_null] 320 321 # If the user has specified one or more sql modes, enable them 322 if sql_mode = opts[:sql_mode] 323 sql_mode = Array(sql_mode).join(',').upcase 324 sqls << "SET sql_mode = '#{sql_mode}'" 325 end 326 327 sqls 328 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 477 def rollback_transaction(conn, opts=OPTS) 478 if (s = opts[:prepare]) && savepoint_level(conn) <= 1 479 log_connection_execute(conn, "XA END #{literal(s)}") 480 log_connection_execute(conn, "XA PREPARE #{literal(s)}") 481 log_connection_execute(conn, "XA ROLLBACK #{literal(s)}") 482 else 483 super 484 end 485 end
# File lib/sequel/adapters/shared/mysql.rb 487 def schema_column_type(db_type) 488 case db_type 489 when /\Aset/io 490 :set 491 when /\Amediumint/io 492 :integer 493 when /\Amediumtext/io 494 :string 495 else 496 super 497 end 498 end
Use the MySQL
specific DESCRIBE syntax to get a table description.
# File lib/sequel/adapters/shared/mysql.rb 501 def schema_parse_table(table_name, opts) 502 m = output_identifier_meth(opts[:dataset]) 503 im = input_identifier_meth(opts[:dataset]) 504 table = SQL::Identifier.new(im.call(table_name)) 505 table = SQL::QualifiedIdentifier.new(im.call(opts[:schema]), table) if opts[:schema] 506 metadata_dataset.with_sql("DESCRIBE ?", table).map do |row| 507 extra = row.delete(:Extra) 508 if row[:primary_key] = row.delete(:Key) == 'PRI' 509 row[:auto_increment] = !!(extra.to_s =~ /auto_increment/i) 510 end 511 if supports_generated_columns? 512 # Extra field contains VIRTUAL or PERSISTENT for generated columns 513 row[:generated] = !!(extra.to_s =~ /VIRTUAL|STORED|PERSISTENT/i) 514 end 515 row[:allow_null] = row.delete(:Null) == 'YES' 516 row[:default] = row.delete(:Default) 517 row[:db_type] = row.delete(:Type) 518 row[:type] = schema_column_type(row[:db_type]) 519 [m.call(row.delete(:Field)), row] 520 end 521 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 525 def split_alter_table_op?(op) 526 server_version >= 50600 && (op[:op] == :drop_index || (op[:op] == :drop_constraint && op[:type] == :unique)) 527 end
Whether the database supports CHECK constraints
# File lib/sequel/adapters/shared/mysql.rb 530 def supports_check_constraints? 531 mariadb? && server_version >= 100200 532 end
MySQL
can combine multiple alter table ops into a single query.
# File lib/sequel/adapters/shared/mysql.rb 535 def supports_combining_alter_table_ops? 536 true 537 end
MySQL
supports CREATE OR REPLACE VIEW.
# File lib/sequel/adapters/shared/mysql.rb 540 def supports_create_or_replace_view? 541 true 542 end
MySQL
does not support named column constraints.
# File lib/sequel/adapters/shared/mysql.rb 545 def supports_named_column_constraints? 546 false 547 end
MySQL
has both datetime and timestamp classes, most people are going to want datetime
# File lib/sequel/adapters/shared/mysql.rb 567 def type_literal_generic_datetime(column) 568 if supports_timestamp_usecs? 569 :'datetime(6)' 570 elsif column[:default] == Sequel::CURRENT_TIMESTAMP 571 :timestamp 572 else 573 :datetime 574 end 575 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 552 def type_literal_generic_file(column) 553 case column[:size] 554 when :tiny # < 2^8 bytes 555 :tinyblob 556 when :medium # < 2^24 bytes 557 :mediumblob 558 when :long # < 2^32 bytes 559 :longblob 560 else # 2^16 bytes 561 :blob 562 end 563 end
MySQL
has both datetime and timestamp classes, most people are going to want datetime.
# File lib/sequel/adapters/shared/mysql.rb 579 def type_literal_generic_only_time(column) 580 if supports_timestamp_usecs? 581 :'time(6)' 582 else 583 :time 584 end 585 end
MySQL
doesn't have a true boolean class, so it uses tinyint(1)
# File lib/sequel/adapters/shared/mysql.rb 588 def type_literal_generic_trueclass(column) 589 :'tinyint(1)' 590 end
MySQL
5.0.2+ supports views with check option.
# File lib/sequel/adapters/shared/mysql.rb 593 def view_with_check_option_support 594 :local if server_version >= 50002 595 end