zakariaf/flutter-skills/persistence-drift
Claude Code and agent skill by zakariaf/flutter-skills
- community
- ext:[{"type":"hook","description":"Pre/post lifecycle hooks"}]
Checking that the SKILL.md file is still in the repository.
Governs the on-device Drift/SQLite data layer: package:drift and package:sqlite3 confined to lib/data/ behind DAOs that map rows to immutable value objects (no Drift symbol leaks past the repository), invariants pushed into the schema (STRICT tables, CHECK/FK/partial-UNIQUE indexes), foreign_keys/WAL pragmas re-asserted idempotently in beforeOpen, one db.transaction per mutation, persist-before-publish, every query awaited, canonical integer storage, derived state recomputed-on-read never stored, scoped .watch streams, keyset (seek) pagination not OFFSET, and WAL-safe backups (checkpoint + VACUUM INTO, verify-by-reopen, never File.copy a live WAL DB). Use when defining or altering a Drift Table, Companion, DAO, index, or CHECK; writing a repository transaction or scoped watch provider; wiring the connection/beforeOpen pragmas; adding SQLCipher; building or verifying a backup; or reviewing a data-layer diff. Migrations and their tests live in run-migration.
Install
npx vskill@latest install zakariaf/flutter-skills/persistence-driftSemi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard
SKILL.md
The same SKILL.md was published earlier as zakariaf/flutter-skills/persistence-drift.
Persistence — Drift / SQLite
The on-device store is the single source of truth: with no server, everything must rebuild from this DB alone after process death, reboot, or restore. Push invariants into the schema, confine Drift to one layer, make every mutation one durable transaction, and store canonical values only. Applies to any lib/data/ Drift table, DAO, repository, connection setup, or backup.
Read the reference for the task at hand:
references/schema-and-daos.md— audit-column mixin, STRICT/CHECK/FK invariants, canonical column types, the index +EXPLAIN QUERY PLANgate, DAO↔repository split, files-on-disk-with-relative-paths for blobs.references/backup-and-wal.md— the checkpoint→vacuum→verify-by-reopen primitive, WAL rules, the backup-before-anything lesson, optional SQLCipher (key-first, assert-cipher, header-check).references/persistence-without-drift.md— the same discipline for a small app on plain JSON files (injected base dir, debounce + lifecycle flush, atomic writes, lenient decode).
Run scripts/check-drift-confinement.sh and scripts/check-persistence-bans.sh before a PR. Migrations and their tests: see run-migration.
Non-negotiable rules
- Drift lives only in `lib/data/`; everything else sees value types.
package:driftandpackage:sqlite3are imported nowhere else — a banned-import lint/grep enforces it. DAOs map rows to immutable value objects; noTable,Companion,TableInfo, or generated row class crosses the boundary. A feature reaching for a raw query is a layering break that also blocks pure testing of everything above it. - Put invariants in the schema, not at call sites. Tables are
STRICT(no silent coercion); enumerable columns getCHECK (col IN (...)), ranges getCHECK (qty BETWEEN 0 AND n)/CHECK (amount_minor >= 0), relations are foreign keys with an explicitonDelete, uniqueness is a (partial)UNIQUE INDEX. A corrupt row must be unrepresentable at the storage layer, not merely policed in Dart. - `foreign_keys` and `synchronous` are set in `beforeOpen`/`setup` on EVERY open; `journal_mode = WAL` is set idempotently there too.
foreign_keysandsynchronousare per-connection and are not persisted in the file, so they must be re-asserted on every open.journal_mode = WAL, by contrast, is persisted in the database file header and survives across connections — but it is still set idempotently in setup so a freshly created or restored DB adopts it.PRAGMA foreign_keys = ONunconditionally (SQLite defaults it OFF and silently no-ops FK actions when off);journal_mode = WALfor concurrent durable reads;synchronous = FULLon any store holding non-regenerable user data (WAL+NORMAL "might rollback following a power failure"). Seeding, and only seeding, goes insideif (details.wasCreated). - One `db.transaction` per mutation; every query inside awaited; persist before publish. A mutation that writes several rows (parent + dependents, or a debit + a credit) is all-or-nothing. A missing
awaitinsidetransaction(() async {lets a query run after the transaction closes — Drift calls this data loss; it is a release blocker. The DAOFutureresolves only after the durable commit; the committed write then makes the watched.watch()stream re-emit the new state on its own — never an optimistic pre-commit update, never a manualstate = …republish, never "save later". (The write→UI-update rule is owned bystate-management-riverpod.) - Store canonical values only; convert at the presentation edge. Money as integer minor units keyed to the real ISO-4217 exponent (never a
REAL/double), other quantities as SI integers, true instants as UTC epoch millis. The local calendar day (anything that drives a day boundary) is a serial-day integer, never a `DateTime` instant — an instant reintroduces the DST/timezone off-by-one. No display strings, localized numerals, or formatted values in any column; switching locale/unit must leave stored rows byte-identical. - Derived state is recomputed on read, never stored as a second authority. Counts, streaks, running totals, histograms are pure folds over their source rows, computed by one
watch…/query fold next to the data. A stored copy is a second source of truth that drifts and that any future sync must reconcile twice. - The repository is the single write path and the single source of truth. DAOs hold single-table queries; repositories own cross-table transactions and row→value-object mapping, and return a typed
Result<T, Failure>for fallible work. Feature code depends on the repository abstraction, never on a DAO or Drift row. - Reads are scoped `.watch()` streams; pagination is keyset, not `OFFSET`. Never subscribe to an unscoped app-wide stream (it recomputes on every write); scope by owner/entity + time window. History uses
WHERE ts < :cursor ORDER BY ts DESC LIMIT n;OFFSETdegrades badly on large tables. - Blob bytes never live in SQLite. Store files on disk (app-private) with only a metadata row; persist the path relative to a base directory and resolve to absolute at read time — an absolute path dies on iOS reinstall/restore when the container UUID changes, and the row survives while the file renders blank with no error. BLOBs bloat the DB and slow every checkpoint and backup.
- Back up via `wal_checkpoint(TRUNCATE)` + `VACUUM INTO`, then verify by reopen — never `File.copy` a live WAL DB. A raw copy of a WAL-mode DB captures a torn state across the
-wal/-shmsidecars and is corrupt and unrestorable. A backup that was not re-opened and integrity-checked did not succeed. Detail inreferences/backup-and-wal.md. - Schema evolution is forward-only, append-only, and snapshot-guarded — and it is a separate ritual. Bump
schemaVersion, add a newstepByStepstep (never edit a shipped one), commit the schema snapshot, and ship no migration without a content-level test. That whole workflow lives inrun-migration; this skill defines the tables it migrates.
Confining Drift to one layer
One @DriftDatabase, per-feature @DriftAccessor DAOs, repositories on top. Use the NativeDatabase FFI backend, never sqflite.
When multi-package (workspace): the same boundary becomes a package (e.g.packages/data) that is the only pubspec depending ondrift/sqlite3, enforced by a banned-import gate. For a single-package app the boundary is thelib/data/directory and the grep inscripts/check-drift-confinement.sh. Do not reach for a workspace to get this boundary — a directory + lint is enough.
Schema: invariants in the table
AuditColumns (a mixin on Table) gives every table a stable text PK (a UUID — collision-free, merge-safe, stable across export), createdAt/updatedAt UTC-ms, rowRevision, and isDeleted/deletedAt for soft-delete. Stamp updatedAt/rowRevision through one shared write wrapper; filter is_deleted = 0 in one shared base-query helper — analytics included. See references/schema-and-daos.md.
The connection: pragmas per open
In MigrationStrategy.beforeOpen, re-assert foreign_keys = ON and seed only under if (details.wasCreated). During a migration, toggle foreign_keys outside any transaction (it is a no-op inside one) and run PRAGMA foreign_key_check afterwards.
DAO + repository: one transaction, mapped to value objects
A DAO holds single-table queries for one table (window is a plain-Dart TimeWindow VO of UTC-ms bounds — never a Flutter DateTimeRange in the data layer):
The repository owns the cross-table transaction (a DAO scoped to [Orders] cannot reference lineItems — that is rule 7) and maps rows to value objects:
The repository maps OrderRow → the immutable Order value object (integer minor units → a Money value object, placedOnDay serial → a calendar-day type) so no feature ever sees a canonical int or a Drift class. Keyset pagination: ..where((o) => o.placedAtUtcMs.isSmallerThanValue(cursor))..limit(n).
Riverpod wiring (state + DI)
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/persistence-drift/SKILL.md
Popularity
- Repository stars
- 22
- Repository forks
- 4
- 7-day trend score
- 16
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Extension points
hookPre/post lifecycle hooks
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/zakariaf/flutter-skills/persistence-drift)