Developers

Database

On this page

This page describes the server's storage: the two SQLite databases, every table and which migration made it, how migrations run, and the conventions to follow when you change the schema. It is for developers who add a table or a column, or who need to read the data directly. When you finish it you will be able to write a migration that fits in, and know what happens on a server when the code and the database disagree.

Two databases and some files

text
var/                       FRAME_VAR_DIR  (default: next to app/; set var_dir in config.php)
├── frames.db              Your decisions. The web user writes it; cron opens it read-only
├── sessions/              Admin sessions (directory mode 0700)
├── device.key             Signing key for trusted-device cookies (mode 0600)
├── login.lock             Lock that serializes password hashing
├── kiosk/<sha256>.apk     Kiosk releases, named by hash
├── notes/<sha256>.<ext>   Card covers and stamps, named by hash
└── photos/
    ├── files/<xx>/<sha256>.jpg and .thumb.jpg   Stored photos and thumbnails
    ├── tmp/               Uploads and decoder scratch space (cleaned automatically)
    └── .ingest.lock       One writer at a time

cache/                     FRAME_CACHE_DIR
├── cache.db               Fetched data. Only cron writes it; the web user opens it read-only
└── fetch.lock             Keeps two fetcher runs apart

Back up var/ (it holds frames.db, the photos, the card art and the kiosk releases) and keep the backup private. cache/ can be rebuilt by the fetcher.

frames.db cache.db
Holds Frames, widget settings, Library records, admin users, albums, photos, cards, kiosk releases, rate-limit events Fetched weather, calendar occurrences and photo album listings; fetch status
Writer The web user (and the command-line tools) The cron fetcher
Schema Versioned by migrations Created by the fetcher with CREATE TABLE IF NOT EXISTS, not versioned
If it is lost Everything you configured is gone The next fetch fills it again

Every connection turns on PRAGMA foreign_keys = ON and waits up to 5 seconds for a lock. The code never switches to write-ahead logging, so the default rollback journal is used. That keeps a read-only reader working without write access to a side file.

Check-then-write sequences run inside db_tx(), which opens the transaction with BEGIN IMMEDIATE so that no other writer can slip in between the check and the write.

How migrations run

Migrations are the numbered files web/app/migrations/NNN_name.sql. bin/migrate.php applies them.

flowchart TD
    start["php app/bin/migrate.php<br/>run as the web user"] --> read["Read PRAGMA user_version<br/>from frames.db, creating it if needed"]
    read --> loop{"Another file<br/>numbered above it?"}
    loop -->|yes| tx["BEGIN<br/>run the whole file<br/>PRAGMA user_version = N<br/>COMMIT"]
    tx -->|"error"| fail["ROLLBACK<br/>print the error, exit 1"]
    tx -->|"ok"| loop
    loop -->|no| check{"user_version equals<br/>SCHEMA_VERSION?"}
    check -->|no| bad["Exit 1:<br/>code and files disagree"]
    check -->|yes| warn["Ask each widget's checks hook<br/>print warnings"]
    warn --> hash["Hash photos with a NULL phash<br/>from their thumbnails<br/>skipped as root or without the image worker"]
  • The version of the database is SQLite's user_version. There are no down-migrations and no record of which file did what beyond that number.
  • Each file runs in one transaction together with the version bump. SQLite's schema changes are transactional, so a failed migration leaves the database as it was.
  • SCHEMA_VERSION in app/bootstrap.php is the number the code expects. It must equal the highest migration.
  • Web requests never migrate. On the first connection of a request, db_frames() compares user_version with SCHEMA_VERSION. A mismatch throws SchemaMismatch, and the visitor sees 503 with Retry-After: 30 and {"error": "maintenance", "code": "maintenance"}. After a deploy that adds a migration, the site answers 503 until you run php app/bin/migrate.php. Frames keep their current page and retry.
  • The command-line tools (user.php, kiosk-release.php) refuse to run on a mismatched database and tell you to run migrate.php first.
  • migrate.php runs with umask(0027) so new files are not world-readable, and needs the var directory to exist.

