@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
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.schemaDdl = exports.createTableSql = exports.addConstraintSql = exports.createIndexSql = exports.createTypeSql = exports.schemaModel = exports.joinTableOf = exports.relationColumn = exports.fkType = exports.pkColumn = exports.columnSpec = exports.enumTypeName = exports.tableName = exports.literal = exports.q = exports.constraintName = void 0;
3
+ exports.schemaDdl = exports.createTableSql = exports.addConstraintSql = exports.sqlIndexStatements = exports.createIndexSql = exports.createTypeSql = exports.schemaModel = exports.joinTableOf = exports.relationColumns = exports.relationColumn = exports.fkType = exports.keyColumn = exports.pkColumn = exports.columnSpec = exports.enumTypeName = exports.tableName = exports.literal = exports.q = exports.constraintName = void 0;
4
4
  /**
5
5
  * Apso's own DDL writer: the CREATE statements for a whole .apsorc schema.
6
6
  *
@@ -11,21 +11,30 @@ exports.schemaDdl = exports.createTableSql = exports.addConstraintSql = exports.
11
11
  * see no drift. test/lib/ddl/project-parity.test.ts checks that against a
12
12
  * real scaffolded service.
13
13
  */
14
- const crypto_1 = require("crypto");
14
+ const entity_1 = require("../types/entity");
15
+ const relationship_1 = require("../types/relationship");
15
16
  const field_1 = require("../utils/field");
16
17
  const casing_1 = require("../utils/casing");
17
18
  const relationships_1 = require("../utils/relationships");
18
19
  // TypeORM's own casing, used for join table and join column names.
19
20
  // eslint-disable-next-line @typescript-eslint/no-var-requires
20
21
  const typeormCase = require("typeorm/util/StringUtils");
21
- const sha1 = (s) => (0, crypto_1.createHash)("sha1").update(s).digest("hex");
22
+ // TypeORM hashes names with its own SHA-1 routine, which differs from the
23
+ // standard one on text with characters such as quotes or "<>" (a check
24
+ // expression, a partial index's condition). Names must come out as TypeORM's.
25
+ const { RandomGenerator,
26
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
27
+ } = require("typeorm/util/RandomGenerator");
28
+ const sha1 = (s) => RandomGenerator.sha1(s);
22
29
  const key = (table, columns) => `${table.replace(".", "_")}_${[...columns].sort().join("_")}`;
23
30
  exports.constraintName = {
24
31
  primaryKey: (t, cols) => "PK_" + sha1(key(t, cols)).slice(0, 27),
25
32
  unique: (t, cols) => "UQ_" + sha1(key(t, cols)).slice(0, 27),
26
33
  relation: (t, cols) => "REL_" + sha1(key(t, cols)).slice(0, 26),
27
34
  foreignKey: (t, cols) => "FK_" + sha1(key(t, cols)).slice(0, 27),
28
- index: (t, cols) => "IDX_" + sha1(key(t, cols)).slice(0, 26),
35
+ check: (t, expression) => "CHK_" + sha1(`${t.replace(".", "_")}_${expression}`).slice(0, 26),
36
+ // TypeORM adds a partial index's condition to the text it hashes.
37
+ index: (t, cols, where) => "IDX_" + sha1(key(t, cols) + (where ? `_${where}` : "")).slice(0, 26),
29
38
  };
30
39
  const q = (name) => `"${name.replace(/"/g, '""')}"`;
31
40
  exports.q = q;
@@ -38,6 +47,22 @@ exports.enumTypeName = enumTypeName;
38
47
  const hasDefault = (f) => f.default !== null && f.default !== undefined;
39
48
  // TypeORM quotes every default it is given except booleans.
40
49
  const quoted = (f) => hasDefault(f) ? (0, exports.literal)(String(f.default)) : undefined;
50
+ /** Types whose template is a bare @Column({ type }) with no size or options. */
51
+ const PLAIN_TYPES = {
52
+ bytea: "bytea",
53
+ real: "real",
54
+ money: "money",
55
+ time: "TIME",
56
+ timetz: "TIME WITH TIME ZONE",
57
+ interval: "interval",
58
+ inet: "inet",
59
+ xml: "xml",
60
+ tsvector: "tsvector",
61
+ int4range: "int4range",
62
+ };
63
+ /** Their templates take no literal default (a SQL default still applies). */
64
+ const NO_LITERAL_DEFAULT = new Set(["xml", "tsvector", "int4range"]);
65
+ const generatedSql = (expression) => ` GENERATED ALWAYS AS (${expression}) STORED`;
41
66
  /** One column as its entity template declares it. */
