class ActiveRecord::ConnectionAdapters::SQLite3Adapter
Active Record SQLite3 Adapter
The SQLite3 adapter works with the sqlite3 driver.
Options:
-
:database
(String): Filesystem path to the database file. -
:statement_limit
(Integer): Maximum number of prepared statements to cache per database connection. (default: 1000) -
:timeout
(Integer): Timeout in milliseconds to use when waiting for a lock. (default: no wait) -
:strict
(Boolean): Enable or disable strict mode. When enabled, this will disallow double-quoted string literals in SQL statements. (default: seestrict_strings_by_default
) -
:extensions
(Array): (requires sqlite3 v2.4.0) Each entry specifies a sqlite extension to load for this database. The entry may be a filesystem path, or the name of a class that responds to.to_path
to provide the filesystem path for the extension. See sqlite3-ruby documentation for more information.
There may be other options available specific to the SQLite3
driver. Please read the documentation for SQLite::Database.new
Inherits From
-
class
ActiveRecord::
ConnectionAdapters:: AbstractAdapter -
module
ActiveRecord::
ConnectionAdapters:: SQLite3:: DatabaseStatements
Constants
{
"foreign_keys" => true,
"journal_mode" => :wal,
"synchronous" => :normal,
"mmap_size" => 134217728, # 128 megabytes
"journal_size_limit" => 67108864, # 64 megabytes
"cache_size" => 2000
}
{
primary_key: "integer PRIMARY KEY AUTOINCREMENT NOT NULL",
string: { name: "varchar" },
text: { name: "text" },
integer: { name: "integer" },
float: { name: "float" },
decimal: { name: "decimal" },
datetime: { name: "datetime" },
time: { name: "time" },
date: { name: "date" },
binary: { name: "blob" },
boolean: { name: "boolean" },
json: { name: "json" },
}
Public class methods
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 60
def dbconsole(config, options = {})
args = []
args << "-#{options[:mode]}" if options[:mode]
args << "-header" if options[:header]
args << File.expand_path(config.database, Rails.respond_to?(:root) ? Rails.root : nil)
find_cmd_and_exec(ActiveRecord.database_cli[:sqlite], *args)
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 125
def initialize(...)
super
@memory_database = false
case @config[:database].to_s
when ""
raise ArgumentError, "No database file specified. Missing argument: database"
when ":memory:"
@memory_database = true
when /\Afile:/
else
# Otherwise we have a path relative to Rails.root
@config[:database] = File.expand_path(@config[:database], Rails.root) if defined?(Rails.root)
dirname = File.dirname(@config[:database])
unless File.directory?(dirname)
begin
FileUtils.mkdir_p(dirname)
rescue SystemCallError
raise ActiveRecord::NoDatabaseError.new(connection_pool: @pool)
end
end
end
@last_affected_rows = nil
@previous_read_uncommitted = nil
@config[:strict] = ConnectionAdapters::SQLite3Adapter.strict_strings_by_default unless @config.key?(:strict)
extensions = @config.fetch(:extensions, []).map do |extension|
extension.safe_constantize || extension
end
@connection_parameters = @config.merge(
database: @config[:database].to_s,
results_as_hash: true,
default_transaction_mode: :immediate,
extensions: extensions
)
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 50
def new_client(config)
::SQLite3::Database.new(config[:database].to_s, config)
rescue Errno::ENOENT => error
if error.message.include?("No such file or directory")
raise ActiveRecord::NoDatabaseError
else
raise
end
end
Configure the SQLite3Adapter
to be used in a “strict strings” mode. When enabled, this will disallow double-quoted string literals in SQL statements, which may prevent some typographical errors like creating an index for a non-existent column. The default is false
.
If you wish to enable this mode you can add the following line to your application.rb file:
config.active_record.sqlite3_adapter_strict_strings_by_default = true
This can also be configured on individual databases by setting the strict:
option.
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 90
class_attribute :strict_strings_by_default, default: false
Public instance methods
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 239
def active?
if connected?
verified!
true
end
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 426
def add_timestamps(table_name, **options)
options[:null] = false if options[:null].nil?
if !options.key?(:precision)
options[:precision] = 6
end
alter_table(table_name) do |definition|
definition.column :created_at, :datetime, **options
definition.column :updated_at, :datetime, **options
end
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 235
def connected?
!(@raw_connection.nil? || @raw_connection.closed?)
end
Creates a virtual table
Example:
create_virtual_table :emails, :fts5, ['sender', 'title',' body']
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 342
def create_virtual_table(table_name, module_name, values)
exec_query "CREATE VIRTUAL TABLE IF NOT EXISTS #{table_name} USING #{module_name} (#{values.join(", ")})"
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 164
def database_exists?
@config[:database] == ":memory:" || File.exist?(@config[:database].to_s)
end
Disconnects from the database if already connected. Otherwise, this method does nothing.
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 250
def disconnect!
super
@raw_connection&.close rescue nil
@raw_connection = nil
end
Drops a virtual table
Although this command ignores module_name
and values
, it can be helpful to provide these in a migration’s change
method so it can be reverted. In that case, module_name
, values
and options
will be used by create_virtual_table
.
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 351
def drop_virtual_table(table_name, module_name, values, **options)
drop_table(table_name)
end
Returns the current database encoding format as a string, e.g. ‘UTF-8’
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 266
def encoding
any_raw_connection.encoding.to_s
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 446
def foreign_keys(table_name)
# SQLite returns 1 row for each column of composite foreign keys.
fk_info = internal_exec_query("PRAGMA foreign_key_list(#{quote(table_name)})", "SCHEMA")
# Deferred or immediate foreign keys can only be seen in the CREATE TABLE sql
fk_defs = table_structure_sql(table_name)
.select do |column_string|
column_string.start_with?("CONSTRAINT") &&
column_string.include?("FOREIGN KEY")
end
.to_h do |fk_string|
_, from, table, to = fk_string.match(FK_REGEX).to_a
_, mode = fk_string.match(DEFERRABLE_REGEX).to_a
deferred = mode&.downcase&.to_sym || false
[[table, from, to], deferred]
end
grouped_fk = fk_info.group_by { |row| row["id"] }.values.each { |group| group.sort_by! { |row| row["seq"] } }
grouped_fk.map do |group|
row = group.first
options = {
on_delete: extract_foreign_key_action(row["on_delete"]),
on_update: extract_foreign_key_action(row["on_update"]),
deferrable: fk_defs[[row["table"], row["from"], row["to"]]]
}
if group.one?
options[:column] = row["from"]
options[:primary_key] = row["to"]
else
options[:column] = group.map { |row| row["from"] }
options[:primary_key] = group.map { |row| row["to"] }
end
ForeignKeyDefinition.new(table_name, row["table"], options)
end
end
Renames a table.
Example:
rename_table('octopuses', 'octopi')
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 359
def rename_table(table_name, new_name, **options)
validate_table_length!(new_name) unless options[:_uses_legacy_table_name]
schema_cache.clear_data_source_cache!(table_name.to_s)
schema_cache.clear_data_source_cache!(new_name.to_s)
exec_query "ALTER TABLE #{quote_table_name(table_name)} RENAME TO #{quote_table_name(new_name)}"
rename_table_indexes(table_name, new_name, **options)
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 188
def requires_reloading?
true
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 196
def supports_check_constraints?
true
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 212
def supports_common_table_expressions?
database_version >= "3.8.3"
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 227
def supports_concurrent_connections?
!@memory_database
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 204
def supports_datetime_with_precision?
true
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 168
def supports_ddl_transactions?
true
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 278
def supports_deferrable_constraints?
true
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 270
def supports_explain?
true
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 184
def supports_expression_index?
database_version >= "3.9.0"
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 192
def supports_foreign_keys?
true
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 257
def supports_index_sort_order?
true
end
Alias for:
supports_insert_on_conflict?
.
Also aliased as:
supports_insert_on_duplicate_skip?
, supports_insert_on_duplicate_update?
, supports_insert_conflict_target?
.
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 220
def supports_insert_on_conflict?
database_version >= "3.24.0"
end
Alias for:
supports_insert_on_conflict?
.
Alias for:
supports_insert_on_conflict?
.
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 216
def supports_insert_returning?
database_version >= "3.35.0"
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 208
def supports_json?
true
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 274
def supports_lazy_transactions?
true
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 180
def supports_partial_index?
true
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 172
def supports_savepoints?
true
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 176
def supports_transaction_isolation?
true
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 200
def supports_views?
true
end
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 231
def supports_virtual_columns?
database_version >= "3.31.0"
end
Returns a list of defined virtual tables
Source code GitHub
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 326
def virtual_tables
query = <<~SQL
SELECT name, sql FROM sqlite_master WHERE sql LIKE 'CREATE VIRTUAL %';
SQL
exec_query(query, "SCHEMA").cast_values.each_with_object({}) do |row, memo|
table_name, sql = row[0], row[1]
_, module_name, arguments = sql.match(VIRTUAL_TABLE_REGEX).to_a
memo[table_name] = [module_name, arguments]
end.to_a
end