create-backon 0.11.0 → 0.13.0
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.
- package/README.md +48 -1
- package/dist/cli.js +578 -10
- package/package.json +1 -1
- package/src/cli.ts +311 -0
- package/src/generate.ts +8 -1
- package/src/schema-edit.ts +253 -0
- package/src/templates/base.ts +56 -5
- package/src/templates/db.ts +35 -4
- package/src/templates/route.ts +5 -2
- package/src/templates/schema.ts +160 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-backon",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Scaffolds a new backend project on backon — like `bun create vite@latest`, but for a consistent controller/routes/services backend layout. Runs via bunx/bun create or npx/npm create.",
|
|
6
6
|
"license": "MIT",
|
package/src/cli.ts
CHANGED
|
@@ -7,6 +7,8 @@
|
|
|
7
7
|
// first line. Local dev (`bun run src/cli.ts`, the "start" script) doesn't
|
|
8
8
|
// need a shebang either; `bun run` executes the given file directly, it
|
|
9
9
|
// doesn't rely on the OS reading a shebang the way `./cli.ts` would.
|
|
10
|
+
import { readFile } from "node:fs/promises";
|
|
11
|
+
import { join } from "node:path";
|
|
10
12
|
import * as p from "@clack/prompts";
|
|
11
13
|
import { runPrompts } from "./prompts";
|
|
12
14
|
import { generateProject } from "./generate";
|
|
@@ -27,6 +29,8 @@ import {
|
|
|
27
29
|
type EndpointSummary,
|
|
28
30
|
} from "./route-methods";
|
|
29
31
|
import { HTTP_VERBS, paramNamesFromPath, pascalCase, type HttpVerb, type MethodSpec } from "./templates/route";
|
|
32
|
+
import { addTable, removeTable, parseSchemaTables, formatTablesDashboard, type ParsedTable } from "./schema-edit";
|
|
33
|
+
import { COLUMN_TYPES, columnIdentifier, tableIdentifier, type ColumnSpec, type ColumnType, type TableSpec } from "./templates/schema";
|
|
30
34
|
|
|
31
35
|
const ADD_ROUTE_SUBCOMMANDS = new Set(["add-route", "route"]);
|
|
32
36
|
const REMOVE_ROUTE_SUBCOMMANDS = new Set(["remove-route", "rm-route"]);
|
|
@@ -44,6 +48,8 @@ const ADD_METHOD_SUBCOMMANDS = new Set(["add-method", "method"]);
|
|
|
44
48
|
// wanted to look.
|
|
45
49
|
const PROJECT_SUBCOMMANDS = new Set(["project"]);
|
|
46
50
|
const SERVER_CONFIG_SUBCOMMANDS = new Set(["server-config"]);
|
|
51
|
+
const ADD_TABLE_SUBCOMMANDS = new Set(["add-table", "table"]);
|
|
52
|
+
const REMOVE_TABLE_SUBCOMMANDS = new Set(["remove-table", "rm-table"]);
|
|
47
53
|
|
|
48
54
|
async function promptForRouteName(introText: string): Promise<string> {
|
|
49
55
|
p.intro(introText);
|
|
@@ -162,6 +168,289 @@ async function runProjectOverview(): Promise<void> {
|
|
|
162
168
|
p.outro("Manage endpoints and methods with `bun run server-config`.");
|
|
163
169
|
}
|
|
164
170
|
|
|
171
|
+
// ---------------------------------------------------------------------------
|
|
172
|
+
// add-table / remove-table / server-config's table actions — schema.ts's
|
|
173
|
+
// interactive editor. Gated to "neon"/"postgres" (the only two db choices
|
|
174
|
+
// schema.ts/drizzle.config.ts get scaffolded for — see templates/db.ts's
|
|
175
|
+
// hasSchemaSupport field); SQLite and "none" fail with a clear message
|
|
176
|
+
// rather than silently no-opping.
|
|
177
|
+
// ---------------------------------------------------------------------------
|
|
178
|
+
|
|
179
|
+
async function ensureSchemaSupport(): Promise<boolean> {
|
|
180
|
+
const status = await detectDbStatus();
|
|
181
|
+
if (status.driver === "neon" || status.driver === "postgres") return true;
|
|
182
|
+
p.log.error(
|
|
183
|
+
`Schema management needs a "neon" or "postgres" db driver (src/config/db reports "${status.driver}") — ` +
|
|
184
|
+
`SQLite and "none" use a different schema dialect (or none at all) and aren't supported here yet.`
|
|
185
|
+
);
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async function readSchemaTables(): Promise<ParsedTable[]> {
|
|
190
|
+
const { root, ext } = await detectProject();
|
|
191
|
+
try {
|
|
192
|
+
const contents = await readFile(join(root, "src/config", `schema.${ext}`), "utf-8");
|
|
193
|
+
return parseSchemaTables(contents);
|
|
194
|
+
} catch {
|
|
195
|
+
return [];
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Type-specific "does this column get a default?" question — returns a pre-rendered modifier fragment (see ColumnSpec.defaultExpr's doc comment), "" for none, or null if cancelled. */
|
|
200
|
+
async function promptDefaultExpr(type: ColumnType): Promise<string | null> {
|
|
201
|
+
if (type === "timestamp") {
|
|
202
|
+
const v = await p.confirm({ message: "Default to now()?", initialValue: false });
|
|
203
|
+
if (p.isCancel(v)) return null;
|
|
204
|
+
return v ? ".defaultNow()" : "";
|
|
205
|
+
}
|
|
206
|
+
if (type === "uuid") {
|
|
207
|
+
const v = await p.confirm({ message: "Default to a random UUID?", initialValue: false });
|
|
208
|
+
if (p.isCancel(v)) return null;
|
|
209
|
+
return v ? ".defaultRandom()" : "";
|
|
210
|
+
}
|
|
211
|
+
if (type === "boolean") {
|
|
212
|
+
const v = await p.select({
|
|
213
|
+
message: "Default value",
|
|
214
|
+
options: [
|
|
215
|
+
{ value: "none", label: "None" },
|
|
216
|
+
{ value: "true", label: "true" },
|
|
217
|
+
{ value: "false", label: "false" },
|
|
218
|
+
],
|
|
219
|
+
initialValue: "none",
|
|
220
|
+
});
|
|
221
|
+
if (p.isCancel(v)) return null;
|
|
222
|
+
return v === "none" ? "" : `.default(${v})`;
|
|
223
|
+
}
|
|
224
|
+
// text / integer
|
|
225
|
+
const v = await p.text({
|
|
226
|
+
message: "Default value (blank for none)",
|
|
227
|
+
placeholder: type === "integer" ? "e.g. 0" : "e.g. pending",
|
|
228
|
+
});
|
|
229
|
+
if (p.isCancel(v)) return null;
|
|
230
|
+
if (!v) return "";
|
|
231
|
+
if (type === "integer") {
|
|
232
|
+
const n = Number(v);
|
|
233
|
+
if (Number.isNaN(n)) {
|
|
234
|
+
p.log.warn(`"${v}" isn't a number — skipping the default.`);
|
|
235
|
+
return "";
|
|
236
|
+
}
|
|
237
|
+
return `.default(${n})`;
|
|
238
|
+
}
|
|
239
|
+
return `.default(${JSON.stringify(v)})`;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Full column-collection loop for one table — stops on a blank column name, propagates a cancel as `null`. */
|
|
243
|
+
async function promptForColumns(existingTables: ParsedTable[]): Promise<ColumnSpec[] | null> {
|
|
244
|
+
const columns: ColumnSpec[] = [];
|
|
245
|
+
p.log.step("Add columns one at a time. Leave the name blank to finish.");
|
|
246
|
+
// eslint-disable-next-line no-constant-condition
|
|
247
|
+
while (true) {
|
|
248
|
+
const nameProbe = await p.text({
|
|
249
|
+
message: columns.length === 0 ? "Column name" : "Another column? (blank to finish)",
|
|
250
|
+
placeholder: columns.length === 0 ? "e.g. email" : "",
|
|
251
|
+
});
|
|
252
|
+
if (p.isCancel(nameProbe)) return null;
|
|
253
|
+
if (!nameProbe) break;
|
|
254
|
+
|
|
255
|
+
const key = columnIdentifier(nameProbe);
|
|
256
|
+
if (columns.some((c) => columnIdentifier(c.name) === key)) {
|
|
257
|
+
p.log.error(`"${key}" is already a column on this table.`);
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
let references: string | undefined;
|
|
262
|
+
if (existingTables.length > 0) {
|
|
263
|
+
const refChoice = await p.select({
|
|
264
|
+
message: `Does "${nameProbe}" reference another table's id?`,
|
|
265
|
+
options: [
|
|
266
|
+
{ value: "__none__", label: "No" },
|
|
267
|
+
...existingTables.map((t) => ({ value: t.identifier, label: t.identifier })),
|
|
268
|
+
],
|
|
269
|
+
initialValue: "__none__",
|
|
270
|
+
});
|
|
271
|
+
if (p.isCancel(refChoice)) return null;
|
|
272
|
+
if (refChoice !== "__none__") references = refChoice;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
let type: ColumnType = "integer";
|
|
276
|
+
let defaultExpr = "";
|
|
277
|
+
if (!references) {
|
|
278
|
+
const typeChoice = await p.select({
|
|
279
|
+
message: "Column type",
|
|
280
|
+
options: COLUMN_TYPES.map((t) => ({ value: t, label: t })),
|
|
281
|
+
});
|
|
282
|
+
if (p.isCancel(typeChoice)) return null;
|
|
283
|
+
type = typeChoice;
|
|
284
|
+
const expr = await promptDefaultExpr(type);
|
|
285
|
+
if (expr === null) return null;
|
|
286
|
+
defaultExpr = expr;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const notNull = await p.confirm({ message: "Required (NOT NULL)?", initialValue: true });
|
|
290
|
+
if (p.isCancel(notNull)) return null;
|
|
291
|
+
const unique = await p.confirm({ message: "Unique?", initialValue: false });
|
|
292
|
+
if (p.isCancel(unique)) return null;
|
|
293
|
+
|
|
294
|
+
columns.push({ name: nameProbe, type, notNull, unique, defaultExpr, references });
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
return columns;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Full table-collection flow: name (unless `forcedName` came from a CLI arg), the id-column question, then promptForColumns(). Returns null on cancel. */
|
|
301
|
+
async function collectTableSpec(existingTables: ParsedTable[], forcedName?: string): Promise<TableSpec | null> {
|
|
302
|
+
let name = forcedName;
|
|
303
|
+
if (name) {
|
|
304
|
+
const id = tableIdentifier(name);
|
|
305
|
+
if (existingTables.some((t) => t.identifier === id)) {
|
|
306
|
+
p.log.error(`"${id}" already exists.`);
|
|
307
|
+
return null;
|
|
308
|
+
}
|
|
309
|
+
} else {
|
|
310
|
+
const answer = await p.text({
|
|
311
|
+
message: "New table name",
|
|
312
|
+
placeholder: "e.g. users",
|
|
313
|
+
validate: (value) => {
|
|
314
|
+
if (!value) return "Required.";
|
|
315
|
+
if (existingTables.some((t) => t.identifier === tableIdentifier(value))) {
|
|
316
|
+
return `"${tableIdentifier(value)}" already exists.`;
|
|
317
|
+
}
|
|
318
|
+
return undefined;
|
|
319
|
+
},
|
|
320
|
+
});
|
|
321
|
+
if (p.isCancel(answer)) return null;
|
|
322
|
+
name = answer;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const includeId = await p.confirm({
|
|
326
|
+
message: "Add an auto-increment id primary key column?",
|
|
327
|
+
initialValue: true,
|
|
328
|
+
});
|
|
329
|
+
if (p.isCancel(includeId)) return null;
|
|
330
|
+
|
|
331
|
+
const columns = await promptForColumns(existingTables);
|
|
332
|
+
if (columns === null) return null;
|
|
333
|
+
|
|
334
|
+
return { name, includeId, columns };
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
async function runAddTable(args: string[]): Promise<void> {
|
|
338
|
+
p.intro("create-backon add-table");
|
|
339
|
+
if (!(await ensureSchemaSupport())) return;
|
|
340
|
+
|
|
341
|
+
const [forcedName] = args;
|
|
342
|
+
let existingTables = await readSchemaTables();
|
|
343
|
+
let first = true;
|
|
344
|
+
|
|
345
|
+
// eslint-disable-next-line no-constant-condition
|
|
346
|
+
while (true) {
|
|
347
|
+
const spec = await collectTableSpec(existingTables, first ? forcedName : undefined);
|
|
348
|
+
first = false;
|
|
349
|
+
if (!spec) {
|
|
350
|
+
p.cancel("Cancelled.");
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
try {
|
|
355
|
+
const { filePath, identifier } = await addTable(spec);
|
|
356
|
+
p.log.success(`Added table "${identifier}" to ${filePath}. Run \`bun run db:generate\` to create a migration for it.`);
|
|
357
|
+
existingTables = await readSchemaTables();
|
|
358
|
+
} catch (err) {
|
|
359
|
+
p.log.error(err instanceof Error ? err.message : String(err));
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
const again = await p.confirm({ message: "Add another table?", initialValue: false });
|
|
363
|
+
if (p.isCancel(again) || !again) break;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
p.outro("Done.");
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
async function runRemoveTable(args: string[]): Promise<void> {
|
|
370
|
+
p.intro("create-backon remove-table");
|
|
371
|
+
if (!(await ensureSchemaSupport())) return;
|
|
372
|
+
|
|
373
|
+
const existingTables = await readSchemaTables();
|
|
374
|
+
if (existingTables.length === 0) {
|
|
375
|
+
p.log.info("No tables yet.");
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const [forcedName] = args;
|
|
380
|
+
let identifier: string;
|
|
381
|
+
if (forcedName) {
|
|
382
|
+
identifier = tableIdentifier(forcedName);
|
|
383
|
+
if (!existingTables.some((t) => t.identifier === identifier)) {
|
|
384
|
+
p.log.error(`No table "${identifier}" found.`);
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
} else {
|
|
388
|
+
const choice = await p.select({
|
|
389
|
+
message: "Remove which table?",
|
|
390
|
+
options: existingTables.map((t) => ({ value: t.identifier, label: `${t.identifier} (${t.columns.length} columns)` })),
|
|
391
|
+
});
|
|
392
|
+
if (p.isCancel(choice)) {
|
|
393
|
+
p.cancel("Cancelled.");
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
identifier = choice;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
const confirmed = await p.confirm({
|
|
400
|
+
message: `Remove table "${identifier}" from schema.ts? This only edits the file — nothing is dropped from the actual database until you run a migration.`,
|
|
401
|
+
initialValue: false,
|
|
402
|
+
});
|
|
403
|
+
if (p.isCancel(confirmed) || !confirmed) {
|
|
404
|
+
p.cancel("Cancelled.");
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
try {
|
|
409
|
+
const { filePath } = await removeTable(identifier);
|
|
410
|
+
p.log.success(`Removed "${identifier}" from ${filePath}. Run \`bun run db:generate\` to create a migration for this change.`);
|
|
411
|
+
} catch (err) {
|
|
412
|
+
p.log.error(err instanceof Error ? err.message : String(err));
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
p.outro("Done.");
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** server-config's single-shot version of runAddTable() — no internal "add another?" loop, since runServerConfig()'s own while loop already re-shows state and re-prompts after every action. */
|
|
419
|
+
async function serverConfigAddTable(existingTables: ParsedTable[]): Promise<void> {
|
|
420
|
+
const spec = await collectTableSpec(existingTables);
|
|
421
|
+
if (!spec) {
|
|
422
|
+
p.cancel("Cancelled.");
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
const { filePath, identifier } = await addTable(spec);
|
|
426
|
+
p.log.success(`Added table "${identifier}" to ${filePath}. Run \`bun run db:generate\` next.`);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
async function serverConfigRemoveTable(existingTables: ParsedTable[]): Promise<void> {
|
|
430
|
+
if (existingTables.length === 0) {
|
|
431
|
+
p.log.info("No tables yet.");
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
const choice = await p.select({
|
|
435
|
+
message: "Remove which table?",
|
|
436
|
+
options: existingTables.map((t) => ({ value: t.identifier, label: `${t.identifier} (${t.columns.length} columns)` })),
|
|
437
|
+
});
|
|
438
|
+
if (p.isCancel(choice)) {
|
|
439
|
+
p.cancel("Cancelled.");
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
const confirmed = await p.confirm({
|
|
443
|
+
message: `Remove table "${choice}" from schema.ts? Nothing is dropped from the actual database until you run a migration.`,
|
|
444
|
+
initialValue: false,
|
|
445
|
+
});
|
|
446
|
+
if (p.isCancel(confirmed) || !confirmed) {
|
|
447
|
+
p.cancel("Cancelled.");
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
const { filePath } = await removeTable(choice);
|
|
451
|
+
p.log.success(`Removed "${choice}" from ${filePath}. Run \`bun run db:generate\` next.`);
|
|
452
|
+
}
|
|
453
|
+
|
|
165
454
|
function suggestMethodName(verb: HttpVerb, path: string): string {
|
|
166
455
|
const params = paramNamesFromPath(path);
|
|
167
456
|
if (verb === "get" && params.length === 0) return "list";
|
|
@@ -569,6 +858,12 @@ async function runServerConfig(): Promise<void> {
|
|
|
569
858
|
const summaries = await listEndpointsWithMethods();
|
|
570
859
|
p.note(formatEndpointsDashboard(summaries), `Endpoints in ${root}`);
|
|
571
860
|
|
|
861
|
+
const dbStatus = await detectDbStatus();
|
|
862
|
+
const schemaCapable = dbStatus.driver === "neon" || dbStatus.driver === "postgres";
|
|
863
|
+
if (schemaCapable) {
|
|
864
|
+
p.note(formatTablesDashboard(await readSchemaTables()), "Database tables");
|
|
865
|
+
}
|
|
866
|
+
|
|
572
867
|
const action = await p.select({
|
|
573
868
|
message: "What do you want to do?",
|
|
574
869
|
options: [
|
|
@@ -577,6 +872,8 @@ async function runServerConfig(): Promise<void> {
|
|
|
577
872
|
{ value: "add-method", label: "Add a method" },
|
|
578
873
|
{ value: "remove-method", label: "Remove a method" },
|
|
579
874
|
{ value: "modify-method", label: "Modify a method" },
|
|
875
|
+
{ value: "add-table", label: "Add a database table" },
|
|
876
|
+
{ value: "remove-table", label: "Remove a database table" },
|
|
580
877
|
{ value: "exit", label: "Exit" },
|
|
581
878
|
],
|
|
582
879
|
});
|
|
@@ -599,6 +896,12 @@ async function runServerConfig(): Promise<void> {
|
|
|
599
896
|
case "modify-method":
|
|
600
897
|
await serverConfigModifyMethod(summaries);
|
|
601
898
|
break;
|
|
899
|
+
case "add-table":
|
|
900
|
+
if (await ensureSchemaSupport()) await serverConfigAddTable(await readSchemaTables());
|
|
901
|
+
break;
|
|
902
|
+
case "remove-table":
|
|
903
|
+
if (await ensureSchemaSupport()) await serverConfigRemoveTable(await readSchemaTables());
|
|
904
|
+
break;
|
|
602
905
|
}
|
|
603
906
|
} catch (err) {
|
|
604
907
|
p.log.error(err instanceof Error ? err.message : String(err));
|
|
@@ -649,6 +952,14 @@ async function main() {
|
|
|
649
952
|
await runServerConfig();
|
|
650
953
|
return;
|
|
651
954
|
}
|
|
955
|
+
if (subcommand && ADD_TABLE_SUBCOMMANDS.has(subcommand)) {
|
|
956
|
+
await runAddTable(rest);
|
|
957
|
+
return;
|
|
958
|
+
}
|
|
959
|
+
if (subcommand && REMOVE_TABLE_SUBCOMMANDS.has(subcommand)) {
|
|
960
|
+
await runRemoveTable(rest);
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
652
963
|
|
|
653
964
|
await runScaffold();
|
|
654
965
|
}
|
package/src/generate.ts
CHANGED
|
@@ -16,7 +16,8 @@ import {
|
|
|
16
16
|
renderVercelJson,
|
|
17
17
|
} from "./templates/base";
|
|
18
18
|
import { renderBlankController, renderBlankRoutes, renderBlankServices } from "./templates/route";
|
|
19
|
-
import { renderDbFile } from "./templates/db";
|
|
19
|
+
import { dbHasSchemaSupport, renderDbFile } from "./templates/db";
|
|
20
|
+
import { renderBlankSchema, renderDrizzleConfig } from "./templates/schema";
|
|
20
21
|
|
|
21
22
|
async function write(path: string, contents: string): Promise<void> {
|
|
22
23
|
await mkdir(dirname(path), { recursive: true });
|
|
@@ -101,6 +102,12 @@ export async function generateProject(answers: Answers, cwd: string = process.cw
|
|
|
101
102
|
],
|
|
102
103
|
[join(root, `src/app.${ext}`), renderAppTs(packageName, answers.framework, answers.deployTarget)],
|
|
103
104
|
[join(root, `src/config/db.${ext}`), renderDbFile(answers.db)],
|
|
105
|
+
...(dbHasSchemaSupport(answers.db)
|
|
106
|
+
? ([
|
|
107
|
+
[join(root, `src/config/schema.${ext}`), renderBlankSchema()],
|
|
108
|
+
[join(root, "drizzle.config.ts"), renderDrizzleConfig(ext)],
|
|
109
|
+
] as Array<[string, string]>)
|
|
110
|
+
: []),
|
|
104
111
|
[
|
|
105
112
|
join(root, `src/middleware/example.middleware.${ext}`),
|
|
106
113
|
renderExampleMiddleware(answers.framework, answers.language),
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { Node, SyntaxKind, type SourceFile } from "ts-morph";
|
|
4
|
+
import { dim } from "./colors";
|
|
5
|
+
import { detectDbStatus } from "./db-status";
|
|
6
|
+
import { detectProject } from "./detect";
|
|
7
|
+
import { editSource, appendStatements } from "./ast-edit";
|
|
8
|
+
import { renderBlankSchema, renderTableBlock, requiredBuilders, tableIdentifier, type TableSpec } from "./templates/schema";
|
|
9
|
+
|
|
10
|
+
const PG_CORE_MODULE = "drizzle-orm/pg-core";
|
|
11
|
+
|
|
12
|
+
export interface ParsedColumn {
|
|
13
|
+
key: string;
|
|
14
|
+
/** Referenced table's JS identifier, when this column is a `.references(() => X.id)` foreign key. */
|
|
15
|
+
references?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface ParsedTable {
|
|
19
|
+
identifier: string;
|
|
20
|
+
sqlName: string;
|
|
21
|
+
columns: ParsedColumn[];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 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.
|
|
33
|
+
*/
|
|
34
|
+
export function parseSchemaTables(contents: string): ParsedTable[] {
|
|
35
|
+
const { sourceFile } = editSourceForReading(contents);
|
|
36
|
+
const tables: ParsedTable[] = [];
|
|
37
|
+
|
|
38
|
+
for (const stmt of sourceFile.getVariableStatements()) {
|
|
39
|
+
if (!stmt.isExported()) continue;
|
|
40
|
+
const decl = stmt.getDeclarations()[0];
|
|
41
|
+
if (!decl) continue;
|
|
42
|
+
const init = decl.getInitializer();
|
|
43
|
+
if (!init || !Node.isCallExpression(init)) continue;
|
|
44
|
+
const callee = init.getExpression();
|
|
45
|
+
if (!Node.isIdentifier(callee) || callee.getText() !== "pgTable") continue;
|
|
46
|
+
|
|
47
|
+
const [sqlNameArg, columnsArg] = init.getArguments();
|
|
48
|
+
const sqlName = sqlNameArg && Node.isStringLiteral(sqlNameArg) ? sqlNameArg.getLiteralValue() : "";
|
|
49
|
+
|
|
50
|
+
const columns: ParsedColumn[] = [];
|
|
51
|
+
if (columnsArg && Node.isObjectLiteralExpression(columnsArg)) {
|
|
52
|
+
for (const prop of columnsArg.getProperties()) {
|
|
53
|
+
if (!Node.isPropertyAssignment(prop)) continue;
|
|
54
|
+
columns.push({ key: prop.getName(), references: findReferencedTable(prop) });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
tables.push({ identifier: decl.getName(), sqlName, columns });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return tables;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function findReferencedTable(propAssignment: Node): string | undefined {
|
|
65
|
+
const init = Node.isPropertyAssignment(propAssignment) ? propAssignment.getInitializer() : undefined;
|
|
66
|
+
if (!init) return undefined;
|
|
67
|
+
for (const call of init.getDescendantsOfKind(SyntaxKind.CallExpression)) {
|
|
68
|
+
const expr = call.getExpression();
|
|
69
|
+
if (!Node.isPropertyAccessExpression(expr) || expr.getName() !== "references") continue;
|
|
70
|
+
const arrowArg = call.getArguments()[0];
|
|
71
|
+
if (!arrowArg || !Node.isArrowFunction(arrowArg)) continue;
|
|
72
|
+
const body = arrowArg.getBody();
|
|
73
|
+
if (Node.isPropertyAccessExpression(body) && Node.isIdentifier(body.getExpression())) {
|
|
74
|
+
return body.getExpression().getText();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
|
|
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
|
+
function editSourceForReading(contents: string): { sourceFile: SourceFile } {
|
|
83
|
+
let sourceFile!: SourceFile;
|
|
84
|
+
editSource("schema.ts", contents, (_project, sf) => {
|
|
85
|
+
sourceFile = sf;
|
|
86
|
+
});
|
|
87
|
+
return { sourceFile };
|
|
88
|
+
}
|
|
89
|
+
|
|
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. */
|
|
91
|
+
function ensurePgCoreImport(sourceFile: SourceFile, builders: Set<string>): void {
|
|
92
|
+
const wanted = [...builders].sort();
|
|
93
|
+
const existing = sourceFile.getImportDeclaration((d) => d.getModuleSpecifierValue() === PG_CORE_MODULE);
|
|
94
|
+
if (!existing) {
|
|
95
|
+
sourceFile.addImportDeclaration({ moduleSpecifier: PG_CORE_MODULE, namedImports: wanted });
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const already = new Set(existing.getNamedImports().map((ni) => ni.getName()));
|
|
99
|
+
const missing = wanted.filter((name) => !already.has(name));
|
|
100
|
+
if (missing.length > 0) existing.addNamedImports(missing);
|
|
101
|
+
}
|
|
102
|
+
|
|
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. */
|
|
104
|
+
function prunePgCoreImport(sourceFile: SourceFile): void {
|
|
105
|
+
const decl = sourceFile.getImportDeclaration((d) => d.getModuleSpecifierValue() === PG_CORE_MODULE);
|
|
106
|
+
if (!decl) return;
|
|
107
|
+
|
|
108
|
+
const used = new Set<string>();
|
|
109
|
+
for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {
|
|
110
|
+
const expr = call.getExpression();
|
|
111
|
+
if (Node.isIdentifier(expr)) used.add(expr.getText());
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
for (const named of decl.getNamedImports()) {
|
|
115
|
+
if (!used.has(named.getName())) named.remove();
|
|
116
|
+
}
|
|
117
|
+
if (decl.getNamedImports().length === 0) decl.remove();
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function removeTableStatement(sourceFile: SourceFile, identifier: string): boolean {
|
|
121
|
+
for (const stmt of sourceFile.getVariableStatements()) {
|
|
122
|
+
const decls = stmt.getDeclarations();
|
|
123
|
+
if (decls.length === 1 && decls[0]!.getName() === identifier) {
|
|
124
|
+
stmt.remove();
|
|
125
|
+
return true;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function requireNeonOrPostgres(cwd: string): Promise<void> {
|
|
132
|
+
const status = await detectDbStatus(cwd);
|
|
133
|
+
if (status.driver === "neon" || status.driver === "postgres") return;
|
|
134
|
+
throw new Error(
|
|
135
|
+
`Schema management needs a "neon" or "postgres" db driver (src/config/db reports "${status.driver}") — ` +
|
|
136
|
+
`SQLite and "none" use a different schema dialect (or none at all) and aren't supported by add-table/remove-table yet.`
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function readSchemaFile(root: string, ext: "ts" | "js"): Promise<{ path: string; contents: string }> {
|
|
141
|
+
const path = join(root, "src/config", `schema.${ext}`);
|
|
142
|
+
try {
|
|
143
|
+
return { path, contents: await readFile(path, "utf-8") };
|
|
144
|
+
} catch (err) {
|
|
145
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") {
|
|
146
|
+
throw new Error(
|
|
147
|
+
`${path} doesn't exist. This project's db.ts predates schema scaffolding — add a src/config/schema.${ext} ` +
|
|
148
|
+
`by hand (see the README's Database section) before using add-table.`
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
throw err;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export interface AddTableResult {
|
|
156
|
+
root: string;
|
|
157
|
+
identifier: string;
|
|
158
|
+
filePath: string;
|
|
159
|
+
}
|
|
160
|
+
|
|
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
|
+
*/
|
|
169
|
+
export async function addTable(spec: TableSpec, cwd: string = process.cwd()): Promise<AddTableResult> {
|
|
170
|
+
await requireNeonOrPostgres(cwd);
|
|
171
|
+
const { root, ext } = await detectProject(cwd);
|
|
172
|
+
const { path, contents } = await readSchemaFile(root, ext);
|
|
173
|
+
|
|
174
|
+
const identifier = tableIdentifier(spec.name);
|
|
175
|
+
const existingTables = parseSchemaTables(contents);
|
|
176
|
+
if (existingTables.some((t) => t.identifier === identifier)) {
|
|
177
|
+
throw new Error(`"${identifier}" is already a table in ${path}.`);
|
|
178
|
+
}
|
|
179
|
+
for (const col of spec.columns) {
|
|
180
|
+
if (col.references && !existingTables.some((t) => t.identifier === col.references)) {
|
|
181
|
+
throw new Error(`Column "${col.name}" references unknown table "${col.references}".`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const withoutPlaceholder = contents.includes(renderBlankSchema()) ? contents.replace(renderBlankSchema(), "") : contents;
|
|
186
|
+
|
|
187
|
+
const updated = editSource(path, withoutPlaceholder, (_project, sourceFile) => {
|
|
188
|
+
ensurePgCoreImport(sourceFile, requiredBuilders(spec));
|
|
189
|
+
appendStatements(sourceFile, renderTableBlock(spec));
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
await writeFile(path, updated);
|
|
193
|
+
return { root, identifier, filePath: path };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export interface RemoveTableResult {
|
|
197
|
+
root: string;
|
|
198
|
+
identifier: string;
|
|
199
|
+
filePath: string;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** server-config/project's "Database tables" note — same spirit as route-methods.ts's formatEndpointsDashboard(). */
|
|
203
|
+
export function formatTablesDashboard(tables: ParsedTable[]): string {
|
|
204
|
+
if (tables.length === 0) return dim("No tables yet.");
|
|
205
|
+
return tables
|
|
206
|
+
.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")}`;
|
|
210
|
+
})
|
|
211
|
+
.join("\n\n");
|
|
212
|
+
}
|
|
213
|
+
|
|
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
|
+
*/
|
|
222
|
+
export async function removeTable(identifier: string, cwd: string = process.cwd()): Promise<RemoveTableResult> {
|
|
223
|
+
await requireNeonOrPostgres(cwd);
|
|
224
|
+
const { root, ext } = await detectProject(cwd);
|
|
225
|
+
const { path, contents } = await readSchemaFile(root, ext);
|
|
226
|
+
|
|
227
|
+
const tables = parseSchemaTables(contents);
|
|
228
|
+
const target = tables.find((t) => t.identifier === identifier);
|
|
229
|
+
if (!target) {
|
|
230
|
+
throw new Error(`No table "${identifier}" found in ${path}.`);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const referencedBy = tables.filter((t) => t.identifier !== identifier && t.columns.some((c) => c.references === identifier));
|
|
234
|
+
if (referencedBy.length > 0) {
|
|
235
|
+
throw new Error(
|
|
236
|
+
`Can't remove "${identifier}" — still referenced by: ${referencedBy.map((t) => t.identifier).join(", ")}. ` +
|
|
237
|
+
`Remove those columns/tables first.`
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
if (tables.length === 1) {
|
|
242
|
+
await writeFile(path, renderBlankSchema());
|
|
243
|
+
return { root, identifier, filePath: path };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const updated = editSource(path, contents, (_project, sourceFile) => {
|
|
247
|
+
removeTableStatement(sourceFile, identifier);
|
|
248
|
+
prunePgCoreImport(sourceFile);
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
await writeFile(path, updated);
|
|
252
|
+
return { root, identifier, filePath: path };
|
|
253
|
+
}
|