Ptree: Interactive Tree of Life Explorer Blog & articles

Blog · Backend · · 2 min read

Self-diffing SQLite schemas without migrations

Ptree's pipeline maintains dozens of long-lived acquisition and cache SQLite stores that accumulate scraped iNaturalist reception, acoustic measurements, photo scores, and fetched metadata over months. Numbered migration scripts (001_init.sql, 002_add_col.sql, 003_fix_index.sql) rot quickly in a single-developer codebase: every schema tweak adds another file, branches conflict on version numbers, and nobody can tell what a table actually looks like without replaying twenty files in their head.

Ptree's database helper replaces migration scripts with a single function, conformSchema(db, ddl), that compares a live database against the declarative CREATE TABLE and CREATE INDEX statements already in the code.

Using SQLite as its own DDL parser

Writing a SQL parser in JavaScript to diff CREATE TABLE statements is fragile, because SQLite accepts type affinities, column constraints, expression indexes, WITHOUT ROWID, and STRICT tables in dozens of syntactic forms. Instead of parsing DDL strings, conformSchema() executes the target ddl inside a fresh :memory: DatabaseSync:

const target = new DatabaseSync(":memory:");
target.exec(ddl);

Now both the live database and the desired schema are real SQLite databases that answer the exact same introspection pragmas:

  • PRAGMA table_info(name) returns every column's name, declared type, notnull flag, default value, and primary-key position.
  • PRAGMA index_list(name) and PRAGMA index_info(index) return every non-autoindex name, uniqueness flag, partial WHERE clause, and ordered column list.

Comparing the two dictionaries tells conformSchema() the exact difference between the on-disk file and the current source code. For example, when Ptree added YAMNet speech-classification columns (classes BLOB) and momentary loudness series (momentary TEXT) to an acoustics store that already held tens of thousands of measured wildlife recordings, there was no migration file to write or version table to bump: editing the table's single CREATE TABLE declaration added both columns on the next open without touching existing rows.

Applying safe diffs and refusing unsafe ones

Once conformSchema() has both table and index maps, it reconciles them inside a transaction in a strict order:

  1. Create missing tables straight from the target sqlite_master SQL.
  2. Drop obsolete or changed indexes first, so no index blocks a subsequent ALTER TABLE DROP COLUMN.
  3. Drop removed columns with ALTER TABLE t DROP COLUMN c.
  4. Add missing columns with ALTER TABLE t ADD COLUMN ..., copied verbatim from the column's definition in the target schema.
  5. Create missing or changed indexes from the target sqlite_master SQL.

When a table's primary key changed, a column's type or nullability changed incompatibly, or a new NOT NULL column has no DEFAULT value on a non-empty table, conformSchema() refuses to guess and throws immediately with the table and column name instead of silently rebuilding tables or inventing fallback values.

One source of truth per store

Every persistent store keeps one declarative SCHEMA string at the top of its module. Adding an acoustic metric column, dropping a retired field, or changing an index column order is a one-line edit to that string. On the next run, every existing database on disk converges to the new shape automatically, and any freshly created database starts from the exact same string.

There is no schema_migrations table to drift out of sync, no historical archive of abandoned columns, and no divergence between a brand-new database and one that has been accumulating records for a year.