diff --git a/docs/guide/database.md b/docs/guide/database.md index 7bace9237..dce9c019f 100644 --- a/docs/guide/database.md +++ b/docs/guide/database.md @@ -20,11 +20,11 @@ const dbFileItems = [ name: "migrations/", description: "Generated SQL migration files", children: [ - { name: "0000_initial.sql" }, + { name: "0000_*.sql" }, { name: "0001_add_posts.sql" }, ], }, - { name: "seed.ts", description: "Seed script (optional)" }, + { name: "seed.sql", description: "Seed SQL for local development (optional)" }, ], }, ] diff --git a/docs/guide/quickstart.md b/docs/guide/quickstart.md index 475d39cf3..1824899b6 100644 --- a/docs/guide/quickstart.md +++ b/docs/guide/quickstart.md @@ -63,7 +63,7 @@ Your `package.json` will then contain an alias like: In an empty directory, `void init` adds the matching Pages adapter and starter dependencies after you choose a framework. Use the same alias pattern for `@void/react`, `@void/vue`, `@void/svelte`, `@void/solid`, and `@void/md` when you add them manually later. -As part of `void init`, you'll choose a Pages framework (React, Vue, Svelte, or Solid) and a starter type. D1 is the default top option and scaffolds a DB-backed page loader, schema, migration, and API route. PostgreSQL scaffolds the same starter and writes `"database": "pg"` to `void.json`. Static Pages skips the database and server starter files so you can start with static content and add Void features later. +As part of `void init`, you'll choose a Pages framework (React, Vue, Svelte, or Solid) and a starter type. D1 is the default top option and scaffolds a DB-backed page loader, schema, generated migration, `db/seed.sql`, and API route. PostgreSQL scaffolds the same starter and writes `"database": "pg"` to `void.json`. Static Pages skips the database and server starter files so you can start with static content and add Void features later. After installation, run the setup flow: diff --git a/docs/reference/cli.md b/docs/reference/cli.md index dcfbf4cd0..18c794c47 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -47,7 +47,7 @@ void init [--tsconfig] [--github] [--agents] Setup wizard for void projects (new or existing). -If run in a scaffoldable empty directory, `void init` scaffolds a Pages starter. If a single Pages adapter is already installed, it reuses that framework; otherwise it asks which framework to scaffold (React, Vue, Svelte, or Solid). It then asks which starter you want: D1, PostgreSQL, or Static Pages. The D1 and PostgreSQL starters write a framework-specific `vite.config.ts`, a `pages/` home page plus `.server.ts` loader, `db/schema.ts`, `db/migrations/0000_initial.sql`, and `routes/api/hello.ts`. The Static Pages starter writes just the framework-specific `vite.config.ts` and a `pages/` home page so you can add server features later. +If run in a scaffoldable empty directory, `void init` scaffolds a Pages starter. If a single Pages adapter is already installed, it reuses that framework; otherwise it asks which framework to scaffold (React, Vue, Svelte, or Solid). It then asks which starter you want: D1, PostgreSQL, or Static Pages. The D1 and PostgreSQL starters write a framework-specific `vite.config.ts`, a `pages/` home page plus `.server.ts` loader, `db/schema.ts`, `db/seed.sql`, a generated initial migration under `db/migrations/`, and `routes/api/hello.ts`. The Static Pages starter writes just the framework-specific `vite.config.ts` and a `pages/` home page so you can add server features later. After that, the full interactive flow walks through: diff --git a/packages/void/src/cli/init.ts b/packages/void/src/cli/init.ts index 55eef434e..3eb7eac88 100644 --- a/packages/void/src/cli/init.ts +++ b/packages/void/src/cli/init.ts @@ -8,11 +8,13 @@ import { } from "node:fs"; import { spawnSync } from "node:child_process"; import { basename, dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; import { parse, type ParseError } from "jsonc-parser"; import { parseArgs } from "node:util"; import { intro, outro, log, confirm, isCancel, cancel, note, select } from "@clack/prompts"; import { ensureProjectTsconfig } from "../codegen/project-tsconfig"; import { getDatabaseDialect, readConfig, type DatabaseDialect } from "../config"; +import { writeDrizzleConfig } from "../drizzle/config"; import { detectFramework, type DetectedFramework } from "../plugin-inference"; import { createPagesStarterTemplate, @@ -104,6 +106,7 @@ const EMPTY_PROJECT_ALLOWED_ENTRIES = new Set([ ]); const PNPM_ONLY_BUILT_DEPENDENCIES = ["better-sqlite3", "esbuild", "workerd"] as const; +const drizzleKitBin = join(fileURLToPath(import.meta.resolve("drizzle-kit")), "..", "bin.cjs"); const EMPTY_PROJECT_ALLOWED_PACKAGES = new Set([ "void", @@ -593,12 +596,12 @@ async function promptStarterMode(): Promise { { value: "sqlite", label: "D1 (SQLite)", - hint: "Recommended starter. Scaffolds a DB-backed page, schema, migration, and API route.", + hint: "Recommended starter. Scaffolds a DB-backed page, schema, generated migration, seed file, and API route.", }, { value: "postgresql", label: "PostgreSQL", - hint: 'Scaffolds the same starter with PostgreSQL and writes "database": "pg" to void.json.', + hint: 'Scaffolds the same starter with PostgreSQL, a generated migration, a seed file, and writes "database": "pg" to void.json.', }, { value: "static", @@ -864,6 +867,41 @@ function installProjectDependencies( log.success(`Installed dependencies with ${packageManager}`); } +export function generateStarterMigration( + root: string, + starterMode: Exclude, +): void { + const dialect = starterMode === "postgresql" ? "postgresql" : "sqlite"; + const configPath = writeDrizzleConfig( + root, + dialect === "postgresql" ? "postgresql://dummy" : ":memory:", + dialect, + ); + + log.step("Generating initial Drizzle migration"); + const result = spawnSync(process.execPath, [drizzleKitBin, "generate", "--config", configPath], { + cwd: root, + stdio: "pipe", + encoding: "utf-8", + shell: process.platform === "win32", + }); + + if (result.error) { + throw result.error; + } + + if (result.status !== 0) { + const detail = [result.stderr, result.stdout].filter(Boolean).join("\n").trim(); + throw new Error( + ["Failed to generate the starter database migration.", ...(detail ? [detail] : [])].join( + "\n\n", + ), + ); + } + + log.success("Generated initial Drizzle migration"); +} + function scaffoldPagesApp( root: string, packageManager: ProjectState["packageManager"], @@ -1261,6 +1299,7 @@ export async function runInitCommand(root: string, initArgs?: InitArgs): Promise const preScaffoldState = detectProjectState(root); const detectedPagesFramework = detectPagesFramework(root); let scaffoldedPagesFramework: ScaffoldFramework | undefined; + let scaffoldedStarterMode: Exclude | undefined; let didScaffoldStarter = false; let scaffoldAddedDependencies = false; @@ -1285,6 +1324,9 @@ export async function runInitCommand(root: string, initArgs?: InitArgs): Promise scaffoldedPagesFramework, starterMode, ); + if (starterMode !== "static") { + scaffoldedStarterMode = starterMode; + } didScaffoldStarter = true; } @@ -1381,6 +1423,9 @@ export async function runInitCommand(root: string, initArgs?: InitArgs): Promise if (scaffoldAddedDependencies) { installProjectDependencies(root, state.packageManager); } + if (scaffoldedStarterMode) { + generateStarterMigration(root, scaffoldedStarterMode); + } outro(`Run \`${getDevCommand(root, framework)}\` to start developing`); } diff --git a/packages/void/src/cli/template.ts b/packages/void/src/cli/template.ts index 73a428f67..bf5dc67fa 100644 --- a/packages/void/src/cli/template.ts +++ b/packages/void/src/cli/template.ts @@ -155,7 +155,7 @@ export function createPagesStarterTemplate(options: { files["pages/index.server.ts"] = getIndexServer(); files["routes/api/hello.ts"] = getHelloRoute(config.label, starterMode); files["db/schema.ts"] = getSchemaFile(starterMode); - files["db/migrations/0000_initial.sql"] = getMigrationFile(starterMode); + files["db/seed.sql"] = getSeedFile(); } return { @@ -243,24 +243,8 @@ export const messages = sqliteTable("messages", { `; } -function getMigrationFile(starterMode: Exclude): string { - if (starterMode === "postgresql") { - return `CREATE TABLE IF NOT EXISTS messages ( - id SERIAL PRIMARY KEY, - text TEXT NOT NULL, - created_at TIMESTAMP NOT NULL DEFAULT now() -); - -INSERT INTO messages (text) VALUES ('Hello from Void'); -`; - } - - return `CREATE TABLE IF NOT EXISTS messages ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - text TEXT NOT NULL, - created_at TEXT NOT NULL DEFAULT (datetime('now')) -); - +function getSeedFile(): string { + return `-- Seed starter content for local development. INSERT INTO messages (text) VALUES ('Hello from Void'); `; } @@ -336,15 +320,22 @@ export default function HomePage({ messages }: Props) {

API example: /api/hello

-
    - {messages.map((message) => ( -
  • - {message.text} -
    - {String(message.createdAt)} -
  • - ))} -
+ {messages.length === 0 ? ( +

+ No messages yet. Run void db seed to load the sample row from + db/seed.sql. +

+ ) : ( +
    + {messages.map((message) => ( +
  • + {message.text} +
    + {String(message.createdAt)} +
  • + ))} +
+ )} ); } @@ -366,7 +357,11 @@ defineProps();

API example: /api/hello

-
    +

    + No messages yet. Run void db seed to load the sample row from + db/seed.sql. +

    +
    • {{ message.text }}
      @@ -392,15 +387,22 @@ defineProps();

      API example: /api/hello

      -
        - {#each messages as message (message.id)} -
      • - {message.text} -
        - {String(message.createdAt)} -
      • - {/each} -
      + {#if messages.length === 0} +

      + No messages yet. Run void db seed to load the sample row from + db/seed.sql. +

      + {:else} +
        + {#each messages as message (message.id)} +
      • + {message.text} +
        + {String(message.createdAt)} +
      • + {/each} +
      + {/if} `; case "solid": @@ -417,15 +419,22 @@ export default function HomePage(props: Props) {

      API example: /api/hello

      -
        - {props.messages.map((message) => ( -
      • - {message.text} -
        - {String(message.createdAt)} -
      • - ))} -
      + {props.messages.length === 0 ? ( +

      + No messages yet. Run void db seed to load the sample row from + db/seed.sql. +

      + ) : ( +
        + {props.messages.map((message) => ( +
      • + {message.text} +
        + {String(message.createdAt)} +
      • + ))} +
      + )} ); } diff --git a/packages/void/test/unit/init-starter-migrations.test.ts b/packages/void/test/unit/init-starter-migrations.test.ts new file mode 100644 index 000000000..e8441358c --- /dev/null +++ b/packages/void/test/unit/init-starter-migrations.test.ts @@ -0,0 +1,94 @@ +import { + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { hasDeploySchemaDrift } from "../../src/cli/deploy"; +import { generateStarterMigration } from "../../src/cli/init"; +import { createPagesStarterTemplate, type ScaffoldStarterMode } from "../../src/cli/template"; + +vi.mock("@clack/prompts", () => ({ + intro: vi.fn(), + outro: vi.fn(), + note: vi.fn(), + cancel: vi.fn(), + confirm: vi.fn(), + isCancel: vi.fn(), + select: vi.fn(), + text: vi.fn(), + spinner: () => ({ start: vi.fn(), stop: vi.fn(), message: vi.fn() }), + log: { success: vi.fn(), warn: vi.fn(), error: vi.fn(), info: vi.fn(), step: vi.fn() }, +})); + +const packageRoot = fileURLToPath(new URL("../..", import.meta.url)); +const tempDirs: string[] = []; + +afterEach(() => { + while (tempDirs.length > 0) { + rmSync(tempDirs.pop()!, { recursive: true, force: true }); + } +}); + +describe("starter migration generation", () => { + it("creates a sqlite starter migration that deploy sees as drift-free", () => { + const root = createStarterApp("sqlite"); + + generateStarterMigration(root, "sqlite"); + + expect(readSqlMigrations(root)).toHaveLength(1); + expect(existsSync(join(root, "db", "migrations", "meta", "_journal.json"))).toBe(true); + expect(hasDeploySchemaDrift(root, "sqlite")).toBe(false); + }); + + it("creates a postgresql starter migration that deploy sees as drift-free", () => { + const root = createStarterApp("postgresql"); + + generateStarterMigration(root, "postgresql"); + + expect(readSqlMigrations(root)).toHaveLength(1); + expect(existsSync(join(root, "db", "migrations", "meta", "_journal.json"))).toBe(true); + expect(hasDeploySchemaDrift(root, "postgresql")).toBe(false); + }); +}); + +function createStarterApp(starterMode: Exclude): string { + const root = mkdtempSync(join(packageRoot, ".tmp-init-starter-")); + tempDirs.push(root); + + const template = createPagesStarterTemplate({ + framework: "react", + starterMode, + voidPackageSpec: "workspace:*", + adapterPackageSpec: "workspace:*", + }); + + for (const [filePath, content] of Object.entries(template.files)) { + const fullPath = join(root, filePath); + mkdirSync(fullPath.slice(0, fullPath.lastIndexOf("/")), { recursive: true }); + writeFileSync(fullPath, content); + } + + const nodeModulesDir = join(root, "node_modules"); + mkdirSync(nodeModulesDir, { recursive: true }); + symlinkSync(packageRoot, join(nodeModulesDir, "void"), "dir"); + + return root; +} + +function readSqlMigrations(root: string): string[] { + const migrationsDir = join(root, "db", "migrations"); + if (!existsSync(migrationsDir)) { + return []; + } + + return readdirSync(migrationsDir) + .filter((entry) => entry.endsWith(".sql")) + .sort(); +} diff --git a/packages/void/test/unit/init.test.ts b/packages/void/test/unit/init.test.ts index 2abcf5442..7e5d7943a 100644 --- a/packages/void/test/unit/init.test.ts +++ b/packages/void/test/unit/init.test.ts @@ -1,4 +1,12 @@ -import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { + existsSync, + mkdtempSync, + mkdirSync, + readFileSync, + readdirSync, + rmSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; @@ -61,6 +69,57 @@ function withTempDir(run: (root: string) => void): void { } } +function writeMockGeneratedMigration(root: string): void { + const schema = readFileSync(join(root, "db", "schema.ts"), "utf-8"); + const isPostgres = schema.includes('from "void/schema-pg"'); + const migrationsDir = join(root, "db", "migrations"); + const metaDir = join(migrationsDir, "meta"); + mkdirSync(metaDir, { recursive: true }); + + writeFileSync( + join(migrationsDir, "0000_generated.sql"), + isPostgres + ? `CREATE TABLE "messages" ( + "id" serial PRIMARY KEY NOT NULL, + "text" text NOT NULL, + "created_at" timestamp DEFAULT now() NOT NULL +); +` + : `CREATE TABLE \`messages\` ( + \`id\` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + \`text\` text NOT NULL, + \`created_at\` text DEFAULT (datetime('now')) NOT NULL +); +`, + ); + writeFileSync( + join(metaDir, "_journal.json"), + JSON.stringify( + { + version: "7", + dialect: isPostgres ? "postgresql" : "sqlite", + entries: [{ idx: 0, version: "6", when: 0, tag: "0000_generated", breakpoints: true }], + }, + null, + 2, + ) + "\n", + ); + writeFileSync( + join(metaDir, "0000_snapshot.json"), + JSON.stringify({ version: "6", dialect: isPostgres ? "postgresql" : "sqlite" }, null, 2) + "\n", + ); +} + +function listMigrationSqlFiles(root: string): string[] { + const migrationsDir = join(root, "db", "migrations"); + if (!existsSync(migrationsDir)) { + return []; + } + return readdirSync(migrationsDir) + .filter((entry) => entry.endsWith(".sql")) + .sort(); +} + afterEach(() => { mockSpawnSync.mockReset(); mockSelect.mockReset(); @@ -75,7 +134,20 @@ afterEach(() => { }); beforeEach(() => { - mockSpawnSync.mockReturnValue({ status: 0 }); + mockSpawnSync.mockImplementation((command, args, options) => { + if ( + command === process.execPath && + Array.isArray(args) && + args[1] === "generate" && + options && + typeof options === "object" && + "cwd" in options && + typeof options.cwd === "string" + ) { + writeMockGeneratedMigration(options.cwd); + } + return { status: 0, stdout: "", stderr: "" }; + }); mockGetToken.mockReturnValue(null); mockRunLogin.mockResolvedValue("token_123"); mockIsStagingMode.mockReturnValue(false); @@ -197,9 +269,14 @@ describe("isScaffoldableEmptyProject", () => { expect(readFileSync(join(root, "db", "schema.ts"), "utf-8")).toContain( 'from "void/schema-d1"', ); - expect(readFileSync(join(root, "db", "migrations", "0000_initial.sql"), "utf-8")).toContain( - "CREATE TABLE IF NOT EXISTS messages", + expect(readFileSync(join(root, "db", "seed.sql"), "utf-8")).toContain("INSERT INTO messages"); + expect(listMigrationSqlFiles(root)).toEqual(["0000_generated.sql"]); + expect(readFileSync(join(root, "db", "migrations", "0000_generated.sql"), "utf-8")).toContain( + "CREATE TABLE", ); + expect( + readFileSync(join(root, "db", "migrations", "meta", "_journal.json"), "utf-8"), + ).toContain('"entries"'); expect(() => readFileSync(join(root, "routes", "api", "hello.get.ts"), "utf-8")).toThrow( /ENOENT/, @@ -207,6 +284,9 @@ describe("isScaffoldableEmptyProject", () => { expect(() => readFileSync(join(root, "index.html"), "utf-8")).toThrow(/ENOENT/); expect(() => readFileSync(join(root, "src", "main.ts"), "utf-8")).toThrow(/ENOENT/); expect(() => readFileSync(join(root, "void.json"), "utf-8")).toThrow(/ENOENT/); + expect(() => + readFileSync(join(root, "db", "migrations", "0000_initial.sql"), "utf-8"), + ).toThrow(/ENOENT/); const tsconfig = JSON.parse(readFileSync(join(root, "tsconfig.json"), "utf-8")); expect(tsconfig.compilerOptions.jsx).toBe("react-jsx"); @@ -244,8 +324,10 @@ describe("isScaffoldableEmptyProject", () => { expect(readFileSync(join(root, "db", "schema.ts"), "utf-8")).toContain( 'from "void/schema-pg"', ); - expect(readFileSync(join(root, "db", "migrations", "0000_initial.sql"), "utf-8")).toContain( - "SERIAL PRIMARY KEY", + expect(readFileSync(join(root, "db", "seed.sql"), "utf-8")).toContain("INSERT INTO messages"); + expect(listMigrationSqlFiles(root)).toEqual(["0000_generated.sql"]); + expect(readFileSync(join(root, "db", "migrations", "0000_generated.sql"), "utf-8")).toContain( + 'CREATE TABLE "messages"', ); const frameworkPrompt = mockSelect.mock.calls[0]?.[0]; @@ -279,12 +361,12 @@ describe("isScaffoldableEmptyProject", () => { { value: "sqlite", label: "D1 (SQLite)", - hint: "Recommended starter. Scaffolds a DB-backed page, schema, migration, and API route.", + hint: "Recommended starter. Scaffolds a DB-backed page, schema, generated migration, seed file, and API route.", }, { value: "postgresql", label: "PostgreSQL", - hint: 'Scaffolds the same starter with PostgreSQL and writes "database": "pg" to void.json.', + hint: 'Scaffolds the same starter with PostgreSQL, a generated migration, a seed file, and writes "database": "pg" to void.json.', }, { value: "static", @@ -322,8 +404,9 @@ describe("isScaffoldableEmptyProject", () => { expect(() => readFileSync(join(root, "pages", "index.server.ts"), "utf-8")).toThrow(); expect(() => readFileSync(join(root, "routes", "api", "hello.ts"), "utf-8")).toThrow(); expect(() => readFileSync(join(root, "db", "schema.ts"), "utf-8")).toThrow(); + expect(() => readFileSync(join(root, "db", "seed.sql"), "utf-8")).toThrow(); expect(() => - readFileSync(join(root, "db", "migrations", "0000_initial.sql"), "utf-8"), + readFileSync(join(root, "db", "migrations", "0000_generated.sql"), "utf-8"), ).toThrow(); expect(() => readFileSync(join(root, "void.json"), "utf-8")).toThrow(); } finally {