📚 Encyclopedia

Databases · updated 2026-10-13

A JSON file as the database (flat-file catalogs)

jsonphpconcurrencyoptimistic-lockingflockcatalog

Small personal sites (videos.jhampton.io, 3d.jhampton.io) keep their whole catalog in one JSON file instead of a database: videos.json or models.json in a data directory outside the web root. It is simple and diffable, but needs a few rules to stay safe once more than one thing writes it.

Layout

Concurrency: revision numbers plus a lock

Several writers touch one catalog: the web admin, a CLI (videos-cli.php, 3d-cli.php) using an API token, and future tools. - The catalog has a rev that increments on every write. Each write sends the rev it read; the server answers 409 if it moved (check_rev()), and the admin reacts by reloading and flashing "The catalog changed elsewhere". Any new writer must send rev and handle 409 the same way, rather than clobbering. - Writes are serialized by an exclusive flock on a lock file in the data dir (with_catalog_lock() over .catalog.lock).

The numeric-string id trap (PHP)

Ids were ten random hex characters. About 1 in 100 comes out all digits, and json_decode turns such an object key into an integer, breaking every strict comparison ($id !== $editId). A video became unsavable, "colliding with its own slug". Fix: (string) casts at every read site, and reject all-digit ids at generation (ctype_digit). In general, never use JSON object keys that can look numeric in PHP, or always cast.

Save semantics: say what absent means

When a save endpoint rebuilds the whole record, decide per field what an absent value means and document it. - On the videos site, absent means keep for alts, lqip and rotate; without that, CLI commands that did not know about rotation straightened every video they touched (it mattered: a renumber rewrote nine records, eight of them rotated). - But absent poster means cleared (legacy behavior). Always send it.

Testing against production data safely

Copy the live catalog down, point a scratch config's data dir at the copy, and run php -S 127.0.0.1:PORT with that config. Writes land on the copy. Delete the scratch config afterwards if it holds real bucket keys.

See also

Linked from

Sources: justinahampton memory (videos-subdomain-plan, videos-rotation-and-api, 3d-subdomain)