Embedded Architecture and Type Affinity

Article · 7:00

One file, no server, and the dynamic type system that lets text into an integer column - with the STRICT tables and PRAGMAs that make it behave.

There is no server. SQLite is a C library linked into your process. sqlite3_open("app.db") opens a file; a query executes on your thread, in your process, reading pages from that file. No socket, no daemon, no handshake.

What follows from that is the whole operational character of the engine. There is no network latency, because there is no network. There is no authentication, because there is no connection to authenticate - the security model is the file system's permissions, and that is the entire story. Deployment is copying a file. And concurrency is bounded by what a single file can support, which Module 3 covers in detail.

The right question is never "is SQLite fast enough" - it usually is, and it will outperform a client-server database for many workloads precisely because there is no round trip. The right question is "does this workload have one writer at a time, and is the file on local storage". When both answers are yes, SQLite is frequently the best available choice. When either is no, it is the wrong tool and no amount of tuning changes that.

Type affinity is the thing to understand first, because it will otherwise cost you a day. SQLite has dynamic typing: the value has a type, not the column. A column declared INTEGER has an integer affinity, which is a preference - SQLite will try to convert a value to it, and if the conversion is not lossless, it stores the original type anyway, without complaint.

So INSERT INTO t (id) VALUES ('hello') into an INTEGER column succeeds and stores the string 'hello'. There is no error. The next developer's SELECT ... WHERE id > 5 then silently omits that row, because in SQLite's type ordering text sorts after all numbers.

The affinity rules themselves are quietly entertaining: a column declared VARCHAR gets TEXT affinity, one declared FLOATING POINT gets INTEGER affinity because the name contains "INT", and a column declared with any type SQLite does not recognise gets BLOB affinity. These are documented and stable; they are also not what anybody expects.

STRICT tables, from version 3.37, fix this. Append STRICT to CREATE TABLE and the column types are enforced: a wrong type is an error. The allowed types narrow to INT, INTEGER, REAL, TEXT, BLOB and ANY. Use STRICT for every new table. The only reason not to is compatibility with an older engine.

The PRAGMAs that matter. foreign_keys is off by default for backwards compatibility, which means your foreign keys do nothing until you turn it on - per connection, every connection. journal_mode = WAL is the single most valuable setting for a concurrent application. busy_timeout decides whether a locked database returns an immediate error or waits. synchronous trades durability against write speed.

Laboratory exercise 1 - provision and verify a sandbox.

Create a database from a written script. Define at least one STRICT table and one legacy table, then demonstrate affinity: insert a string into an integer column in both, and show the legacy table accepting it and the STRICT table refusing. Record the engine version, page size, journal mode and the full PRAGMA configuration your application sets.

Load at least 50,000 synthetic rows using a recursive CTE rather than typing them. Verify reads and writes, and record the resulting file size against the row count.

Deliverable: a schema.sql, a short README taking a colleague from nothing to a loaded database, the demonstration of affinity with its output, and your PRAGMA settings with one sentence of justification each. A setting you cannot justify is one you copied.

-- ------------------------------------------------------------------
-- The configuration an application should set on EVERY connection.
-- These are per-connection, not stored in the file - the commonest
-- SQLite bug is assuming otherwise.
-- ------------------------------------------------------------------
PRAGMA foreign_keys = ON;      -- OFF BY DEFAULT. Your foreign keys do
                               -- nothing until this runs. Every time.
PRAGMA journal_mode = WAL;     -- persists in the file; readers no
                               -- longer block the writer. Module 3.
PRAGMA synchronous = NORMAL;   -- with WAL this is safe against process
                               -- crash; FULL also survives power loss
                               -- at a cost. Never OFF in production.
PRAGMA busy_timeout = 5000;    -- wait 5s for a lock rather than
                               -- returning SQLITE_BUSY immediately.
PRAGMA temp_store = MEMORY;
PRAGMA cache_size = -64000;    -- negative = kibibytes. 64 MB here.

