/** * Tests for the preview-D1 helpers in preview-db.ts: * - `applyWranglerMigrations` — applies `.migrations/` (schema authority). * - `seedWranglerDb` — clears + re-inserts DATA only (no schema). * * Both must thread `--persist-to` so wrangler writes the same SQLite file the * sandbox preview-runtime's miniflare reads (without it, wrangler writes to * `{ws}/.wrangler/state/v3/d1/` while miniflare reads a shared dir → table-not-found). */ import { describe, it, expect, vi, beforeEach } from "vitest"; import { mkdtemp, mkdir, writeFile, readFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; const mockExeca = vi.hoisted(() => vi.fn()); vi.mock("execa", () => ({ execa: mockExeca })); // These live in @upstart.gg/sdk; import the .ts source directly. import { seedWranglerDb, applyWranglerMigrations } from "../preview-db"; const utilsPath = path.resolve(__dirname, "../utils.ts"); async function makeWorkspace(): Promise { const ws = await mkdtemp(path.join(tmpdir(), "fwdb-test-")); await mkdir(path.join(ws, ".tmp"), { recursive: true }); await mkdir(path.join(ws, "app", "config", "datasources"), { recursive: true }); return ws; } async function writeWranglerWithD1(ws: string): Promise { await writeFile( path.join(ws, "wrangler.json"), JSON.stringify({ name: "site-test", d1_databases: [{ binding: "DB", database_name: "site-test" }], }), "utf-8", ); } async function writeDatasource(ws: string, id: string, schemaBody: string): Promise { await writeFile( path.join(ws, "app", "config", "datasources", `${id}.ts`), `import { z } from "zod"; import { defineDatasource } from "${utilsPath}"; export default defineDatasource({ id: "${id}", label: "${id}", provider: "internal", schema: ${schemaBody}, indexes: [], });`, "utf-8", ); } beforeEach(() => { mockExeca.mockReset(); // Default: pretend wrangler succeeded with no stderr. mockExeca.mockResolvedValue({ exitCode: 0, all: "", stderr: "" }); delete process.env.UPSTART_D1_PERSIST_DIR; }); describe("seedWranglerDb — persistTo wiring", () => { it("passes --persist-to when options.persistTo is provided", async () => { const ws = await makeWorkspace(); try { await writeWranglerWithD1(ws); await writeDatasource(ws, "things", "z.object({ name: z.string() })"); await seedWranglerDb(ws, path.join(ws, ".tmp"), { persistTo: "/shared/persist" }); expect(mockExeca).toHaveBeenCalledTimes(1); const [cmd, args] = mockExeca.mock.calls[0]; expect(cmd).toBe("pnpm"); const idx = (args as string[]).indexOf("--persist-to"); expect(idx).toBeGreaterThan(-1); expect((args as string[])[idx + 1]).toBe("/shared/persist"); } finally { await rm(ws, { recursive: true, force: true }); } }); it("falls back to UPSTART_D1_PERSIST_DIR env var when options.persistTo is omitted", async () => { process.env.UPSTART_D1_PERSIST_DIR = "/env/persist"; const ws = await makeWorkspace(); try { await writeWranglerWithD1(ws); await writeDatasource(ws, "things", "z.object({ name: z.string() })"); await seedWranglerDb(ws, path.join(ws, ".tmp")); const args = mockExeca.mock.calls[0][1] as string[]; const idx = args.indexOf("--persist-to"); expect(idx).toBeGreaterThan(-1); expect(args[idx + 1]).toBe("/env/persist"); } finally { await rm(ws, { recursive: true, force: true }); } }); it("explicit options.persistTo wins over the env var", async () => { process.env.UPSTART_D1_PERSIST_DIR = "/env/persist"; const ws = await makeWorkspace(); try { await writeWranglerWithD1(ws); await writeDatasource(ws, "things", "z.object({ name: z.string() })"); await seedWranglerDb(ws, path.join(ws, ".tmp"), { persistTo: "/explicit" }); const args = mockExeca.mock.calls[0][1] as string[]; const idx = args.indexOf("--persist-to"); expect(args[idx + 1]).toBe("/explicit"); } finally { await rm(ws, { recursive: true, force: true }); } }); it("omits --persist-to entirely when neither option nor env var is set", async () => { const ws = await makeWorkspace(); try { await writeWranglerWithD1(ws); await writeDatasource(ws, "things", "z.object({ name: z.string() })"); await seedWranglerDb(ws, path.join(ws, ".tmp")); const args = mockExeca.mock.calls[0][1] as string[]; expect(args.includes("--persist-to")).toBe(false); } finally { await rm(ws, { recursive: true, force: true }); } }); it("no-ops when wrangler.json has no d1_databases configured", async () => { const ws = await makeWorkspace(); try { await writeFile(path.join(ws, "wrangler.json"), JSON.stringify({ name: "x" }), "utf-8"); await seedWranglerDb(ws, path.join(ws, ".tmp"), { persistTo: "/shared" }); expect(mockExeca).not.toHaveBeenCalled(); } finally { await rm(ws, { recursive: true, force: true }); } }); it("no-ops when there are no datasources", async () => { const ws = await makeWorkspace(); try { await writeWranglerWithD1(ws); await seedWranglerDb(ws, path.join(ws, ".tmp"), { persistTo: "/shared" }); expect(mockExeca).not.toHaveBeenCalled(); } finally { await rm(ws, { recursive: true, force: true }); } }); it("writes DELETE (not DROP/CREATE) to clear each datasource table — schema is owned by migrations", async () => { const ws = await makeWorkspace(); try { await writeWranglerWithD1(ws); await writeDatasource(ws, "gallery_images", "z.object({ title: z.string(), order: z.number() })"); await seedWranglerDb(ws, path.join(ws, ".tmp"), { persistTo: "/shared" }); const args = mockExeca.mock.calls[0][1] as string[]; const fileIdx = args.indexOf("--file"); expect(fileIdx).toBeGreaterThan(-1); const sql = await readFile(args[fileIdx + 1], "utf-8"); expect(sql).toContain('DELETE FROM "gallery_images"'); expect(sql).not.toContain("DROP TABLE"); expect(sql).not.toContain("CREATE TABLE"); } finally { await rm(ws, { recursive: true, force: true }); } }); it("throws when wrangler d1 execute fails", async () => { mockExeca.mockResolvedValueOnce({ exitCode: 1, all: "boom", stderr: "boom" }); const ws = await makeWorkspace(); try { await writeWranglerWithD1(ws); await writeDatasource(ws, "things", "z.object({ name: z.string() })"); await expect(seedWranglerDb(ws, path.join(ws, ".tmp"), { persistTo: "/x" })).rejects.toThrow( /wrangler d1 execute failed/, ); } finally { await rm(ws, { recursive: true, force: true }); } }); }); describe("applyWranglerMigrations", () => { async function withMigrations(ws: string): Promise { await mkdir(path.join(ws, ".migrations"), { recursive: true }); await writeFile( path.join(ws, ".migrations", "20260101000000_create_things.sql"), 'CREATE TABLE IF NOT EXISTS "things" ("$id" TEXT PRIMARY KEY);', "utf-8", ); } it("runs `d1 migrations apply` with --persist-to when .migrations exists", async () => { const ws = await makeWorkspace(); try { await writeWranglerWithD1(ws); await withMigrations(ws); await applyWranglerMigrations(ws, { persistTo: "/shared" }); expect(mockExeca).toHaveBeenCalledTimes(1); const args = mockExeca.mock.calls[0][1] as string[]; expect(args.slice(0, 7)).toEqual(["exec", "wrangler", "d1", "migrations", "apply", "DB", "--local"]); const idx = args.indexOf("--persist-to"); expect(args[idx + 1]).toBe("/shared"); } finally { await rm(ws, { recursive: true, force: true }); } }); it("no-ops when the .migrations dir is missing", async () => { const ws = await makeWorkspace(); try { await writeWranglerWithD1(ws); await applyWranglerMigrations(ws, { persistTo: "/shared" }); expect(mockExeca).not.toHaveBeenCalled(); } finally { await rm(ws, { recursive: true, force: true }); } }); it("no-ops when wrangler.json has no d1_databases configured", async () => { const ws = await makeWorkspace(); try { await writeFile(path.join(ws, "wrangler.json"), JSON.stringify({ name: "x" }), "utf-8"); await withMigrations(ws); await applyWranglerMigrations(ws, { persistTo: "/shared" }); expect(mockExeca).not.toHaveBeenCalled(); } finally { await rm(ws, { recursive: true, force: true }); } }); it("throws when wrangler d1 migrations apply fails", async () => { mockExeca.mockResolvedValueOnce({ exitCode: 1, all: "boom", stderr: "boom" }); const ws = await makeWorkspace(); try { await writeWranglerWithD1(ws); await withMigrations(ws); await expect(applyWranglerMigrations(ws, { persistTo: "/x" })).rejects.toThrow( /wrangler d1 migrations apply failed/, ); } finally { await rm(ws, { recursive: true, force: true }); } }); });