mirror of
https://github.com/tiennm99/miti99bot.git
synced 2026-04-17 13:21:31 +00:00
4.7 KiB
4.7 KiB
Phase 01 — D1 Setup
Priority: P0 (blocker for 02/03/04) Status: Complete
Overview
Wire Cloudflare D1 into the framework: binding, per-module migrations, SqlStore factory mirroring the KVStore shape, Miniflare-backed tests.
Key Insights
- D1 is SQLite at the edge; prepared statements +
db.prepare().bind().all()/first()/run(). vitest-pool-workers(or plain Miniflare) exposes D1 in tests without real Cloudflare calls.- Per-module table prefixing mirrors the existing KV prefixing — module authors never touch raw
env.DB.
Requirements
Functional
- Module init receives
sqlalongsidedbininit({ db, sql, env }). sql.prepare(query, ...binds)/sql.run(query, ...binds)/sql.all(query, ...binds)/sql.first(query, ...binds).- Table names referenced in queries are left literal — authors write
trading_tradesdirectly (prefix is convention, not rewriting). sql.tablePrefixexposed for authors who want to interpolate.- Migrations auto-discovered from
src/modules/*/migrations/*.sql, applied viawrangler d1 migrations applyin deploy script.
Non-functional
- Zero overhead when a module does not use SQL.
- Tests run fully offline against Miniflare.
Architecture
src/db/
├── kv-store-interface.js # existing
├── cf-kv-store.js # existing
├── create-store.js # existing (KV)
├── sql-store-interface.js # NEW — JSDoc typedef
├── cf-sql-store.js # NEW — wraps env.DB
└── create-sql-store.js # NEW — factory, sets tablePrefix = `${moduleName}_`
createSqlStore(moduleName, env) returns an object exposing prepare, run, all, first, batch, tablePrefix.
Related Code Files
Create
src/db/sql-store-interface.jssrc/db/cf-sql-store.jssrc/db/create-sql-store.jstests/db/create-sql-store.test.jstests/fakes/fake-d1.js(Miniflare D1 helper for tests)
Modify
src/modules/registry.js— passsqlintoinit({ db, sql, env })src/modules/dispatcher.js— samewrangler.toml— add[[d1_databases]]block,migrations_diroptionalpackage.json— adddb:migratescript:wrangler d1 migrations apply miti99bot-db --remote; chain intodeployscripts/register.js— no change needed, but verify no breakage
Implementation Steps
- Create D1 database:
npx wrangler d1 create miti99bot-db. Record UUID inwrangler.toml. - Author
sql-store-interface.jswith JSDoc@typedefforSqlStore. - Implement
cf-sql-store.js— thin wrapper aroundenv.DB.prepare(). - Implement
create-sql-store.js— returns wrapper +tablePrefix. - Update
registry.js+dispatcher.jsto passsqlinto moduleinit+ command handler contexts (viactx.sql? decision below). - Add migration discovery: walk
src/modules/*/migrations/at deploy time, consolidate into a centralmigrations/or use wrangler's default per-dir. - Wire
db:migrateintonpm run deploy:wrangler deploy && npm run db:migrate && npm run register. - Add
fake-d1.jsusing@miniflare/d1orbetter-sqlite3-backed fake. - Tests:
create-sql-store.test.jsverifying prefix exposure + basic CRUD.
Open Decisions
- Command handler access to
sql: expose viactx.sql(grammY context extension in dispatcher) or require modules to close oversqlcaptured ininit? Lean close over in init — matches howdbis currently used. - Migration runner: wrangler's native
d1 migrations applyrequires a singlemigrations_dir. Options:- (a) consolidate all per-module SQL into root
migrations/at build time via a prebuild script. - (b) custom runner script that applies each
src/modules/*/migrations/*.sqlin order. - Lean (b) — keeps per-module locality.
- (a) consolidate all per-module SQL into root
Todo List
- Create D1 database + update
wrangler.toml sql-store-interface.jswith typedefscf-sql-store.jsimplementationcreate-sql-store.jsfactory- Update
registry.jsinit signature - Update
dispatcher.jsto passsql(no change needed — delegates to buildRegistry) - Write custom migration runner at
scripts/migrate.js - Wire into
npm run deploy fake-d1.jstest helper- Unit tests for
create-sql-store
Success Criteria
- A module can define
init({ sql }) => sql.run("INSERT INTO mymod_foo VALUES (?)", "x")and it works in dev + test + prod. npm testgreen.- No regression in existing KV-only modules.
Risks
- Wrangler migration tooling may not support per-module layout → fallback to custom runner.
- D1 read-after-write consistency in eventually-consistent replicas — document for module authors.
Next Steps
- Phase 02 can start once
sqlthreads throughinit.