@apso/cli 0.51.0 → 0.53.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.
Files changed (98) hide show
  1. package/dist/commands/generate.js +3 -2
  2. package/dist/commands/import/supabase.js +31 -6
  3. package/dist/commands/init.d.ts +9 -0
  4. package/dist/commands/init.js +31 -1
  5. package/dist/commands/mcp/serve.js +23 -2
  6. package/dist/lib/apsorc-parser.d.ts +13 -1
  7. package/dist/lib/apsorc-parser.js +47 -4
  8. package/dist/lib/ddl/catalog.js +5 -2
  9. package/dist/lib/ddl/change.js +13 -2
  10. package/dist/lib/ddl/index.d.ts +62 -3
  11. package/dist/lib/ddl/index.js +211 -40
  12. package/dist/lib/generators/go.js +17 -3
  13. package/dist/lib/generators/python.js +17 -3
  14. package/dist/lib/generators/typescript.d.ts +2 -1
  15. package/dist/lib/generators/typescript.js +87 -13
  16. package/dist/lib/import/copy-data.js +4 -0
  17. package/dist/lib/import/introspect.d.ts +40 -0
  18. package/dist/lib/import/introspect.js +137 -49
  19. package/dist/lib/import/pg-to-apsorc.d.ts +62 -0
  20. package/dist/lib/import/pg-to-apsorc.js +248 -37
  21. package/dist/lib/import/types.d.ts +48 -3
  22. package/dist/lib/migrate/sandbox.js +23 -6
  23. package/dist/lib/migrate/snapshot.d.ts +5 -0
  24. package/dist/lib/plan/index.d.ts +4 -1
  25. package/dist/lib/plan/index.js +9 -3
  26. package/dist/lib/templates/entities/entity-col-array.eta +2 -1
  27. package/dist/lib/templates/entities/entity-col-bigint.eta +2 -2
  28. package/dist/lib/templates/entities/entity-col-bigserial.eta +2 -2
  29. package/dist/lib/templates/entities/entity-col-boolean.eta +1 -1
  30. package/dist/lib/templates/entities/entity-col-bytea.eta +2 -2
  31. package/dist/lib/templates/entities/entity-col-char.eta +4 -3
  32. package/dist/lib/templates/entities/entity-col-date.eta +6 -2
  33. package/dist/lib/templates/entities/entity-col-datetime.eta +8 -1
  34. package/dist/lib/templates/entities/entity-col-decimal.eta +2 -2
  35. package/dist/lib/templates/entities/entity-col-double.eta +2 -2
  36. package/dist/lib/templates/entities/entity-col-float.eta +1 -1
  37. package/dist/lib/templates/entities/entity-col-geography.eta +1 -1
  38. package/dist/lib/templates/entities/entity-col-geometry.eta +1 -1
  39. package/dist/lib/templates/entities/entity-col-geometrycollection.eta +1 -1
  40. package/dist/lib/templates/entities/entity-col-inet.eta +2 -2
  41. package/dist/lib/templates/entities/entity-col-int4range.eta +1 -1
  42. package/dist/lib/templates/entities/entity-col-integer.eta +2 -2
  43. package/dist/lib/templates/entities/entity-col-interval.eta +2 -2
  44. package/dist/lib/templates/entities/entity-col-json-plain.eta +1 -1
  45. package/dist/lib/templates/entities/entity-col-json.eta +1 -1
  46. package/dist/lib/templates/entities/entity-col-jsonb.eta +1 -1
  47. package/dist/lib/templates/entities/entity-col-linestring.eta +1 -1
  48. package/dist/lib/templates/entities/entity-col-money.eta +2 -2
  49. package/dist/lib/templates/entities/entity-col-multilinestring.eta +1 -1
  50. package/dist/lib/templates/entities/entity-col-multipoint.eta +1 -1
  51. package/dist/lib/templates/entities/entity-col-multipolygon.eta +1 -1
  52. package/dist/lib/templates/entities/entity-col-numeric.eta +2 -2
  53. package/dist/lib/templates/entities/entity-col-point.eta +1 -1
  54. package/dist/lib/templates/entities/entity-col-polygon.eta +1 -1
  55. package/dist/lib/templates/entities/entity-col-real.eta +2 -2
  56. package/dist/lib/templates/entities/entity-col-serial.eta +2 -2
  57. package/dist/lib/templates/entities/entity-col-smallint.eta +2 -2
  58. package/dist/lib/templates/entities/entity-col-smallserial.eta +2 -2
  59. package/dist/lib/templates/entities/entity-col-string.eta +2 -2
  60. package/dist/lib/templates/entities/entity-col-text.eta +4 -3
  61. package/dist/lib/templates/entities/entity-col-time.eta +2 -2
  62. package/dist/lib/templates/entities/entity-col-timestamp.eta +8 -1
  63. package/dist/lib/templates/entities/entity-col-timestamptz.eta +8 -1
  64. package/dist/lib/templates/entities/entity-col-timetz.eta +2 -2
  65. package/dist/lib/templates/entities/entity-col-tsvector.eta +2 -2
  66. package/dist/lib/templates/entities/entity-col-uuid.eta +5 -2
  67. package/dist/lib/templates/entities/entity-col-varchar.eta +4 -3
  68. package/dist/lib/templates/entities/entity-col-xml.eta +2 -2
  69. package/dist/lib/templates/entities/entity.eta +30 -18
  70. package/dist/lib/templates/go/models/model.eta +3 -3
  71. package/dist/lib/templates/python/models/model.eta +1 -1
  72. package/dist/lib/templates/rest/controller-rest.eta +25 -7
  73. package/dist/lib/templates/rest/dto-rest.eta +2 -2
  74. package/dist/lib/templates/rest/index-module-rest.eta +10 -0
  75. package/dist/lib/templates/rest/schema-extras-module.eta +24 -0
  76. package/dist/lib/types/constraints.d.ts +13 -0
  77. package/dist/lib/types/entity.d.ts +67 -2
  78. package/dist/lib/types/entity.js +39 -1
  79. package/dist/lib/types/field.d.ts +20 -2
  80. package/dist/lib/types/generator.d.ts +16 -0
  81. package/dist/lib/types/index.d.ts +1 -1
  82. package/dist/lib/types/indices.d.ts +21 -0
  83. package/dist/lib/types/relationship.d.ts +33 -0
  84. package/dist/lib/types/relationship.js +13 -0
  85. package/dist/lib/utils/field.d.ts +22 -0
  86. package/dist/lib/utils/field.js +62 -3
  87. package/dist/lib/utils/relationships/index.d.ts +1 -1
  88. package/dist/lib/utils/relationships/index.js +2 -1
  89. package/dist/lib/utils/relationships/parse.d.ts +11 -0
  90. package/dist/lib/utils/relationships/parse.js +44 -1
  91. package/dist/lib/utils/template.d.ts +3 -3
  92. package/dist/lib/utils/template.js +4 -4
  93. package/dist/lib/verify/crud-plan.d.ts +2 -0
  94. package/dist/lib/verify/crud-plan.js +19 -5
  95. package/dist/lib/verify/index.js +32 -3
  96. package/npm-shrinkwrap.json +72 -87
  97. package/oclif.manifest.json +7 -1
  98. package/package.json +3 -2
