SQLite
suggest changeSQLite is a full SQL database in a library. There is no server to install or run: the whole database is one file on disk (or a block of memory), and your process reads and writes it directly. That makes it a good fit for command line tools, desktop apps, tests, caches, local data analysis and, with a few settings, small and medium web apps.
Ruby talks to SQLite through the sqlite3 gem. This article covers that gem in depth: opening databases, placeholders, prepared statements, how Ruby values map to SQLite types, transactions, concurrency settings (WAL, busy timeouts), upserts, JSON, full-text search, Ruby functions callable from SQL, and backups. The layers above the driver (Sequel, Active Record, migrations, pools) are covered in Relational databases.
The examples were run with Ruby 4.0, sqlite3 2.10 and SQLite 3.54.
Installing
# Gemfile
gem "sqlite3", "~> 2.0"
The gem ships precompiled native builds for Linux, macOS and Windows with SQLite bundled, so gem install sqlite3 needs no compiler and no system library. Check which versions you got:
require 'sqlite3'
puts SQLite3::VERSION # the gem
puts SQLite3::SQLITE_VERSION # the bundled SQLite library
2.10.0
3.54.0
Opening a database and running queries
SQLite3::Database.new(path) opens the file, creating it if it doesn't exist. SQLite3::Database.open with a block closes the database when the block ends, even if it raises:
require 'sqlite3'
SQLite3::Database.open('notes.db') do |db|
db.execute(<<~SQL)
CREATE TABLE notes (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
body TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)
SQL
db.execute('INSERT INTO notes (title, body) VALUES (?, ?)', ['Shopping', 'milk, eggs'])
db.execute('INSERT INTO notes (title, body) VALUES (:t, :b)', t: 'Ideas', b: nil)
db.execute('INSERT INTO notes (title, body) VALUES (?1, ?1)', ['Echo'])
puts "last id: #{db.last_insert_row_id}"
p db.execute('SELECT id, title, body FROM notes')
p db.get_first_row('SELECT title, body FROM notes WHERE id = ?', 3)
p db.get_first_value('SELECT count(*) FROM notes')
end
db = SQLite3::Database.new('notes.db', results_as_hash: true)
db.execute('SELECT id, title FROM notes ORDER BY title') { |row| p row }
p db.closed?
db.close
p db.closed?
last id: 3
[[1, "Shopping", "milk, eggs"], [2, "Ideas", nil], [3, "Echo", "Echo"]]
["Echo", "Echo"]
3
{"id" => 3, "title" => "Echo"}
{"id" => 2, "title" => "Ideas"}
{"id" => 1, "title" => "Shopping"}
false
true
The main query methods:
| Method | Returns |
|---|---|
execute(sql, binds) |
all rows as an array, or yields each row to a block |
get_first_row(sql, *binds) |
the first row, or nil |
get_first_value(sql, *binds) |
the first column of the first row, or nil |
execute_batch(sql) |
runs several ;-separated statements (no results) |
last_insert_row_id |
the rowid of the most recent INSERT |
changes |
rows affected by the last INSERT, UPDATE or DELETE |
Rows are arrays by default. With results_as_hash: true they are hashes keyed by column name (strings). Placeholders come in three forms: ? (positional), :name (bound from a hash, with symbol or string keys) and ?1 (numbered, can be reused).
Other ways to open a database:
SQLite3::Database.new(':memory:') # private in-memory database
SQLite3::Database.new('app.db', readonly: true) # fails on any write
SQLite3::Database.new('file:app.db?mode=ro', flags: SQLite3::Constants::Open::READONLY | SQLite3::Constants::Open::URI)
An :memory: database belongs to one connection and disappears when it closes. A second Database.new(':memory:') gets a different, empty database.
Always use placeholders for values. Building SQL with "WHERE title = '#{input}'" is an SQL injection hole, and it also breaks on any value with a quote in it. See Application security.
Prepared statements
execute compiles the SQL every time. When you run the same statement many times, compile it once with prepare and run it with different values:
require 'sqlite3'
db = SQLite3::Database.new(':memory:')
db.execute('CREATE TABLE temps (city TEXT, day TEXT, celsius REAL)')
ins = db.prepare('INSERT INTO temps VALUES (?, ?, ?)')
[['Oslo', '2026-10-15', 7.5], ['Oslo', '2026-10-16', 6.0],
['Rome', '2026-10-15', 19.0], ['Rome', '2026-10-16', 21.5]].each do |row|
ins.execute(*row)
end
ins.close
stmt = db.prepare('SELECT day, celsius FROM temps WHERE city = :city ORDER BY day')
p stmt.columns
p stmt.types
p stmt.bind_parameter_count
%w[Oslo Rome].each do |city|
rs = stmt.execute(city: city)
rs.each { |day, c| puts "#{city} #{day} #{c}" }
end
stmt.reset!
stmt.bind_param(:city, "Rome")
while (row = stmt.step)
p row
end
stmt.reset!
p stmt.execute!('Oslo')
stmt.close
p stmt.closed?
["day", "celsius"]
["text", "real"]
1
Oslo 2026-10-15 7.5
Oslo 2026-10-16 6.0
Rome 2026-10-15 19.0
Rome 2026-10-16 21.5
["2026-10-15", 19.0]
["2026-10-16", 21.5]
[["2026-10-15", 7.5], ["2026-10-16", 6.0]]
true
execute(*binds)resets the statement, binds the values and returns a lazyResultSetyou can iterate.execute!(*binds)does the same and returns all rows as an array.bind_paramplusstepis the low-level interface:stepreturns one row at a time andnilat the end. Callreset!before binding new values.columnsandtypesdescribe the result (the declared column types).
Close statements when you're done with them. An unfinished statement keeps memory and can keep a read transaction open, which blocks WAL checkpoints. A small helper makes closing automatic:
def with_statement(db, sql)
stmt = db.prepare(sql)
yield stmt
ensure
stmt&.close
end
Types: what Ruby values become
SQLite has only five storage classes: INTEGER, REAL, TEXT, BLOB and NULL. The gem maps Ruby values onto them directly:
require 'sqlite3'
db = SQLite3::Database.new(':memory:')
db.execute('CREATE TABLE vals (v)') # no declared type: any value goes
values = [42, 2**62, 3.14, 'héllo', nil, SQLite3::Blob.new("\x00\xFF\x10".b)]
values.each { |v| db.execute('INSERT INTO vals VALUES (?)', [v]) }
db.execute('SELECT v, typeof(v) FROM vals') do |v, type|
printf("%-8s %-22p %s\n", type, v, v.class)
end
p db.execute('SELECT v FROM vals WHERE typeof(v) = ?', ['text']).first.first.encoding
[true, Time.utc(2026, 10, 17, 12, 30), :sym, 1.5r].each do |v|
db.execute('INSERT INTO vals VALUES (?)', [v])
rescue => e
puts "#{v.inspect}: #{e.class}: #{e.message}"
end
integer 42 Integer
integer 4611686018427387904 Integer
real 3.14 Float
text "héllo" String
null nil NilClass
blob "\x00\xFF\x10" String
#<Encoding:UTF-8>
true: RuntimeError: can't prepare TrueClass
2026-10-17 12:30:00 UTC: RuntimeError: can't prepare Time
:sym: RuntimeError: can't prepare Symbol
(3/2): RuntimeError: can't prepare Rational
Things to remember:
- Strings are stored as UTF-8
TEXT. Wrap binary data inSQLite3::Blob(or use a string withASCII-8BITencoding) to store it as aBLOB. Blobs come back as binary strings. - There is no boolean type. Store
1and0, and compare with== 1when reading. - There is no date type, and the gem won't convert a
Timefor you. Convert to a string or integer yourself (see below). - Integers are 64-bit. A larger Ruby
Integeris silently stored as aREALand loses precision, so store big numbers as text.
Type affinity and STRICT tables
Declared column types in SQLite are affinities, not constraints. SQLite converts a value to the column's type when it can do so without loss, and otherwise stores it as it is. VARCHAR(3) doesn't limit length either. Add STRICT to a table to get real type checks:
db = SQLite3::Database.new(':memory:')
db.execute('CREATE TABLE loose (n INTEGER, s VARCHAR(3))')
db.execute('INSERT INTO loose VALUES (?, ?)', ['123', 'far too long'])
db.execute('INSERT INTO loose VALUES (?, ?)', ['abc', 7])
p db.execute('SELECT n, typeof(n), s, typeof(s) FROM loose')
db.execute('CREATE TABLE strict (n INTEGER, s TEXT) STRICT')
db.execute('INSERT INTO strict VALUES (?, ?)', ['123', 'ok'])
p db.execute('SELECT n, typeof(n) FROM strict')
begin
db.execute('INSERT INTO strict VALUES (?, ?)', ['abc', 'x'])
rescue SQLite3::ConstraintException => e
puts "#{e.class}: #{e.message}"
end
[[123, "integer", "far too long", "text"], ["abc", "text", "7", "text"]]
[[123, "integer"]]
SQLite3::ConstraintException: cannot store TEXT value in INTEGER column strict.n
STRICT tables allow only INTEGER, REAL, TEXT, BLOB and ANY as column types. Use them for new schemas unless you need the loose behaviour.
Dates and times
SQLite's date functions (datetime, date, strftime, unixepoch) understand text in the form YYYY-MM-DD HH:MM:SS and Unix timestamps. Text in that form, in UTC, also sorts correctly, so range queries and indexes work on it:
require 'sqlite3'
require 'time'
FMT = '%Y-%m-%d %H:%M:%S' # SQLite's own format; sorts correctly as text
db = SQLite3::Database.new(':memory:', results_as_hash: true)
db.execute('CREATE TABLE logins (user TEXT, at TEXT, ok INTEGER)')
now = Time.utc(2026, 10, 17, 9, 15, 0)
db.execute('INSERT INTO logins VALUES (?, ?, ?)', ['ann', now.strftime(FMT), 1])
db.execute('INSERT INTO logins VALUES (?, ?, ?)', ['ann', (now - 3 * 86_400).strftime(FMT), 0])
db.execute('INSERT INTO logins VALUES (?, ?, ?)', ['bob', (now - 3600).strftime(FMT), 1])
rows = db.execute(<<~SQL, [now.strftime(FMT)])
SELECT user, at, ok, unixepoch(at) AS epoch FROM logins
WHERE at >= datetime(?, '-1 day')
ORDER BY at
SQL
rows.each do |r|
at = Time.strptime("#{r['at']} UTC", "#{FMT} %Z")
puts "#{r['user']} #{at.iso8601} ok=#{r['ok'] == 1} #{Time.at(r['epoch']).utc == at}"
end
bob 2026-10-17T08:15:00Z ok=true true
ann 2026-10-17T09:15:00Z ok=true true
Always convert to UTC before storing (time.utc.strftime(FMT)). Mixing formats, for example 2026-10-17T09:15:00Z in one row and 2026-10-17 09:15:00 in another, breaks text comparisons. Storing time.to_i in an INTEGER column is the other common choice. See Time for more on Ruby's time classes.
Transactions
Outside an explicit transaction, every statement is its own transaction. On a file database each commit waits for the data to reach the disk, which makes many single inserts very slow. Wrap bulk writes in transaction:
require 'sqlite3'
require 'benchmark'
def fresh_db
File.delete('bulk.db') if File.exist?('bulk.db')
db = SQLite3::Database.new('bulk.db')
db.execute('CREATE TABLE events (id INTEGER PRIMARY KEY, name TEXT, at INTEGER)')
db
end
N = 2_000
db = fresh_db
t1 = Benchmark.realtime do
N.times { |i| db.execute('INSERT INTO events (name, at) VALUES (?, ?)', ["e#{i}", i]) }
end
db.close
db = fresh_db
t2 = Benchmark.realtime do
db.transaction do
stmt = db.prepare('INSERT INTO events (name, at) VALUES (?, ?)')
N.times { |i| stmt.execute("e#{i}", i) }
stmt.close
end
end
printf("autocommit: %7.1f ms\n", t1 * 1000)
printf("one transaction: %7.1f ms\n", t2 * 1000)
p db.get_first_value('SELECT count(*) FROM events')
db.close
autocommit: 11874.2 ms
one transaction: 13.9 ms
2000
The exact numbers depend on the disk and OS (this was Windows with an SSD), but a difference of two or three orders of magnitude is typical.
With a block, transaction commits when the block finishes and rolls back if it raises. The exception is re-raised after the rollback:
require 'sqlite3'
db = SQLite3::Database.new(':memory:')
db.execute_batch(<<~SQL)
CREATE TABLE accounts (
id INTEGER PRIMARY KEY,
owner TEXT NOT NULL UNIQUE,
balance INTEGER NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts (owner, balance) VALUES ('alice', 100), ('bob', 20);
SQL
def transfer(db, from, to, amount)
db.transaction(:immediate) do
db.execute('UPDATE accounts SET balance = balance + ? WHERE owner = ?', [amount, to])
db.execute('UPDATE accounts SET balance = balance - ? WHERE owner = ?', [amount, from])
end
end
transfer(db, 'alice', 'bob', 30)
p db.execute('SELECT owner, balance FROM accounts')
begin
transfer(db, 'bob', 'alice', 500)
rescue SQLite3::ConstraintException => e
puts "rolled back: #{e.message}"
end
p db.execute('SELECT owner, balance FROM accounts')
p db.transaction_active?
db.transaction # without a block: BEGIN only
db.execute("UPDATE accounts SET balance = 0 WHERE owner = 'alice'")
p db.transaction_active?
db.rollback
p db.get_first_value("SELECT balance FROM accounts WHERE owner = 'alice'")
begin
db.execute("INSERT INTO accounts (owner, balance) VALUES ('bob', 5)")
rescue SQLite3::ConstraintException => e
puts "#{e.class}: #{e.message} (code #{e.code})"
end
p SQLite3::ConstraintException.ancestors.take(3)
[["alice", 70], ["bob", 50]]
rolled back: CHECK constraint failed: balance >= 0
[["alice", 70], ["bob", 50]]
false
true
70
SQLite3::ConstraintException: UNIQUE constraint failed: accounts.owner (code 19)
[SQLite3::ConstraintException, SQLite3::Exception, StandardError]
The second transfer added 500 to alice before the CHECK failed on bob. The rollback undid that, so both balances are unchanged.
transaction takes a mode:
| Mode | BEGIN ... |
When the write lock is taken |
|---|---|---|
:deferred (default) |
BEGIN DEFERRED |
at the first write statement |
:immediate |
BEGIN IMMEDIATE |
right away |
:exclusive |
BEGIN EXCLUSIVE |
right away; in rollback-journal mode also blocks readers |
Use :immediate for any transaction that writes. A deferred transaction that reads first and then writes can fail with SQLite3::BusyException in the middle if another connection wrote in between, and the busy timeout can't help in that case. With :immediate the wait happens at BEGIN, where it is safe to retry.
Every SQLite error is a subclass of SQLite3::Exception: ConstraintException, BusyException, ReadOnlyException, SQLException (bad SQL, missing table), CorruptException and so on. e.code gives the numeric SQLite result code. SQLite has no nested transaction calls, but you can use SAVEPOINT name / RELEASE name / ROLLBACK TO name through execute.
Concurrency: WAL, busy timeouts and pragmas
SQLite allows any number of readers but only one writer at a time, for the whole database. Two settings make this work well for apps with several threads or processes:
- WAL mode (
journal_mode = WAL): writers append to a separate-walfile, so readers keep reading the last committed state while a write is in progress. The setting is stored in the database file. - A busy timeout: when the database is locked, wait and retry instead of failing at once with
database is locked. This is per connection and off by default.
require 'sqlite3'
def connect
db = SQLite3::Database.new('app.db')
db.journal_mode = 'wal' # PRAGMA journal_mode = WAL (persisted in the file)
db.synchronous = 'normal' # safe with WAL, much faster than FULL
db.foreign_keys = true # off by default, per connection
db.busy_handler_timeout = 2000 # wait up to 2 s for locks, releasing the GVL
db
end
writer = connect
writer.execute('CREATE TABLE IF NOT EXISTS jobs (id INTEGER PRIMARY KEY, name TEXT)')
p writer.journal_mode
p writer.foreign_keys
p writer.get_first_value('PRAGMA synchronous')
other = connect
writer.transaction(:immediate) # takes the write lock
writer.execute("INSERT INTO jobs (name) VALUES ('a')")
p other.get_first_value('SELECT count(*) FROM jobs') # WAL: readers don't block
t = Thread.new do
sleep 0.3
writer.commit
end
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
other.execute("INSERT INTO jobs (name) VALUES ('b')") # waits for the lock
waited = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
t.join
puts "second write waited #{(waited * 1000).round(-2)} ms"
p other.get_first_value('SELECT count(*) FROM jobs')
nowait = SQLite3::Database.new('app.db') # no busy handler
writer.transaction(:immediate)
begin
nowait.execute("INSERT INTO jobs (name) VALUES ('c')")
rescue SQLite3::BusyException => e
puts "#{e.class}: #{e.message}"
end
writer.rollback
[writer, other, nowait].each(&:close)
"wal"
true
1
0
second write waited 300 ms
2
SQLite3::BusyException: database is locked
The reader saw 0 rows because the insert of 'a' wasn't committed yet. The second writer waited until the first one committed, and the connection without a busy handler failed immediately.
The Database object has accessor methods for most pragmas (journal_mode=, synchronous=, foreign_keys=, cache_size=, user_version= and so on). For anything else, run PRAGMA through execute. Pragmas other than journal_mode apply only to the connection that sets them, so set them every time you connect.
There are two ways to set a timeout:
busy_timeout = msuses SQLite's built-in handler, which sleeps while holding Ruby's GVL. Other Ruby threads in the process freeze while it waits.busy_handler_timeout = ms(gem 2.0+) retries from Ruby and releases the GVL between attempts. Prefer it in threaded programs such as Puma servers.
A connection in gem 2.x may be used from several threads, but only one statement runs at a time on it. Give each thread its own connection (or use a pool, see Database connection pooling) for real concurrency. After fork, the gem closes connections inherited from the parent in the child process and prints a warning, because sharing an SQLite connection across processes corrupts databases. Open new connections in the child.
While a WAL database is open you'll see app.db-wal and app.db-shm next to it. They belong to the database: copy all three, or use the backup methods below, never just app.db while it is in use.
Upserts and RETURNING
INSERT ... ON CONFLICT DO UPDATE inserts a row or updates the existing one in a single statement. RETURNING makes INSERT, UPDATE and DELETE return the affected rows, so you don't need a follow-up SELECT:
require 'sqlite3'
db = SQLite3::Database.new(':memory:', results_as_hash: true)
db.execute('CREATE TABLE page_views (path TEXT PRIMARY KEY, hits INTEGER NOT NULL)')
upsert = <<~SQL
INSERT INTO page_views (path, hits) VALUES (?, 1)
ON CONFLICT (path) DO UPDATE SET hits = hits + 1
RETURNING path, hits
SQL
%w[/ /about / / /about].each do |path|
p db.execute(upsert, [path]).first
end
p db.execute('DELETE FROM page_views WHERE hits < ? RETURNING path', [3])
{"path" => "/", "hits" => 1}
{"path" => "/about", "hits" => 1}
{"path" => "/", "hits" => 2}
{"path" => "/", "hits" => 3}
{"path" => "/about", "hits" => 2}
[{"path" => "/about"}]
Use ON CONFLICT DO NOTHING to skip duplicates silently. Inside DO UPDATE, excluded.column refers to the value you tried to insert.
JSON
SQLite has built-in JSON functions. Store a document as TEXT with to_json, and query into it with ->> (extract an SQL value), json_each (turn an array into rows) and json_set (modify):
require 'sqlite3'
require 'json'
db = SQLite3::Database.new(':memory:')
db.execute('CREATE TABLE orders (id INTEGER PRIMARY KEY, data TEXT NOT NULL CHECK (json_valid(data)))')
orders = [
{ customer: 'ann', items: [{ sku: 'A1', qty: 2 }, { sku: 'B7', qty: 1 }], paid: true },
{ customer: 'ben', items: [{ sku: 'A1', qty: 5 }], paid: false }
]
orders.each { |o| db.execute('INSERT INTO orders (data) VALUES (?)', [o.to_json]) }
p db.execute("SELECT id, data ->> '$.customer', data ->> '$.paid' FROM orders")
p db.execute(<<~SQL)
SELECT item.value ->> 'sku' AS sku, sum(item.value ->> 'qty') AS total
FROM orders, json_each(orders.data, '$.items') AS item
GROUP BY sku ORDER BY sku
SQL
db.execute("UPDATE orders SET data = json_set(data, '$.paid', json('true')) WHERE data ->> '$.customer' = ?", ['ben'])
raw = db.get_first_value('SELECT data FROM orders WHERE id = 2')
p JSON.parse(raw, symbolize_names: true)
[[1, "ann", 1], [2, "ben", 0]]
[["A1", 7], ["B7", 1]]
{customer: "ben", items: [{sku: "A1", qty: 5}], paid: true}
JSON true and false come out of ->> as 1 and 0. To search a JSON field quickly, index the expression: CREATE INDEX orders_customer ON orders (data ->> '$.customer'). More on Ruby's side of JSON in JSON with Ruby.
Full-text search with FTS5
The bundled SQLite includes FTS5, a full-text index with word matching, prefix queries, phrases, boolean operators and relevance ranking:
require 'sqlite3'
db = SQLite3::Database.new(':memory:')
db.execute('CREATE VIRTUAL TABLE docs USING fts5(title, body)')
docs = {
'Blocks' => 'A block is a chunk of code passed to a method and called with yield.',
'Procs and lambdas' => 'Procs and lambdas are blocks turned into objects you can store.',
'Threads' => 'Threads run code concurrently; the GVL limits parallel Ruby code.',
}
ins = db.prepare('INSERT INTO docs (title, body) VALUES (?, ?)')
docs.each { |t, b| ins.execute(t, b) }
ins.close
search = <<~SQL
SELECT title, snippet(docs, 1, '[', ']', '...', 6) AS snip
FROM docs WHERE docs MATCH ? ORDER BY rank
SQL
['block*', 'code NOT threads', '"parallel ruby"', 'title:lambdas'].each do |q|
puts "#{q}:"
db.execute(search, [q]) { |title, snip| puts " #{title}: #{snip}" }
end
block*:
Blocks: A [block] is a chunk of...
Procs and lambdas: Procs and lambdas are [blocks] turned...
code NOT threads:
Blocks: ...chunk of [code] passed to a...
"parallel ruby":
Threads: ...the GVL limits [parallel Ruby] code.
title:lambdas:
Procs and lambdas: Procs and lambdas are blocks turned...
ORDER BY rank sorts by BM25 relevance. snippet(table, column, before, after, ellipsis, tokens) returns a short excerpt with the matches marked. The query string has its own syntax, so a stray " or - typed by a user raises SQLite3::SQLException. Quote user input as a phrase ('"' + input.gsub('"', '""') + '"') if you don't want to expose that syntax.
Ruby functions in SQL
You can define SQL functions in Ruby. The block receives the arguments and returns the result. SQLite parses x REGEXP y but has no implementation for it: it calls a function named regexp, which you can provide:
require 'sqlite3'
db = SQLite3::Database.new(':memory:')
db.execute_batch(<<~SQL)
CREATE TABLE users (name TEXT, email TEXT, score INTEGER);
INSERT INTO users VALUES
('Ann', 'ann@Example.com', 7), ('Ben', 'ben@test.org', 3),
('Cid', 'cid@example.COM', 9), ('Dee', NULL, 4);
SQL
db.define_function('email_domain') do |email|
email&.split('@', 2)&.last&.downcase
end
# SQLite parses `x REGEXP y` but has no built-in implementation: it calls regexp(y, x)
db.define_function('regexp') do |pattern, value|
value && Regexp.new(pattern).match?(value) ? 1 : 0
end
p db.execute('SELECT email_domain(email), count(*) FROM users GROUP BY 1 ORDER BY 1')
p db.execute("SELECT name FROM users WHERE name REGEXP '^[AB]'")
class Median
def step(value)
(@values ||= []) << value unless value.nil?
end
def finalize
sorted = (@values || []).sort
return nil if sorted.empty?
mid = sorted.size / 2
sorted.size.even? ? (sorted[mid - 1] + sorted[mid]) / 2.0 : sorted[mid]
end
end
db.define_aggregator('median', Median.new)
p db.get_first_value('SELECT median(score) FROM users')
p db.execute("SELECT email_domain(email) AS d, median(score) FROM users GROUP BY d ORDER BY d")
[[nil, 1], ["example.com", 2], ["test.org", 1]]
[["Ann"], ["Ben"]]
5.5
[[nil, 4], ["example.com", 8.0], ["test.org", 3]]
The number of SQL arguments is taken from the block's arity. For an aggregate, pass define_aggregator a template object with step (called once per row) and finalize (returns the result). The gem clones the template for each group, and clone is shallow, so create instance variables lazily in step as above. If you set them in initialize, all groups share the same array. Functions exist only on the connection that defines them, and SQLite can't use an index on them, so WHERE email_domain(email) = ? scans the whole table.
Backups and read-only copies
Don't copy a database file while it's in use. Use SQLite's online backup API, or VACUUM INTO, which writes a compact, consistent copy:
require 'sqlite3'
src = SQLite3::Database.new('app.db')
dst = SQLite3::Database.new('backup.db')
backup = SQLite3::Backup.new(dst, 'main', src, 'main')
loop do
rc = backup.step(100) # copy 100 pages at a time
break if rc == SQLite3::Constants::ErrorCode::DONE
end
backup.finish
p dst.get_first_value('SELECT count(*) FROM jobs')
dst.close
src.execute('VACUUM INTO ?', ['snapshot.db']) # the target file must not exist
src.close
ro = SQLite3::Database.new('snapshot.db', readonly: true)
p ro.readonly?
p ro.execute('SELECT name FROM jobs ORDER BY id')
begin
ro.execute("DELETE FROM jobs")
rescue SQLite3::ReadOnlyException => e
puts "#{e.class}: #{e.message}"
end
p ro.get_first_value('PRAGMA integrity_check')
ro.close
2
true
[["a"], ["b"]]
SQLite3::ReadOnlyException: attempt to write a readonly database
"ok"
Copying in steps lets other connections write between steps. The backup API also works in the other direction: load a file database into :memory: for fast, throwaway processing, or save an in-memory database to disk.
Using SQLite with Sequel and Active Record
Everything above is the raw driver. For a query builder, migrations and models, put Sequel or Active Record on top. Both use the sqlite3 gem underneath:
require 'sequel'
DB = Sequel.sqlite('app.db') # or Sequel.connect('sqlite://app.db')
DB.run('PRAGMA journal_mode = WAL')
DB[:jobs].where(name: 'a').all
Rails 8 uses SQLite as its default database in production too, with WAL mode, IMMEDIATE transactions and a GVL-friendly busy handler already configured. Both libraries are covered in Relational databases.
Checklist
- Use placeholders for every value; never interpolate input into SQL.
- Wrap batches of writes in one
transaction, and use:immediatefor transactions that write. - For apps with concurrent access: WAL mode,
synchronous = normal,busy_handler_timeout, one connection per thread. - Turn on
foreign_keys = trueon every connection if you rely on foreign keys. - Use
STRICTtables to get type checking, store times as UTC text or integers, and booleans as1/0. - Close statements and databases, or use the block forms.
- Back up with
SQLite3::BackuporVACUUM INTO, not by copying the file.