module Sequel::SQLite::DatabaseMethods
No matter how you connect to SQLite, the following Database options can be used to set PRAGMAs on connections in a thread-safe manner: :auto_vacuum, :foreign_keys, :synchronous, and :temp_store.
Constants
- AUTO_VACUUM
- DATABASE_ERROR_REGEXPS
- SYNCHRONOUS
- TEMP_STORE
- TRANSACTION_MODE
Attributes
Whether to keep CURRENT_TIMESTAMP and similar expressions in UTC. By default, the expressions are converted to localtime.
A symbol signifying the value of the default transaction mode
Override the default setting for whether to use timezones in timestamps. It is set to false by default, as SQLite’s date/time methods do not support timezones in timestamps.
Public Instance Methods
Source
# File lib/sequel/adapters/shared/sqlite.rb 58 def database_type 59 :sqlite 60 end
SQLite uses the :sqlite database type.
Source
# File lib/sequel/adapters/shared/sqlite.rb 69 def foreign_key_list(table, opts=OPTS) 70 m = output_identifier_meth 71 h = {} 72 _foreign_key_list_ds(table).each do |row| 73 if r = h[row[:id]] 74 r[:columns] << m.call(row[:from]) 75 r[:key] << m.call(row[:to]) if r[:key] 76 else 77 h[row[:id]] = {:columns=>[m.call(row[:from])], :table=>m.call(row[:table]), :key=>([m.call(row[:to])] if row[:to]), :on_update=>on_delete_sql_to_sym(row[:on_update]), :on_delete=>on_delete_sql_to_sym(row[:on_delete])} 78 end 79 end 80 h.values 81 end
Return the array of foreign key info hashes using the foreign_key_list PRAGMA, including information for the :on_update and :on_delete entries.
Source
# File lib/sequel/adapters/shared/sqlite.rb 83 def freeze 84 sqlite_version 85 use_timestamp_timezones? 86 super 87 end
Source
# File lib/sequel/adapters/shared/sqlite.rb 90 def indexes(table, opts=OPTS) 91 m = output_identifier_meth 92 im = input_identifier_meth 93 indexes = {} 94 table = table.value if table.is_a?(Sequel::SQL::Identifier) 95 metadata_dataset.with_sql("PRAGMA index_list(?)", im.call(table)).each do |r| 96 if opts[:only_autocreated] 97 # If specifically asked for only autocreated indexes, then return those an only those 98 next unless r[:name].start_with?('sqlite_autoindex_') 99 elsif r.has_key?(:origin) 100 # If origin is set, then only exclude primary key indexes and partial indexes 101 next if r[:origin] == 'pk' 102 next if r[:partial].to_i == 1 103 else 104 # When :origin key not present, assume any autoindex could be a primary key one and exclude it 105 next if r[:name].start_with?('sqlite_autoindex_') 106 end 107 108 indexes[m.call(r[:name])] = {:unique=>r[:unique].to_i==1} 109 end 110 indexes.each do |k, v| 111 v[:columns] = metadata_dataset.with_sql("PRAGMA index_info(?)", im.call(k)).map(:name).map{|x| m.call(x)} 112 end 113 indexes 114 end
Use the index_list and index_info PRAGMAs to determine the indexes on the table.
Source
# File lib/sequel/adapters/shared/sqlite.rb 63 def set_integer_booleans 64 @integer_booleans = @opts.has_key?(:integer_booleans) ? typecast_value_boolean(@opts[:integer_booleans]) : true 65 end
Set the integer_booleans option using the passed in :integer_boolean option.
Source
# File lib/sequel/adapters/shared/sqlite.rb 118 def sqlite_version 119 return @sqlite_version if defined?(@sqlite_version) 120 @sqlite_version = begin 121 v = fetch('SELECT sqlite_version()').single_value 122 [10000, 100, 1].zip(v.split('.')).inject(0){|a, m| a + m[0] * Integer(m[1])} 123 rescue 124 0 125 end 126 end
The version of the server as an integer, where 3.6.19 = 30619. If the server version can’t be determined, 0 is used.
Source
# File lib/sequel/adapters/shared/sqlite.rb 149 def support_without_rowid? 150 sqlite_version >= 30802 151 end
SQLite 3.8.2+ supports the without rowid table constraint
Source
# File lib/sequel/adapters/shared/sqlite.rb 129 def supports_create_table_if_not_exists? 130 sqlite_version >= 30300 131 end
SQLite supports CREATE TABLE IF NOT EXISTS syntax since 3.3.0.
Source
# File lib/sequel/adapters/shared/sqlite.rb 134 def supports_deferrable_foreign_key_constraints? 135 sqlite_version >= 30619 136 end
SQLite 3.6.19+ supports deferrable foreign key constraints.
Source
# File lib/sequel/adapters/shared/sqlite.rb 139 def supports_partial_indexes? 140 sqlite_version >= 30800 141 end
SQLite 3.8.0+ supports partial indexes.
Source
# File lib/sequel/adapters/shared/sqlite.rb 144 def supports_savepoints? 145 sqlite_version >= 30608 146 end
SQLite 3.6.8+ supports savepoints.
Source
# File lib/sequel/adapters/shared/sqlite.rb 168 def tables(opts=OPTS) 169 tables_and_views(Sequel.~(:name=>'sqlite_sequence') & {:type => 'table'}, opts) 170 end
Array of symbols specifying the table names in the current database.
Options:
- :server
-
Set the server to use.
Source
# File lib/sequel/adapters/shared/sqlite.rb 49 def transaction_mode=(value) 50 if TRANSACTION_MODE.include?(value) 51 @transaction_mode = value 52 else 53 raise Error, "Invalid value for transaction_mode. Please specify one of :deferred, :immediate, :exclusive, nil" 54 end 55 end
Set the default transaction mode.
Source
# File lib/sequel/adapters/shared/sqlite.rb 160 def use_timestamp_timezones? 161 defined?(@use_timestamp_timezones) ? @use_timestamp_timezones : (@use_timestamp_timezones = false) 162 end
SQLite supports timezones in timestamps, since it just stores them as strings, but it breaks the usage of SQLite’s datetime functions.
Source
# File lib/sequel/adapters/shared/sqlite.rb 176 def values(v) 177 raise Error, "Cannot provide an empty array for values" if v.empty? 178 @default_dataset.clone(:values=>v) 179 end
Creates a dataset that uses the VALUES clause:
DB.values([[1, 2], [3, 4]]) # VALUES ((1, 2), (3, 4))
Source
# File lib/sequel/adapters/shared/sqlite.rb 185 def views(opts=OPTS) 186 tables_and_views({:type => 'view'}, opts) 187 end
Array of symbols specifying the view names in the current database.
Options:
- :server
-
Set the server to use.
Private Instance Methods
Source
# File lib/sequel/adapters/shared/sqlite.rb 192 def _foreign_key_list_ds(table) 193 metadata_dataset.with_sql("PRAGMA foreign_key_list(?)", input_identifier_meth.call(table)) 194 end
Dataset used for parsing foreign key lists
Source
# File lib/sequel/adapters/shared/sqlite.rb 197 def _parse_pragma_ds(table_name, opts) 198 metadata_dataset.with_sql("PRAGMA table_#{'x' if sqlite_version > 33100}info(?)".freeze, input_identifier_meth(opts[:dataset]).call(table_name)) 199 end
Dataset used for parsing schema
Source
# File lib/sequel/adapters/shared/sqlite.rb 247 def alter_table_sql(table, op) 248 case op[:op] 249 when :add_index, :drop_index 250 super 251 when :add_column 252 if op[:unique] || op[:primary_key] 253 duplicate_table(table){|columns| columns.push(op)} 254 else 255 super 256 end 257 when :drop_column 258 if sqlite_version >= 33500 && !indexes(table).any?{|_, h| h[:columns].include?(op[:name])} 259 super 260 else 261 ocp = lambda{|oc| oc.delete_if{|c| c.to_s == op[:name].to_s}} 262 duplicate_table(table, :old_columns_proc=>ocp){|columns| columns.delete_if{|s| s[:name].to_s == op[:name].to_s}} 263 end 264 when :rename_column 265 if sqlite_version >= 32500 266 super 267 else 268 ncp = lambda{|nc| nc.map!{|c| c.to_s == op[:name].to_s ? op[:new_name] : c}} 269 duplicate_table(table, :new_columns_proc=>ncp){|columns| columns.each{|s| s[:name] = op[:new_name] if s[:name].to_s == op[:name].to_s}} 270 end 271 when :set_column_default 272 duplicate_table(table){|columns| columns.each{|s| s[:default] = op[:default] if s[:name].to_s == op[:name].to_s}} 273 when :set_column_null 274 if sqlite_version >= 35300 275 super 276 else 277 duplicate_table(table){|columns| columns.each{|s| s[:null] = op[:null] if s[:name].to_s == op[:name].to_s}} 278 end 279 when :set_column_type 280 duplicate_table(table){|columns| columns.each{|s| s.merge!(op) if s[:name].to_s == op[:name].to_s}} 281 when :drop_constraint 282 case op[:type] 283 when :primary_key 284 duplicate_table(table) do |columns| 285 columns.each do |s| 286 s[:unique] = false if s[:primary_key] 287 s[:primary_key] = s[:auto_increment] = nil 288 end 289 end 290 when :foreign_key 291 if op[:columns] 292 duplicate_table(table, :skip_foreign_key_columns=>op[:columns]) 293 else 294 duplicate_table(table, :no_foreign_keys=>true) 295 end 296 when :unique 297 duplicate_table(table, :no_unique=>true) 298 else 299 if sqlite_version >= 35300 300 super 301 else 302 duplicate_table(table) 303 end 304 end 305 when :add_constraint 306 if op[:type] == :check && sqlite_version >= 35300 307 super 308 else 309 duplicate_table(table, :constraints=>[op]) 310 end 311 when :add_constraints 312 duplicate_table(table, :constraints=>op[:ops]) 313 else 314 raise Error, "Unsupported ALTER TABLE operation: #{op[:op].inspect}" 315 end 316 end
SQLite supports limited table modification. You can add a column or an index. Dropping columns is supported by copying the table into a temporary table, dropping the table, and creating a new table without the column inside of a transaction.
Source
# File lib/sequel/adapters/shared/sqlite.rb 203 def apply_alter_table(table, ops) 204 fks = fetch("PRAGMA foreign_keys") 205 if fks 206 run "PRAGMA foreign_keys = 0" 207 run "PRAGMA legacy_alter_table = 1" if sqlite_version >= 32600 208 end 209 transaction do 210 combine_constraints = if ops.length > 1 && !ops.any?{|op| op[:op] != :add_constraint && op[:op] != :set_column_null} 211 if sqlite_version >= 35300 212 !ops.all?{|op| (op[:op] == :add_constraint && op[:type] == :check) || op[:op] == :set_column_null} 213 else 214 true 215 end 216 else 217 false 218 end 219 220 if combine_constraints 221 null_ops, ops = ops.partition{|op| op[:op] == :set_column_null} 222 223 # Apply NULL/NOT NULL ops first, since those should be purely independent of the constraints. 224 null_ops.each{|op| alter_table_sql_list(table, [op]).flatten.each{|sql| execute_ddl(sql)}} 225 226 # If you are just doing constraints, apply all of them at the same time, 227 # as otherwise all but the last one get lost. 228 alter_table_sql_list(table, [{:op=>:add_constraints, :ops=>ops}]).flatten.each{|sql| execute_ddl(sql)} 229 else 230 # Run each operation separately, as later operations may depend on the 231 # results of earlier operations. 232 ops.each{|op| alter_table_sql_list(table, [op]).flatten.each{|sql| execute_ddl(sql)}} 233 end 234 end 235 remove_cached_schema(table) 236 ensure 237 if fks 238 run "PRAGMA foreign_keys = 1" 239 run "PRAGMA legacy_alter_table = 0" if sqlite_version >= 32600 240 end 241 end
Run all alter_table commands in a transaction. This is technically only needed for drop column.
Source
# File lib/sequel/adapters/shared/sqlite.rb 326 def backup_table_name(table, opts=OPTS) 327 table = table.delete('`') 328 (opts[:times]||1000).times do |i| 329 table_name = "#{table}_backup#{i}" 330 return table_name unless table_exists?(table_name) 331 end 332 end
A name to use for the backup table
Source
# File lib/sequel/adapters/shared/sqlite.rb 318 def begin_new_transaction(conn, opts) 319 mode = opts[:mode] || @transaction_mode 320 sql = TRANSACTION_MODE[mode] or raise Error, "transaction :mode must be one of: :deferred, :immediate, :exclusive, nil" 321 log_connection_execute(conn, sql) 322 set_transaction_isolation(conn, opts) 323 end
Source
# File lib/sequel/adapters/shared/sqlite.rb 336 def can_add_primary_key_constraint_on_nullable_columns? 337 false 338 end
SQLite allows adding primary key constraints on NULLABLE columns, but then does not enforce NOT NULL for such columns, so force setting the columns NOT NULL.
Source
# File lib/sequel/adapters/shared/sqlite.rb 341 def column_definition_default_sql(sql, column) 342 sql << " DEFAULT (#{literal(column[:default])})" if column.include?(:default) 343 if (generated = column[:generated_always_as]) 344 if (generated_type = column[:generated_type]) && (generated_type == :stored || generated_type == :virtual) 345 generated_type = generated_type.to_s.upcase 346 end 347 sql << " GENERATED ALWAYS AS (#{literal(generated)}) #{generated_type}" 348 end 349 end
Surround default with parens to appease SQLite. Add support for GENERATED ALWAYS AS.
Source
# File lib/sequel/adapters/shared/sqlite.rb 352 def column_schema_integer_min_max_values(column) 353 nil 354 end
SQLite does not restrict the integer or decimal type to a specific range.
Source
# File lib/sequel/adapters/shared/sqlite.rb 359 def connection_pragmas 360 ps = [] 361 v = typecast_value_boolean(opts.fetch(:foreign_keys, 1)) 362 ps << "PRAGMA foreign_keys = #{v ? 1 : 0}" 363 v = typecast_value_boolean(opts.fetch(:case_sensitive_like, 1)) 364 ps << "PRAGMA case_sensitive_like = #{v ? 1 : 0}" 365 [[:auto_vacuum, AUTO_VACUUM], [:synchronous, SYNCHRONOUS], [:temp_store, TEMP_STORE]].each do |prag, con| 366 if v = opts[prag] 367 raise(Error, "Value for PRAGMA #{prag} not supported, should be one of #{con.join(', ')}") unless v = con.index(v.to_sym) 368 ps << "PRAGMA #{prag} = #{v}" 369 end 370 end 371 ps 372 end
Source
# File lib/sequel/adapters/shared/sqlite.rb 375 def create_table_sql(name, generator, options) 376 if options[:strict] && options[:without_rowid] 377 "#{super} STRICT, WITHOUT ROWID" 378 elsif options[:strict] 379 "#{super} STRICT" 380 elsif options[:without_rowid] 381 "#{super} WITHOUT ROWID" 382 elsif options[:using] 383 "CREATE VIRTUAL TABLE#{' IF NOT EXISTS' if options[:if_not_exists]} #{create_table_table_name_sql(name, options)} USING #{options[:using]}" 384 else 385 super 386 end 387 end
Support creating STRICT AND/OR WITHOUT ROWID tables via :strict and :without_rowid options, and VIRTUAL tables with :using option.
Source
# File lib/sequel/adapters/shared/sqlite.rb 390 def create_view_prefix_sql(name, options) 391 create_view_sql_append_columns("CREATE #{'TEMPORARY 'if options[:temp]}VIEW #{quote_schema_table(name)}", options[:columns]) 392 end
SQLite support creating temporary views.
Source
# File lib/sequel/adapters/shared/sqlite.rb 404 def database_error_regexps 405 DATABASE_ERROR_REGEXPS 406 end
Source
# File lib/sequel/adapters/shared/sqlite.rb 409 def database_specific_error_class(exception, opts) 410 case sqlite_error_code(exception) 411 when 1299 412 NotNullConstraintViolation 413 when 1555, 2067, 2579 414 UniqueConstraintViolation 415 when 787 416 ForeignKeyConstraintViolation 417 when 275 418 CheckConstraintViolation 419 when 19 420 ConstraintViolation 421 when 517 422 SerializationFailure 423 else 424 super 425 end 426 end
Recognize SQLite error codes if the exception provides access to them.
Source
# File lib/sequel/adapters/shared/sqlite.rb 429 def defined_columns_for(table) 430 cols = parse_pragma(table, OPTS) 431 cols.each do |c| 432 c[:default] = LiteralString.new(c[:default]).freeze if c[:default] 433 c[:type] = c[:db_type] 434 end 435 cols 436 end
The array of column schema hashes for the current columns in the table
Source
# File lib/sequel/adapters/shared/sqlite.rb 441 def duplicate_table(table, opts=OPTS) 442 remove_cached_schema(table) 443 def_columns = defined_columns_for(table) 444 old_columns = def_columns.map{|c| c[:name]} 445 opts[:old_columns_proc].call(old_columns) if opts[:old_columns_proc] 446 447 yield def_columns if defined?(yield) 448 449 constraints = (opts[:constraints] || []).dup 450 pks = [] 451 def_columns.each{|c| pks << c[:name] if c[:primary_key]} 452 if pks.length > 1 453 constraints << {:type=>:primary_key, :columns=>pks} 454 def_columns.each{|c| c[:primary_key] = false if c[:primary_key]} 455 end 456 457 # If dropping a foreign key constraint, drop all foreign key constraints, 458 # as there is no way to determine which one to drop. 459 unless opts[:no_foreign_keys] 460 fks = foreign_key_list(table) 461 462 # If dropping a column, if there is a foreign key with that 463 # column, don't include it when building a copy of the table. 464 if ocp = opts[:old_columns_proc] 465 fks.delete_if{|c| ocp.call(c[:columns].dup) != c[:columns]} 466 end 467 468 # Skip any foreign key columns where a constraint for those 469 # foreign keys is being dropped. 470 if sfkc = opts[:skip_foreign_key_columns] 471 fks.delete_if{|c| c[:columns] == sfkc} 472 end 473 474 constraints.concat(fks.each{|h| h[:type] = :foreign_key}) 475 end 476 477 # Determine unique constraints and make sure the new columns have them 478 unique_columns = [] 479 skip_indexes = [] 480 indexes(table, :only_autocreated=>true).each do |name, h| 481 skip_indexes << name 482 if h[:unique] && !opts[:no_unique] 483 if h[:columns].length == 1 484 unique_columns.concat(h[:columns]) 485 elsif h[:columns].map(&:to_s) != pks 486 constraints << {:type=>:unique, :columns=>h[:columns]} 487 end 488 end 489 end 490 unique_columns -= pks 491 unless unique_columns.empty? 492 unique_columns.map!{|c| quote_identifier(c)} 493 def_columns.each do |c| 494 c[:unique] = true if unique_columns.include?(quote_identifier(c[:name])) && c[:unique] != false 495 end 496 end 497 498 def_columns_str = (def_columns.map{|c| column_definition_sql(c)} + constraints.map{|c| constraint_definition_sql(c)}).join(', ') 499 new_columns = old_columns.dup 500 opts[:new_columns_proc].call(new_columns) if opts[:new_columns_proc] 501 502 qt = quote_schema_table(table) 503 bt = quote_identifier(backup_table_name(qt)) 504 a = [ 505 "ALTER TABLE #{qt} RENAME TO #{bt}", 506 "CREATE TABLE #{qt}(#{def_columns_str})", 507 "INSERT INTO #{qt}(#{dataset.send(:identifier_list, new_columns)}) SELECT #{dataset.send(:identifier_list, old_columns)} FROM #{bt}", 508 "DROP TABLE #{bt}" 509 ] 510 indexes(table).each do |name, h| 511 next if skip_indexes.include?(name) 512 if (h[:columns].map(&:to_s) - new_columns).empty? 513 a << alter_table_sql(table, h.merge(:op=>:add_index, :name=>name)) 514 end 515 end 516 a 517 end
Duplicate an existing table by creating a new table, copying all records from the existing table into the new table, deleting the existing table and renaming the new table to the existing table’s name.
Source
# File lib/sequel/adapters/shared/sqlite.rb 521 def on_delete_sql_to_sym(str) 522 case str 523 when 'RESTRICT' 524 :restrict 525 when 'CASCADE' 526 :cascade 527 when 'SET NULL' 528 :set_null 529 when 'SET DEFAULT' 530 :set_default 531 when 'NO ACTION' 532 :no_action 533 end 534 end
Does the reverse of on_delete_clause, eg. converts strings like +‘SET NULL’+ to symbols :set_null.
Source
# File lib/sequel/adapters/shared/sqlite.rb 537 def parse_pragma(table_name, opts) 538 pks = 0 539 sch = _parse_pragma_ds(table_name, opts).map do |row| 540 if sqlite_version > 33100 541 # table_xinfo PRAGMA used, remove hidden columns 542 # that are not generated columns 543 if row[:generated] = (row.delete(:hidden) != 0) 544 row[:type] = row[:type].sub(' GENERATED ALWAYS', '') 545 end 546 end 547 548 row.delete(:cid) 549 row[:allow_null] = row.delete(:notnull).to_i == 0 550 row[:default] = row.delete(:dflt_value) 551 row[:default] = nil if blank_object?(row[:default]) || row[:default] == 'NULL' 552 row[:db_type] = row.delete(:type) 553 if row[:primary_key] = row.delete(:pk).to_i > 0 554 pks += 1 555 # Guess that an integer primary key uses auto increment, 556 # since that is Sequel's default and SQLite does not provide 557 # a way to introspect whether it is actually autoincrementing. 558 row[:auto_increment] = row[:db_type].downcase == 'integer' 559 end 560 row[:type] = schema_column_type(row[:db_type]) 561 row 562 end 563 564 sch.compact! 565 566 if pks > 1 567 # SQLite does not allow use of auto increment for tables 568 # with composite primary keys, so remove auto_increment 569 # if composite primary keys are detected. 570 sch.each{|r| r.delete(:auto_increment)} 571 end 572 573 sch 574 end
Parse the output of the table_info pragma
Source
# File lib/sequel/adapters/shared/sqlite.rb 578 def schema_parse_table(table_name, opts) 579 m = output_identifier_meth(opts[:dataset]) 580 parse_pragma(table_name, opts).map do |row| 581 [m.call(row.delete(:name)), row] 582 end 583 end
Source
# File lib/sequel/adapters/shared/sqlite.rb 586 def sqlite_error_code(exception) 587 nil 588 end
Don’t support SQLite error codes for exceptions by default.
Source
# File lib/sequel/adapters/shared/sqlite.rb 591 def tables_and_views(filter, opts) 592 m = output_identifier_meth 593 metadata_dataset.from(:sqlite_master).server(opts[:server]).where(filter).map{|r| m.call(r[:name])} 594 end
Backbone of the tables and views support.
Source
# File lib/sequel/adapters/shared/sqlite.rb 599 def type_literal_generic_bignum_symbol(column) 600 column[:auto_increment] ? :integer : super 601 end
SQLite only supports AUTOINCREMENT on integer columns, not bigint columns, so use integer instead of bigint for those columns.