Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/reference/cli/generate.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ The generated routes automatically detect your validation library from `package.

Column format: `name:type` or `name:type?` (nullable). Types: `string`, `text`, `datetime`, `integer`, `boolean`, `real`, `blob`.

Column names must be unique. The names `id`, `created_at`, and `updated_at` are reserved for automatically generated columns.

Model names must be lowercase alphanumeric with underscores (e.g. `posts`, `user_roles`). Existing files are never overwritten.

## `void gen migration` {#void-gen-migration}
Expand Down
15 changes: 15 additions & 0 deletions packages/void/src/cli/gen-args.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { parseArgs } from 'node:util';
import { GENERATED_MODEL_COLUMNS } from './model-columns.ts';
import type { SubcommandDef } from './subcommand-prompt.ts';

export const genSubcommands: Array<SubcommandDef> = [
Expand Down Expand Up @@ -54,6 +55,12 @@ export type GenArgs =
| { subcommand: 'queue'; name: string };

const COLUMN_TYPES = new Set(['string', 'text', 'datetime', 'integer', 'boolean', 'real', 'blob']);
const GENERATED_MODEL_COLUMN_NAMES = new Set<string>(
Object.values(GENERATED_MODEL_COLUMNS).flatMap(({ propertyName, columnName }) => [
propertyName,
columnName,
]),
);

const VALID_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete']);

Expand All @@ -73,6 +80,7 @@ function parseModelArgs(args: Array<string>): GenArgs {
}

const columns: Array<{ name: string; type: string; nullable: boolean }> = [];
const usedNames = new Set<string>();
for (const col of rest) {
const match = col.match(/^([a-z_][a-z0-9_]*):([a-z]+)(\?)?$/);
if (!match) {
Expand All @@ -84,6 +92,13 @@ function parseModelArgs(args: Array<string>): GenArgs {
`gen: Unknown column type '${colType}'. Use one of: ${[...COLUMN_TYPES].join(', ')}.`,
);
}
if (GENERATED_MODEL_COLUMN_NAMES.has(colName)) {
throw new Error(`gen: Void adds '${colName}' automatically. Remove '${col}'.`);
}
if (usedNames.has(colName)) {
throw new Error(`gen: Column '${colName}' was specified more than once.`);
}
usedNames.add(colName);
columns.push({ name: colName, type: colType, nullable: !!nullable });
}

Expand Down
25 changes: 14 additions & 11 deletions packages/void/src/cli/gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { readProjectPaths } from '../project-paths.ts';
import { hasOwnKey } from '../shared/has-own-key.ts';
import type { GenArgs } from './gen-args.ts';
import { log, select, isCancel, cancel } from './interactive-prompts.ts';
import { GENERATED_MODEL_COLUMNS } from './model-columns.ts';
import { printSuccess } from './output.ts';
import { buildDrizzleKitSpawnEnv, drizzleKitBin } from './yarn-pnp.ts';

Expand Down Expand Up @@ -357,14 +358,15 @@ export const POST = defineHandler.withValidator({
}

function generateIdRoute(name: string, validator: Validator): string {
const idProperty = GENERATED_MODEL_COLUMNS.id.propertyName;
if (validator === 'none') {
return `import { defineHandler } from "void";
import { db, eq } from "void/db";
import { ${name} } from "@schema";

