create-backon 0.13.3 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,27 @@
1
1
  import { readFile, writeFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
- import { Node, SyntaxKind, type SourceFile } from "ts-morph";
3
+ import { Node, SyntaxKind, type ObjectLiteralExpression, type SourceFile } from "ts-morph";
4
4
  import { dim } from "./colors";
5
5
  import { detectDbStatus } from "./db-status";
6
6
  import { detectProject } from "./detect";
7
7
  import { editSource, appendStatements } from "./ast-edit";
8
- import { renderBlankSchema, renderTableBlock, requiredBuilders, tableIdentifier, type TableSpec } from "./templates/schema";
8
+ import {
9
+ columnIdentifier,
10
+ renderBlankSchema,
11
+ renderColumnExpression,
12
+ renderTableBlock,
13
+ requiredBuilders,
14
+ tableIdentifier,
15
+ type ColumnSpec,
16
+ type TableSpec,
17
+ } from "./templates/schema";
9
18
 
10
19
  const PG_CORE_MODULE = "drizzle-orm/pg-core";
11
20
 
12
21
  export interface ParsedColumn {
13
22
  key: string;
23
+ /** Pg builder name, e.g. "text", "integer", "jsonb". */
24
+ type?: string;
14
25
  /** Referenced table's JS identifier, when this column is a `.references(() => X.id)` foreign key. */
15
26
  references?: string;
16
27
  }
@@ -18,18 +29,13 @@ export interface ParsedColumn {
18
29
  export interface ParsedTable {
19
30
  identifier: string;
20
31
  sqlName: string;
32
+ isJunction?: boolean;
21
33
  columns: ParsedColumn[];
22
34
  }
23
35
 
24
36
  /**
25
37
  * Reads every `export const <id> = pgTable("<name>", {...})` out of a real
26
- * schema.ts — used for the duplicate-name check in addTable(), the
27
- * dangling-reference check in removeTable(), and server-config's "which
28
- * table are you removing" / "reference another table?" prompts. Walks the
29
- * real AST (a throwaway in-memory ts-morph Project, same approach
30
- * ast-edit.ts's helpers use) rather than regexing the file, so a
31
- * hand-reformatted schema.ts (reordered columns, different quote style)
32
- * doesn't throw this off.
38
+ * schema.ts via ts-morph AST traversal.
33
39
  */
34
40
  export function parseSchemaTables(contents: string): ParsedTable[] {
35
41
  const { sourceFile } = editSourceForReading(contents);
@@ -44,23 +50,44 @@ export function parseSchemaTables(contents: string): ParsedTable[] {
44
50
  const callee = init.getExpression();
45
51
  if (!Node.isIdentifier(callee) || callee.getText() !== "pgTable") continue;
46
52
 
47
- const [sqlNameArg, columnsArg] = init.getArguments();
53
+ const [sqlNameArg, columnsArg, extraArg] = init.getArguments();
48
54
  const sqlName = sqlNameArg && Node.isStringLiteral(sqlNameArg) ? sqlNameArg.getLiteralValue() : "";
55
+ const isJunction = Boolean(extraArg && extraArg.getText().includes("primaryKey"));
49
56
 
50
57
  const columns: ParsedColumn[] = [];
51
58
  if (columnsArg && Node.isObjectLiteralExpression(columnsArg)) {
52
59
  for (const prop of columnsArg.getProperties()) {
53
60
  if (!Node.isPropertyAssignment(prop)) continue;
54
- columns.push({ key: prop.getName(), references: findReferencedTable(prop) });
61
+ columns.push({
62
+ key: prop.getName(),
63
+ type: findColumnBuilderType(prop),
64
+ references: findReferencedTable(prop),
65
+ });
55
66
  }
56
67
  }
57
68
 
58
- tables.push({ identifier: decl.getName(), sqlName, columns });
69
+ tables.push({ identifier: decl.getName(), sqlName, isJunction, columns });
59
70
  }
60
71
 
61
72
  return tables;
62
73
  }
63
74
 
75
+ function findColumnBuilderType(propAssignment: Node): string | undefined {
76
+ const init = Node.isPropertyAssignment(propAssignment) ? propAssignment.getInitializer() : undefined;
77
+ if (!init) return undefined;
78
+ let deepest: Node = init;
79
+ while (Node.isCallExpression(deepest)) {
80
+ const expr = deepest.getExpression();
81
+ if (Node.isIdentifier(expr)) return expr.getText();
82
+ if (Node.isPropertyAccessExpression(expr)) {
83
+ deepest = expr.getExpression();
84
+ } else {
85
+ break;
86
+ }
87
+ }
88
+ return undefined;
89
+ }
90
+
64
91
  function findReferencedTable(propAssignment: Node): string | undefined {
65
92
  const init = Node.isPropertyAssignment(propAssignment) ? propAssignment.getInitializer() : undefined;
66
93
  if (!init) return undefined;
@@ -77,8 +104,6 @@ function findReferencedTable(propAssignment: Node): string | undefined {
77
104
  return undefined;
78
105
  }
79
106
 
80
- // A read-only pass doesn't need editSource()'s write-back plumbing, just
81
- // the same throwaway in-memory Project + parse step it uses internally.
82
107
  function editSourceForReading(contents: string): { sourceFile: SourceFile } {
83
108
  let sourceFile!: SourceFile;
84
109
  editSource("schema.ts", contents, (_project, sf) => {
@@ -87,7 +112,7 @@ function editSourceForReading(contents: string): { sourceFile: SourceFile } {
87
112
  return { sourceFile };
88
113
  }
89
114
 
90
- /** Adds every builder in `builders` to the shared `drizzle-orm/pg-core` import, merging into the existing declaration instead of creating a second one — unlike ast-edit.ts's ensureImports(), which is line-for-line/per-method by design (see its own doc comment), this one grows a single declaration's named-import set across repeated addTable() calls. */
115
+ /** Merges builders into the shared `drizzle-orm/pg-core` import declaration. */
91
116
  function ensurePgCoreImport(sourceFile: SourceFile, builders: Set<string>): void {
92
117
  const wanted = [...builders].sort();
93
118
  const existing = sourceFile.getImportDeclaration((d) => d.getModuleSpecifierValue() === PG_CORE_MODULE);
@@ -100,7 +125,7 @@ function ensurePgCoreImport(sourceFile: SourceFile, builders: Set<string>): void
100
125
  if (missing.length > 0) existing.addNamedImports(missing);
101
126
  }
102
127
 
103
- /** The undo side of ensurePgCoreImport() — after a table's removed, prunes any pg-core builder no longer referenced by a surviving pgTable() call anywhere in the file, and drops the whole import if nothing's left. */
128
+ /** Prunes unused `drizzle-orm/pg-core` builders after table removal. */
104
129
  function prunePgCoreImport(sourceFile: SourceFile): void {
105
130
  const decl = sourceFile.getImportDeclaration((d) => d.getModuleSpecifierValue() === PG_CORE_MODULE);
106
131
  if (!decl) return;
@@ -117,6 +142,21 @@ function prunePgCoreImport(sourceFile: SourceFile): void {
117
142
  if (decl.getNamedImports().length === 0) decl.remove();
118
143
  }
119
144
 
145
+ function findTableColumnsObject(sourceFile: SourceFile, identifier: string): ObjectLiteralExpression | undefined {
146
+ for (const stmt of sourceFile.getVariableStatements()) {
147
+ if (!stmt.isExported()) continue;
148
+ const decl = stmt.getDeclarations()[0];
149
+ if (!decl || decl.getName() !== identifier) continue;
150
+ const init = decl.getInitializer();
151
+ if (!init || !Node.isCallExpression(init)) continue;
152
+ const callee = init.getExpression();
153
+ if (!Node.isIdentifier(callee) || callee.getText() !== "pgTable") continue;
154
+ const columnsArg = init.getArguments()[1];
155
+ if (columnsArg && Node.isObjectLiteralExpression(columnsArg)) return columnsArg;
156
+ }
157
+ return undefined;
158
+ }
159
+
120
160
  function removeTableStatement(sourceFile: SourceFile, identifier: string): boolean {
121
161
  for (const stmt of sourceFile.getVariableStatements()) {
122
162
  const decls = stmt.getDeclarations();
@@ -158,14 +198,7 @@ export interface AddTableResult {
158
198
  filePath: string;
159
199
  }
160
200
 
161
- /**
162
- * Appends one real `pgTable(...)` export to schema.ts — merges into the
163
- * shared drizzle-orm/pg-core import rather than duplicating it (see
164
- * ensurePgCoreImport()), and only ever edits schema.ts on disk. Never runs
165
- * drizzle-kit, never touches the actual database — generate/migrate/push
166
- * stay separate, explicit commands, same reasoning db-status.ts's own doc
167
- * comment gives for why it never makes a live connection either.
168
- */
201
+ /** Appends one `pgTable(...)` export to `schema.ts`. */
169
202
  export async function addTable(spec: TableSpec, cwd: string = process.cwd()): Promise<AddTableResult> {
170
203
  await requireNeonOrPostgres(cwd);
171
204
  const { root, ext } = await detectProject(cwd);
@@ -193,32 +226,81 @@ export async function addTable(spec: TableSpec, cwd: string = process.cwd()): Pr
193
226
  return { root, identifier, filePath: path };
194
227
  }
195
228
 
229
+ export interface AddColumnResult {
230
+ root: string;
231
+ table: string;
232
+ columnKey: string;
233
+ filePath: string;
234
+ }
235
+
236
+ /**
237
+ * Adds a column to an existing `pgTable(...)` export in `schema.ts`, merging
238
+ * its builder into the shared `drizzle-orm/pg-core` import.
239
+ */
240
+ export async function addColumn(
241
+ table: string,
242
+ col: ColumnSpec,
243
+ cwd: string = process.cwd()
244
+ ): Promise<AddColumnResult> {
245
+ await requireNeonOrPostgres(cwd);
246
+ const { root, ext } = await detectProject(cwd);
247
+ const { path, contents } = await readSchemaFile(root, ext);
248
+
249
+ const tableId = tableIdentifier(table);
250
+ const existingTables = parseSchemaTables(contents);
251
+ const target = existingTables.find((t) => t.identifier === tableId || t.identifier === table);
252
+ if (!target) {
253
+ throw new Error(`No table "${table}" found in ${path}.`);
254
+ }
255
+
256
+ const columnKey = columnIdentifier(col.name);
257
+ if (target.columns.some((c) => c.key === columnKey)) {
258
+ throw new Error(`Column "${columnKey}" already exists on table "${target.identifier}".`);
259
+ }
260
+ if (col.references && !existingTables.some((t) => t.identifier === col.references)) {
261
+ throw new Error(`Column "${col.name}" references unknown table "${col.references}".`);
262
+ }
263
+
264
+ const builder = col.references ? "integer" : col.type;
265
+ const initializer = renderColumnExpression(col);
266
+
267
+ const updated = editSource(path, contents, (_project, sourceFile) => {
268
+ ensurePgCoreImport(sourceFile, new Set([builder]));
269
+ const columnsObj = findTableColumnsObject(sourceFile, target.identifier);
270
+ if (!columnsObj) {
271
+ throw new Error(`Could not locate columns object for table "${target.identifier}".`);
272
+ }
273
+ columnsObj.addPropertyAssignment({ name: columnKey, initializer });
274
+ });
275
+
276
+ await writeFile(path, updated);
277
+ return { root, table: target.identifier, columnKey, filePath: path };
278
+ }
279
+
196
280
  export interface RemoveTableResult {
197
281
  root: string;
198
282
  identifier: string;
199
283
  filePath: string;
200
284
  }
201
285
 
202
- /** server-config/project's "Database tables" note — same spirit as route-methods.ts's formatEndpointsDashboard(). */
286
+ /** server-config/project's "Database tables" summary note. */
203
287
  export function formatTablesDashboard(tables: ParsedTable[]): string {
204
288
  if (tables.length === 0) return dim("No tables yet.");
205
289
  return tables
206
290
  .map((t) => {
207
- if (t.columns.length === 0) return `${t.identifier} (${t.sqlName})\n ${dim("(no columns)")}`;
208
- const lines = t.columns.map((c) => ` ${c.key}${c.references ? dim(` → references ${c.references}.id`) : ""}`);
209
- return `${t.identifier} (${t.sqlName})\n${lines.join("\n")}`;
291
+ const badge = t.isJunction ? dim(" [junction]") : "";
292
+ if (t.columns.length === 0) return `${t.identifier} (${t.sqlName})${badge}\n ${dim("(no columns)")}`;
293
+ const lines = t.columns.map((c) => {
294
+ const typeLabel = c.type ? dim(` : ${c.type}`) : "";
295
+ const refLabel = c.references ? dim(` → references ${c.references}.id`) : "";
296
+ return ` ${c.key}${typeLabel}${refLabel}`;
297
+ });
298
+ return `${t.identifier} (${t.sqlName})${badge}\n${lines.join("\n")}`;
210
299
  })
211
300
  .join("\n\n");
212
301
  }
213
302
 
214
- /**
215
- * The undo for addTable(): removes one table's `pgTable(...)` export and
216
- * prunes any pg-core builder import nothing else still uses. Refuses to
217
- * remove a table another table's column still `.references()` — leaving
218
- * that in place would compile to a runtime `ReferenceError` the moment
219
- * drizzle tries to resolve it, so this is caught here instead of at
220
- * `drizzle-kit generate` time.
221
- */
303
+ /** Removes one `pgTable(...)` export and prunes unused pg-core imports. */
222
304
  export async function removeTable(identifier: string, cwd: string = process.cwd()): Promise<RemoveTableResult> {
223
305
  await requireNeonOrPostgres(cwd);
224
306
  const { root, ext } = await detectProject(cwd);
@@ -520,17 +520,17 @@ export function renderPackageJson(
520
520
  framework === "express"
521
521
  ? {
522
522
  "@mednours/backon": "latest",
523
- express: "^4.21.0",
523
+ express: "^5.3.0",
524
524
  cors: "^2.8.5",
525
525
  helmet: "^8.0.0",
526
526
  compression: "^1.7.5",
527
- zod: "^3.24.1",
527
+ zod: "^4.6.7",
528
528
  ...dbDependencies(db),
529
529
  }
530
530
  : {
531
531
  "@mednours/backon": "latest",
532
- hono: "^4.6.14",
533
- zod: "^3.24.1",
532
+ hono: "^4.13.23",
533
+ zod: "^4.6.7",
534
534
  ...dbDependencies(db),
535
535
  };
536
536
 
@@ -545,14 +545,14 @@ export function renderPackageJson(
545
545
  : framework === "express"
546
546
  ? {
547
547
  "@types/bun": "latest",
548
- "@types/express": "^4.17.21",
549
- typescript: "^5.7.2",
548
+ "@types/express": "^5.0.6",
549
+ typescript: "^7.0.2",
550
550
  ...dbDevDependencies(db),
551
551
  ...dbTypeOnlyDevDependencies(db),
552
552
  }
553
553
  : {
554
554
  "@types/bun": "latest",
555
- typescript: "^5.7.2",
555
+ typescript: "^7.0.2",
556
556
  ...dbDevDependencies(db),
557
557
  ...dbTypeOnlyDevDependencies(db),
558
558
  };
@@ -593,6 +593,7 @@ export function renderPackageJson(
593
593
  // directly (not create-backon) — schema.ts is a real drizzle-kit
594
594
  // config target, no wrapper needed.
595
595
  scripts["add-table"] = "bunx create-backon add-table";
596
+ scripts["add-column"] = "bunx create-backon add-column";
596
597
  scripts["remove-table"] = "bunx create-backon remove-table";
597
598
  scripts["db:generate"] = "drizzle-kit generate";
598
599
  scripts["db:migrate"] = "drizzle-kit migrate";
@@ -2,19 +2,27 @@ import { toKebabCase } from "../prompts";
2
2
  import { camelCase } from "./route";
3
3
 
4
4
  /**
5
- * The column types offered by `add-table`/`server-config`'s table editor.
6
- * Deliberately a curated subset of what drizzle-orm/pg-core actually
7
- * offers, not the full set (no jsonb, arrays, enums, numeric/decimal,
8
- * varchar-with-length, etc. — those still work fine, they just have to be
9
- * hand-added to schema.ts, same "escape hatch, not a lock-in" approach
10
- * obfuscateTailwind()/frontonCompression() use elsewhere in this monorepo).
11
- * Every one of these, plus the modifier chains below, was checked against a
12
- * real `tsc --noEmit` run against real drizzle-orm/pg-core types before
13
- * this went in, not assumed from docs.
5
+ * Curated set of drizzle-orm/pg-core column builders offered by
6
+ * `add-table`, `add-column`, and `server-config`.
14
7
  */
15
- export const COLUMN_TYPES = ["text", "integer", "boolean", "timestamp", "uuid"] as const;
8
+ export const COLUMN_TYPES = [
9
+ "text",
10
+ "varchar",
11
+ "integer",
12
+ "serial",
13
+ "numeric",
14
+ "real",
15
+ "boolean",
16
+ "timestamp",
17
+ "date",
18
+ "uuid",
19
+ "jsonb",
20
+ ] as const;
16
21
  export type ColumnType = (typeof COLUMN_TYPES)[number];
17
22
 
23
+ export const ON_DELETE_ACTIONS = ["cascade", "set null", "restrict"] as const;
24
+ export type OnDeleteAction = (typeof ON_DELETE_ACTIONS)[number];
25
+
18
26
  export interface ColumnSpec {
19
27
  /** Raw name as typed, e.g. "Login Count" — sqlName/jsKey are both derived from this. */
20
28
  name: string;
@@ -24,27 +32,29 @@ export interface ColumnSpec {
24
32
  /**
25
33
  * Pre-rendered modifier chain fragment for a default value, e.g.
26
34
  * `.default(true)`, `.defaultNow()`, `.defaultRandom()` — empty string
27
- * means no default. Kept pre-rendered (rather than a structured value)
28
- * because each column type's default looks nothing like the others
29
- * (timestamp/uuid use a no-arg method, text/integer/boolean take a
30
- * literal), so there's no shared shape worth modeling.
35
+ * means no default.
31
36
  */
32
37
  defaultExpr: string;
38
+ /** Optional max length when `type === "varchar"`. Defaults to 255. */
39
+ varcharLength?: number;
33
40
  /**
34
41
  * A referenced table's JS identifier, e.g. "users" — when set, this
35
- * column is always rendered as `integer(...).references(() => X.id)`
36
- * regardless of `type`, matching the idiomatic Drizzle FK pattern (an
37
- * `integer` column referencing another table's `serial` primary key).
38
- * Verified against a real `tsc --noEmit`.
42
+ * column is rendered as `integer(...).references(() => X.id)`.
39
43
  */
40
44
  references?: string;
45
+ /** Optional foreign-key referential action (`onDelete`). */
46
+ onDelete?: OnDeleteAction;
41
47
  }
42
48
 
43
49
  export interface TableSpec {
44
50
  /** Raw name as typed, e.g. "Blog Posts" — identifier/sqlName are both derived from this. */
45
51
  name: string;
46
- /** Whether to prepend `id: serial("id").primaryKey()` — on by default, matches near-universal convention. */
52
+ /** Whether to prepend `id: serial("id").primaryKey()` — on by default for entity tables, off for junction tables. */
47
53
  includeId: boolean;
54
+ /** Whether to append `createdAt` / `updatedAt` timestamp columns defaulting to `now()`. */
55
+ includeTimestamps?: boolean;
56
+ /** JS column keys forming a composite primary key (used for junction / many-to-many tables). */
57
+ compositePrimaryKey?: string[];
48
58
  columns: ColumnSpec[];
49
59
  }
50
60
 
@@ -64,23 +74,71 @@ function columnSqlName(name: string): string {
64
74
  return toKebabCase(name).replace(/-/g, "_");
65
75
  }
66
76
 
67
- /** Which drizzle-orm/pg-core builder functions a table actually needs — used to keep the shared import declaration minimal and merge-friendly across repeated add-table calls. */
77
+ function singularizeIdentifier(name: string): string {
78
+ if (name.endsWith("ies") && name.length > 3) return `${name.slice(0, -3)}y`;
79
+ if (/(?:ss|x|ch|sh)es$/i.test(name) && name.length > 4) return name.slice(0, -2);
80
+ if (name.endsWith("s") && !name.endsWith("ss") && name.length > 1) return name.slice(0, -1);
81
+ return name;
82
+ }
83
+
84
+ export interface JunctionTableOptions {
85
+ leftTable: string;
86
+ rightTable: string;
87
+ name?: string;
88
+ extraColumns?: ColumnSpec[];
89
+ includeTimestamps?: boolean;
90
+ onDelete?: OnDeleteAction;
91
+ }
92
+
93
+ /**
94
+ * Builds a many-to-many junction `TableSpec` pairing two existing tables with
95
+ * foreign-key columns, a composite `primaryKey`, and optional timestamps/extra columns.
96
+ */
97
+ export function buildJunctionTableSpec(options: JunctionTableOptions): TableSpec {
98
+ const { leftTable, rightTable, extraColumns = [], includeTimestamps = false, onDelete = "cascade" } = options;
99
+ const selfJoin = leftTable === rightTable;
100
+ const leftBase = singularizeIdentifier(leftTable);
101
+ const rightBase = singularizeIdentifier(rightTable);
102
+ const leftColName = selfJoin ? `${leftBase} a id` : `${leftBase} id`;
103
+ const rightColName = selfJoin ? `${rightBase} b id` : `${rightBase} id`;
104
+
105
+ const columns: ColumnSpec[] = [
106
+ { name: leftColName, type: "integer", notNull: true, unique: false, defaultExpr: "", references: leftTable, onDelete },
107
+ { name: rightColName, type: "integer", notNull: true, unique: false, defaultExpr: "", references: rightTable, onDelete },
108
+ ...extraColumns,
109
+ ];
110
+
111
+ return {
112
+ name: options.name?.trim() || `${leftTable}_${rightTable}`,
113
+ includeId: false,
114
+ includeTimestamps,
115
+ compositePrimaryKey: [columnIdentifier(leftColName), columnIdentifier(rightColName)],
116
+ columns,
117
+ };
118
+ }
119
+
120
+ /** Which drizzle-orm/pg-core builder functions a table actually needs. */
68
121
  export function requiredBuilders(table: TableSpec): Set<string> {
69
122
  const builders = new Set<string>(["pgTable"]);
70
123
  if (table.includeId) builders.add("serial");
124
+ if (table.includeTimestamps) builders.add("timestamp");
125
+ if (table.compositePrimaryKey?.length) builders.add("primaryKey");
71
126
  for (const col of table.columns) {
72
127
  builders.add(col.references ? "integer" : col.type);
73
128
  }
74
129
  return builders;
75
130
  }
76
131
 
77
- function renderColumnLine(col: ColumnSpec): string {
78
- const key = columnIdentifier(col.name);
132
+ export function renderColumnExpression(col: ColumnSpec): string {
79
133
  const sqlName = columnSqlName(col.name);
80
134
 
81
135
  let expr: string;
82
136
  if (col.references) {
83
- expr = `integer("${sqlName}").references(() => ${col.references}.id)`;
137
+ const refOpts = col.onDelete ? `, { onDelete: "${col.onDelete}" }` : "";
138
+ expr = `integer("${sqlName}").references(() => ${col.references}.id${refOpts})`;
139
+ } else if (col.type === "varchar") {
140
+ const length = col.varcharLength ?? 255;
141
+ expr = `varchar("${sqlName}", { length: ${length} })`;
84
142
  } else {
85
143
  expr = `${col.type}("${sqlName}")`;
86
144
  }
@@ -89,14 +147,16 @@ function renderColumnLine(col: ColumnSpec): string {
89
147
  if (col.unique) expr += ".unique()";
90
148
  if (col.defaultExpr) expr += col.defaultExpr;
91
149
 
92
- return ` ${key}: ${expr},`;
150
+ return expr;
151
+ }
152
+
153
+ function renderColumnLine(col: ColumnSpec): string {
154
+ return ` ${columnIdentifier(col.name)}: ${renderColumnExpression(col)},`;
93
155
  }
94
156
 
95
157
  /**
96
158
  * Renders one `export const <identifier> = pgTable(...)` block — appended
97
- * as-is to schema.ts by schema-edit.ts's ts-morph layer, the same
98
- * append-real-statements approach templates/route.ts's method codegen
99
- * uses.
159
+ * as-is to schema.ts by schema-edit.ts's ts-morph layer.
100
160
  */
101
161
  export function renderTableBlock(table: TableSpec): string {
102
162
  const identifier = tableIdentifier(table.name);
@@ -104,6 +164,21 @@ export function renderTableBlock(table: TableSpec): string {
104
164
  const lines: string[] = [];
105
165
  if (table.includeId) lines.push(` id: serial("id").primaryKey(),`);
106
166
  for (const col of table.columns) lines.push(renderColumnLine(col));
167
+ if (table.includeTimestamps) {
168
+ lines.push(` createdAt: timestamp("created_at").notNull().defaultNow(),`);
169
+ lines.push(` updatedAt: timestamp("updated_at").notNull().defaultNow(),`);
170
+ }
171
+
172
+ if (table.compositePrimaryKey?.length) {
173
+ const pkCols = table.compositePrimaryKey.map((key) => `table.${key}`).join(", ");
174
+ return `export const ${identifier} = pgTable(
175
+ "${sqlName}",
176
+ {
177
+ ${lines.map((line) => ` ${line}`).join("\n")}
178
+ },
179
+ (table) => [primaryKey({ columns: [${pkCols}] })]
180
+ );`;
181
+ }
107
182
 
108
183
  return `export const ${identifier} = pgTable("${sqlName}", {
109
184
  ${lines.join("\n")}