@apso/cli 0.52.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 (93) hide show
  1. package/dist/commands/import/supabase.js +31 -6
  2. package/dist/commands/init.d.ts +9 -0
  3. package/dist/commands/init.js +31 -1
  4. package/dist/commands/mcp/serve.js +20 -0
  5. package/dist/lib/apsorc-parser.js +7 -3
  6. package/dist/lib/ddl/catalog.js +5 -2
  7. package/dist/lib/ddl/change.js +13 -2
  8. package/dist/lib/ddl/index.d.ts +62 -3
  9. package/dist/lib/ddl/index.js +211 -40
  10. package/dist/lib/generators/go.js +17 -3
  11. package/dist/lib/generators/python.js +17 -3
  12. package/dist/lib/generators/typescript.js +85 -15
  13. package/dist/lib/import/copy-data.js +4 -0
  14. package/dist/lib/import/introspect.d.ts +40 -0
  15. package/dist/lib/import/introspect.js +137 -49
  16. package/dist/lib/import/pg-to-apsorc.d.ts +62 -0
  17. package/dist/lib/import/pg-to-apsorc.js +248 -37
  18. package/dist/lib/import/types.d.ts +48 -3
  19. package/dist/lib/migrate/sandbox.js +23 -6
  20. package/dist/lib/migrate/snapshot.d.ts +5 -0
  21. package/dist/lib/plan/index.d.ts +4 -1
  22. package/dist/lib/plan/index.js +9 -3
  23. package/dist/lib/templates/entities/entity-col-array.eta +2 -1
  24. package/dist/lib/templates/entities/entity-col-bigint.eta +2 -2
  25. package/dist/lib/templates/entities/entity-col-bigserial.eta +2 -2
  26. package/dist/lib/templates/entities/entity-col-boolean.eta +1 -1
  27. package/dist/lib/templates/entities/entity-col-bytea.eta +2 -2
  28. package/dist/lib/templates/entities/entity-col-char.eta +4 -3
  29. package/dist/lib/templates/entities/entity-col-date.eta +6 -2
  30. package/dist/lib/templates/entities/entity-col-datetime.eta +8 -1
  31. package/dist/lib/templates/entities/entity-col-decimal.eta +2 -2
  32. package/dist/lib/templates/entities/entity-col-double.eta +2 -2
  33. package/dist/lib/templates/entities/entity-col-float.eta +1 -1
  34. package/dist/lib/templates/entities/entity-col-geography.eta +1 -1
  35. package/dist/lib/templates/entities/entity-col-geometry.eta +1 -1
  36. package/dist/lib/templates/entities/entity-col-geometrycollection.eta +1 -1
  37. package/dist/lib/templates/entities/entity-col-inet.eta +2 -2
  38. package/dist/lib/templates/entities/entity-col-int4range.eta +1 -1
  39. package/dist/lib/templates/entities/entity-col-integer.eta +2 -2
  40. package/dist/lib/templates/entities/entity-col-interval.eta +2 -2
  41. package/dist/lib/templates/entities/entity-col-json-plain.eta +1 -1
  42. package/dist/lib/templates/entities/entity-col-json.eta +1 -1
  43. package/dist/lib/templates/entities/entity-col-jsonb.eta +1 -1
  44. package/dist/lib/templates/entities/entity-col-linestring.eta +1 -1
  45. package/dist/lib/templates/entities/entity-col-money.eta +2 -2
  46. package/dist/lib/templates/entities/entity-col-multilinestring.eta +1 -1
  47. package/dist/lib/templates/entities/entity-col-multipoint.eta +1 -1
  48. package/dist/lib/templates/entities/entity-col-multipolygon.eta +1 -1
  49. package/dist/lib/templates/entities/entity-col-numeric.eta +2 -2
  50. package/dist/lib/templates/entities/entity-col-point.eta +1 -1
  51. package/dist/lib/templates/entities/entity-col-polygon.eta +1 -1
  52. package/dist/lib/templates/entities/entity-col-real.eta +2 -2
  53. package/dist/lib/templates/entities/entity-col-serial.eta +2 -2
  54. package/dist/lib/templates/entities/entity-col-smallint.eta +2 -2
  55. package/dist/lib/templates/entities/entity-col-smallserial.eta +2 -2
  56. package/dist/lib/templates/entities/entity-col-string.eta +2 -2
  57. package/dist/lib/templates/entities/entity-col-text.eta +4 -3
  58. package/dist/lib/templates/entities/entity-col-time.eta +2 -2
  59. package/dist/lib/templates/entities/entity-col-timestamp.eta +8 -1
  60. package/dist/lib/templates/entities/entity-col-timestamptz.eta +8 -1
  61. package/dist/lib/templates/entities/entity-col-timetz.eta +2 -2
  62. package/dist/lib/templates/entities/entity-col-tsvector.eta +2 -2
  63. package/dist/lib/templates/entities/entity-col-uuid.eta +5 -2
  64. package/dist/lib/templates/entities/entity-col-varchar.eta +4 -3
  65. package/dist/lib/templates/entities/entity-col-xml.eta +2 -2
  66. package/dist/lib/templates/entities/entity.eta +30 -18
  67. package/dist/lib/templates/go/models/model.eta +3 -3
  68. package/dist/lib/templates/python/models/model.eta +1 -1
  69. package/dist/lib/templates/rest/controller-rest.eta +16 -5
  70. package/dist/lib/templates/rest/dto-rest.eta +2 -2
  71. package/dist/lib/templates/rest/index-module-rest.eta +6 -0
  72. package/dist/lib/templates/rest/schema-extras-module.eta +24 -0
  73. package/dist/lib/types/constraints.d.ts +13 -0
  74. package/dist/lib/types/entity.d.ts +67 -2
  75. package/dist/lib/types/entity.js +39 -1
  76. package/dist/lib/types/field.d.ts +20 -2
  77. package/dist/lib/types/indices.d.ts +21 -0
  78. package/dist/lib/types/relationship.d.ts +33 -0
  79. package/dist/lib/types/relationship.js +13 -0
  80. package/dist/lib/utils/field.d.ts +22 -0
  81. package/dist/lib/utils/field.js +62 -3
  82. package/dist/lib/utils/relationships/index.d.ts +1 -1
  83. package/dist/lib/utils/relationships/index.js +2 -1
  84. package/dist/lib/utils/relationships/parse.d.ts +11 -0
  85. package/dist/lib/utils/relationships/parse.js +44 -1
  86. package/dist/lib/utils/template.d.ts +3 -3
  87. package/dist/lib/utils/template.js +4 -4
  88. package/dist/lib/verify/crud-plan.d.ts +2 -0
  89. package/dist/lib/verify/crud-plan.js +19 -5
  90. package/dist/lib/verify/index.js +32 -3
  91. package/npm-shrinkwrap.json +72 -87
  92. package/oclif.manifest.json +7 -1
  93. package/package.json +3 -2
@@ -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;
@@ -1014,4 +1014,24 @@ is tracked separately.
1014
1014
  "index": true
1015
1015
  }
1016
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\`).
1017
1037
  `;
@@ -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;
@@ -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. */