export const GET = defineHandler(async (c) => {
const id = c.req.param("id");
const [row] = await db.select().from(${name}).where(eq(${name}.id, Number(id)));
const [row] = await db.select().from(${name}).where(eq(${name}.${idProperty}, Number(id)));

if (!row) {
return new Response("Not found", { status: 404 });
Expand All @@ -388,7 +390,7 @@ import { ${name} } from "@schema";
export const GET = defineHandler.withValidator({
params: ${paramsSchema},
})(async (c, { params }) => {
const [row] = await db.select().from(${name}).where(eq(${name}.id, Number(params.id)));
const [row] = await db.select().from(${name}).where(eq(${name}.${idProperty}, Number(params.id)));

if (!row) {
return new Response("Not found", { status: 404 });
Expand All @@ -413,6 +415,7 @@ async function runModel(root: string, name: string, columns: Array<ColumnSpec>):
const modelPath = join(schemaDir, `${name}.ts`);

// 1. Generate Drizzle table definition
const { id, createdAt, updatedAt } = GENERATED_MODEL_COLUMNS;
const colDefs = columns.map((col) => drizzleColumnDef(dialect, col));
const columnImports = drizzleImportsForColumns(dialect, columns).join(', ');
let content: string;
Expand All @@ -421,10 +424,10 @@ async function runModel(root: string, name: string, columns: Array<ColumnSpec>):
`import { pgTable, ${columnImports} } from "void/schema-pg";`,
'',
`export const ${name} = pgTable("${name}", {`,
` id: serial("id").primaryKey(),`,
` ${id.propertyName}: serial("${id.columnName}").primaryKey(),`,
...colDefs,
` createdAt: timestamp("created_at").notNull().defaultNow(),`,
` updatedAt: timestamp("updated_at").notNull().defaultNow(),`,
` ${createdAt.propertyName}: timestamp("${createdAt.columnName}").notNull().defaultNow(),`,
` ${updatedAt.propertyName}: timestamp("${updatedAt.columnName}").notNull().defaultNow(),`,
'});',
'',
].join('\n');
Expand All @@ -433,10 +436,10 @@ async function runModel(root: string, name: string, columns: Array<ColumnSpec>):
`import { mysqlTable, ${columnImports} } from "void/schema-mysql";`,
'',
`export const ${name} = mysqlTable("${name}", {`,
` id: int("id").autoincrement().primaryKey(),`,
` ${id.propertyName}: int("${id.columnName}").autoincrement().primaryKey(),`,
...colDefs,
` createdAt: timestamp("created_at").notNull().defaultNow(),`,
` updatedAt: timestamp("updated_at").notNull().defaultNow(),`,
` ${createdAt.propertyName}: timestamp("${createdAt.columnName}").notNull().defaultNow(),`,
` ${updatedAt.propertyName}: timestamp("${updatedAt.columnName}").notNull().defaultNow(),`,
'});',
'',
].join('\n');
Expand All @@ -446,10 +449,10 @@ async function runModel(root: string, name: string, columns: Array<ColumnSpec>):
`import { sql } from "void/db";`,
'',
`export const ${name} = sqliteTable("${name}", {`,
` id: integer("id").primaryKey({ autoIncrement: true }),`,
` ${id.propertyName}: integer("${id.columnName}").primaryKey({ autoIncrement: true }),`,
...colDefs,
' createdAt: text("created_at").notNull().default(sql`(datetime(\'now\'))`),',
' updatedAt: text("updated_at").notNull().default(sql`(datetime(\'now\'))`),',
` ${createdAt.propertyName}: text("${createdAt.columnName}").notNull().default(sql\`(datetime('now'))\`),`,
` ${updatedAt.propertyName}: text("${updatedAt.columnName}").notNull().default(sql\`(datetime('now'))\`),`,
'});',
'',
].join('\n');
Expand Down
5 changes: 5 additions & 0 deletions packages/void/src/cli/model-columns.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const GENERATED_MODEL_COLUMNS = {
id: { propertyName: 'id', columnName: 'id' },
createdAt: { propertyName: 'createdAt', columnName: 'created_at' },
updatedAt: { propertyName: 'updatedAt', columnName: 'updated_at' },
} as const;
49 changes: 49 additions & 0 deletions packages/void/test/integration/gen-model-cli.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { spawnSync } from 'node:child_process';
import { readdirSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { expect, it } from 'vite-plus/test';
import { createPackageFixtureDir } from '../../../../test/fixture-dir.ts';

const packageRoot = join(import.meta.dirname, '../..');
const cliEntry = join(packageRoot, 'dist/cli/cli.mjs');

it.each([
{
name: 'a repeated column',
columns: ['title:string', 'title:text'],
message: "Column 'title' was specified more than once.",
},
{
name: 'the generated primary key',
columns: ['id:integer'],
message: "Void adds 'id' automatically. Remove 'id:integer'.",
},
{
name: 'the generated creation timestamp',
columns: ['created_at:text'],
message: "Void adds 'created_at' automatically. Remove 'created_at:text'.",
},
{
name: 'the generated update timestamp',
columns: ['updated_at:text'],
message: "Void adds 'updated_at' automatically. Remove 'updated_at:text'.",
},
])('rejects $name before scaffolding', ({ columns, message }) => {
const root = createPackageFixtureDir(packageRoot, 'gen-model-cli-');
try {
writeFileSync(join(root, 'package.json'), '{"dependencies":{"zod":"*"}}\n');
const result = spawnSync(process.execPath, [cliEntry, 'gen', 'model', 'posts', ...columns], {
cwd: root,
encoding: 'utf8',
timeout: 10_000,
});

expect(result.error).toBeUndefined();
const output = result.stdout + result.stderr;
expect(result.status, output).toBe(1);
expect(output).toContain(message);
expect(readdirSync(root)).toEqual(['package.json']);
} finally {
rmSync(root, { recursive: true, force: true });
}
});