Add a migration

  1. Create NNN_short_name.sql with the next number. Never edit a migration that has been applied anywhere.
  2. Write SQL only. A migration cannot call PHP.
  3. Raise SCHEMA_VERSION in app/bootstrap.php to NNN.
  4. Update tests/migrate_test.php (it checks the version and what each migration does). fresh_db() in the test runner applies every file in order, so every test sees the new schema.
  5. If existing rows need a value, backfill in the same file, as migrations 005, 007 and 011 did.
  6. Run the tests and PHPStan.

A widget that needs its own table must add a core migration today; widgets cannot ship migrations of their own.

Conventions

Rule Why
Every table is STRICT. Column types are INTEGER, TEXT, REAL or BLOB SQLite then rejects a value of the wrong type instead of storing it. A BLOB column rejects TEXT, so bind images with PDO::PARAM_LOB
Timestamps are INTEGER Unix seconds, UTC One format; no time-zone ambiguity. Times that are meant in the frame's own zone (pick_time, bedtime, wake_time) are TEXT HH:MM
Booleans are INTEGER 0 or 1 with a CHECK
Hashes and tokens are lowercase hex TEXT with CHECK (length(x) = 64 AND x NOT GLOB '*[^0-9a-f]*') The database refuses malformed values even if the application has a bug
CHECK constraints repeat the application's rules (lengths, allowed values) Defense in depth
Settings that vary by widget are JSON in a TEXT column frame_widgets.config, validated by the widget on save
INTEGER PRIMARY KEY for most tables A rowid may be reused after the newest row is deleted
INTEGER PRIMARY KEY AUTOINCREMENT where an id must never be reused kiosk_releases, photo_albums, person_links, photos. Rate limits and history are keyed by these ids; a reused id would inherit another record's limits
Foreign keys say what happens on delete: CASCADE for owned rows, SET NULL for a record that outlives its source, RESTRICT (or no clause, which refuses the same way) where deleting would break a reference kiosk_releases cannot be deleted while a frame targets it
WITHOUT ROWID for small tables with a composite key
Secrets are stored as hashes where the server never needs the original Frame keys, link tokens, admin passwords, PINs

Tables, by migration

001 init (the original schema)

Table Holds
frames One row per frame: id (32 hex), key_hash, status (unclaimed, active, revoked), pairing code and expiry, name, display_kind and display_url, layout, tz, config_version, enrollment and last-seen details, and the last telemetry (app_version, local_ip, mac, ssid, rssi, reported_at). Indexes: a unique index on pairing_code (unclaimed rows only) and two for expiry and per-address limits
frame_widgets (frame_id, widget) primary key, enabled, position, config (JSON). ON DELETE CASCADE from frames
locations Library places: name (unique), lat, lon, optional stations
calendars Library calendars: label, url (unique, a secret), color, created_at
settings Key/value pairs. Reserved; the code does not use it now
rate_events (bucket, at) rows that every rate limit counts. Index on (bucket, at)
admins Dropped by 002

002 to 008 (frames grow)

Migration Change
002 drop_admins Drops the admins table from 001. The built-in login arrived later, as admin_users in 012
003 idle_home frames.idle_home_seconds (default 120)
004 uptime_ipkey frames.uptime; frames.enrolled_ip_key (the address, or the IPv6 /64) with an index, for enrollment limits
005 frame_pin frames.pin_hash (JSON {alg, iter, salt, hash}). Moves the old global PIN into active frames and deletes it from settings
006 ha_dashboards frames.ha_dashboards (JSON list of {path, title}) and ha_dashboards_at
007 photo_set_bedtime frames.pick_time, bedtime, wake_time (with HH:MM checks; existing active frames get pick times two minutes apart from 05:00). Tables frame_photo_sets (the stored daily set: album_key, picked_for, picked_at, ids) and frame_photo_shown (photos already shown in this pass through an album)
008 screenshots_photoset frames.screenshot_request_id (32 hex or null) and screenshot_requested_at; table frame_screenshots (the latest capture per frame, jpeg as a BLOB); frame_photo_sets.new_ids