@@ -20,7 +20,7 @@ class Generate extends base_command_1.default {
20
20
  const { flags } = await this.parse(Generate);
21
21
  const skipFormat = flags["skip-format"];
22
22
  const totalBuildStart = perf_hooks_1.performance.now();
23
- const { rootFolder, entities, relationshipMap, apiType, auth, emitEvents, http, coAuthor, language: configLanguage } = (0, lib_1.parseApsorc)();
23
+ const { rootFolder, entities, relationshipMap, apiType, auth, emitEvents, http, coAuthor, query, guards, language: configLanguage } = (0, lib_1.parseApsorc)();
24
24
  // Resolve language: flag > .apsorc > prompt
25
25
  let language;
26
26
  if (flags.language) {
@@ -180,6 +180,7 @@ class Generate extends base_command_1.default {
180
180
  apiType: lowerCaseApiType,
181
181
  relationshipMap,
182
182
  auth,
183
+ query,
183
184
  }));
184
185
  }
185
186
  // eslint-disable-next-line no-await-in-loop
@@ -209,7 +210,7 @@ class Generate extends base_command_1.default {
209
210
  await writeGenerated(file.path, file.content);
210
211
  }
211
212
  // Generate index module
212
- const indexFiles = await generator.generateIndexModule(entities, lowerCaseApiType, { emitEvents, http, auth });
213
+ const indexFiles = await generator.generateIndexModule(entities, lowerCaseApiType, { emitEvents, http, auth, guards });
213
214
  for (const file of indexFiles) {
214
215
  // eslint-disable-next-line no-await-in-loop
215
216
  await writeGenerated(file.path, file.content);
@@ -60,12 +60,22 @@ function formatReport(report) {
60
60
  review.push(` - Tables with no primary key: ${w.noPrimaryKey.join(", ")}`);
61
61
  if (w.compositeFks.length > 0)
62
62
  review.push(` - Composite foreign keys (kept as columns, no relationship): ${w.compositeFks.join(", ")}`);
63
- if (w.fkColumnNameUnmapped.length > 0)
64
- review.push(` - Foreign keys whose generated column may differ: ${w.fkColumnNameUnmapped.join(", ")}`);
65
63
  if (w.joinTablesDetected.length > 0)
66
64
  review.push(` - Join tables (could be modeled as ManyToMany): ${w.joinTablesDetected.join(", ")}`);
67
65
  if (w.arraysLossy.length > 0)
68
- review.push(` - Array columns reduced to text: ${w.arraysLossy.join(", ")}`);
66
+ review.push(` - Array columns with an unknown element type (imported as text[]): ${w.arraysLossy.join(", ")}`);
67
+ if (w.checksNotValid.length > 0)
68
+ review.push(` - Check constraints that are NOT VALID in the source (kept NOT VALID in migrations; TypeORM's schema sync creates them validated): ${w.checksNotValid.join(", ")}`);
69
+ if (w.timestampDefaultsAdded.length > 0)
70
+ review.push(` - created_at / updated_at with no default in the source (kept without one in migrations; TypeORM's schema sync adds DEFAULT now()): ${w.timestampDefaultsAdded.join(", ")}`);
71
+ if (w.foreignKeysNotCarried.length > 0)
72
+ review.push(` - Foreign keys left out because the column already has one (the database keeps them; apso migrate does not know about them): ${w.foreignKeysNotCarried.join(", ")}`);
73
+ if (w.relationshipsRenamed.length > 0)
74
+ review.push(` - Relationships renamed because a column has the natural name (columns unchanged): ${w.relationshipsRenamed.join(", ")}`);
75
+ if (w.indexesNotCarried.length > 0)
76
+ review.push(` - Indexes .apsorc cannot fully express yet:\n${w.indexesNotCarried
77
+ .map((i) => ` ${i}`)
78
+ .join("\n")}`);
69
79
  if (w.typesDefaulted.length > 0)
70
80
  review.push(` - Unknown types defaulted to text: ${w.typesDefaulted
71
81
  .map((t) => `${t.column} (${t.udt})`)
@@ -84,10 +94,20 @@ exports.formatReport = formatReport;
84
94
  */
85
95
  function writeApsorcFile(apsorc, outPath) {
86
96
  let backupPath;
97
+ // `apso generate` needs a language to run without prompting. Keep the
98
+ // project's own when the file exists; foreign key column names need
99
+ // TypeScript, so that is the default.
100
+ let language = "typescript";
87
101
  if (fs.existsSync(outPath)) {
88
102
  backupPath = (0, config_1.createBackup)(outPath);
103
+ try {
104
+ language = JSON.parse(fs.readFileSync(outPath).toString()).language || language;
105
+ }
106
+ catch {
107
+ // An unreadable file is replaced; the backup keeps it.
108
+ }
89
109
  }
90
- fs.writeFileSync(outPath, JSON.stringify(apsorc, null, 2), "utf-8");
110
+ fs.writeFileSync(outPath, JSON.stringify({ language, ...apsorc }, null, 2), "utf-8");
91
111
  return { backupPath };
92
112
  }
93
113
  exports.writeApsorcFile = writeApsorcFile;
@@ -154,8 +174,13 @@ class ImportSupabase extends base_command_1.default {
154
174
  this.log("");
155
175
  this.log("Next steps:");
156
176
  this.log(" - Review the .apsorc, especially any items flagged above");
157
- this.log(" - Run 'apso migrate' to validate the schema locally");
158
- this.log(" - Run 'apso generate' to scaffold code");
177
+ if (fs.existsSync(path.join(path.dirname(outPath), "package.json"))) {
178
+ this.log(" - Run 'apso migrate' to validate the schema locally");
179
+ this.log(" - Run 'apso generate' to scaffold code");
180
+ }
181
+ else {
182
+ this.log(` - No project here yet: run 'apso init --schema ${path.relative(process.cwd(), outPath) || outPath}' to create one from this schema`);
183
+ }
159
184
  }
160
185
  catch (error) {
161
186
  const message = error instanceof Error ? error.message : String(error);
@@ -6,6 +6,7 @@ export default class Init extends BaseCommand {
6
6
  name: import("@oclif/core/lib/interfaces").OptionFlag<string | undefined, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
7
7
  language: import("@oclif/core/lib/interfaces").OptionFlag<string | undefined, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
8
8
  "skip-platform": import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
9
+ schema: import("@oclif/core/lib/interfaces").OptionFlag<string | undefined, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
9
10
  };
10
11
  run(): Promise<void>;
11
12
  private runAuthenticated;
@@ -17,6 +18,14 @@ export default class Init extends BaseCommand {
17
18
  * fails the command. No `.apsorc` may exist yet at init time, so we only
18
19
  * respect the `APSO_NO_COAUTHOR=1` env opt-out (handled inside the installer).
19
20
  */
21
+ /**
22
+ * Replace the template's starter schema with the one --schema names.
23
+ *
24
+ * @param {string | undefined} schema - Path given to --schema, if any.
25
+ * @param {string} projectPath - The new project's folder.
26
+ * @returns {void}
27
+ */
28
+ private useSchema;
20
29
  private installCoAuthorHook;
21
30
  private postSetup;
22
31
  }
@@ -23,7 +23,19 @@ class Init extends base_command_1.default {
23
23
  }
24
24
  // Detect existing project
25
25
  const cwd = process.cwd();
26
- if (fs.existsSync(path.join(cwd, ".apsorc")) ||
26
+ // --schema is how an imported .apsorc becomes a project: that file may
27
+ // sit in this directory without making the directory a project.
28
+ if (flags.schema) {
29
+ try {
30
+ JSON.parse(fs.readFileSync(flags.schema).toString());
31
+ }
32
+ catch {
33
+ this.error(`--schema ${flags.schema} is not a readable .apsorc file.`);
34
+ }
35
+ }
36
+ const schemaHere = flags.schema !== undefined &&
37
+ path.resolve(flags.schema) === path.join(cwd, ".apsorc");
38
+ if ((fs.existsSync(path.join(cwd, ".apsorc")) && !schemaHere) ||
27
39
  fs.existsSync(path.join(cwd, ".apso", "link.json"))) {
28
40
  this.error("An Apso project already exists in this directory. Run commands from a different directory or remove .apsorc / .apso/link.json first.");
29
41
  }
@@ -211,6 +223,7 @@ class Init extends base_command_1.default {
211
223
  }));
212
224
  // Clone template
213
225
  (0, template_1.cloneTemplate)(projectPath, language, this.log.bind(this));
226
+ this.useSchema(flags.schema, projectPath);
214
227
  (0, template_1.initGitRepo)(projectPath);
215
228
  // Write project link
216
229
  const link = {
@@ -282,6 +295,7 @@ class Init extends base_command_1.default {
282
295
  }
283
296
  // Clone template and init git
284
297
  (0, template_1.cloneTemplate)(projectPath, language, this.log.bind(this));
298
+ this.useSchema(flags.schema, projectPath);
285
299
  (0, template_1.initGitRepo)(projectPath);
286
300
  await this.postSetup(projectPath, language);
287
301
  this.log(`\nProject created at ${projectPath}`);
@@ -293,6 +307,19 @@ class Init extends base_command_1.default {
293
307
  * fails the command. No `.apsorc` may exist yet at init time, so we only
294
308
  * respect the `APSO_NO_COAUTHOR=1` env opt-out (handled inside the installer).
295
309
  */
310
+ /**
311
+ * Replace the template's starter schema with the one --schema names.
312
+ *
313
+ * @param {string | undefined} schema - Path given to --schema, if any.
314
+ * @param {string} projectPath - The new project's folder.
315
+ * @returns {void}
316
+ */
317
+ useSchema(schema, projectPath) {
318
+ if (!schema)
319
+ return;
320
+ fs.copyFileSync(schema, path.join(projectPath, ".apsorc"));
321
+ this.log(`Using ${schema} as the project's .apsorc`);
322
+ }
296
323
  installCoAuthorHook(projectPath) {
297
324
  try {
298
325
  const result = (0, git_hooks_1.installCoAuthorHook)(projectPath);
@@ -358,5 +385,8 @@ Init.flags = {
358
385
  description: "Skip platform linking (offline mode)",
359
386
  default: false,
360
387
  }),
388
+ schema: core_1.Flags.string({
389
+ description: "Use this .apsorc as the new project's schema, for example the one 'apso import' wrote",
390
+ }),
361
391
  };
362
392
  exports.default = Init;
@@ -280,7 +280,7 @@ class McpServe extends base_command_1.default {
280
280
  isError: true,
281
281
  };
282
282
  }
283
- const { rootFolder, entities, relationshipMap, apiType, auth, language: configLanguage, } = (0, apsorc_parser_1.parseApsorc)();
283
+ const { rootFolder, entities, relationshipMap, apiType, auth, query, guards, language: configLanguage, } = (0, apsorc_parser_1.parseApsorc)();
284
284
  // Resolve language
285
285
  let lang;
286
286
  if (language) {
@@ -371,6 +371,7 @@ class McpServe extends base_command_1.default {
371
371
  apiType: lowerCaseApiType,
372
372
  relationshipMap,
373
373
  auth,
374
+ query,
374
375
  }),
375
376
  generator.generateModule({
376
377
  entity,
@@ -401,7 +402,7 @@ class McpServe extends base_command_1.default {
401
402
  if (guardFiles.length > 0)
402
403
  (0, crud_deps_1.writeAccessManifest)(process.cwd(), this.config.version);
403
404
  // Generate index module
404
- const indexFiles = await generator.generateIndexModule(entities, lowerCaseApiType, { auth });
405
+ const indexFiles = await generator.generateIndexModule(entities, lowerCaseApiType, { auth, guards });
405
406
  for (const file of indexFiles) {
406
407
  const fullPath = path.join(autogenPath, file.path);
407
408
  // eslint-disable-next-line no-await-in-loop
@@ -1013,4 +1014,24 @@ is tracked separately.
1013
1014
  "index": true
1014
1015
  }
1015
1016
  \`\`\`
1017
+
1018
+ ## Mirroring an existing database
1019
+ \`apso import\` writes these so the generated service builds the database it was imported from. A new schema rarely needs them.
1020
+
1021
+ | Setting | On | Meaning |
1022
+ |---------|----|---------|
1023
+ | joinColumnName | relationship | The foreign key column's own name, e.g. \`patient_id\`. The property stays \`patientId\`. TypeScript only |
1024
+ | foreignKeyName | relationship | The foreign key constraint's name. TypeScript only |
1025
+ | onDelete | relationship | CASCADE, SET NULL, RESTRICT or NO ACTION. \`cascadeDelete: true\` is CASCADE |
1026
+ | primary | relationship | The foreign key column is the entity's primary key. No \`id\` is generated. TypeScript only |
1027
+ | primaryKeyName | entity | The primary key constraint's name. TypeScript only |
1028
+ | timestampType | entity | \`timestamp\` (default) or \`timestamptz\` for created_at and updated_at: one value, or \`{ "created_at": ..., "updated_at": ... }\` |
1029
+ | timestampNullable | entity | Whether created_at and updated_at accept NULL: one boolean, or one per column |
1030
+ | timestampDefault | entity | \`false\` when created_at or updated_at has no \`DEFAULT now()\`: one boolean, or one per column. Migrations honor it |
1031
+ | validate | check | \`false\` keeps a check constraint NOT VALID in migrations |
1032
+ | primary | field | The field is the primary key, or part of it |
1033
+ | elementType | field | Element type of an \`array\` field, e.g. \`uuid\` |
1034
+ | generated | field | The SQL expression of a stored generated column, e.g. \`(quantity * price)\`. Postgres computes it; create and update requests do not accept the field. TypeScript only |
1035
+
1036
+ In \`indexes\` and \`uniques\`, a foreign key may be named by its relationship (\`patient\`), its id property (\`patientId\`) or its column (\`patient_id\`).
1016
1037
  `;
@@ -1,7 +1,7 @@
1
1
  import { Entity } from "./types/entity";
2
2
  import { ApsorcRelationship, Relationship, RelationshipMap } from "./types/relationship";
3
3
  import { AuthConfig } from "./types/auth";
4
- import { TargetLanguage } from "./types/generator";
4
+ import { QueryConfig, TargetLanguage } from "./types/generator";
5
5
  export declare enum ApiType {
6
6
  Graphql = "graphql",
7
7
  Rest = "rest"
@@ -31,6 +31,14 @@ export type ApsorcType = {
31
31
  * trailer. Defaults to enabled.
32
32
  */
33
33
  coAuthor?: boolean;
34
+ /** TypeScript list route settings; see QueryConfig. */
35
+ query?: QueryConfig;
36
+ /**
37
+ * TypeScript only. False leaves the generated GuardsModule out of the
38
+ * autogen module list, for an app that registers its own global guards.
39
+ * Not allowed with `auth`, whose checks run in those guards.
40
+ */
41
+ guards?: boolean;
34
42
  };
35
43
  type ParsedApsorcData = {
36
44
  entities: Entity[];
@@ -49,6 +57,8 @@ export type ParsedApsorc = {
49
57
  http?: boolean;
50
58
  /** Opt-out for the Apso commit co-author hook (defaults to enabled). */
51
59
  coAuthor?: boolean;
60
+ query?: QueryConfig;
61
+ guards?: boolean;
52
62
  };
53
63
  export declare const parseApsorcV1: (apsorc: ApsorcType) => ParsedApsorcData;
54
64
  /**
@@ -94,6 +104,8 @@ export declare const dedupeIndexes: (entity: Entity) => Entity;
94
104
  */
95
105
  export declare const dedupeOneToOneUniques: (entity: Entity, relationships?: Relationship[]) => Entity;
96
106
  export declare const parseApsorcV2: (apsorc: ApsorcType) => ParsedApsorcData;
107
+ /** Checks the .apsorc `query` block; undefined when it is left out. */
108
+ export declare function parseQuery(raw: unknown): QueryConfig | undefined;
97
109
  export declare const parseApsorc: () => ParsedApsorc;
98
110
  /**
99
111
  * Finds the .apsorc configuration file path.
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.findConfigPath = exports.readApsorcFile = exports.parseApsorc = exports.parseApsorcV2 = exports.dedupeOneToOneUniques = exports.dedupeIndexes = exports.assertCodegenSafeNames = exports.ApsorcNamingError = exports.parseApsorcV1 = exports.ApiType = void 0;
3
+ exports.findConfigPath = exports.readApsorcFile = exports.parseApsorc = exports.parseQuery = exports.parseApsorcV2 = exports.dedupeOneToOneUniques = exports.dedupeIndexes = exports.assertCodegenSafeNames = exports.ApsorcNamingError = exports.parseApsorcV1 = exports.ApiType = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const fs = tslib_1.__importStar(require("fs"));
6
6
  const path = tslib_1.__importStar(require("path"));
@@ -57,6 +57,9 @@ const assertCodegenSafeNames = (apsorc) => {
57
57
  };
58
58
  exports.assertCodegenSafeNames = assertCodegenSafeNames;
59
59
  const columns = (fields) => fields.join(",");
60
+ // An index with its own name or a WHERE condition is a different index from
61
+ // a plain one on the same columns, so only plain ones are merged.
62
+ const plain = (index) => !index.name && !index.where;
60
63
  /**
61
64
  * Drop indexes the database cannot create alongside another. TypeORM names an
62
65
  * index from its table and columns only, so a plain and a unique index on the
@@ -72,13 +75,14 @@ const dedupeIndexes = (entity) => {
72
75
  if (!((_a = entity.indexes) === null || _a === void 0 ? void 0 : _a.length))
73
76
  return entity;
74
77
  const uniqueColumns = new Set(entity.indexes
75
- .filter((index) => index.unique)
78
+ .filter((index) => index.unique && plain(index))
76
79
  .map((index) => columns(index.fields)));
77
80
  const seen = new Set();
78
81
  const indexes = entity.indexes.filter((index) => {
79
- const key = `${columns(index.fields)}|${index.unique ? "unique" : ""}`;
82
+ var _a, _b;
83
+ const key = `${columns(index.fields)}|${index.unique ? "unique" : ""}|${(_a = index.where) !== null && _a !== void 0 ? _a : ""}|${(_b = index.name) !== null && _b !== void 0 ? _b : ""}`;
80
84
  if (seen.has(key) ||
81
- (!index.unique && uniqueColumns.has(columns(index.fields))))
85
+ (plain(index) && !index.unique && uniqueColumns.has(columns(index.fields))))
82
86
  return false;
83
87
  seen.add(key);
84
88
  return true;
@@ -136,6 +140,12 @@ const parseRc = () => {
136
140
  const emitEvents = apsoConfig.emitEvents;
137
141
  const http = apsoConfig.http;
138
142
  const coAuthor = apsoConfig.coAuthor;
143
+ const query = parseQuery(apsoConfig.query);
144
+ const guards = apsoConfig.guards;
145
+ if (guards !== undefined && typeof guards !== "boolean")
146
+ throw new Error(`.apsorc "guards" must be true or false`);
147
+ if (guards === false && auth)
148
+ throw new Error(`.apsorc "guards": false leaves out the guards that enforce "auth"; remove one of them`);
139
149
  return {
140
150
  rootFolder,
141
151
  apiType,
@@ -147,8 +157,37 @@ const parseRc = () => {
147
157
  emitEvents,
148
158
  http,
149
159
  coAuthor,
160
+ query,
161
+ guards,
150
162
  };
151
163
  };
164
+ const DIALECTS = new Set(["postgrest", "nestjsx"]);
165
+ /** Checks the .apsorc `query` block; undefined when it is left out. */
166
+ function parseQuery(raw) {
167
+ if (raw === undefined)
168
+ return undefined;
169
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw))
170
+ throw new Error(`.apsorc "query" must be an object`);
171
+ const { dialects, limit, alwaysPaginate, ...rest } = raw;
172
+ const unknown = Object.keys(rest);
173
+ if (unknown.length > 0)
174
+ throw new Error(`.apsorc "query" has unknown setting(s) ${unknown.join(", ")}; use dialects, limit or alwaysPaginate`);
175
+ if (dialects !== undefined &&
176
+ (!Array.isArray(dialects) ||
177
+ dialects.length === 0 ||
178
+ dialects.some((d) => !DIALECTS.has(d))))
179
+ throw new Error(`.apsorc "query.dialects" must list one or both of "postgrest" and "nestjsx"`);
180
+ if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > 100))
181
+ throw new Error(`.apsorc "query.limit" must be a whole number from 1 to 100`);
182
+ if (alwaysPaginate !== undefined && typeof alwaysPaginate !== "boolean")
183
+ throw new Error(`.apsorc "query.alwaysPaginate" must be true or false`);
184
+ return {
185
+ dialects: dialects,
186
+ limit: limit,
187
+ alwaysPaginate: alwaysPaginate,
188
+ };
189
+ }
190
+ exports.parseQuery = parseQuery;
152
191
  const parseApsorc = () => {
153
192
  const debug = process.env.DEBUG;
154
193
  const start = perf_hooks_1.performance.now();
@@ -169,6 +208,8 @@ const parseApsorc = () => {
169
208
  emitEvents: apsoConfig.emitEvents,
170
209
  http: apsoConfig.http,
171
210
  coAuthor: apsoConfig.coAuthor,
211
+ query: apsoConfig.query,
212
+ guards: apsoConfig.guards,
172
213
  ...(0, exports.parseApsorcV1)(apsoConfig),
173
214
  };
174
215
  if (debug) {
@@ -188,6 +229,8 @@ const parseApsorc = () => {
188
229
  emitEvents: apsoConfig.emitEvents,
189
230
  http: apsoConfig.http,
190
231
  coAuthor: apsoConfig.coAuthor,
232
+ query: apsoConfig.query,
233
+ guards: apsoConfig.guards,
191
234
  ...(() => {
192
235
  const relStart = perf_hooks_1.performance.now();
193
236
  const parsed = (0, exports.parseApsorcV2)(apsoConfig);
@@ -10,10 +10,13 @@ exports.catalogDiff = exports.readCatalog = void 0;
10
10
  const COLUMNS = `
11
11
  SELECT table_name || '.' || column_name || ' ' || format_type(a.atttypid, a.atttypmod)
12
12
  || CASE WHEN c.is_nullable = 'NO' THEN ' NOT NULL' ELSE '' END
13
- || COALESCE(' DEFAULT ' || c.column_default, '') AS line
13
+ || COALESCE(' DEFAULT ' || c.column_default, '')
14
+ || CASE WHEN c.is_generated = 'ALWAYS' THEN ' GENERATED ' || c.generation_expression ELSE '' END AS line
14
15
  FROM information_schema.columns c
15
16
  JOIN pg_attribute a ON a.attrelid = ('"' || c.table_name || '"')::regclass AND a.attname = c.column_name
16
- WHERE c.table_schema = 'public'`;
17
+ WHERE c.table_schema = 'public'
18
+ -- TypeORM's bookkeeping table, written by its schema sync.
19
+ AND c.table_name <> 'typeorm_metadata'`;
17
20
  const CONSTRAINTS = `
18
21
  SELECT conrelid::regclass::text || ' ' || conname || ' ' || pg_get_constraintdef(oid) AS line
19
22
  FROM pg_constraint
@@ -148,7 +148,7 @@ function changeDdl(before, after, plan) {
148
148
  if (!rTables.has(t.name)) {
149
149
  up.push((0, _1.createTableSql)(t, A.constraints));
150
150
  for (const c of A.constraints)
151
- if (c.table === t.name && c.kind !== "fk")
151
+ if (c.table === t.name && c.kind !== "fk" && !c.late)
152
152
  createdInline.add(c.key);
153
153
  }
154
154
  // Columns on tables that stay.
@@ -173,12 +173,23 @@ function changeDdl(before, after, plan) {
173
173
  const o = old.columns.find((x) => x.name === c.name);
174
174
  const at = `ALTER TABLE ${(0, _1.q)(t.name)} ALTER COLUMN ${(0, _1.q)(c.name)}`;
175
175
  if (!o) {
176
- const needsData = c.notNull && c.default === undefined && !c.serial;
176
+ const needsData = c.notNull && c.default === undefined && !c.serial && !c.generated;
177
177
  up.push(`ALTER TABLE ${(0, _1.q)(t.name)} ADD ${needsData ? nullableSql(c) : c.sql}`);
178
178
  if (needsData)
179
179
  setNotNull.push(`${at} SET NOT NULL`);
180
180
  continue;
181
181
  }
182
+ if (c.generated && (o.generated !== c.generated || o.type !== c.type)) {
183
+ // Postgres 15 cannot change a generated column's expression in
184
+ // place, and the values are derived, so the column is rebuilt.
185
+ // ponytail: an index or constraint on the column goes with it and is
186
+ // not rebuilt here; the check after the migration reports it.
187
+ up.push(`ALTER TABLE ${(0, _1.q)(t.name)} DROP COLUMN ${(0, _1.q)(c.name)}`, `ALTER TABLE ${(0, _1.q)(t.name)} ADD ${c.sql}`);
188
+ continue;
189
+ }
190
+ // Now a plain column: it keeps the values Postgres computed.
191
+ if (o.generated && !c.generated)
192
+ up.push(`${at} DROP EXPRESSION`);
182
193
  const enumName = typeOf(c.type);
183
194
  const retype = o.type !== c.type || (enumName && swapped.has(enumName));
184
195
  if (retype) {
@@ -1,3 +1,13 @@
1
+ /**
2
+ * Apso's own DDL writer: the CREATE statements for a whole .apsorc schema.
3
+ *
4
+ * Column rules mirror the TypeScript entity templates (templates/entities),
5
+ * and names follow TypeORM's DefaultNamingStrategy (a prefix plus a sha1 of
6
+ * "table_columns"). A database built from this SQL therefore matches the one
7
+ * TypeORM builds for the generated entities, and services already deployed
8
+ * see no drift. test/lib/ddl/project-parity.test.ts checks that against a
9
+ * real scaffolded service.
10
+ */
1
11
  import { Entity } from "../types/entity";
2
12
  import { ComputedField } from "../types/field";
3
13
  import { RelationshipForTemplate, RelationshipMap } from "../types/relationship";
@@ -6,7 +16,8 @@ export declare const constraintName: {
6
16
  unique: (t: string, cols: string[]) => string;
7
17
  relation: (t: string, cols: string[]) => string;
8
18
  foreignKey: (t: string, cols: string[]) => string;
9
- index: (t: string, cols: string[]) => string;
19
+ check: (t: string, expression: string) => string;
20
+ index: (t: string, cols: string[], where?: string) => string;
10
21
  };
11
22
  export declare const q: (name: string) => string;
12
23
  export declare const literal: (v: string) => string;
@@ -18,6 +29,8 @@ export interface ColumnSpec {
18
29
  type: string;
19
30
  notNull: boolean;
20
31
  default?: string;
32
+ /** The expression of a stored generated column. */
33
+ generated?: string;
21
34
  unique: boolean;
22
35
  index: boolean;
23
36
  }
@@ -36,6 +49,8 @@ export interface ModelColumn {
36
49
  default?: string;
37
50
  /** A SERIAL id, whose default is the table's id sequence. */
38
51
  serial?: boolean;
52
+ /** The expression of a stored generated column. */
53
+ generated?: string;
39
54
  }
40
55
  export interface ModelTable {
41
56
  name: string;
@@ -46,11 +61,15 @@ export interface ModelConstraint {
46
61
  key: string;
47
62
  name: string;
48
63
  table: string;
49
- kind: "pk" | "unique" | "fk";
64
+ kind: "pk" | "unique" | "fk" | "check";
50
65
  columns: string[];
66
+ /** The condition of a check constraint. */
67
+ expression?: string;
51
68
  /** Everything after CONSTRAINT "name". */
52
69
  body: string;
53
70
  references?: string;
71
+ /** Added by ALTER TABLE after the table exists, as a foreign key is. */
72
+ late?: boolean;
54
73
  }
55
74
  export interface ModelIndex {
56
75
  key: string;
@@ -58,6 +77,10 @@ export interface ModelIndex {
58
77
  table: string;
59
78
  columns: string[];
60
79
  unique: boolean;
80
+ /** The condition of a partial index. */
81
+ where?: string;
82
+ /** The column list as SQL, for an index TypeORM cannot declare. */
83
+ columnsSql?: string;
61
84
  }
62
85
  export interface ModelEnum {
63
86
  name: string;
@@ -72,9 +95,36 @@ export interface Model {
72
95
  indexes: ModelIndex[];
73
96
  }
74
97
  export declare const pkColumn: (e: Entity) => string;
98
+ /**
99
+ * The primary key column of an entity, as a foreign key onto it must copy it:
100
+ * its SQL type, the matching TypeORM column options and the TypeScript type.
101
+ * A key declared as a field (varchar(100), text, bigint) keeps that type
102
+ * instead of falling back to integer.
103
+ *
104
+ * @param {Entity} [target] - The referenced entity.
105
+ * @returns {object} sql, options and ts for the key column.
106
+ */
107
+ export declare const keyColumn: (target?: Entity) => {
108
+ sql: string;
109
+ options: string;
110
+ ts: "string" | "number";
111
+ };
75
112
  export declare const fkType: (target?: Entity) => string;
76
- /** The foreign key column of a ManyToOne or an owning OneToOne. */
113
+ /**
114
+ * The foreign key column of a ManyToOne or an owning OneToOne:
115
+ * "joinColumnName" when the .apsorc sets one (an imported database keeps its
116
+ * own column names), else the name TypeORM derives.
117
+ */
77
118
  export declare const relationColumn: (r: RelationshipForTemplate) => string;
119
+ /**
120
+ * Every name an "indexes" or "uniques" entry may use for a foreign key, mapped
121
+ * to its column: the relationship ("patient"), the id property ("patientId")
122
+ * and the column itself ("patient_id").
123
+ *
124
+ * @param {RelationshipForTemplate[]} relationships - One entity's relationships.
125
+ * @returns {Map<string, string>} Name to database column.
126
+ */
127
+ export declare const relationColumns: (relationships: RelationshipForTemplate[]) => Map<string, string>;
78
128
  /** The join table of an owning ManyToMany and its two key columns. */
79
129
  export declare const joinTableOf: (e: Entity, r: RelationshipForTemplate, target: Entity) => {
80
130
  name: string;
@@ -84,6 +134,15 @@ export declare const joinTableOf: (e: Entity, r: RelationshipForTemplate, target
84
134
  export declare function schemaModel(input: SchemaInput): Model;
85
135
  export declare const createTypeSql: (e: ModelEnum) => string;
86
136
  export declare const createIndexSql: (i: ModelIndex) => string;
137
+ /**
138
+ * The statements that create an entity's "sqlIndexes", safe to run again:
139
+ * a generated service runs them after TypeORM's schema sync, which cannot
140
+ * create these indexes itself.
141
+ *
142
+ * @param {Entity} e - An entity from .apsorc.
143
+ * @returns {string[]} One CREATE INDEX IF NOT EXISTS per entry.
144
+ */
145
+ export declare const sqlIndexStatements: (e: Entity) => string[];
87
146
  export declare const addConstraintSql: (c: ModelConstraint) => string;
88
147
  export declare const createTableSql: (t: ModelTable, constraints: ModelConstraint[]) => string;
89
148
  /** CREATE statements for every enum type, table, index and foreign key. */