-- ------------------------------------------------------------------
-- TYPE AFFINITY, demonstrated. Run this; it is more convincing than
-- any explanation.
-- ------------------------------------------------------------------
CREATE TABLE legacy (id INTEGER, amount REAL, label TEXT);

INSERT INTO legacy VALUES ('hello', 'world', 42);
--                         ^^^^^^^  ^^^^^^^  ^^
-- All three accepted. No error, no warning. The declared types are
-- PREFERENCES, and a conversion that would lose information is simply
-- not performed.

SELECT id, typeof(id), amount, typeof(amount), label, typeof(label)
FROM legacy;
--  hello|text|world|text|42|integer
--
-- And now the bug this causes, three months later:
SELECT count(*) FROM legacy WHERE id > 5;   -- 0. The row is invisible.
-- In SQLite's sort order NULL < numbers < text < blob, so 'hello'
-- compares greater than every integer, and this filter excludes it
-- while a filter for `id < 5` also excludes it.

-- ------------------------------------------------------------------
-- STRICT tables. Available since 3.37. Use them for everything new.
-- ------------------------------------------------------------------
CREATE TABLE expense (
    id          INTEGER PRIMARY KEY,          -- rowid alias: no extra
                                              -- index, and it is fast
    category_id INTEGER NOT NULL REFERENCES category(id) ON DELETE RESTRICT,
    -- Money as integer minor units. REAL is binary floating point and
    -- a ledger in binary floating point does not balance.
    amount_minor INTEGER NOT NULL CHECK (amount_minor > 0),
    currency    TEXT    NOT NULL CHECK (length(currency) = 3),
    -- SQLite has no date type. ISO-8601 text sorts correctly and reads
    -- correctly; the alternative is an integer epoch. Pick one and be
    -- consistent - mixing them is a long afternoon.
    spent_at    TEXT    NOT NULL CHECK (spent_at LIKE '____-__-__%'),
    note        TEXT,
    metadata    TEXT    CHECK (metadata IS NULL OR json_valid(metadata))
) STRICT;
-- ^^^^^^ the whole point of this table definition

CREATE TABLE category (
    id   INTEGER PRIMARY KEY,
    name TEXT NOT NULL UNIQUE
) STRICT;

-- Now the same insert is rejected:
-- INSERT INTO expense (id) VALUES ('hello');
-- Error: cannot store TEXT value in INTEGER column expense.id
--
-- STRICT narrows the allowed declared types to INT, INTEGER, REAL,
-- TEXT, BLOB and ANY. Anything else is a schema error, which also
-- catches the typo'd `VARCHAR2` you inherited from an Oracle schema.

-- ------------------------------------------------------------------
-- Synthetic data, generated. A recursive CTE is SQLite's
-- generate_series, and it is in every laboratory in this course.
-- ------------------------------------------------------------------
INSERT INTO category (name) VALUES ('food'),('travel'),('software'),('rent');

WITH RECURSIVE seq(n) AS (
    SELECT 1 UNION ALL SELECT n + 1 FROM seq WHERE n < 50000
)
INSERT INTO expense (category_id, amount_minor, currency, spent_at, note)
SELECT (n % 4) + 1,
       abs(random() % 50000) + 1,
       'GBP',
       date('2026-01-01', '+' || (n % 365) || ' days'),
       'expense number ' || n
FROM seq;

-- ------------------------------------------------------------------
-- Verifying the install - the deliverable.
-- ------------------------------------------------------------------
SELECT sqlite_version();                      -- must be >= 3.37
PRAGMA journal_mode;  PRAGMA foreign_keys;
PRAGMA page_size;     PRAGMA page_count;
SELECT count(*) FROM expense;

-- Where the bytes went, which is worth knowing before Module 4:
SELECT name, SUM(pgsize) AS bytes
FROM dbstat GROUP BY name ORDER BY bytes DESC;

Discussion

No questions on this topic yet. Sign in to ask the first one.