009 to 011 (cards and widget order)

Migration Change
009 notes The cards feature: frame_notes (per-frame settings: keep_days 1 to 30, recipient_label, categories JSON or null for all), note_senders (a person's link, replaced by person_links in 018: token_hash unique, revoked_at, last_used_at, unique (frame_id, name)), note_designs (covers) and note_stamps (file name is the hash plus extension, with a CHECK on its characters), note_cards (message 1 to 400 characters; exactly one of signature JSON or signature_text; opened_at; unique (sender_id, client_id) so a repeated send is the same card)
010 notes_widget Makes cards a normal widget: copies each frame_notes.enabled into a frame_widgets row (position 7). frame_notes.enabled stays but is no longer read
011 widget_enabled_at frame_widgets.enabled_at (when the widget was switched on, null while off). Existing enabled rows get 1735689600 + position so they keep their order. The admin lists widgets in this order

012 admin_users (the built-in login)

admin_users: username (unique; GLOB '[a-z0-9]*', 1 to 64 characters), password_hash, created_at, password_changed_at, last_login_at, session_epoch (16 characters; changes to sign the user out everywhere), totp_secret (base32, null when two-step sign-in is off) and totp_last_step (the replay guard). Users are different from card senders. See Security.

013 kiosk_releases (self-update)

Table or column Holds
kiosk_releases version_code (unique, 1 to 2,100,000,000), version_name (up to 64), sha256 (unique), size, signature (the detached release signature, base64), notes (up to 500), uploaded_at, uploaded_by. AUTOINCREMENT
kiosk_downloads (frame_id, release_id) primary key, at. A frame that fetched a release in full. With a later report of that version it proves the release
frames.kiosk_target_id The release this frame should run (foreign key to kiosk_releases, ON DELETE RESTRICT), and kiosk_target_at
frames.kiosk_version_code The version the kiosk reported
frames.kiosk_watchdog 1 or 0: whether it reported a working rollback watchdog
frames.kiosk_update_failure JSON {sha256, reason} of a held failure
frames.kiosk_attempt Rises when an admin clears a failure, so the kiosk may retry

014 photo_library (local photos)

Table Holds
photo_albums name (unique, 1 to 60), created_at. AUTOINCREMENT
photo_drop_links (dropped in 018) album_id (cascade), name (unique within the album, 1 to 40), token_hash (unique, 64 hex), created_at, revoked_at, last_used_at. AUTOINCREMENT. Replaced by person_links in 018
photos album_id (cascade), src_sha256 (hash of the uploaded bytes; unique with the album, for duplicate detection), file (hash of the stored JPEG; unique with the album), width, height, bytes, thumb_bytes, added_at, status (pending or approved), approved_at, person_link_id (SET NULL, was drop_link_id until 018; references person_links), added_by. A CHECK ties status = 'approved' to approved_at being set. Indexes on album and time, album and status, file, and person_link_id. AUTOINCREMENT

Stored photos live in var/photos/files/, named by file. Several albums may share one file; it is deleted only when no row refers to it.

015 reboot (remote reboot)

Column Holds
frames.reboot_request_id The pending request: 32 lowercase hex (a CHECK) or null. Cleared when telemetry shows the frame booted after the request
frames.reboot_requested_at When the last request was made. Kept after completion, for the 10-minute minimum gap
frames.rebooted_at Boot time (server clock minus reported uptime) of the frame's last completed request
frames.kiosk_reboot 1 or 0: the kiosk's header-auth report that the boot script can reboot the frame. Null until reported

016 wifi_forget (remote Forget Wi-Fi)

Column Holds
frames.wifi_forget_request_id The pending request: 32 lowercase hex (a CHECK) or null. Cleared when telemetry carries the matching id, even after the pickup window
frames.wifi_forget_requested_at When the last request was made. Kept after completion, for the 60-second minimum gap
frames.wifi_forgotten_at When the frame acknowledged its last completed request (reported just before it removes its networks)
Change Detail
photo_drop_links.expires_at Dropped. A link works until an admin revokes it; revoking never deletes photos

Replaces photo drop links and card senders with one table. A person link belongs to one frame and one person; its URL opens a landing page that offers what the frame's widgets accept, and it authenticates the widgets' public routes. One revoke switch turns off every power at once.

Table or column Holds
person_links id (AUTOINCREMENT), frame_id (cascade), name (1 to 40, unique within the frame), token_hash (unique, 64 hex), legacy_token_hash (unique, 64 hex or null; a CHECK keeps it different from token_hash), created_at, revoked_at, last_used_at. Either hash opens the link
photos.person_link_id Replaces drop_link_id. ON DELETE SET NULL: deleting a person keeps their photos. Index photos_person replaces photos_drop
note_cards.person_link_id Replaces sender_id. NOT NULL, with no ON DELETE clause, so deleting a person who has cards fails (the admin answers 409 in_use) while deleting a frame removes its cards and its people together. Unique (person_link_id, client_id); index note_cards_person replaces note_cards_sender
photo_drop_links, note_senders Dropped

The migration rebuilds photos and note_cards (create the new table, copy, drop the old, rename, recreate the indexes). It copies every other column, CHECK and UNIQUE as they were and carries the photos AUTOINCREMENT counter over, so no id is reused. It runs inside bin/migrate.php's transaction with foreign keys on. There is no down migration: to go back, restore the database backup and the previous code.

How existing rows are converted, in pure SQL:

  1. Each frame's album is read from its photos widget config (source local, an integer local_album), whether the widget is on or off. This is the same rule as photos_album_used_by().
  2. Every note_senders row becomes a person link on the same frame with the same name, created_at and last_used_at. An active sender keeps its token as token_hash. A revoked one keeps revoked_at and gets a random token nobody holds.
  3. Each drop link picks one frame that shows its album: first a frame that already has a person with exactly that name (lowest frame id if several), otherwise the lowest frame id. A drop link whose album no frame shows is not converted: its URL stops working and its photos keep added_by with person_link_id null.
  4. A drop link is inserted as a person link on that frame. If the frame already has a person with that name the two merge: revoked if either was revoked (the later revoked_at, a random token, no alias); otherwise the person keeps the sender's token and the drop link's token becomes legacy_token_hash. created_at is the earlier of the two and last_used_at the later.
  5. photos.person_link_id and note_cards.person_link_id are remapped through those choices.
  6. Old rate-limit buckets are left to age out; the new ones use new prefixes.

A converted person has two valid secrets until an admin rotates or restores the link (both clear the alias).

019 ha_rescan (remote dashboard rescan)

Column Holds
frames.ha_rescan_request_id The pending request: 32 lowercase hex (a CHECK) or null. Cleared when telemetry carries the matching id
frames.ha_rescan_requested_at When the last request was made. Kept after completion, for the 30-second minimum gap
frames.ha_rescanned_at When the frame reported its last completed rescan
frames.ha_rescan_ok 1 if the frame reached Home Assistant on that rescan, 0 if not. Null until a rescan completes

020 photo_phash (near-duplicate detection)

Column Holds
photos.phash INTEGER, nullable. A 64-bit difference hash of the stored frame (9x8 grey, one bit per "brighter than the right neighbour"), stored as a signed integer. Computed by the image worker. NULL means never tried: photos from before 020 until the backfill reaches them. 0 means tried, no usable hash: a solid-colour picture, or (in the backfill) a missing or unreadable thumbnail. 0 and NULL are never compared

Ingest compares the new picture's hash with every usable phash in the same album and treats a Hamming distance of PHOTO_PHASH_MAX_DISTANCE (6) or less as a duplicate, but only against approved photos and pending ones with the same person_link_id (an admin upload matches approved photos only), so one sender's pending copy cannot block someone else's original. Exact matches on src_sha256 and file ignore that scope. This is a scan of one album (at most a few thousand rows) with the bit count done in PHP, so there is no index on phash; the album index already narrows the rows. The migration is just the ALTER TABLE. bin/migrate.php then hashes existing photos from their thumbnails through the worker (photos_phash_backfill()), a batch of ten at a time under the ingest lock, pausing a quarter of a second between batches. It only touches NULL rows and marks the unhashable ones 0, so each photo is tried once, and running migrate.php again is safe and finishes any that were missed (for instance when the image worker was unavailable). It is skipped with a warning when run as root: run it as the web user.

cache.db (created by the fetcher)

Table Holds
cache k (key), v (JSON), fetched_at. Keys look like wx:1:obs, wx:1:hourly, cal:3, ph:0123456789abcdef
fetch_state k, last_ok, last_err (up to 200 characters), fail_count, next_at (the earliest next try). Drives back-off
photo_seen (album_key, file_id) primary key, added_at. When the fetcher first saw each Nextcloud photo. Rows are never deleted, so a bad listing cannot make an album look new

How the tables relate

erDiagram
    frames ||--o{ frame_widgets : "has"
    frames ||--o| frame_screenshots : "latest capture"
    frames ||--o| frame_photo_sets : "today's set"
    frames ||--o{ frame_photo_shown : "shown so far"
    frames ||--o| frame_notes : "card settings"
    frames ||--o{ person_links : "people"
    frames ||--o{ note_cards : "receives"
    frames ||--o{ kiosk_downloads : "fetched"
    frames }o--o| kiosk_releases : "target"
    kiosk_releases ||--o{ kiosk_downloads : "fetched by"
    person_links ||--o{ note_cards : "sent"
    note_designs ||--o{ note_cards : "cover"
    note_stamps ||--o{ note_cards : "stamp"
    photo_albums ||--o{ photos : "contains"
    person_links ||--o{ photos : "brought"
    locations }o--o{ frame_widgets : "referenced in config"
    calendars }o--o{ frame_widgets : "referenced in config"
    admin_users
    rate_events

Two relationships are not foreign keys. A widget's config JSON names a location or calendar by id, and the application checks that on save and before it deletes a Library record (409 in_use). A frame's local-album setting names an album by id the same way.

Rate-limit buckets

rate_events is one table for every limit. A bucket is a name; the limit counts rows with that name inside a window. rate_purge() deletes rows older than a day, and several request paths call it.

Bucket Counts
enroll:<address key> Enrollments from an address
pairing_fail Wrong pairing codes (all addresses together)
login_fail_ip:<address key>, login_fail_user:<16 hex of a hash of the name> Admin sign-in attempts, refunded on success
kiosk_dl:<frame id> Kiosk release downloads
pl_auth_fail:<address key>, pl_req:<person link id> Person link guesses (20 per 10 minutes per address) and requests (120 per 10 minutes per link), for the landing page and every public route
pl_decode_fail:<person link id>, drop_up_ip:<address key> Rejected photo files (10 per hour per person) and photo uploads per address (drop_ip_per_day of the photos widget)
pl_send:<person link id>, note_send_ip:<address key> Card sends (6 per hour and 20 per day per person) and sends per address

Before migration 018 the buckets were drop_auth_fail, drop_req, drop_up, drop_decode_fail, note_auth_fail, note_req and note_send. Their rows are not read any more and age out.

The address key is the IPv4 address, or the IPv6 /64 as <16 hex>::/64.

Reading the data by hand

Open the file read-only, and do it as a user who may read it (the web user):

sh
sudo -u www-data sqlite3 -readonly /srv/frame/var/frames.db \
  "SELECT id, name, status, kiosk_version_code FROM frames;"

Do not write to frames.db while the site is up. If you must, stop the web server first, or use the admin, which holds the right locks. Never copy the live file with cp and expect a consistent copy; use sqlite3 … ".backup '<file>'".