magic-local-storage
Skill3 starsChanged 18 days agoMITView on GitHub
Store data locally in a Magic app with SQLite: DB, Schema, migrations, seeders, factories, useLocal models and SyncFeed.
1 other project uses a version of this.
Adopted by
Most recently taken up by
- anilcancakir/aiword for word, first seen Nov 16, 2026
Other versions1 project uses a version of this.
Word for word · 1
- anilcancakir/ai★ 3100% same
Edited · 0
None found.
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository19 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- crumbsSkill
- dowelSkill
- flutter-reviewSkill
- magic-analyticsSkill
- magic-deeplinkSkill
- magic-deviceSkill
- magic-devtoolsSkill
- magic-encryptionSkill
- magic-frameworkSkill
- magic-notificationsSkill
- magic-paymentsSkill
- magic-pickerSkill
- magic-sentrySkill
- magic-social-authSkill
- magic-socketSkill
- magic-starterSkill
- tapirSkill
- wind-uiSkill
The file
We split this skill into the rules it gives an agent
2 rules. About 0 are common, 0 are distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 27
Run the migration before the first save.
- Very specific: line 35
Never call DB.beginTransaction, DB.commit or DB.rollback in a migration.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
magic_local_storage
The local SQLite layer of a Magic app. DB and Schema run queries and table changes on one connection that DatabaseManager opens (FFI on native, sqlite3.wasm on web). Migration classes run through Migrator, Seeder and Factory fill tables, and SyncFeed keeps a table consistent with a server. DatabaseServiceProvider also binds the QueryModelStore at local_model_store, which is what a useLocal => true model persists through.
This skill covers magic_local_storage only. The Magic framework itself (container, providers, Model and InteractsWithPersistence, Http, config) is the magic-framework skill.
Install
flutter pub add magic_local_storage
dart run magic:dowel plugin:install magic_local_storageRequires Dart >=3.13, Flutter >=3.47 and magic ^1.0.0. The installer adds DatabaseServiceProvider to lib/config/app.dart and () => databaseConfig to the configFactories of lib/main.dart, then chains local_storage:install, which downloads web/sqlite3.wasm for a project with a web/ folder. It publishes no config. Import only package:magic_local_storage/magic_local_storage.dart.
Model rules
- A
useLocal => truemodel needs this package. With no store bound, every persistence leg (find,all,save,delete,refresh) throws aStateErrornamingmagic_local_storage, and it is thrown before the leg's owntry, so no fallback hides it. Fix it by registering the provider, never by catching the error. - The store keeps only the attributes the table has a column for. A typo in an attribute name is dropped without an error, so check the table when a value does not persist.
- Run the migration before the first save. A table that does not exist makes the store throw a
StateErrornaming it, sosave()answersfalseon a local-only model andFactory.create()throws. model.query()returns raw row maps. Booleans arrive as0and1; hydrate through the model to apply its casts.- Another engine or a test double implements core's
LocalModelStoreand binds it atlocal_model_store.
Migration rules
up()anddown()returnvoidand stay synchronous.void up() asynccompiles andrunrecords it complete at the first suspension.- Inside a migration use
Schema.create,Schema.table,Schema.drop,Schema.dropIfExists,Schema.rename,DB.statementandDB.select.Schema.hasTable,hasColumn,getColumnsandDatabaseManager.getColumnsreturn futures; readPRAGMA table_infowithDB.selectinstead. - Never call
DB.beginTransaction,DB.commitorDB.rollbackin a migration. Onerunis oneSAVEPOINT, and a commit inside it closes that unit;runthrows aStateErrornaming the migration. nameis the ledger key inmagic_migrations. Keep it unique and never rename a released one, or it runs again.- There is no discovery: pass every migration to
Migrator().run, in order, afterMagic.init. It skips applied names, so calling it on every launch is safe. - A migration with no honest rollback throws
UnsupportedErrorfromdown(); doing nothing makesrollbackforget a migration that is still applied. - A column added to an existing table must be
nullable()or carrydefaultValue; SQLite refuses aNOT NULLcolumn with no default.
Query rules
- Raw
DB.select,insert,update,deleteandstatementare synchronous;QueryBuilderterminals return futures. - Values are bound. A plain table or column name (
order,users.id) is quoted, soorderworks as a column inwhere,orderBy,valueandpluck; any other text (lower(email),name COLLATE NOCASE,RANDOM()) and everyselect([...])entry is raw SQL. Never pass user input as a name. wheretakes=,==,!=,<>,<,<=,>,>=,like,not like,glob,not glob,match,isandis not;orderBytakesascordesc. Anything else,inincluded, throws anArgumentError.- A
nullvalue inwherebecomesIS NULL(=,==,is, two arguments) orIS NOT NULL(!=,<>,is not); preferwhereNullandwhereNotNull. Constraints are alwaysANDed. insertorupdateon a table that does not exist throws aStateErrornaming it, sosave()on a local-only model answersfalseuntil its migration ran.insertAllis one insert per record and not atomic; wrap it inDB.transaction.DB.transactionowns its transaction. ADB.commit()orDB.rollback()inside it makes the call throw. For manual control usebeginTransaction,commitandrollbackthroughout and do not mix the two.
Seeding rules
Seeding.run(List<Seeder>)runs the seeders in order. Core'sMagic.seedis gone.- Guard it (
kDebugMode, acount()check) so a restart does not seed twice. - A
Factory<T>implementsdefinition(),newInstance()andnewFactory().countandstatereturn copies built throughnewFactory; name reusable states as an extension onFactory<T>, since a method on the subclass is lost aftercount(). - A factory fills its models unguarded.
create()saves throughsave(), so the model needsInteractsWithPersistence; a refused save throws aStateError.
Sync rules
- A feed overrides
feed,resource,envelopeKey,pendingandadoptRow.run({scope, account})pushesPOST <resource>/sync, then, only after a push with no failure, pullsGET <resource>pages untilhas_moreis false. runnever throws; readSyncReport.failure. It needs a network driver and thesync_cursorstable: listCreateSyncCursorsTableinMigrator().run, or pointSyncLedger(table: ...)at your own five-column table.pendingreturns rows oldest first, filtered by a strict>onsinceMillis. Only the push advances the mark; an adopted row never does.adoptRowanswersfalsefor a row it cannot read.
Recipes
A migration, model and save:
import 'package:magic/magic.dart';
import 'package:magic_local_storage/magic_local_storage.dart';
class CreateNotesTable extends Migration {
@override
String get name => '20261114120000_create_notes_table';
@override
void up() {
Schema.create('notes', (Blueprint table) {
table.id();
table.string('title');
table.timestamps();
});
}
@override
void down() {
Schema.dropIfExists('notes');
}
}
class Note extends Model with HasTimestamps, InteractsWithPersistence {
@override
String get table => 'notes';
@override
String get resource => 'notes';
@override
List<String> get fillable => ['title'];
@override
bool get useLocal => true;
@override
bool get useRemote => false;
}
Future<void> saveNote() async {
await Migrator().run([CreateNotesTable()]);
await (Note()..fill({'title': 'First'})).save();
}Query and transact:
import 'package:magic_local_storage/magic_local_storage.dart';
Future<void> archive(int id) async {
await DB.transaction(() async {
final Map<String, dynamic>? row = await DB.table('notes').where('id', id).first();
await DB.table('archive').insert({'title': row?['title']});
await DB.table('notes').where('id', id).delete();
});
}Seed with a factory:
import 'package:magic/magic.dart';
import 'package:magic_local_storage/magic_local_storage.dart';
class Note extends Model with InteractsWithPersistence {
@override
String get table => 'notes';
@override
String get resource => 'notes';
@override
List<String> get fillable => ['title'];
@override
bool get useLocal => true;
@override
bool get useRemote => false;
}
class NoteFactory extends Factory<Note> {
@override
Factory<Note> newFactory() => NoteFactory();
@override
Note newInstance() => Note();
@override
Map<String, dynamic> definition() => {'title': faker.lorem.sentence()};
}
class NoteSeeder extends Seeder {
@override
Future<void> run() async {
await NoteFactory().count(10).create();
}
}
Future<void> seed() => Seeding.run([NoteSeeder()]);Generators
dart run magic:dowel make:migration create_notes_table --create=notes writes lib/database/migrations/m_<timestamp>_create_notes_table.dart; make:seeder Note and make:factory Note write lib/database/seeders/note_seeder.dart and lib/database/factories/note_factory.dart. Core's make:model -m -f -s calls them through the dowel registry and prints a hint naming this package when it is absent. A generated factory throws UnimplementedError until you import the model and implement newInstance(). Nothing registers a generated migration: add it to Migrator().run.
Testing
In setUp() call MagicApp.reset() and Magic.flush(), set an in-memory connection with DatabaseManager().setConnection(sqlite3.openInMemory()) (add sqlite3 as a dev dependency), bind the store with MagicApp.instance.singleton('local_model_store', () => QueryModelStore()), then run the migrations the test needs. :memory: does not work as a database config value on native platforms.
DatabaseManager is a singleton that Magic.flush() does not clear: call DatabaseManager().dispose() in tearDown(). Call Log.fake() before Seeding.run, and Http.fake plus Http.unfake() around a SyncFeed test. A useLocal test with no store bound fails with the StateError, which is the behaviour to assert when that is the point.
import 'package:flutter_test/flutter_test.dart';
import 'package:magic/magic.dart';
import 'package:magic_local_storage/magic_local_storage.dart';
import 'package:sqlite3/sqlite3.dart';
void main() {
setUp(() {
MagicApp.reset();
Magic.flush();
DatabaseManager().setConnection(sqlite3.openInMemory());
MagicApp.instance.singleton('local_model_store', () => QueryModelStore());
});
tearDown(() {
DatabaseManager().dispose();
});
test('the table accepts a row', () async {
DB.statement('CREATE TABLE notes (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT)');
await DB.table('notes').insert({'title': 'First'});
expect(await DB.table('notes').count(), 1);
});
}Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

