@apso/cli 0.54.0 → 0.56.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.
@@ -58,6 +58,8 @@ function formatReport(report) {
58
58
  review.push(` - Non-"id" primary keys (kept as fields): ${w.nonStandardPks.join(", ")}`);
59
59
  if (w.noPrimaryKey.length > 0)
60
60
  review.push(` - Tables with no primary key: ${w.noPrimaryKey.join(", ")}`);
61
+ if (w.foreignKeysNotCarried.length > 0)
62
+ review.push(` - Foreign keys left out; the column itself is kept (the key points at a table that was not imported, or at a column that is not that table's primary key): ${w.foreignKeysNotCarried.join(", ")}`);
61
63
  if (w.compositeFks.length > 0)
62
64
  review.push(` - Composite foreign keys (kept as columns, no relationship): ${w.compositeFks.join(", ")}`);
63
65
  if (w.joinTablesDetected.length > 0)
@@ -68,8 +70,6 @@ function formatReport(report) {
68
70
  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
71
  if (w.timestampDefaultsAdded.length > 0)
70
72
  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
73
  if (w.relationshipsRenamed.length > 0)
74
74
  review.push(` - Relationships renamed because a column has the natural name (columns unchanged): ${w.relationshipsRenamed.join(", ")}`);
75
75
  if (w.indexesNotCarried.length > 0)
@@ -1022,7 +1022,10 @@ is tracked separately.
1022
1022
  |---------|----|---------|
1023
1023
  | joinColumnName | relationship | The foreign key column's own name, e.g. \`patient_id\`. The property stays \`patientId\`. TypeScript only |
1024
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 |
1025
+ | onDelete | relationship | CASCADE, SET NULL, SET DEFAULT, RESTRICT or NO ACTION. \`cascadeDelete: true\` is CASCADE. SET DEFAULT is TypeScript only |
1026
+ | onUpdate | relationship | The same rules for a change to the referenced key. Defaults to NO ACTION. TypeScript only |
1027
+ | joinColumnDefault | relationship | The foreign key column's DEFAULT, as a SQL expression. TypeScript only |
1028
+ | deferrable | relationship | \`INITIALLY DEFERRED\` or \`INITIALLY IMMEDIATE\`: the key is DEFERRABLE and checked at commit or per statement. TypeScript only |
1026
1029
  | primary | relationship | The foreign key column is the entity's primary key. No \`id\` is generated. TypeScript only |
1027
1030
  | primaryKeyName | entity | The primary key constraint's name. TypeScript only |
1028
1031
  | timestampType | entity | \`timestamp\` (default) or \`timestamptz\` for created_at and updated_at: one value, or \`{ "created_at": ..., "updated_at": ... }\` |
@@ -1032,6 +1035,7 @@ is tracked separately.
1032
1035
  | primary | field | The field is the primary key, or part of it |
1033
1036
  | elementType | field | Element type of an \`array\` field, e.g. \`uuid\` |
1034
1037
  | 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 |
1038
+ | foreignKeys | entity | A second foreign key on a column, as \`{ name, column, to, onDelete?, onUpdate?, deferrable?, validate? }\`. A database constraint only; \`apso import\` writes it when a column has two keys. TypeScript only |
1035
1039
 
1036
1040
  In \`indexes\` and \`uniques\`, a foreign key may be named by its relationship (\`patient\`), its id property (\`patientId\`) or its column (\`patient_id\`).
1037
1041
  `;
@@ -25,7 +25,7 @@ const subject = (id) => {
25
25
  };
26
26
  /** The deployed .apsorc with every answered rename applied. */
27
27
  function applyRenames(before, after, plan) {
28
- var _a, _b, _c;
28
+ var _a, _b, _c, _d, _e;
29
29
  const copy = JSON.parse(JSON.stringify(before));
30
30
  for (const x of answered(plan, "removedField")) {
31
31
  if (!x.answer.startsWith("rename:"))
@@ -33,8 +33,12 @@ function applyRenames(before, after, plan) {
33
33
  const { entity, field } = subject(x.id);
34
34
  const f = (_b = (_a = copy.entities
35
35
  .find((e) => e.name === entity)) === null || _a === void 0 ? void 0 : _a.fields) === null || _b === void 0 ? void 0 : _b.find((g) => g.name === field);
36
- if (f)
37
- f.name = x.answer.slice("rename:".length);
36
+ if (!f)
37
+ continue;
38
+ f.name = x.answer.slice("rename:".length);
39
+ for (const k of (_d = (_c = copy.entities.find((e) => e.name === entity)) === null || _c === void 0 ? void 0 : _c.foreignKeys) !== null && _d !== void 0 ? _d : [])
40
+ if (k.column === field)
41
+ k.column = f.name;
38
42
  }
39
43
  for (const x of answered(plan, "removedEntity")) {
40
44
  if (!x.answer.startsWith("rename:"))
@@ -50,12 +54,15 @@ function applyRenames(before, after, plan) {
50
54
  e.table = target.table;
51
55
  else
52
56
  delete e.table;
53
- for (const r of (_c = copy.relationships) !== null && _c !== void 0 ? _c : []) {
57
+ for (const r of (_e = copy.relationships) !== null && _e !== void 0 ? _e : []) {
54
58
  if (r.from === from)
55
59
  r.from = to;
56
60
  if (r.to === from)
57
61
  r.to = to;
58
62
  }
63
+ for (const k of copy.entities.flatMap((y) => { var _a; return (_a = y.foreignKeys) !== null && _a !== void 0 ? _a : []; }))
64
+ if (k.to === from)
65
+ k.to = to;
59
66
  }
60
67
  return copy;
61
68
  }
@@ -94,27 +94,49 @@ export interface Model {
94
94
  constraints: ModelConstraint[];
95
95
  indexes: ModelIndex[];
96
96
  }
97
- export declare const pkColumn: (e: Entity) => string;
97
+ export declare const pkColumn: (e: Entity, schema?: SchemaInput) => string;
98
98
  /**
99
99
  * The primary key column of an entity, as a foreign key onto it must copy it:
100
100
  * its SQL type, the matching TypeORM column options and the TypeScript type.
101
101
  * A key declared as a field (varchar(100), text, bigint) keeps that type
102
102
  * instead of falling back to integer.
103
103
  *
104
+ * A key that is a relationship has the type of the key that one references.
105
+ *
104
106
  * @param {Entity} [target] - The referenced entity.
107
+ * @param {SchemaInput} [schema] - The schema, to follow such a key through.
105
108
  * @returns {object} sql, options and ts for the key column.
106
109
  */
107
- export declare const keyColumn: (target?: Entity) => {
110
+ export declare const keyColumn: (target?: Entity, schema?: SchemaInput) => {
108
111
  sql: string;
109
112
  options: string;
110
113
  ts: "string" | "number";
111
114
  };
112
- export declare const fkType: (target?: Entity) => string;
115
+ export declare const fkType: (target?: Entity, schema?: SchemaInput) => string;
113
116
  /**
114
117
  * The foreign key column of a ManyToOne or an owning OneToOne:
115
118
  * "joinColumnName" when the .apsorc sets one (an imported database keeps its
116
119
  * own column names), else the name TypeORM derives.
117
120
  */
121
+ /**
122
+ * An entity's "foreignKeys" entries with the table and key column each one
123
+ * references.
124
+ * @param {Entity} e - The entity.
125
+ * @param {SchemaInput} schema - The schema the entity is in.
126
+ * @returns {Array} One resolved entry per key.
127
+ */
128
+ export declare const extraForeignKeys: (e: Entity, schema: SchemaInput) => {
129
+ target: string;
130
+ targetTable: string;
131
+ targetColumn: string;
132
+ name: string;
133
+ column: string;
134
+ to: string;
135
+ onDelete?: import("../types/relationship").OnDelete | undefined;
136
+ onUpdate?: import("../types/relationship").OnDelete | undefined;
137
+ deferrable?: import("../types/relationship").Deferrable | undefined;
138
+ validate?: boolean | undefined;
139
+ }[];
118
140
  export declare const relationColumn: (r: RelationshipForTemplate) => string;
119
141
  /**
120
142
  * Every name an "indexes" or "uniques" entry may use for a foreign key, mapped
@@ -126,7 +148,7 @@ export declare const relationColumn: (r: RelationshipForTemplate) => string;
126
148
  */
127
149
  export declare const relationColumns: (relationships: RelationshipForTemplate[]) => Map<string, string>;
128
150
  /** The join table of an owning ManyToMany and its two key columns. */
129
- export declare const joinTableOf: (e: Entity, r: RelationshipForTemplate, target: Entity) => {
151
+ export declare const joinTableOf: (e: Entity, r: RelationshipForTemplate, target: Entity, schema?: SchemaInput) => {
130
152
  name: string;
131
153
  ownCol: string;
132
154
  otherCol: string;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
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;
3
+ exports.schemaDdl = exports.createTableSql = exports.addConstraintSql = exports.sqlIndexStatements = exports.createIndexSql = exports.createTypeSql = exports.schemaModel = exports.joinTableOf = exports.relationColumns = exports.relationColumn = exports.extraForeignKeys = 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
  *
@@ -192,7 +192,28 @@ const column = (name, type, notNull, def, serial, generated) => ({
192
192
  serial,
193
193
  generated,
194
194
  });
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"; };
195
+ /**
196
+ * The relationship that is an entity's whole primary key ("primary": true and
197
+ * no primary field): a table keyed by the row it extends.
198
+ *
199
+ * @param {Entity} e - The entity.
200
+ * @param {SchemaInput} [schema] - The schema, to look its relationships up in.
201
+ * @returns {RelationshipForTemplate | undefined} The relationship, if one is the key.
202
+ */
203
+ const keyRelationship = (e, schema) => {
204
+ var _a;
205
+ if (!schema || ((_a = e.fields) !== null && _a !== void 0 ? _a : []).some((f) => f.primary))
206
+ return;
207
+ const keys = (0, relationships_1.getRelationshipForTemplate)(e.name, schema.relationshipMap[e.name] || [], schema.entities).filter((r) => r.primary && ownsColumn(r) && r.name !== e.name);
208
+ return keys.length === 1 ? keys[0] : undefined;
209
+ };
210
+ const pkColumn = (e, schema) => {
211
+ var _a, _b, _c;
212
+ const r = keyRelationship(e, schema);
213
+ return r
214
+ ? (0, exports.relationColumn)(r)
215
+ : (_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";
216
+ };
196
217
  exports.pkColumn = pkColumn;
197
218
  /**
198
219
  * The primary key column of an entity, as a foreign key onto it must copy it:
@@ -200,11 +221,17 @@ exports.pkColumn = pkColumn;
200
221
  * A key declared as a field (varchar(100), text, bigint) keeps that type
201
222
  * instead of falling back to integer.
202
223
  *
224
+ * A key that is a relationship has the type of the key that one references.
225
+ *
203
226
  * @param {Entity} [target] - The referenced entity.
227
+ * @param {SchemaInput} [schema] - The schema, to follow such a key through.
204
228
  * @returns {object} sql, options and ts for the key column.
205
229
  */
206
- const keyColumn = (target) => {
230
+ const keyColumn = (target, schema) => {
207
231
  var _a, _b;
232
+ const through = target && keyRelationship(target, schema);
233
+ if (through)
234
+ return (0, exports.keyColumn)(schema.entities.find((e) => e.name === through.name), schema);
208
235
  const keys = ((_a = target === null || target === void 0 ? void 0 : target.fields) !== null && _a !== void 0 ? _a : []).filter((f) => f.primary);
209
236
  if (target && keys.length === 1) {
210
237
  const [f] = (0, field_1.getFieldForTemplate)(keys, target.name);
@@ -227,13 +254,36 @@ const keyColumn = (target) => {
227
254
  return { sql: "integer", options: 'type: "integer"', ts: "number" };
228
255
  };
229
256
  exports.keyColumn = keyColumn;
230
- const fkType = (target) => (0, exports.keyColumn)(target).sql;
257
+ const fkType = (target, schema) => (0, exports.keyColumn)(target, schema).sql;
231
258
  exports.fkType = fkType;
232
259
  /**
233
260
  * The foreign key column of a ManyToOne or an owning OneToOne:
234
261
  * "joinColumnName" when the .apsorc sets one (an imported database keeps its
235
262
  * own column names), else the name TypeORM derives.
236
263
  */
264
+ /**
265
+ * An entity's "foreignKeys" entries with the table and key column each one
266
+ * references.
267
+ * @param {Entity} e - The entity.
268
+ * @param {SchemaInput} schema - The schema the entity is in.
269
+ * @returns {Array} One resolved entry per key.
270
+ */
271
+ const extraForeignKeys = (e, schema) => {
272
+ var _a;
273
+ return ((_a = e.foreignKeys) !== null && _a !== void 0 ? _a : []).map((k) => {
274
+ var _a;
275
+ const target = schema.entities.find((x) => x.name === k.to);
276
+ if (!k.name || !k.column || !target)
277
+ throw new Error(`${e.name} "foreignKeys" entry ${JSON.stringify((_a = k.name) !== null && _a !== void 0 ? _a : k)} needs a "name", a "column" and a "to" that names an entity in .apsorc.`);
278
+ return {
279
+ ...k,
280
+ target: target.name,
281
+ targetTable: (0, exports.tableName)(target),
282
+ targetColumn: (0, exports.pkColumn)(target, schema),
283
+ };
284
+ });
285
+ };
286
+ exports.extraForeignKeys = extraForeignKeys;
237
287
  const relationColumn = (r) => r.joinColumnName ||
238
288
  (r.type === "ManyToOne"
239
289
  ? r.camelCasedId
@@ -259,15 +309,16 @@ const relationColumns = (relationships) => {
259
309
  };
260
310
  exports.relationColumns = relationColumns;
261
311
  /** The join table of an owning ManyToMany and its two key columns. */
262
- const joinTableOf = (e, r, target) => {
312
+ const joinTableOf = (e, r, target, schema) => {
263
313
  const table = (0, exports.tableName)(e);
264
314
  const targetTable = (0, exports.tableName)(target);
265
315
  return {
266
316
  name: r.joinTableName ||
267
317
  typeormCase.snakeCase(`${table}_${r.pluralizedRelationshipName}_${targetTable}`),
268
- ownCol: r.joinColumnName || typeormCase.camelCase(`${table}_${(0, exports.pkColumn)(e)}`),
318
+ ownCol: r.joinColumnName ||
319
+ typeormCase.camelCase(`${table}_${(0, exports.pkColumn)(e, schema)}`),
269
320
  otherCol: r.inverseJoinColumnName ||
270
- typeormCase.camelCase(`${targetTable}_${(0, exports.pkColumn)(target)}`),
321
+ typeormCase.camelCase(`${targetTable}_${(0, exports.pkColumn)(target, schema)}`),
271
322
  };
272
323
  };
273
324
  exports.joinTableOf = joinTableOf;
@@ -323,8 +374,8 @@ function schemaModel(input) {
323
374
  columns,
324
375
  body: `PRIMARY KEY (${cols(columns)})`,
325
376
  });
326
- const foreignKey = (table, col, target, targetCol, actions, name = exports.constraintName.foreignKey(table, [col])) => foreignKeys.push({
327
- key: `fk:${table}(${col})->${target}`,
377
+ const foreignKey = (table, col, target, targetCol, actions, name = exports.constraintName.foreignKey(table, [col]), key = `fk:${table}(${col})->${target}`) => foreignKeys.push({
378
+ key,
328
379
  name,
329
380
  table,
330
381
  kind: "fk",
@@ -424,22 +475,22 @@ function schemaModel(input) {
424
475
  const onDelete = oneToOne ? "CASCADE" : (_g = (0, relationship_1.onDeleteOf)(r)) !== null && _g !== void 0 ? _g : "NO ACTION";
425
476
  if (r.type === "ManyToOne" || (oneToOne && r.joinTable)) {
426
477
  const col = (0, exports.relationColumn)(r);
427
- t.columns.push(column(col, (0, exports.fkType)(target), !(r.nullable || oneToOne)));
478
+ t.columns.push(column(col, (0, exports.fkType)(target, input), !(r.nullable || oneToOne), r.joinColumnDefault));
428
479
  if (oneToOne)
429
480
  unique(table, [col], exports.constraintName.relation(table, [col]));
430
481
  if (r.type === "ManyToOne" && r.index)
431
482
  index(table, [col]);
432
- foreignKey(table, col, targetTable, (0, exports.pkColumn)(target),
483
+ foreignKey(table, col, targetTable, (0, exports.pkColumn)(target, input),
433
484
  // 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);
485
+ (0, relationship_1.keyRulesSql)(onDelete, r), r.foreignKeyName || undefined);
435
486
  }
436
487
  if (r.type === "ManyToMany" && r.joinTable) {
437
- const { name: join, ownCol, otherCol } = (0, exports.joinTableOf)(e, r, target);
488
+ const { name: join, ownCol, otherCol } = (0, exports.joinTableOf)(e, r, target, input);
438
489
  joinTables.push({
439
490
  name: join,
440
491
  columns: [
441
- column(ownCol, (0, exports.fkType)(e), true),
442
- column(otherCol, (0, exports.fkType)(target), true),
492
+ column(ownCol, (0, exports.fkType)(e, input), true),
493
+ column(otherCol, (0, exports.fkType)(target, input), true),
443
494
  ],
444
495
  });
445
496
  primaryKey(join, [ownCol, otherCol]);
@@ -447,10 +498,17 @@ function schemaModel(input) {
447
498
  index(join, [otherCol]);
448
499
  // TypeORM cascades the inverse key only when no inverse relation exists.
449
500
  const inverse = r.biDirectional ? "NO ACTION" : "CASCADE";
450
- foreignKey(join, ownCol, table, (0, exports.pkColumn)(e), "ON DELETE CASCADE ON UPDATE CASCADE");
451
- foreignKey(join, otherCol, targetTable, (0, exports.pkColumn)(target), `ON DELETE ${inverse} ON UPDATE ${inverse}`);
501
+ foreignKey(join, ownCol, table, (0, exports.pkColumn)(e, input), "ON DELETE CASCADE ON UPDATE CASCADE");
502
+ foreignKey(join, otherCol, targetTable, (0, exports.pkColumn)(target, input), `ON DELETE ${inverse} ON UPDATE ${inverse}`);
452
503
  }
453
504
  }
505
+ for (const k of (0, exports.extraForeignKeys)(e, input)) {
506
+ if (!t.columns.some((c) => c.name === k.column))
507
+ throw new Error(`${e.name} "foreignKeys" entry "${k.name}" names column "${k.column}", which ${e.name} does not have.`);
508
+ if (foreignKeys.some((c) => c.table === table && c.name === k.name))
509
+ throw new Error(`${e.name} "foreignKeys" entry "${k.name}" repeats the name of another foreign key on ${e.name}.`);
510
+ foreignKey(table, k.column, k.targetTable, k.targetColumn, (0, relationship_1.keyRulesSql)(k.onDelete, k), k.name, `fk:${table}:${k.name}`);
511
+ }
454
512
  const keyColumns = customPk
455
513
  ? [
456
514
  ...((_h = e.fields) !== null && _h !== void 0 ? _h : []).filter((f) => f.primary).map((f) => f.name),
@@ -105,7 +105,7 @@ class GoGenerator extends base_1.BaseGenerator {
105
105
  return ".go";
106
106
  }
107
107
  validateConfig(config) {
108
- var _a, _b, _c, _d, _e;
108
+ var _a, _b, _c, _d, _e, _f, _g;
109
109
  const errors = [];
110
110
  const warnings = [];
111
111
  // Validate that entities are provided
@@ -119,6 +119,9 @@ class GoGenerator extends base_1.BaseGenerator {
119
119
  if (f.generated)
120
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
121
  for (const e of (_d = config.entities) !== null && _d !== void 0 ? _d : [])
122
+ if ((_e = e.foreignKeys) === null || _e === void 0 ? void 0 : _e.length)
123
+ errors.push(`${e.name} sets "foreignKeys". The Go generator cannot declare a second foreign key on a column yet; remove it or generate a TypeScript service.`);
124
+ for (const e of (_f = config.entities) !== null && _f !== void 0 ? _f : [])
122
125
  if (e.primaryKeyName)
123
126
  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.`);
124
127
  // Validate each entity
@@ -127,7 +130,7 @@ class GoGenerator extends base_1.BaseGenerator {
127
130
  errors.push("Entity missing required 'name' property");
128
131
  }
129
132
  // Validate field types
130
- for (const field of (_e = entity.fields) !== null && _e !== void 0 ? _e : []) {
133
+ for (const field of (_g = entity.fields) !== null && _g !== void 0 ? _g : []) {
131
134
  if (!field.name) {
132
135
  errors.push(`Entity '${entity.name}' has a field without a name`);
133
136
  }
@@ -143,7 +143,7 @@ class PythonGenerator extends base_1.BaseGenerator {
143
143
  return ".py";
144
144
  }
145
145
  validateConfig(config) {
146
- var _a, _b, _c, _d, _e, _f, _g;
146
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
147
147
  const errors = [];
148
148
  const warnings = [];
149
149
  // Validate that entities are provided
@@ -160,6 +160,9 @@ class PythonGenerator extends base_1.BaseGenerator {
160
160
  if (f.generated)
161
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
162
  for (const e of (_f = config.entities) !== null && _f !== void 0 ? _f : [])
163
+ if ((_g = e.foreignKeys) === null || _g === void 0 ? void 0 : _g.length)
164
+ errors.push(`${e.name} sets "foreignKeys". The Python generator cannot declare a second foreign key on a column yet; remove it or generate a TypeScript service.`);
165
+ for (const e of (_h = config.entities) !== null && _h !== void 0 ? _h : [])
163
166
  if (e.primaryKeyName)
164
167
  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.`);
165
168
  // Validate each entity
@@ -168,7 +171,7 @@ class PythonGenerator extends base_1.BaseGenerator {
168
171
  errors.push("Entity missing required 'name' property");
169
172
  }
170
173
  // Validate field types
171
- for (const field of (_g = entity.fields) !== null && _g !== void 0 ? _g : []) {
174
+ for (const field of (_j = entity.fields) !== null && _j !== void 0 ? _j : []) {
172
175
  if (!field.name) {
173
176
  errors.push(`Entity '${entity.name}' has a field without a name`);
174
177
  }
@@ -54,7 +54,7 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
54
54
  return ".ts";
55
55
  }
56
56
  validateConfig(config) {
57
- var _a, _b;
57
+ var _a, _b, _c, _d;
58
58
  const errors = [];
59
59
  const warnings = [];
60
60
  // Validate that entities are provided
@@ -77,6 +77,17 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
77
77
  }
78
78
  }
79
79
  }
80
+ // "foreignKeys" entries are checked by the writer `apso migrate` uses.
81
+ if (((_c = config.entities) !== null && _c !== void 0 ? _c : []).some((e) => { var _a; return (_a = e.foreignKeys) === null || _a === void 0 ? void 0 : _a.length; }))
82
+ try {
83
+ (0, ddl_1.schemaModel)({
84
+ entities: config.entities,
85
+ relationshipMap: (_d = config.relationshipMap) !== null && _d !== void 0 ? _d : {},
86
+ });
87
+ }
88
+ catch (error) {
89
+ errors.push(error.message);
90
+ }
80
91
  // Validate API type
81
92
  if (config.apiType && !["rest", "graphql"].includes(config.apiType)) {
82
93
  errors.push(`Invalid API type: '${config.apiType}'. Must be 'rest' or 'graphql'`);
@@ -121,8 +132,25 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
121
132
  ...c,
122
133
  fields: c.fields.map((f) => { var _a, _b; return fieldNames.has(f) ? f : (_b = (_a = oneToOneColumns.get(f)) !== null && _a !== void 0 ? _a : joinColumns.get(f)) !== null && _b !== void 0 ? _b : f; }),
123
134
  }));
135
+ const schema = {
136
+ entities: allEntities,
137
+ relationshipMap: {
138
+ ...this.config.relationshipMap,
139
+ [name]: relationships,
140
+ },
141
+ };
142
+ const foreignKeys = (0, ddl_1.extraForeignKeys)(entity, schema).map((k) => ({
143
+ ...k,
144
+ options: [
145
+ `name: ${JSON.stringify(k.name)}`,
146
+ (0, relationship_1.keyRuleOptions)(k.onDelete, k),
147
+ ]
148
+ .filter(Boolean)
149
+ .join(", "),
150
+ }));
124
151
  const data = {
125
152
  name,
153
+ foreignKeys,
126
154
  indexes: toProperties(indexes),
127
155
  uniques: toProperties(uniques),
128
156
  checks: (_a = entity.checks) !== null && _a !== void 0 ? _a : [],
@@ -147,15 +175,21 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
147
175
  : c),
148
176
  associations: [...new Set(relationshipsForTemplate)].map((r) => {
149
177
  // A foreign key column copies the type of the key it references.
150
- const key = (0, ddl_1.keyColumn)(allEntities.find((e) => e.name === r.name));
178
+ const key = (0, ddl_1.keyColumn)(allEntities.find((e) => e.name === r.name), schema);
151
179
  return {
152
180
  ...r,
153
- onDeleteRule: (0, relationship_1.onDeleteOf)(r),
154
- fkColumnOptions: key.options,
181
+ keyRules: (0, relationship_1.keyRuleOptions)((0, relationship_1.onDeleteOf)(r), r),
182
+ // The entity spells a default the way TypeORM reads it back.
183
+ fkColumnOptions: key.options +
184
+ (r.joinColumnDefault
185
+ ? `, default: () => ${JSON.stringify((0, field_1.typeormDefault)(r.joinColumnDefault))}`
186
+ : ""),
155
187
  fkTsType: key.ts,
156
188
  };
157
189
  }),
158
- entitiesToImport,
190
+ entitiesToImport: [
191
+ ...new Set([...entitiesToImport, ...foreignKeys.map((k) => k.target)]),
192
+ ].filter((other) => other !== name),
159
193
  importEnums: (0, field_1.typeExistsInEntity)(entity, "enum") !== -1,
160
194
  apiType,
161
195
  };
@@ -318,10 +352,14 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
318
352
  const relationshipsTemplate = (0, relationships_1.getRelationshipForTemplate)(entityName, relationships);
319
353
  // Add foreign key columns for ManyToOne relationships
320
354
  relationshipsTemplate.forEach((rel) => {
355
+ var _a;
321
356
  if (rel.type === "ManyToOne") {
322
357
  const fkName = (0, casing_1.camelCase)(rel.referenceName || rel.name) + "Id";
323
358
  const referencedEntity = allEntities === null || allEntities === void 0 ? void 0 : allEntities.find((e) => e.name === rel.name);
324
- const fkDataType = (0, ddl_1.keyColumn)(referencedEntity).ts;
359
+ const fkDataType = (0, ddl_1.keyColumn)(referencedEntity, {
360
+ entities: allEntities !== null && allEntities !== void 0 ? allEntities : [],
361
+ relationshipMap: (_a = this.config.relationshipMap) !== null && _a !== void 0 ? _a : {},
362
+ }).ts;
325
363
  const fkType = fkDataType === "string" ? "text" : "integer";
326
364
  if (!columns.some((col) => col.name === fkName)) {
327
365
  columns.push({
@@ -28,7 +28,7 @@ exports.targetTableName = targetTableName;
28
28
  function buildColumnMapping(table) {
29
29
  const fkRefByColumn = new Map();
30
30
  for (const fk of table.foreignKeys) {
31
- if (fk.columns.length === 1) {
31
+ if (fk.columns.length === 1 && !fk.referencedSchema) {
32
32
  fkRefByColumn.set(fk.columns[0], fk.referencedTable);
33
33
  }
34
34
  }
@@ -60,7 +60,9 @@ function topoSortTables(tables) {
60
60
  for (const t of tables) {
61
61
  const d = new Set();
62
62
  for (const fk of t.foreignKeys) {
63
- if (fk.referencedTable !== t.name && names.has(fk.referencedTable)) {
63
+ if (!fk.referencedSchema &&
64
+ fk.referencedTable !== t.name &&
65
+ names.has(fk.referencedTable)) {
64
66
  d.add(fk.referencedTable);
65
67
  }
66
68
  }
@@ -162,12 +162,15 @@ const PRIMARY_KEYS_SQL = `
162
162
  ORDER BY cl.relname, ord.n`;
163
163
  const FOREIGN_KEYS_SQL = `
164
164
  SELECT con.conname, cl.relname AS table_name, att.attname AS column_name,
165
- clf.relname AS referenced_table, attf.attname AS referenced_column,
166
- con.confdeltype, con.convalidated, ord.n AS key_index
165
+ clf.relname AS referenced_table, nsf.nspname AS referenced_schema,
166
+ attf.attname AS referenced_column,
167
+ con.confdeltype, con.confupdtype, con.condeferrable, con.condeferred,
168
+ con.convalidated, ord.n AS key_index
167
169
  FROM pg_constraint con
168
170
  JOIN pg_class cl ON cl.oid = con.conrelid
169
171
  JOIN pg_namespace ns ON ns.oid = cl.relnamespace
170
172
  JOIN pg_class clf ON clf.oid = con.confrelid
173
+ JOIN pg_namespace nsf ON nsf.oid = clf.relnamespace
171
174
  JOIN LATERAL unnest(con.conkey) WITH ORDINALITY AS ord(attnum, n) ON true
172
175
  JOIN pg_attribute att ON att.attrelid = con.conrelid AND att.attnum = ord.attnum
173
176
  JOIN pg_attribute attf ON attf.attrelid = con.confrelid AND attf.attnum = con.confkey[ord.n]
@@ -303,33 +306,49 @@ function buildSchema(schema, raw) {
303
306
  if (row.conname)
304
307
  pkNameByTable.set(row.table_name, row.conname);
305
308
  }
306
- // Foreign keys (grouped by constraint name to handle composite keys)
309
+ // Foreign keys, grouped by table and constraint name to handle composite
310
+ // keys. Postgres keeps a key's name unique per table, not per schema.
307
311
  const fkByConstraint = new Map();
308
312
  for (const row of raw.fkRows) {
309
- const existing = fkByConstraint.get(row.conname);
313
+ const id = JSON.stringify([row.table_name, row.conname]);
314
+ const existing = fkByConstraint.get(id);
310
315
  if (existing) {
311
316
  existing.columns.push(row.column_name);
312
317
  existing.refColumns.push(row.referenced_column);
313
318
  }
314
319
  else {
315
- fkByConstraint.set(row.conname, {
320
+ fkByConstraint.set(id, {
321
+ name: row.conname,
316
322
  table: row.table_name,
317
323
  columns: [row.column_name],
318
324
  refTable: row.referenced_table,
325
+ ...(row.referenced_schema &&
326
+ row.referenced_schema !== schema && {
327
+ refSchema: row.referenced_schema,
328
+ }),
319
329
  refColumns: [row.referenced_column],
320
330
  confdeltype: row.confdeltype,
331
+ onUpdate: CONFDELTYPE_TO_ACTION[row.confupdtype],
332
+ ...(row.condeferrable === true && {
333
+ deferrable: row.condeferred
334
+ ? "INITIALLY DEFERRED"
335
+ : "INITIALLY IMMEDIATE",
336
+ }),
321
337
  notValid: row.convalidated === false,
322
338
  });
323
339
  }
324
340
  }
325
341
  const fksByTable = new Map();
326
- for (const [name, fk] of fkByConstraint.entries()) {
342
+ for (const fk of fkByConstraint.values()) {
327
343
  const list = (_j = fksByTable.get(fk.table)) !== null && _j !== void 0 ? _j : [];
328
344
  list.push({
329
- name,
345
+ name: fk.name,
330
346
  ...(fk.notValid && { notValid: true }),
347
+ ...(fk.onUpdate && fk.onUpdate !== "NO ACTION" && { onUpdate: fk.onUpdate }),
348
+ ...(fk.deferrable && { deferrable: fk.deferrable }),
331
349
  columns: fk.columns,
332
350
  referencedTable: fk.refTable,
351
+ ...(fk.refSchema && { referencedSchema: fk.refSchema }),
333
352
  referencedColumns: fk.refColumns,
334
353
  onDelete: (_k = CONFDELTYPE_TO_ACTION[fk.confdeltype]) !== null && _k !== void 0 ? _k : "NO ACTION",
335
354
  });
@@ -11,6 +11,7 @@
11
11
  * platform derives FK column names in `getRelationshipIdField`
12
12
  * (src/lib/utils/relationships/parse.ts) so imported relationships round-trip.
13
13
  */
14
+ import { KeyRules, OnDelete } from "../types/relationship";
14
15
  import { Entity } from "../types/entity";
15
16
  import { ImportReport, IntrospectedColumn, IntrospectedSchema } from "./types";
16
17
  export interface ApsorcImportFieldOutput {
@@ -48,6 +49,7 @@ export interface ApsorcImportEntityOutput {
48
49
  expression: string;
49
50
  validate?: boolean;
50
51
  }>;
52
+ foreignKeys?: Entity["foreignKeys"];
51
53
  timestampDefault?: Entity["timestampDefault"];
52
54
  sqlIndexes?: Array<{
53
55
  name: string;
@@ -70,7 +72,10 @@ export interface ApsorcImportRelationshipOutput {
70
72
  nullable?: boolean;
71
73
  bi_directional?: boolean;
72
74
  cascadeDelete?: boolean;
73
- onDelete?: "SET NULL" | "RESTRICT";
75
+ onDelete?: OnDelete;
76
+ onUpdate?: OnDelete;
77
+ deferrable?: KeyRules["deferrable"];
78
+ joinColumnDefault?: string;
74
79
  foreignKeyName?: string;
75
80
  primary?: boolean;
76
81
  validate?: boolean;
@@ -245,11 +245,11 @@ function emptyReport(schema) {
245
245
  systemSchemasSkipped: schema.skipped.systemSchemas,
246
246
  warnings: {
247
247
  arraysLossy: [],
248
+ foreignKeysNotCarried: [],
248
249
  checksNotValid: [],
249
250
  timestampDefaultsAdded: [],
250
251
  indexesNotCarried: [],
251
252
  relationshipsRenamed: [],
252
- foreignKeysNotCarried: [],
253
253
  compositePks: [],
254
254
  compositeFks: [],
255
255
  nonStandardPks: [],
@@ -274,11 +274,12 @@ function isJoinTable(table) {
274
274
  * report of everything that could not be represented losslessly.
275
275
  */
276
276
  function pgToApsorc(schema) {
277
- var _a, _b, _c;
277
+ var _a, _b, _c, _d, _e, _f;
278
278
  const report = emptyReport(schema);
279
279
  const enumLabels = new Map(schema.enums.map((e) => [e.name, e.labels]));
280
280
  const entities = [];
281
281
  const relationships = [];
282
+ const keyByTable = new Map(schema.tables.map((t) => [t.name, t.primaryKey]));
282
283
  for (const table of schema.tables) {
283
284
  report.tablesImported.push(table.name);
284
285
  if (isJoinTable(table)) {
@@ -291,14 +292,27 @@ function pgToApsorc(schema) {
291
292
  entity.primaryKeyName = table.primaryKeyName;
292
293
  // Columns covered by a single-column FK are materialized by the
293
294
  // relationship, so they must not also be emitted as scalar fields.
295
+ // A relationship, like a "foreignKeys" entry, references the primary key
296
+ // of an imported table. Any other single-column key is reported and its
297
+ // column stays a plain field.
294
298
  const fkColumns = new Map();
299
+ const singleKeys = [];
295
300
  for (const fk of table.foreignKeys) {
296
- if (fk.columns.length === 1) {
297
- fkColumns.set(fk.columns[0], fk);
298
- }
299
- else {
301
+ if (fk.columns.length !== 1) {
300
302
  report.warnings.compositeFks.push(table.name);
303
+ continue;
304
+ }
305
+ const targetKey = fk.referencedSchema
306
+ ? []
307
+ : keyByTable.get(fk.referencedTable);
308
+ if ((targetKey === null || targetKey === void 0 ? void 0 : targetKey.length) !== 1 || targetKey[0] !== fk.referencedColumns[0]) {
309
+ report.warnings.foreignKeysNotCarried.push(`${table.name}.${fk.name} (${fk.columns[0]} -> ${fk.referencedSchema ? `${fk.referencedSchema}.` : ""}${fk.referencedTable}.${fk.referencedColumns[0]})`);
310
+ continue;
301
311
  }
312
+ singleKeys.push(fk);
313
+ // The first key on a column is the relationship's.
314
+ if (!fkColumns.has(fk.columns[0]))
315
+ fkColumns.set(fk.columns[0], fk);
302
316
  }
303
317
  // --- Primary key handling ---
304
318
  const pk = table.primaryKey;
@@ -325,7 +339,7 @@ function pgToApsorc(schema) {
325
339
  // key when the column is a foreign key (a table keyed by the row it
326
340
  // extends).
327
341
  pkAsField = true;
328
- const keyIsForeignKey = table.foreignKeys.some((fk) => fk.columns.length === 1 && fk.columns[0] === pk[0]);
342
+ const keyIsForeignKey = fkColumns.has(pk[0]);
329
343
  if (!keyIsForeignKey)
330
344
  report.warnings.nonStandardPks.push(table.name);
331
345
  }
@@ -535,14 +549,19 @@ function pgToApsorc(schema) {
535
549
  entities.push(entity);
536
550
  // --- Foreign keys -> ManyToOne relationships ---
537
551
  const keyed = new Set();
538
- for (const fk of table.foreignKeys) {
539
- if (fk.columns.length !== 1)
540
- continue; // composite FK handled above
552
+ for (const fk of singleKeys) {
541
553
  const sourceColumn = fk.columns[0];
542
554
  // A relationship holds one key per column. A second key on the same
543
- // column (usually an exact duplicate) is left out and reported.
555
+ // column (usually an exact duplicate) is kept as a constraint only.
544
556
  if (keyed.has(sourceColumn)) {
545
- report.warnings.foreignKeysNotCarried.push(`${table.name}.${fk.name} (${sourceColumn} -> ${fk.referencedTable})`);
557
+ // Postgres names every constraint, so the name is always there.
558
+ ((_d = entity.foreignKeys) !== null && _d !== void 0 ? _d : (entity.foreignKeys = [])).push({
559
+ name: (_e = fk.name) !== null && _e !== void 0 ? _e : "",
560
+ column: sourceColumn,
561
+ to: fk.referencedTable,
562
+ ...(fk.onDelete !== "NO ACTION" && { onDelete: fk.onDelete }),
563
+ ...keyRules(fk),
564
+ });
546
565
  continue;
547
566
  }
548
567
  keyed.add(sourceColumn);
@@ -563,15 +582,17 @@ function pgToApsorc(schema) {
563
582
  rel.foreignKeyName = fk.name;
564
583
  if (pkSet.has(sourceColumn))
565
584
  rel.primary = true;
566
- // Migrations keep the key NOT VALID. A database built by TypeORM's own
567
- // schema sync has it validated, which only matters on an empty one.
568
- if (fk.notValid)
569
- rel.validate = false;
585
+ Object.assign(rel, keyRules(fk));
586
+ // The relationship makes the column, so it carries the default too.
587
+ if ((_f = col === null || col === void 0 ? void 0 : col.default) === null || _f === void 0 ? void 0 : _f.trim().toLowerCase().startsWith("nextval("))
588
+ report.warnings.defaultsDropped.push(`${table.name}.${col.name}`);
589
+ else if (col === null || col === void 0 ? void 0 : col.default)
590
+ rel.joinColumnDefault = col.default;
570
591
  if (col === null || col === void 0 ? void 0 : col.nullable)
571
592
  rel.nullable = true;
572
593
  if (fk.onDelete === "CASCADE")
573
594
  rel.cascadeDelete = true;
574
- else if (fk.onDelete === "SET NULL" || fk.onDelete === "RESTRICT")
595
+ else if (fk.onDelete !== "NO ACTION")
575
596
  rel.onDelete = fk.onDelete;
576
597
  relationships.push(rel);
577
598
  }
@@ -589,6 +610,20 @@ function pgToApsorc(schema) {
589
610
  };
590
611
  }
591
612
  exports.pgToApsorc = pgToApsorc;
613
+ /**
614
+ * A source key's ON UPDATE rule, DEFERRABLE setting and NOT VALID mark, as
615
+ * .apsorc states them on a relationship or a "foreignKeys" entry.
616
+ * Migrations keep a key NOT VALID. A database built by TypeORM's own schema
617
+ * sync has it validated, which only matters on an empty one.
618
+ *
619
+ * @param {IntrospectedFk} fk - The key as read from the source database.
620
+ * @returns {KeyRules} Only the settings that differ from the defaults.
621
+ */
622
+ const keyRules = (fk) => ({
623
+ ...(fk.onUpdate && { onUpdate: fk.onUpdate }),
624
+ ...(fk.deferrable && { deferrable: fk.deferrable }),
625
+ ...(fk.notValid && { validate: false }),
626
+ });
592
627
  /**
593
628
  * Invariant guard: every emitted field type must be a recognized `.apsorc`
594
629
  * column type, so code generation never silently falls back to varchar.
@@ -36,9 +36,15 @@ export interface IntrospectedFk {
36
36
  notValid?: boolean;
37
37
  /** The constraint's name in the source database. */
38
38
  name?: string;
39
+ /** The key's ON UPDATE rule, when it is not NO ACTION. */
40
+ onUpdate?: OnDeleteAction;
41
+ /** Set when the key is DEFERRABLE: when it is checked. */
42
+ deferrable?: "INITIALLY IMMEDIATE" | "INITIALLY DEFERRED";
39
43
  /** Local column(s) participating in the FK. */
40
44
  columns: string[];
41
45
  referencedTable: string;
46
+ /** The referenced table's schema, when it is not the imported one. */
47
+ referencedSchema?: string;
42
48
  referencedColumns: string[];
43
49
  onDelete: OnDeleteAction;
44
50
  }
@@ -117,6 +123,12 @@ export interface ImportReport {
117
123
  warnings: {
118
124
  /** "table.column" arrays whose element type is unknown, imported as text[]. */
119
125
  arraysLossy: string[];
126
+ /**
127
+ * "table.constraint (column -> target.column)" for a foreign key that
128
+ * does not reference the primary key of an imported table. The column is
129
+ * kept as a plain field and the key is left out of .apsorc.
130
+ */
131
+ foreignKeysNotCarried: string[];
120
132
  /** "table.constraint" for CHECK constraints marked NOT VALID in the source. */
121
133
  checksNotValid: string[];
122
134
  /**
@@ -129,11 +141,6 @@ export interface ImportReport {
129
141
  * the table has a column of that name. The column itself is unchanged.
130
142
  */
131
143
  relationshipsRenamed: string[];
132
- /**
133
- * "table.constraint (column -> target)" for a foreign key on a column
134
- * that already has one. Only the first is imported.
135
- */
136
- foreignKeysNotCarried: string[];
137
144
  /**
138
145
  * Indexes .apsorc cannot express, as Postgres defines them: an expression
139
146
  * or DESC index that is not a btree. They are left out.
@@ -157,6 +157,10 @@ function buildEntityClasses(entities, relationshipMap = {}) {
157
157
  if ((0, relationship_1.onDeleteOf)(relationship)) {
158
158
  relationOptions.onDelete = (0, relationship_1.onDeleteOf)(relationship);
159
159
  }
160
+ if (relationship.onUpdate)
161
+ relationOptions.onUpdate = relationship.onUpdate;
162
+ if (relationship.deferrable)
163
+ relationOptions.deferrable = relationship.deferrable;
160
164
  if (relationship.type === "ManyToOne") {
161
165
  if (relationship.index) {
162
166
  typeorm.Index()(EntityClass.prototype, relationship.relationshipName);
@@ -23,6 +23,9 @@ import {
23
23
  Index,
24
24
  Unique,
25
25
  Check,
26
+ <% if (it.foreignKeys.length > 0) { %>
27
+ ForeignKey,
28
+ <% } %>
26
29
  PrimaryColumn
27
30
  } from "typeorm";
28
31
  import {
@@ -58,6 +61,9 @@ const { CREATE, UPDATE } = CrudValidationGroups;
58
61
  <% it.checks.forEach((check) => { %>
59
62
  @Check(<% if (check.name) { %><%~ JSON.stringify(check.name) %>, <% } %><%~ JSON.stringify(check.expression) %>)
60
63
  <% }) %>
64
+ <% it.foreignKeys.forEach((key) => { %>
65
+ @ForeignKey(() => <%= key.target %>, [<%~ JSON.stringify(key.column) %>], [<%~ JSON.stringify(key.targetColumn) %>], { <%~ key.options %> })
66
+ <% }) %>
61
67
  <% it.uniques.forEach((unique) => { %>
62
68
  @Unique(<% if (unique.name) {%> "<%= unique.name %>", <%} %>[<%~ unique.fields.map((field) => `"${field}"`).join(', ') %>])
63
69
  <% }) %>
@@ -130,7 +136,7 @@ const columnCode = includeFile(`./entities/entity-col-${field.type}`, { field })
130
136
  <% if (assoc.index) { %>
131
137
  @Index()
132
138
  <% } %>
133
- @ManyToOne(() => <%= assoc.name %><% if (assoc.biDirectional) { %>, <%= assoc.camelCasedName %> => <%= assoc.camelCasedName %>.<%= assoc.inverseSidePropertyName %><% } %><% if (assoc.onDeleteRule) { %>, { onDelete: "<%= assoc.onDeleteRule %>" }<% } %>)
139
+ @ManyToOne(() => <%= assoc.name %><% if (assoc.biDirectional) { %>, <%= assoc.camelCasedName %> => <%= assoc.camelCasedName %>.<%= assoc.inverseSidePropertyName %><% } %><% if (assoc.keyRules) { %>, { <%~ assoc.keyRules %> }<% } %>)
134
140
  @JoinColumn({ name: '<%= assoc.joinColumnName || assoc.camelCasedId %>'<% if (assoc.foreignKeyName) { %>, foreignKeyConstraintName: '<%= assoc.foreignKeyName %>'<% } %> })
135
141
  <%= assoc.relationshipName %>: <%= assoc.name %>;
136
142
 
@@ -1,3 +1,4 @@
1
+ import { Deferrable, OnDelete } from "./relationship";
1
2
  export interface Unique {
2
3
  fields: string[];
3
4
  name?: string;
@@ -15,3 +16,21 @@ export interface Check {
15
16
  */
16
17
  validate?: boolean;
17
18
  }
19
+ /**
20
+ * A foreign key beyond the one a relationship makes, for a column that has
21
+ * more than one. It is a database constraint only: no relation property.
22
+ */
23
+ export interface ExtraForeignKey {
24
+ name: string;
25
+ /** The column's database name. */
26
+ column: string;
27
+ /** The entity it references, by its primary key. */
28
+ to: string;
29
+ onDelete?: OnDelete;
30
+ /** The key's ON UPDATE rule. Defaults to NO ACTION. */
31
+ onUpdate?: OnDelete;
32
+ /** Makes the key DEFERRABLE, checked as the value says. */
33
+ deferrable?: Deferrable;
34
+ /** False keeps the key NOT VALID in migrations, as on a relationship. */
35
+ validate?: boolean;
36
+ }
@@ -1,4 +1,4 @@
1
- import { Unique, Check } from "./constraints";
1
+ import { Unique, Check, ExtraForeignKey } from "./constraints";
2
2
  import { Field } from "./field";
3
3
  import { Index, SqlIndex } from "./indices";
4
4
  import { Association } from "./relationship";
@@ -98,6 +98,8 @@ export interface Entity {
98
98
  uniques?: Unique[];
99
99
  /** CHECK constraints, for example "end_date >= start_date". */
100
100
  checks?: Check[];
101
+ /** A second foreign key on a column that a relationship already keys. */
102
+ foreignKeys?: ExtraForeignKey[];
101
103
  /**
102
104
  * Fields or paths that define the authorization scope for this entity.
103
105
  * Can be a single field name (e.g., 'workspaceId') or an array of fields/paths
@@ -1,6 +1,33 @@
1
1
  export type RelationshipType = "OneToMany" | "ManyToOne" | "ManyToMany" | "OneToOne";
2
2
  /** A foreign key's ON DELETE rule. "cascadeDelete": true is "CASCADE". */
3
- export type OnDelete = "CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION";
3
+ export type OnDelete = "CASCADE" | "SET NULL" | "SET DEFAULT" | "RESTRICT" | "NO ACTION";
4
+ /** When a DEFERRABLE foreign key is checked: per statement, or at commit. */
5
+ export type Deferrable = "INITIALLY IMMEDIATE" | "INITIALLY DEFERRED";
6
+ /** The rules of a foreign key beyond the column and the table it references. */
7
+ export interface KeyRules {
8
+ /** The key's ON UPDATE rule. Defaults to NO ACTION. */
9
+ onUpdate?: OnDelete;
10
+ /** Makes the key DEFERRABLE, checked as the value says. */
11
+ deferrable?: Deferrable;
12
+ /** false keeps the key NOT VALID. Only migrations can create it that way. */
13
+ validate?: boolean;
14
+ }
15
+ /**
16
+ * A foreign key's rules as SQL writes them after REFERENCES.
17
+ *
18
+ * @param {OnDelete | undefined} onDelete - The ON DELETE rule, if not the default.
19
+ * @param {KeyRules} k - The key's other rules.
20
+ * @returns {string} "ON DELETE ... ON UPDATE ..." and what follows.
21
+ */
22
+ export declare const keyRulesSql: (onDelete: OnDelete | undefined, k: KeyRules) => string;
23
+ /**
24
+ * A foreign key's rules as TypeORM options, without the braces.
25
+ *
26
+ * @param {OnDelete | undefined} onDelete - The ON DELETE rule, if not the default.
27
+ * @param {KeyRules} k - The key's other rules.
28
+ * @returns {string} For example `onDelete: "CASCADE", onUpdate: "CASCADE"`.
29
+ */
30
+ export declare const keyRuleOptions: (onDelete: OnDelete | undefined, k: KeyRules) => string;
4
31
  /**
5
32
  * The ON DELETE rule of a ManyToOne's foreign key, undefined for the
6
33
  * database default (NO ACTION).
@@ -21,6 +48,12 @@ export interface ApsorcRelationship {
21
48
  bi_directional?: boolean;
22
49
  cascadeDelete?: boolean;
23
50
  onDelete?: OnDelete;
51
+ /** The foreign key's ON UPDATE rule. Defaults to NO ACTION. */
52
+ onUpdate?: OnDelete;
53
+ /** Makes the foreign key DEFERRABLE, checked as the value says. */
54
+ deferrable?: Deferrable;
55
+ /** The foreign key column's DEFAULT, as a SQL expression. */
56
+ joinColumnDefault?: string;
24
57
  /** Name of the foreign key constraint; defaults to the name TypeORM derives. */
25
58
  foreignKeyName?: string;
26
59
  /** The foreign key column is (part of) the entity's primary key. */
@@ -44,6 +77,12 @@ export interface Relationship {
44
77
  biDirectional?: boolean;
45
78
  cascadeDelete?: boolean;
46
79
  onDelete?: OnDelete;
80
+ /** The foreign key's ON UPDATE rule. Defaults to NO ACTION. */
81
+ onUpdate?: OnDelete;
82
+ /** Makes the foreign key DEFERRABLE, checked as the value says. */
83
+ deferrable?: Deferrable;
84
+ /** The foreign key column's DEFAULT, as a SQL expression. */
85
+ joinColumnDefault?: string;
47
86
  /** Name of the foreign key constraint; defaults to the name TypeORM derives. */
48
87
  foreignKeyName?: string;
49
88
  /** The foreign key column is (part of) the entity's primary key. */
@@ -1,6 +1,39 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.onDeleteOf = void 0;
3
+ exports.onDeleteOf = exports.keyRuleOptions = exports.keyRulesSql = void 0;
4
+ /**
5
+ * A foreign key's rules as SQL writes them after REFERENCES.
6
+ *
7
+ * @param {OnDelete | undefined} onDelete - The ON DELETE rule, if not the default.
8
+ * @param {KeyRules} k - The key's other rules.
9
+ * @returns {string} "ON DELETE ... ON UPDATE ..." and what follows.
10
+ */
11
+ const keyRulesSql = (onDelete, k) => {
12
+ var _a;
13
+ return `ON DELETE ${onDelete !== null && onDelete !== void 0 ? onDelete : "NO ACTION"} ON UPDATE ${(_a = k.onUpdate) !== null && _a !== void 0 ? _a : "NO ACTION"}${k.deferrable ? ` DEFERRABLE ${k.deferrable}` : ""}${k.validate === false ? " NOT VALID" : ""}`;
14
+ };
15
+ exports.keyRulesSql = keyRulesSql;
16
+ /**
17
+ * A foreign key's rules as TypeORM options, without the braces.
18
+ *
19
+ * @param {OnDelete | undefined} onDelete - The ON DELETE rule, if not the default.
20
+ * @param {KeyRules} k - The key's other rules.
21
+ * @returns {string} For example `onDelete: "CASCADE", onUpdate: "CASCADE"`.
22
+ */
23
+ const keyRuleOptions = (onDelete, k) => {
24
+ // TypeORM types the rule "DEFAULT" and writes whatever it is given into
25
+ // the SQL, where Postgres needs "SET DEFAULT".
26
+ const rule = (r) => r === "SET DEFAULT" ? '"SET DEFAULT" as never' : JSON.stringify(r);
27
+ const onUpdate = k.onUpdate === "NO ACTION" ? undefined : k.onUpdate;
28
+ return [
29
+ onDelete && `onDelete: ${rule(onDelete)}`,
30
+ onUpdate && `onUpdate: ${rule(onUpdate)}`,
31
+ k.deferrable && `deferrable: ${JSON.stringify(k.deferrable)}`,
32
+ ]
33
+ .filter(Boolean)
34
+ .join(", ");
35
+ };
36
+ exports.keyRuleOptions = keyRuleOptions;
4
37
  /**
5
38
  * The ON DELETE rule of a ManyToOne's foreign key, undefined for the
6
39
  * database default (NO ACTION).
@@ -267,6 +267,13 @@ isOwner // Is the 'from' side the owner?
267
267
  * @returns A RelationshipMap, potentially containing entries for both entities involved in the relationship.
268
268
  */
269
269
  const parseRelationship = (relationship, allRelationships) => {
270
+ // These describe the one foreign key of a ManyToOne, or of the OneToMany
271
+ // that mirrors it. Anywhere else they would be dropped without a word.
272
+ if (relationship.type !== "ManyToOne" && relationship.type !== "OneToMany") {
273
+ const set = ["onUpdate", "deferrable", "joinColumnDefault"].find((key) => relationship[key] !== undefined);
274
+ if (set)
275
+ throw new Error(`${relationship.from} ${relationship.type} ${relationship.to} sets "${set}", which only a ManyToOne or OneToMany takes.`);
276
+ }
270
277
  if (relationship.type === "ManyToMany") {
271
278
  return (0, exports.parseManyToMany)(relationship, allRelationships);
272
279
  }
@@ -299,6 +306,9 @@ const parseRelationship = (relationship, allRelationships) => {
299
306
  foreignKeyName: relationship.foreignKeyName,
300
307
  primary: relationship.primary,
301
308
  validate: relationship.validate,
309
+ onUpdate: relationship.onUpdate,
310
+ deferrable: relationship.deferrable,
311
+ joinColumnDefault: relationship.joinColumnDefault,
302
312
  },
303
313
  ],
304
314
  };
@@ -321,11 +331,15 @@ const parseRelationship = (relationship, allRelationships) => {
321
331
  referenceName: manySideRefName,
322
332
  nullable: relationship.nullable || false,
323
333
  index: relationship.index || false,
334
+ cascadeDelete: relationship.cascadeDelete,
324
335
  joinColumnName: relationship.joinColumnName,
325
336
  onDelete: relationship.onDelete,
326
337
  foreignKeyName: relationship.foreignKeyName,
327
338
  primary: relationship.primary,
328
339
  validate: relationship.validate,
340
+ onUpdate: relationship.onUpdate,
341
+ deferrable: relationship.deferrable,
342
+ joinColumnDefault: relationship.joinColumnDefault,
329
343
  },
330
344
  ],
331
345
  };
@@ -346,6 +360,9 @@ const parseRelationship = (relationship, allRelationships) => {
346
360
  foreignKeyName: relationship.foreignKeyName,
347
361
  primary: relationship.primary,
348
362
  validate: relationship.validate,
363
+ onUpdate: relationship.onUpdate,
364
+ deferrable: relationship.deferrable,
365
+ joinColumnDefault: relationship.joinColumnDefault,
349
366
  },
350
367
  ],
351
368
  [relationship.to]: [
@@ -697,6 +714,14 @@ const joinColumnErrors = (relationshipMap, language) => Object.entries(relations
697
714
  ]
698
715
  : []),
699
716
  ...keyAndNameErrors(entity, r, language),
717
+ ...(r.onUpdate ||
718
+ r.deferrable ||
719
+ r.joinColumnDefault ||
720
+ r.onDelete === "SET DEFAULT"
721
+ ? [
722
+ `${entity} ${r.type} ${r.name} sets "onUpdate", "deferrable", "joinColumnDefault" or "SET DEFAULT". The ${language} generator cannot keep those foreign key settings yet; remove them or generate a TypeScript service.`,
723
+ ]
724
+ : []),
700
725
  ]));
701
726
  exports.joinColumnErrors = joinColumnErrors;
702
727
  const keyAndNameErrors = (entity, r, language) => ["joinColumnName", "foreignKeyName", "primary"]
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@apso/cli",
3
- "version": "0.54.0",
3
+ "version": "0.56.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@apso/cli",
9
- "version": "0.54.0",
9
+ "version": "0.56.0",
10
10
  "license": "Apache-2.0",
11
11
  "dependencies": {
12
12
  "@apso/schema-tools": "^0.2.3",
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.54.0",
2
+ "version": "0.56.0",
3
3
  "commands": {
4
4
  "config": {
5
5
  "id": "config",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@apso/cli",
3
- "version": "0.54.0",
3
+ "version": "0.56.0",
4
4
  "mcpName": "io.github.apsoai/apso",
5
5
  "description": "Apso CLI",
6
6
  "author": "Apso by Mavric - @mavric",