/flutter:run-migrationfrom Flutter Skills
Runs the forward-only Drift/SQLite schema-migration ritual for offline-first apps. Enforces ordered steps: pre-migration snapshot, schemaVersion bump, append-only forward steps, drift_dev schema dump, and migration tests covering all version paths.
Ships in Flutter Skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description, though model invocation is off: only you can start it.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Apply a schema change to a local Drift/SQLite database by following the exact ordered ritual below. In an offline-first app there is no server and no re-sync path, so the on-device DB is the single source of truth: a migration that drops or corrupts a column permanently destroys hand-entered records that exist nowhere else, and with no telemetry nobody ever reports it — the user just uninstalls. This is a manual, low-freedom, human-run workflow. Execute the steps in order; do not improvise, reorder, or skip.
AppDatabase, never inside
onUpgrade: PRAGMA wal_checkpoint(TRUNCATE) any live handle so the -wal
is folded into the main file, then copy the DB file and its -wal/-shm
sidecars while nothing holds the file open. Opening the database is what
triggers the migration. Never copy or overwrite bytes under a live
connection. The snapshot is the only "rollback" SQLite has; restore it on any
failure.schemaVersion — never back-edit history.schemaVersion by exactly one per shipped schema change, and add the
matching fromNToM branch. A schema changed without a version bump means
no migration runs at all on the user's device — a CI gate must catch it.drift_dev make-migrations
(or schema dump), commit the exported snapshot under drift_schemas/, and
commit schema_versions.dart. The delta becomes a reviewable diff and the
test suite diffs live schema against it.onUpgrade.migrateAndValidate
compares CREATE statements only — it never reads a row. A migration that
rebuilds a table perfectly and copies zero rows passes it, green. The content
test is the deliverable, not the shape test.from → to
path (including multi-version jumps), a content test per new pair,
PRAGMA integrity_check == ok, PRAGMA foreign_key_check empty, and a
forced mid-migration throw that restores the snapshot.Run commands from the package that owns the database (single-package apps: the app root; see the multi-package note at the end).
persistence-drift). Edit the table class.schemaVersion by one in the database class.dart run drift_dev make-migrations
On pinned versions where make-migrations is not confirmed working, use the
three explicit commands instead (see "Snapshot commands" below).fromNToM branch. Never
modify an existing branch. Create only the objects this version adds; never
reference a column added in a later version.run-codegen skill):
dart run build_runner build --delete-conflicting-outputs
schemaVersion,
the new step, the committed snapshot, and the tests together in one change.The snapshot/restore lives at the composition boundary, entirely outside any
open connection; onUpgrade only runs the steps and checks foreign keys. Keep
this exact shape.
// ── composition boundary (app_database_opener.dart) ─────────────────────────
// Snapshot BEFORE the open, restore AFTER a failed open — no connection is ever
// live while the bytes are copied. Opening is what triggers onUpgrade.
Future<AppDatabase> openMigratedDatabase(File dbFile) async {
// 1. Checkpoint any prior handle, then copy dbFile + its -wal/-shm sidecars.
final snapshot = await _snapshotDbFiles(dbFile);
final db = AppDatabase(NativeDatabase(dbFile));
try {
// 2. Force the migration to run NOW, while the file fallback still stands.
await db.customStatement('PRAGMA user_version;');
return db;
} catch (_) {
// 3. The failed connection is dead — close it, THEN restore with nothing open.
await db.close();
await _restoreDbFiles(snapshot);
rethrow;
}
}
// ── app_database.dart ───────────────────────────────────────────────────────
@override
int get schemaVersion => 3; // bump by exactly ONE per shipped schema change
@override
MigrationStrategy get migration => MigrationStrategy(
onCreate: (m) => m.createAll(),
onUpgrade: (m, from, to) async {
// FKs OFF here — BEFORE the migration's own transaction opens, because
// the pragma is ignored once a transaction is running.
await customStatement('PRAGMA foreign_keys = OFF;');
// Forward-only, append-only stepwise migration in one transaction.
await transaction(() => _steps(m, from, to));
// Prove the body left no dangling references — in production, not tests.
final orphans = await customSelect('PRAGMA foreign_key_check').get();
if (orphans.isNotEmpty) {
throw StateError('foreign_key_check found ${orphans.length} orphans');
}
},
// Pragmas are per-connection, NOT persisted — re-assert on every open.
beforeOpen: (details) async {
await customStatement('PRAGMA foreign_keys = ON;');
},
);
final _steps = stepByStep(
from1To2: (m, schema) async { /* shipped — DO NOT EDIT */ },
from2To3: (m, schema) async {
// Create EXACTLY the objects this version adds.
await m.addColumn(schema.notes, schema.notes.archivedAtUtc);
},
);
When not using make-migrations, re-run all three on every schemaVersion
bump and commit the results:
# 1. Export the schema for the CURRENT schemaVersion.
dart run drift_dev schema dump lib/data/app_database.dart drift_schemas/
# 2. Era-correct classes. --data-classes --companions is LOAD-BEARING: it emits
# DatabaseAtV1 / DatabaseAtV2 with era-correct data classes and companions,
# the only mechanism that lets a test write rows in the v1 world and read
# them back in the v2 world. Without it only shape tests are possible.
dart run drift_dev schema generate --data-classes --companions \
drift_schemas/ test/drift/generated/
# 3. Step-by-step helpers — each callback gets a schema frozen at its version.
dart run drift_dev schema steps drift_schemas/ lib/data/schema_versions.dart
The suite must prove all of the following.
Every from→to path, including the skips. A user who ignored updates upgrades
v1 → v3 directly — a code path nobody ran. A nested loop covers every pair
forever, so a new bump cannot forget a skip path:
group('schema shape', () {
for (var from = 1; from < kLatestSchemaVersion; from++) {
for (var to = from + 1; to <= kLatestSchemaVersion; to++) {
test('v$from -> v$to', () async {
final connection = await verifier.startAt(from);
final db = AppDatabase(connection);
await verifier.migrateAndValidate(db, to); // shape only — necessary, not sufficient
await db.close();
});
}
}
});
The content test — the one that matters. Write rows at v(n) with era-correct
classes, run the real migration, read back at v(n+1), assert the rows are still
there, still correct, and still in place. Use a hostile fixture — apostrophes,
non-ASCII, em dashes, emoji, quotes, backslashes, whitespace-only — exactly where
a columnTransformer or hand-rolled INSERT ... SELECT mangles a value. 'test1'
survives everything and proves nothing. Put a reason: on every expect — the
failure message is the whole debugging session when no crash report is coming.
test('v2 -> v3 preserves every note, byte for byte', () async {
final schema = await verifier.schemaAt(2);
// Write real data with v2-era classes. newConnection() over the SAME bytes is
// what lets different-era database objects see one database.
final old = v2.DatabaseAtV2(schema.newConnection());
await old.into(old.notes).insert(
v2.NotesCompanion.insert(title: 'Blank-ish', body: const Value(' ')),
);
await old.close();
// Run the REAL migration, then prove integrity — FKs are off during migration
// and SQLite reports a dangling reference to nobody.
final db = AppDatabase(schema.newConnection());
await verifier.migrateAndValidate(db, 3);
expect(await db.customSelect('PRAGMA integrity_check').get(),
[predicate((QueryRow r) => r.data.values.first == 'ok')]);
expect(await db.customSelect('PRAGMA foreign_key_check').get(), isEmpty,
reason: 'migration left dangling references — a lost record');
await db.close();
// Read back with v3-era classes and assert CONTENT, not just shape.
final now = v3.DatabaseAtV3(schema.newConnection());
final rows = await now.select(now.notes).get();
expect(rows, hasLength(1), reason: 'a row disappeared during migration');
expect(rows.single.body, ' ', reason: 'whitespace-only body must survive intact');
await now.close();
});
The forced mid-migration throw restores the snapshot. Inject a step that throws partway, open the database through the boundary opener so the migration runs, assert the open rethrows and that the pre-open snapshot was restored — prior schema and rows left byte-identical. The restore path is the last line of defense and the one that is never exercised in production until it is.
Never mark a migration done on a green analyzer alone. It is safe only once the content test, both PRAGMAs, the all-paths loop, and the snapshot-restore test are green.
PRAGMA foreign_keys is ignored once a transaction is open — toggle FKs
OFF at the top of onUpgrade, before the transaction() that wraps the
steps, and re-enable them unconditionally in beforeOpen (the pragma is
per-connection, not persisted in the file).PRAGMA foreign_key_check after the migration body, not only in tests.flutter test runs in a plain Dart VM where sqlite3_flutter_libs does
nothing; macOS falls back to the system libsqlite3 (real version-skew risk)
and Linux needs libsqlite3-dev installed before the run.schemaVersion — no migration runs on
the user's device; the schema and code silently diverge.migrateAndValidate alone — it is a shape comparison that
reads zero rows; a migration that copies nothing passes it green.INSERT ... SELECT / columnTransformer verified only with 'test1'
fixtures — the mangling lives in apostrophes, emoji, and backslashes.select/update of a not-yet-added column in an older step — write
queries only against the schema frozen at that step's version.foreign_keys, synchronous,
and any cipher key are per-connection; re-assert on every open.eraseDatabaseOnSchemaChange reachable in a release build — it is
a DEBUG-only convenience; shipped, it wipes real user data on every bump.schemaVersion bumped by exactly one; a matching append-only fromNToM
step added; no edit to any already-shipped step; no down migration.make-migrations (or the three explicit schema commands) re-run; the
committed snapshot and schema_versions.dart are in the same change.--delete-conflicting-outputs.kLatestSchemaVersion.reason: on
every expect, and per-key (not per-list-index) assertions.PRAGMA integrity_check == ok and PRAGMA foreign_key_check empty after
the migration; FKs disabled before the migration transaction, re-enabled
in beforeOpen.eraseDatabaseOnSchemaChange is DEBUG-only and unreachable in release.If Drift is confined to a data package inside a Dart pub workspace, run every
command from that package (or the workspace root for make-migrations), keep
drift_schemas/ and schema_versions.dart inside that package, and run the
migration suite there. In a single-package app all of this lives at the app root
— nothing about the ritual requires a workspace.
persistence-drift for the data-layer conventions the schema change must
obey (STRICT tables, schema-level CHECK/FK, WAL/pragmas, DAO transactions).run-codegen for the deterministic build_runner pass invoked in step 5.error-handling-typed-results for the never-lose-data guarantees
(transactions, autosave drafts, soft-delete/Undo) this workflow complements.testing-strategy for the real-in-memory-DB test discipline the content
and shape tests follow.ci-pipeline-and-gates for the schema-freshness gate that fails a build
when the schema changed without a committed snapshot bump.SchemaVerifier, make-migrations):
https://drift.simonbinder.eu/Migrations/tests/stepByStep: https://drift.simonbinder.eu/Migrations/step_by_step/PRAGMA integrity_check / foreign_key_check:
https://sqlite.org/pragma.htmlWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub zakariaf/flutter-skills --plugin flutter40 skills in this plugin
/accessibility-as-codeEnforces accessibility as a correctness property authored into each widget — Semantics(button/label) or ExcludeSemantics on every node, a11y state read from MediaQuery not app state, never MediaQuery.withClampedTextScaling / textScaleFactor / FittedBox / TextOverflow.ellipsis to fit a label, non-color redundant channels (icon+label+shape+text) for every state, contrast against composited backgrounds (4.5:1 body / 3:1 large), 44px single-tap targets, OrdinalSortKey traversal, and honoring boldText / reduce-motion. Use when adding a GestureDetector/InkWell or any tap target, adding an Icon or Image, reaching for withClampedTextScaling/FittedBox/ellipsis/textScaleFactor to make text fit, encoding state via color, sizing type, ordering focus traversal, or reviewing any View for screen-reader/switch/low-vision support./adaptive-layoutEnforces adapting layout by available CONSTRAINTS/size, never device or platform checks — LayoutBuilder + MediaQuery.sizeOf/paddingOf/viewInsetsOf (not .of) for narrow rebuilds, Material 3 window size classes (compact <600, medium 600-840, expanded 840-1200, large >1200) as the breakpoint vocabulary, navigation affordance chosen by width (NavigationBar → NavigationRail → NavigationDrawer), list-detail single-pane-vs-two-pane, readable max-width via ConstrainedBox, Flexible/Expanded/FractionallySizedBox over fixed widths, SafeArea + display cutouts + keyboard insets, never lock orientation, foldable/hinge awareness via MediaQuery.displayFeatures, and golden-matrix verification across sizes. Use when building responsive or adaptive UI, tablet/desktop/foldable support, master-detail or two-pane screens, a NavigationRail-vs-BottomNav shell, breakpoints, LayoutBuilder, MediaQuery sizing, SafeArea/cutouts, or fixing overflow at large widths./ads-and-iap-monetizationEnforces opt-in, rewarded-first monetization over the service seam — a rewarded view grants exactly one benefit and only on a genuine reward outcome (a sealed Rewarded/Dismissed/NoFill), earn loops capped per day against an injected Clock, the earn control preloaded and hidden unless an ad is loaded so a fresh account never dead-ends on "no ads available" (a Guideline 2.1 risk), interstitials only at a natural break under a count-and-elapsed cap owned by the service so callers stay dumb, no banner on the primary work surface, one non-consumable unlock plus Restore re-checked each launch and committed through the single write path before the UI reacts, one derived isEntitled provider as the only gate, and the entitlement restored BEFORE the ad SDK initializes so a paying user never starts it, resolves consent, or sees a tracking prompt. Use when adding ads, wiring a rewarded earn loop, placing an interstitial, building a paywall, gating an entitlement, or setting up ad units./app-startup-and-bootstrapEnforces a fixed main() cold-launch order — crash-log sink + FlutterError.onError + PlatformDispatcher.onError installed BEFORE any code that can throw, settings/theme read before runApp so the first frame paints correct, real infra constructed in a composition-root bootstrap() and injected via ProviderScope overrideWithValue over throwing placeholder providers, non-blocking warm-up deferred to addPostFrameCallback, exactly two error handlers with NO runZonedGuarded, ProviderException unwrapped before logging, and a WidgetsBindingObserver that flushes durable state on background/resume. Use when editing lib/main.dart, main_<flavor>.dart, bootstrap.dart or app.dart, reordering anything in main(), adding a splash/onboarding/permission gate, restoring theme before first paint, wiring a DB or service into ProviderScope, handling app-lifecycle background/resume flushes, or chasing cold-start latency, ANRs, or first-frame jank./async-safetyEnforces no-silent-failure async discipline in Flutter/Dart — the arrow-callback Future-drop hole no lint catches (`onTap: () => vm.save(x)`), void-returning event handlers, a mounted/ref.mounted guard after EVERY await before touching BuildContext, capturing Navigator/ScaffoldMessenger before the gap, honest `unawaited()` that always ends in catchError, no empty/bare catches, `rethrow` over `throw e`, and disposing every StreamSubscription/StreamController/Timer/sink. Use when writing or reviewing async/await, wiring onTap/onPressed/onSubmitted or any VoidCallback, touching BuildContext after an await, writing initState/dispose/addPostFrameCallback, adding a Timer or Future.delayed, writing a try/catch, or seeing use_build_context_synchronously, cancel_subscriptions, close_sinks, unawaited_futures, or discarded_futures./ci-pipeline-and-gatesEnforces a lean GitHub Actions Flutter CI where every gate maps to one named release-blocking contract — pinned runner + subosito/flutter-action@v2 toolchain, dart format --set-exit-if-changed, flutter analyze --fatal-infos, build_runner and drift schema freshness (git diff --exit-code), flutter test --test-randomize-ordering-seed random, static import/banned-string greps that catch what runtime can't, coverage-as-report-never-a-gate with the upward-lie fixed, verify-never-bless goldens (no --update-goldens in CI), and an honest statement of what CI cannot prove (audio, real fonts, on-device behaviour). Use when editing .github/workflows/*.yml, adding or removing a job or step, wiring a codegen/schema/format/analyze/coverage gate, writing a grep-based policy test or gate script under test/policy or tool/, pinning action versions, or claiming CI proves something it can't.Other plugins' skills for the same job