42
67
  function columnSpec(table, f) {
43
68
  const textLike = (type) => [
@@ -90,15 +115,19 @@ function columnSpec(table, f) {
90
115
  case "uuid":
91
116
  type = "uuid";
92
117
  def = hasDefault(f) ? String(f.default) : undefined;
118
+ unique = Boolean(f.unique);
93
119
  break;
94
120
  case "date":
95
121
  type = "date";
122
+ unique = Boolean(f.unique);
96
123
  break;
97
124
  case "timestamp":
98
125
  type = "TIMESTAMP";
126
+ unique = Boolean(f.unique);
99
127
  break;
100
128
  case "timestamptz":
101
129
  type = "TIMESTAMP WITH TIME ZONE";
130
+ unique = Boolean(f.unique);
102
131
  break;
103
132
  case "json":
104
133
  case "jsonb":
@@ -116,10 +145,28 @@ function columnSpec(table, f) {
116
145
  break;
117
146
  }
118
147
  default:
119
- // ponytail: spatial, range and other special templates; add each with a parity case.
148
+ if (PLAIN_TYPES[f.type]) {
149
+ type = PLAIN_TYPES[f.type];
150
+ if (!NO_LITERAL_DEFAULT.has(f.type))
151
+ def = quoted(f);
152
+ break;
153
+ }
154
+ // ponytail: spatial and serial templates; add each with a parity case
155
+ // (spatial needs PostGIS, which the parity test's PGlite does not load).
120
156
  throw new Error(`The DDL writer does not support field type "${f.type}" yet (${table}.${f.name}).`);
121
157
  }
158
+ // A SQL expression or JSON literal default applies to any type, and
159
+ // "noDefault" removes the default a boolean would otherwise get.
160
+ if (f.defaultSql !== undefined)
161
+ def = f.defaultSql;
162
+ else if (f.noDefault)
163
+ def = undefined;
164
+ // Postgres computes a generated column, so it has no default.
165
+ if (f.generated)
166
+ def = undefined;
122
167
  let sql = `${(0, exports.q)(f.name)} ${type}`;
168
+ if (f.generated)
169
+ sql += generatedSql(f.generated);
123
170
  if (!f.nullable)
124
171
  sql += " NOT NULL";
125
172
  if (def !== undefined)
@@ -129,29 +176,88 @@ function columnSpec(table, f) {
129
176
  type,
130
177
  notNull: !f.nullable,
131
178
  default: def,
179
+ generated: f.generated,
132
180
  unique,
133
181
  index: Boolean(f.index),
134
182
  };
135
183
  }
136
184
  exports.columnSpec = columnSpec;
137
185
  const cols = (c) => c.map((x) => (0, exports.q)(x)).join(", ");
138
- const column = (name, type, notNull, def, serial) => ({
186
+ const column = (name, type, notNull, def, serial, generated) => ({
139
187
  name,
140
- sql: `${(0, exports.q)(name)} ${serial ? "SERIAL" : type}${notNull ? " NOT NULL" : ""}${def && !serial ? ` DEFAULT ${def}` : ""}`,
188
+ sql: `${(0, exports.q)(name)} ${serial ? "SERIAL" : type}${generated ? generatedSql(generated) : ""}${notNull ? " NOT NULL" : ""}${def && !serial ? ` DEFAULT ${def}` : ""}`,
141
189
  type,
142
190
  notNull,
143
191
  default: def,
144
192
  serial,
193
+ generated,
145
194
  });
146
195
  const pkColumn = (e) => { var _a, _b, _c; return (_c = (_b = ((_a = e.fields) !== null && _a !== void 0 ? _a : []).find((f) => f.primary)) === null || _b === void 0 ? void 0 : _b.name) !== null && _c !== void 0 ? _c : "id"; };
147
196
  exports.pkColumn = pkColumn;
148
- const fkType = (target) => (target === null || target === void 0 ? void 0 : target.primaryKeyType) === "uuid" ? "uuid" : "integer";
197
+ /**
198
+ * The primary key column of an entity, as a foreign key onto it must copy it:
199
+ * its SQL type, the matching TypeORM column options and the TypeScript type.
200
+ * A key declared as a field (varchar(100), text, bigint) keeps that type
201
+ * instead of falling back to integer.
202
+ *
203
+ * @param {Entity} [target] - The referenced entity.
204
+ * @returns {object} sql, options and ts for the key column.
205
+ */
206
+ const keyColumn = (target) => {
207
+ var _a, _b;
208
+ const keys = ((_a = target === null || target === void 0 ? void 0 : target.fields) !== null && _a !== void 0 ? _a : []).filter((f) => f.primary);
209
+ if (target && keys.length === 1) {
210
+ const [f] = (0, field_1.getFieldForTemplate)(keys, target.name);
211
+ const type = f.type;
212
+ const length = ["varchar", "char"].includes(type)
213
+ ? `, length: ${(_b = f.length) !== null && _b !== void 0 ? _b : (type === "char" ? 1 : 255)}`
214
+ : "";
215
+ return {
216
+ sql: columnSpec((0, exports.tableName)(target), f).type,
217
+ options: `type: "${type}"${length}`,
218
+ ts: ["integer", "smallint", "serial"].includes(type)
219
+ ? "number"
220
+ : "string",
221
+ };
222
+ }
223
+ if ((target === null || target === void 0 ? void 0 : target.primaryKeyType) === "uuid")
224
+ return { sql: "uuid", options: 'type: "uuid"', ts: "string" };
225
+ if ((target === null || target === void 0 ? void 0 : target.primaryKeyType) === "text")
226
+ return { sql: "text", options: 'type: "text"', ts: "string" };
227
+ return { sql: "integer", options: 'type: "integer"', ts: "number" };
228
+ };
229
+ exports.keyColumn = keyColumn;
230
+ const fkType = (target) => (0, exports.keyColumn)(target).sql;
149
231
  exports.fkType = fkType;
150
- /** The foreign key column of a ManyToOne or an owning OneToOne. */
151
- const relationColumn = (r) => r.type === "ManyToOne"
152
- ? r.camelCasedId
153
- : typeormCase.camelCase(`${r.relationshipName}_id`);
232
+ /**
233
+ * The foreign key column of a ManyToOne or an owning OneToOne:
234
+ * "joinColumnName" when the .apsorc sets one (an imported database keeps its
235
+ * own column names), else the name TypeORM derives.
236
+ */
237
+ const relationColumn = (r) => r.joinColumnName ||
238
+ (r.type === "ManyToOne"
239
+ ? r.camelCasedId
240
+ : typeormCase.camelCase(`${r.relationshipName}_id`));
154
241
  exports.relationColumn = relationColumn;
242
+ const ownsColumn = (r) => r.type === "ManyToOne" || (r.type === "OneToOne" && r.joinTable);
243
+ /**
244
+ * Every name an "indexes" or "uniques" entry may use for a foreign key, mapped
245
+ * to its column: the relationship ("patient"), the id property ("patientId")
246
+ * and the column itself ("patient_id").
247
+ *
248
+ * @param {RelationshipForTemplate[]} relationships - One entity's relationships.
249
+ * @returns {Map<string, string>} Name to database column.
250
+ */
251
+ const relationColumns = (relationships) => {
252
+ const columns = new Map();
253
+ for (const r of relationships.filter((r) => ownsColumn(r))) {
254
+ const column = (0, exports.relationColumn)(r);
255
+ for (const name of [r.relationshipName, r.camelCasedId, column])
256
+ columns.set(name, column);
257
+ }
258
+ return columns;
259
+ };
260
+ exports.relationColumns = relationColumns;
155
261
  /** The join table of an owning ManyToMany and its two key columns. */
156
262
  const joinTableOf = (e, r, target) => {
157
263
  const table = (0, exports.tableName)(e);
@@ -166,7 +272,7 @@ const joinTableOf = (e, r, target) => {
166
272
  };
167
273
  exports.joinTableOf = joinTableOf;
168
274
  function schemaModel(input) {
169
- var _a, _b, _c, _d, _e;
275
+ var _a, _b, _c, _d, _e, _f, _g, _h;
170
276
  const { entities, relationshipMap } = input;
171
277
  const byName = new Map(entities.map((e) => [e.name, e]));
172
278
  const model = {
@@ -183,8 +289,10 @@ function schemaModel(input) {
183
289
  // The same columns can be indexed twice (a field or relationship
184
290
  // "index": true plus an "indexes" entry). TypeORM names an index by its
185
291
  // table and columns, so a second CREATE INDEX would fail on deploy: keep one.
186
- const index = (table, columns, unique = false) => {
187
- const key = `index:${table}(${columns.join(",")})`;
292
+ // A named or partial index is its own index, so it is never merged.
293
+ const index = (table, columns, isUnique, name, where) => {
294
+ const unique = Boolean(isUnique);
295
+ const key = `index:${table}(${columns.join(",")})${where ? ` where ${where}` : ""}${name ? ` as ${name}` : ""}`;
188
296
  const seen = model.indexes.find((i) => i.key === key);
189
297
  if (seen) {
190
298
  seen.unique || (seen.unique = unique);
@@ -192,10 +300,11 @@ function schemaModel(input) {
192
300
  }
193
301
  model.indexes.push({
194
302
  key,
195
- name: exports.constraintName.index(table, columns),
303
+ name: name || exports.constraintName.index(table, columns, where),
196
304
  table,
197
305
  columns,
198
306
  unique,
307
+ ...(where && { where }),
199
308
  });
200
309
  };
201
310
  const unique = (table, columns, name, list = inline) => list.push({
@@ -206,17 +315,17 @@ function schemaModel(input) {
206
315
  columns,
207
316
  body: `UNIQUE (${cols(columns)})`,
208
317
  });
209
- const primaryKey = (table, columns, list = inline) => list.push({
318
+ const primaryKey = (table, columns, list = inline, name = exports.constraintName.primaryKey(table, columns)) => list.push({
210
319
  key: `pk:${table}`,
211
- name: exports.constraintName.primaryKey(table, columns),
320
+ name,
212
321
  table,
213
322
  kind: "pk",
214
323
  columns,
215
324
  body: `PRIMARY KEY (${cols(columns)})`,
216
325
  });
217
- const foreignKey = (table, col, target, targetCol, actions) => foreignKeys.push({
326
+ const foreignKey = (table, col, target, targetCol, actions, name = exports.constraintName.foreignKey(table, [col])) => foreignKeys.push({
218
327
  key: `fk:${table}(${col})->${target}`,
219
- name: exports.constraintName.foreignKey(table, [col]),
328
+ name,
220
329
  table,
221
330
  kind: "fk",
222
331
  columns: [col],
@@ -226,22 +335,30 @@ function schemaModel(input) {
226
335
  for (const e of entities) {
227
336
  const table = (0, exports.tableName)(e);
228
337
  const t = { name: table, columns: [] };
229
- const customPk = ((_a = e.fields) !== null && _a !== void 0 ? _a : []).some((f) => f.primary);
338
+ const relationships = (0, relationships_1.getRelationshipForTemplate)(e.name, relationshipMap[e.name] || [], entities);
339
+ // A foreign key can be the primary key ("primary": true on the
340
+ // relationship): a table keyed by the row it extends.
341
+ const relationKeys = relationships
342
+ .filter((r) => r.primary && ownsColumn(r))
343
+ .map((r) => (0, exports.relationColumn)(r));
344
+ const customPk = ((_a = e.fields) !== null && _a !== void 0 ? _a : []).some((f) => f.primary) || relationKeys.length > 0;
230
345
  if (!customPk) {
231
346
  const pkType = e.primaryKeyType || "serial";
232
347
  if (pkType === "uuid") {
233
- model.extensions.push(`CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`);
234
- t.columns.push(column("id", "uuid", true, "uuid_generate_v4()"));
348
+ if (!e.primaryKeyDefault)
349
+ model.extensions.push(`CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`);
350
+ t.columns.push(column("id", "uuid", true, e.primaryKeyDefault || "uuid_generate_v4()"));
235
351
  }
236
352
  else if (pkType === "text")
237
353
  t.columns.push(column("id", "text", true));
238
354
  else
239
355
  t.columns.push(column("id", "integer", true, `nextval('${table}_id_seq'::regclass)`, true));
240
356
  }
241
- if (e.created_at)
242
- t.columns.push(column("created_at", "TIMESTAMP", true, "now()"));
243
- if (e.updated_at)
244
- t.columns.push(column("updated_at", "TIMESTAMP", true, "now()"));
357
+ for (const stamp of ["created_at", "updated_at"])
358
+ if (e[stamp])
359
+ t.columns.push(column(stamp, (0, entity_1.timestampTypeOf)(e, stamp) === "timestamptz"
360
+ ? "TIMESTAMP WITH TIME ZONE"
361
+ : "TIMESTAMP", !(0, entity_1.timestampNullableOf)(e, stamp), (0, entity_1.timestampDefaultOf)(e, stamp) ? "now()" : undefined));
245
362
  for (const f of (0, field_1.getFieldForTemplate)((_b = e.fields) !== null && _b !== void 0 ? _b : [], e.name)) {
246
363
  if (!customPk && f.name === "id")
247
364
  continue;
@@ -255,24 +372,56 @@ function schemaModel(input) {
255
372
  values: [...f.values],
256
373
  });
257
374
  const spec = columnSpec(table, f);
258
- t.columns.push(column(f.name, spec.type, spec.notNull, spec.default));
375
+ t.columns.push(column(f.name, spec.type, spec.notNull, spec.default, false, spec.generated));
259
376
  if (spec.unique)
260
377
  unique(table, [f.name], exports.constraintName.unique(table, [f.name]));
261
378
  if (spec.index)
262
379
  index(table, [f.name]);
263
380
  }
381
+ // "indexes" and "uniques" may name a foreign key by its relationship.
382
+ // A field wins over a relationship of the same name.
383
+ const columnByName = (0, exports.relationColumns)(relationships);
384
+ for (const c of t.columns)
385
+ columnByName.set(c.name, c.name);
264
386
  for (const i of (_c = e.indexes) !== null && _c !== void 0 ? _c : [])
265
- index(table, i.fields, i.unique);
266
- for (const u of (_d = e.uniques) !== null && _d !== void 0 ? _d : [])
267
- unique(table, u.fields, u.name || exports.constraintName.unique(table, u.fields));
268
- for (const r of (0, relationships_1.getRelationshipForTemplate)(e.name, relationshipMap[e.name] || [], entities)) {
387
+ index(table, i.fields.map((f) => { var _a; return (_a = columnByName.get(f)) !== null && _a !== void 0 ? _a : f; }), i.unique, i.name, i.where);
388
+ for (const i of (_d = e.sqlIndexes) !== null && _d !== void 0 ? _d : [])
389
+ model.indexes.push({
390
+ key: `sqlindex:${table}:${i.name}(${i.columns})${i.where ? ` where ${i.where}` : ""}`,
391
+ name: i.name,
392
+ table,
393
+ columns: [],
394
+ columnsSql: i.columns,
395
+ unique: Boolean(i.unique),
396
+ ...(i.where && { where: i.where }),
397
+ });
398
+ for (const c of (_e = e.checks) !== null && _e !== void 0 ? _e : []) {
399
+ const name = c.name || exports.constraintName.check(table, c.expression);
400
+ // NOT VALID is allowed only on a constraint added by ALTER TABLE.
401
+ const late = c.validate === false;
402
+ (late ? foreignKeys : inline).push({
403
+ key: `check:${table}:${name}`,
404
+ name,
405
+ table,
406
+ kind: "check",
407
+ columns: [],
408
+ expression: c.expression,
409
+ body: `CHECK (${c.expression})${late ? " NOT VALID" : ""}`,
410
+ ...(late && { late }),
411
+ });
412
+ }
413
+ for (const u of (_f = e.uniques) !== null && _f !== void 0 ? _f : []) {
414
+ const columns = u.fields.map((f) => { var _a; return (_a = columnByName.get(f)) !== null && _a !== void 0 ? _a : f; });
415
+ unique(table, columns, u.name || exports.constraintName.unique(table, columns));
416
+ }
417
+ for (const r of relationships) {
269
418
  const target = byName.get(r.name);
270
419
  if (!target)
271
420
  continue;
272
421
  const targetTable = (0, exports.tableName)(target);
273
422
  // The template gives OneToOne onDelete CASCADE and a nullable join column.
274
423
  const oneToOne = r.type === "OneToOne";
275
- const onDelete = r.cascadeDelete || oneToOne ? "CASCADE" : "NO ACTION";
424
+ const onDelete = oneToOne ? "CASCADE" : (_g = (0, relationship_1.onDeleteOf)(r)) !== null && _g !== void 0 ? _g : "NO ACTION";
276
425
  if (r.type === "ManyToOne" || (oneToOne && r.joinTable)) {
277
426
  const col = (0, exports.relationColumn)(r);
278
427
  t.columns.push(column(col, (0, exports.fkType)(target), !(r.nullable || oneToOne)));
@@ -280,7 +429,9 @@ function schemaModel(input) {
280
429
  unique(table, [col], exports.constraintName.relation(table, [col]));
281
430
  if (r.type === "ManyToOne" && r.index)
282
431
  index(table, [col]);
283
- foreignKey(table, col, targetTable, (0, exports.pkColumn)(target), `ON DELETE ${onDelete} ON UPDATE NO ACTION`);
432
+ foreignKey(table, col, targetTable, (0, exports.pkColumn)(target),
433
+ // NOT VALID exists only on a key added by ALTER TABLE, as these are.
434
+ `ON DELETE ${onDelete} ON UPDATE NO ACTION${r.validate === false ? " NOT VALID" : ""}`, r.foreignKeyName || undefined);
284
435
  }
285
436
  if (r.type === "ManyToMany" && r.joinTable) {
286
437
  const { name: join, ownCol, otherCol } = (0, exports.joinTableOf)(e, r, target);
@@ -300,9 +451,13 @@ function schemaModel(input) {
300
451
  foreignKey(join, otherCol, targetTable, (0, exports.pkColumn)(target), `ON DELETE ${inverse} ON UPDATE ${inverse}`);
301
452
  }
302
453
  }
303
- primaryKey(table, customPk
304
- ? ((_e = e.fields) !== null && _e !== void 0 ? _e : []).filter((f) => f.primary).map((f) => f.name)
305
- : ["id"]);
454
+ const keyColumns = customPk
455
+ ? [
456
+ ...((_h = e.fields) !== null && _h !== void 0 ? _h : []).filter((f) => f.primary).map((f) => f.name),
457
+ ...relationKeys,
458
+ ]
459
+ : ["id"];
460
+ primaryKey(table, keyColumns, inline, e.primaryKeyName || undefined);
306
461
  entityTables.unshift(t);
307
462
  }
308
463
  model.extensions = [...new Set(model.extensions)];
@@ -315,14 +470,30 @@ const createTypeSql = (e) => `CREATE TYPE "public".${(0, exports.q)(e.name)} AS
315
470
  .map((v) => (0, exports.literal)(v))
316
471
  .join(", ")})`;
317
472
  exports.createTypeSql = createTypeSql;
318
- const createIndexSql = (i) => `CREATE ${i.unique ? "UNIQUE " : ""}INDEX ${(0, exports.q)(i.name)} ON ${(0, exports.q)(i.table)} (${cols(i.columns)})`;
473
+ const createIndexSql = (i) => {
474
+ var _a;
475
+ return `CREATE ${i.unique ? "UNIQUE " : ""}INDEX ${(0, exports.q)(i.name)} ON ${(0, exports.q)(i.table)} (${(_a = i.columnsSql) !== null && _a !== void 0 ? _a : cols(i.columns)})${i.where ? ` WHERE ${i.where}` : ""}`;
476
+ };
319
477
  exports.createIndexSql = createIndexSql;
478
+ /**
479
+ * The statements that create an entity's "sqlIndexes", safe to run again:
480
+ * a generated service runs them after TypeORM's schema sync, which cannot
481
+ * create these indexes itself.
482
+ *
483
+ * @param {Entity} e - An entity from .apsorc.
484
+ * @returns {string[]} One CREATE INDEX IF NOT EXISTS per entry.
485
+ */
486
+ const sqlIndexStatements = (e) => {
487
+ var _a;
488
+ return ((_a = e.sqlIndexes) !== null && _a !== void 0 ? _a : []).map((i) => `CREATE ${i.unique ? "UNIQUE " : ""}INDEX IF NOT EXISTS ${(0, exports.q)(i.name)} ON ${(0, exports.q)((0, exports.tableName)(e))} (${i.columns})${i.where ? ` WHERE ${i.where}` : ""}`);
489
+ };
490
+ exports.sqlIndexStatements = sqlIndexStatements;
320
491
  const addConstraintSql = (c) => `ALTER TABLE ${(0, exports.q)(c.table)} ADD CONSTRAINT ${(0, exports.q)(c.name)} ${c.body}`;
321
492
  exports.addConstraintSql = addConstraintSql;
322
493
  const createTableSql = (t, constraints) => `CREATE TABLE ${(0, exports.q)(t.name)} (${[
323
494
  ...t.columns.map((c) => c.sql),
324
495
  ...constraints
325
- .filter((c) => c.table === t.name && c.kind !== "fk")
496
+ .filter((c) => c.table === t.name && c.kind !== "fk" && !c.late)
326
497
  .map((c) => `CONSTRAINT ${(0, exports.q)(c.name)} ${c.body}`),
327
498
  ].join(", ")})`;
328
499
  exports.createTableSql = createTableSql;
@@ -335,7 +506,7 @@ function schemaDdl(input) {
335
506
  ...m.tables.map((t) => (0, exports.createTableSql)(t, m.constraints)),
336
507
  ...m.indexes.map((i) => (0, exports.createIndexSql)(i)),
337
508
  ...m.constraints
338
- .filter((c) => c.kind === "fk")
509
+ .filter((c) => c.kind === "fk" || c.late)
339
510
  .map((c) => (0, exports.addConstraintSql)(c)),
340
511
  ];
341
512
  }
@@ -6,6 +6,8 @@ const path = tslib_1.__importStar(require("path"));
6
6
  const Eta = tslib_1.__importStar(require("eta"));
7
7
  const base_1 = require("./base");
8
8
  const types_1 = require("../types");
9
+ const entity_1 = require("../types/entity");
10
+ const relationship_1 = require("../types/relationship");
9
11
  const guards_1 = require("../guards");
10
12
  const field_1 = require("../utils/field");
11
13
  const relationships_1 = require("../utils/relationships");
@@ -103,7 +105,7 @@ class GoGenerator extends base_1.BaseGenerator {
103
105
  return ".go";
104
106
  }
105
107
  validateConfig(config) {
106
- var _a, _b;
108
+ var _a, _b, _c, _d, _e;
107
109
  const errors = [];
108
110
  const warnings = [];
109
111
  // Validate that entities are provided
@@ -111,13 +113,21 @@ class GoGenerator extends base_1.BaseGenerator {
111
113
  errors.push("No entities defined in configuration");
112
114
  }
113
115
  errors.push(...(0, guards_1.removedScopeOptionErrors)((_a = config.entities) !== null && _a !== void 0 ? _a : []));
116
+ errors.push(...(0, relationships_1.joinColumnErrors)(config.relationshipMap, "Go"));
117
+ for (const e of (_b = config.entities) !== null && _b !== void 0 ? _b : [])
118
+ for (const f of (_c = e.fields) !== null && _c !== void 0 ? _c : [])
119
+ if (f.generated)
120
+ errors.push(`${e.name}.${f.name} sets "generated". The Go generator cannot declare a generated column yet; remove it or generate a TypeScript service.`);
121
+ for (const e of (_d = config.entities) !== null && _d !== void 0 ? _d : [])
122
+ if (e.primaryKeyName)
123
+ errors.push(`${e.name} sets "primaryKeyName": "${e.primaryKeyName}". The Go generator cannot keep a custom primary key constraint name yet; remove it or generate a TypeScript service.`);
114
124
  // Validate each entity
115
125
  for (const entity of config.entities) {
116
126
  if (!entity.name) {
117
127
  errors.push("Entity missing required 'name' property");
118
128
  }
119
129
  // Validate field types
120
- for (const field of (_b = entity.fields) !== null && _b !== void 0 ? _b : []) {
130
+ for (const field of (_e = entity.fields) !== null && _e !== void 0 ? _e : []) {
121
131
  if (!field.name) {
122
132
  errors.push(`Entity '${entity.name}' has a field without a name`);
123
133
  }
@@ -268,7 +278,7 @@ class GoGenerator extends base_1.BaseGenerator {
268
278
  : undefined,
269
279
  // The child's foreign key field, for OneToMany and the inverse OneToOne.
270
280
  foreignKey: `${(0, casing_1.pascalCase)(rel.inverseReferenceName || entity.name)}ID`,
271
- onDeleteCascade: rel.type === "OneToOne" || Boolean(rel.cascadeDelete),
281
+ onDelete: rel.type === "OneToOne" ? "CASCADE" : (0, relationship_1.onDeleteOf)(rel),
272
282
  join,
273
283
  camelReferenceName: (0, casing_1.camelCase)(rel.referenceName || rel.name),
274
284
  snakeReferenceName: (0, casing_1.snakeCase)(rel.referenceName || rel.name),
@@ -289,6 +299,10 @@ class GoGenerator extends base_1.BaseGenerator {
289
299
  tableName: (0, ddl_1.tableName)(entity),
290
300
  createdAt: entity.created_at,
291
301
  updatedAt: entity.updated_at,
302
+ createdAtType: (0, entity_1.timestampTypeOf)(entity, "created_at"),
303
+ updatedAtType: (0, entity_1.timestampTypeOf)(entity, "updated_at"),
304
+ createdAtNotNull: (0, entity_1.timestampNullableOf)(entity, "created_at") ? "" : "not null;",
305
+ updatedAtNotNull: (0, entity_1.timestampNullableOf)(entity, "updated_at") ? "" : "not null;",
292
306
  columns,
293
307
  associations,
294
308
  importTime: Boolean(entity.created_at || entity.updated_at) ||
@@ -143,7 +143,7 @@ class PythonGenerator extends base_1.BaseGenerator {
143
143
  return ".py";
144
144
  }
145
145
  validateConfig(config) {
146
- var _a, _b;
146
+ var _a, _b, _c, _d, _e, _f, _g;
147
147
  const errors = [];
148
148
  const warnings = [];
149
149
  // Validate that entities are provided
@@ -151,13 +151,24 @@ class PythonGenerator extends base_1.BaseGenerator {
151
151
  errors.push("No entities defined in configuration");
152
152
  }
153
153
  errors.push(...(0, guards_1.removedScopeOptionErrors)((_a = config.entities) !== null && _a !== void 0 ? _a : []));
154
+ errors.push(...(0, relationships_1.joinColumnErrors)(config.relationshipMap, "Python"));
155
+ for (const e of (_b = config.entities) !== null && _b !== void 0 ? _b : [])
156
+ if ((_c = e.sqlIndexes) === null || _c === void 0 ? void 0 : _c.length)
157
+ errors.push(`${e.name} sets "sqlIndexes". The Python generator cannot create an index on an expression or a descending column yet; remove it or generate a TypeScript service.`);
158
+ for (const e of (_d = config.entities) !== null && _d !== void 0 ? _d : [])
159
+ for (const f of (_e = e.fields) !== null && _e !== void 0 ? _e : [])
160
+ if (f.generated)
161
+ errors.push(`${e.name}.${f.name} sets "generated". The Python generator cannot declare a generated column yet; remove it or generate a TypeScript service.`);
162
+ for (const e of (_f = config.entities) !== null && _f !== void 0 ? _f : [])
163
+ if (e.primaryKeyName)
164
+ errors.push(`${e.name} sets "primaryKeyName": "${e.primaryKeyName}". The Python generator cannot keep a custom primary key constraint name yet; remove it or generate a TypeScript service.`);
154
165
  // Validate each entity
155
166
  for (const entity of config.entities) {
156
167
  if (!entity.name) {
157
168
  errors.push("Entity missing required 'name' property");
158
169
  }
159
170
  // Validate field types
160
- for (const field of (_b = entity.fields) !== null && _b !== void 0 ? _b : []) {
171
+ for (const field of (_g = entity.fields) !== null && _g !== void 0 ? _g : []) {
161
172
  if (!field.name) {
162
173
  errors.push(`Entity '${entity.name}' has a field without a name`);
163
174
  }
@@ -227,9 +238,12 @@ class PythonGenerator extends base_1.BaseGenerator {
227
238
  .map((c) => `UniqueConstraint(${c.columns
228
239
  .map((x) => (0, migration_file_1.pyString)(x))
229
240
  .join(", ")}, name=${(0, migration_file_1.pyString)(c.name)})`),
241
+ ...model.constraints
242
+ .filter((c) => c.kind === "check" && c.table === t)
243
+ .map((c) => { var _a; return `CheckConstraint(${(0, migration_file_1.pyString)((_a = c.expression) !== null && _a !== void 0 ? _a : "")}, name=${(0, migration_file_1.pyString)(c.name)})`; }),
230
244
  ...model.indexes
231
245
  .filter((i) => i.table === t)
232
- .map((i) => `Index(${[i.name, ...i.columns].map((x) => (0, migration_file_1.pyString)(x)).join(", ")}${i.unique ? ", unique=True" : ""})`),
246
+ .map((i) => `Index(${[i.name, ...i.columns].map((x) => (0, migration_file_1.pyString)(x)).join(", ")}${i.unique ? ", unique=True" : ""}${i.where ? `, postgresql_where=text(${(0, migration_file_1.pyString)(i.where)})` : ""})`),
233
247
  ],
234
248
  };
235
249
  };
@@ -16,9 +16,10 @@ export declare class TypeScriptGenerator extends BaseGenerator {
16
16
  generateModule(options: EntityGenerationOptions): Promise<GeneratedFile[]>;
17
17
  generateMigration(_options: MigrationGenerationOptions): Promise<GeneratedFile[]>;
18
18
  generateEnums(entities: Entity[], apiType: string): Promise<GeneratedFile[]>;
19
- generateIndexModule(entities: Entity[], apiType: string, _opts?: {
19
+ generateIndexModule(entities: Entity[], apiType: string, opts?: {
20
20
  emitEvents?: boolean;
21
21
  auth?: AuthConfig;
22
+ guards?: boolean;
22
23
  }): Promise<GeneratedFile[]>;
23
24
  generateGuards(entities: Entity[], auth?: AuthConfig, relationshipMap?: RelationshipMap): Promise<GeneratedFile[]>;
24
25
  /**