forked from imbytecat/fullstack-starter
feat(deploy): migrations 嵌入二进制,实现真单文件部署
- embed-migrations.ts:扫 ./drizzle/meta/_journal.json,生成 src/server/db/migrations.gen.ts,每条 SQL 通过 `import sql_<idx> from '../../../drizzle/<tag>.sql' with { type: 'text' }` 在 bun build --compile 时被静态嵌入二进制
- migrate.ts 重写:runtime 用 createHash('sha256') 计算迁移哈希,仅用 db.execute(sql) + db.transaction() 公开 API 写入 drizzle.__drizzle_migrations 簿记表(不依赖 @internal 的 db.dialect/db.session)
- db:generate 链 db:embed,保证 SQL 改动总是同步到 migrations.gen.ts
- Dockerfile 删 COPY drizzle/,binary 是部署唯一 artifact
- 同步 README / AGENTS / biome.json
This commit is contained in:
@@ -20,8 +20,9 @@ bun run typecheck # tsc --noEmit
|
||||
bun run test # bun test — runs all *.test.ts files (colocated with source)
|
||||
bun run fix # biome check --write (lint + format + organize imports)
|
||||
bun run db:push # dev only — push schema to DB, no migration file
|
||||
bun run db:generate # produce SQL migration files in ./drizzle
|
||||
bun run db:migrate # apply migrations via drizzle-kit (local convenience)
|
||||
bun run db:generate # drizzle-kit generate && embed-migrations.ts (regenerates migrations.gen.ts)
|
||||
bun run db:embed # embed-migrations.ts only — regenerate migrations.gen.ts from ./drizzle/
|
||||
bun run db:migrate # apply migrations via drizzle-kit (local dev convenience; prod uses ./server migrate)
|
||||
bun run db:studio # Drizzle Studio
|
||||
```
|
||||
|
||||
@@ -47,7 +48,7 @@ Before committing: `bun run fix && bun run typecheck && bun run test`. No CI, no
|
||||
- Every table must spread `...generatedFields` from `src/server/db/fields.ts` (`id` UUIDv7 via `$defaultFn(uuidv7)`, `createdAt`, `updatedAt` with `$onUpdateFn`). `generatedFieldKeys` (hand-written `as const`) feeds `createInsertSchema(...).omit(...)`.
|
||||
- `src/server/db/index.ts` exports a module-level `const db = drizzle(...)` — not a lazy singleton. On Bun this is a long-lived process, so top-level side effects are fine and requested. Don't reintroduce `getDB/closeDB` ceremony; the Nitro shutdown plugin calls `db.$client.end()` directly. (Cloudflare Workers would need per-request init — we don't support that deployment target.)
|
||||
- `drizzle.config.ts` runs outside Vite — `@/*` path aliases do NOT resolve there. It currently does `import { env } from './src/env'` (relative). Preserve that.
|
||||
- The `./drizzle/` migrations directory ships empty with a `.gitkeep`. Migrations are applied via the CLI (`./server migrate`, see "CLI & single-binary deploy" below), NOT at server startup. Dev uses `db:push`. Don't mix `push` and `migrate` on the same DB.
|
||||
- **Migrations are embedded in the binary, not read from disk.** `bun run db:generate` chains `drizzle-kit generate && bun embed-migrations.ts`, which regenerates `src/server/db/migrations.gen.ts` (committed, AUTO-GENERATED header) by `import sql_<idx> from '../../../drizzle/<tag>.sql' with { type: 'text' }`. `src/cli/migrate.ts` reads `embeddedMigrations`, computes SHA-256 hashes at runtime, and applies pending entries via `db.execute(sql\`...\`)` + `db.transaction(...)` against the `drizzle.__drizzle_migrations` book-keeping table — public APIs only, no `db.dialect`/`db.session` (those are `@internal`). Dev helpers `db:push` / `drizzle-kit migrate` still read `./drizzle/`.
|
||||
|
||||
## CLI & single-binary deploy
|
||||
|
||||
@@ -65,7 +66,7 @@ Before committing: `bun run fix && bun run typecheck && bun run test`. No CI, no
|
||||
|
||||
Add a subcommand: drop a file in `src/cli/` that default-exports `defineCommand({...})`, then register it in `bin.ts`'s `subCommands` with a `() => import(...)` thunk. Keep top-level imports limited to `citty` + Node built-ins; pull env / db / etc. via `await import(...)` inside `run()`.
|
||||
|
||||
**Deploy flow is always migrate-then-serve.** The compiled binary bundles neither the `./drizzle/` SQL files nor the app schema migrations at runtime — they're read from disk next to the binary. Dockerfile copies `drizzle/` alongside `./server`, and `compose.yaml` models this with a one-shot `migrate` service that `app` `depends_on: service_completed_successfully`. On k8s, run `./server migrate` as an initContainer or a Helm `pre-upgrade` Job; run `./server` (= `./server serve`) as the main container.
|
||||
**Deploy flow is always migrate-then-serve.** Migrations are embedded in the binary (see "Drizzle" section), so the binary is the only artifact — no `./drizzle/` directory at runtime. Dockerfile copies just `./server`. `compose.yaml` models the pattern with a one-shot `migrate` service that `app` `depends_on: service_completed_successfully`. On k8s, run `./server migrate` as an initContainer or a Helm `pre-upgrade` Job; run `./server` (= `./server serve`) as the main container.
|
||||
|
||||
## Compile flags
|
||||
|
||||
@@ -124,7 +125,6 @@ Path alias: `@/* → src/*`. For files outside `src/` use `@/../<file>` (example
|
||||
## Docker / deploy
|
||||
|
||||
- Multi-stage: `oven/bun:1.3.13` builds and runs `bun compile.ts`, then `gcr.io/distroless/cc-debian13:nonroot` runs the single `./server` binary. The `cc` (glibc) distroless variant is required because Bun's compiled binary links glibc.
|
||||
- `drizzle/` folder is copied into the runtime image so `./server migrate` can find migrations at runtime.
|
||||
- `compose.yaml`: one-shot `migrate` service runs `./server migrate` with `restart: "no"`, then `app` starts (`depends_on: migrate: service_completed_successfully`). `DATABASE_URL=postgres://postgres:postgres@db:5432/postgres` for both.
|
||||
- Distroless has no shell, so any init-then-serve pattern must use exec-form `command: [...]`, not `sh -c`.
|
||||
|
||||
@@ -159,6 +159,7 @@ src/
|
||||
│ ├── db/
|
||||
│ │ ├── index.ts # module-level `export const db = drizzle({...})`
|
||||
│ │ ├── fields.ts # generatedFields (id/createdAt/updatedAt) + generatedFieldKeys
|
||||
│ │ ├── migrations.gen.ts # AUTO-GENERATED by `bun run db:embed`; embeds ./drizzle/*.sql via `with { type: 'text' }`
|
||||
│ │ └── schema/ # pgTable definitions; also put `relations()` here when adding
|
||||
│ └── plugins/
|
||||
│ └── shutdown.ts # SIGINT/SIGTERM → db.$client.end() with 500ms delay (prod only)
|
||||
@@ -168,17 +169,20 @@ src/
|
||||
├── styles.css # Tailwind v4 entry
|
||||
└── routeTree.gen.ts # auto-generated, do not edit
|
||||
bin.ts # citty entry (root) — keep imports minimal (see "CLI" section)
|
||||
compile.ts # `bun build --compile` driver; resolves --target
|
||||
drizzle/ # SQL migrations (.gitkeep until first `bun run db:generate`)
|
||||
compile.ts # `bun build --compile` driver; resolves --target; sets minify/bytecode/sourcemap
|
||||
embed-migrations.ts # codegen: scans ./drizzle/meta/_journal.json → src/server/db/migrations.gen.ts
|
||||
drizzle/ # SQL migrations (source of truth for `db:generate`; not shipped in binary)
|
||||
```
|
||||
|
||||
Nitro plugins are wired in `vite.config.ts` (`nitro({ plugins: [...] })`), not via a Nitro config file.
|
||||
|
||||
## Don'ts (specific, non-obvious)
|
||||
|
||||
- Don't edit `routeTree.gen.ts`.
|
||||
- Don't edit `routeTree.gen.ts` or `src/server/db/migrations.gen.ts`.
|
||||
- Don't eager-import anything from `.output/` in `bin.ts` or any module it statically imports — it starts the HTTP server as a side effect. Subcommands must be lazy via citty's `() => import(...)` thunks.
|
||||
- Don't re-add an auto-migrate Nitro plugin. Migrations are an explicit deploy step via `./server migrate`.
|
||||
- Don't reach into `db.dialect`/`db.session` from `migrate.ts` — they're `@internal`. The current implementation uses public `db.execute(sql)` + `db.transaction(...)` against the documented `drizzle.__drizzle_migrations` schema.
|
||||
- Don't add `./drizzle/` back to the runtime image — migrations are embedded into the binary.
|
||||
- Don't reintroduce `getDB/closeDB` or any "lazy DB init" pattern — that's a Cloudflare Workers shape; we deploy on Bun processes.
|
||||
- Don't import `os` from `@orpc/server` in middleware/routers — always `@/server/api/server`.
|
||||
- Don't import from `drizzle-orm/zod` (1.0 beta only). Use `drizzle-zod`.
|
||||
|
||||
Reference in New Issue
Block a user