@apso/cli 0.55.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.
@@ -59,7 +59,7 @@ function formatReport(report) {
59
59
  if (w.noPrimaryKey.length > 0)
60
60
  review.push(` - Tables with no primary key: ${w.noPrimaryKey.join(", ")}`);
61
61
  if (w.foreignKeysNotCarried.length > 0)
62
- review.push(` - Second foreign keys on a column left out (the target table was not imported, the key points at a column that is not the target's primary key, or it has an ON UPDATE, SET DEFAULT or DEFERRABLE rule): ${w.foreignKeysNotCarried.join(", ")}`);
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(", ")}`);
63
63
  if (w.compositeFks.length > 0)
64
64
  review.push(` - Composite foreign keys (kept as columns, no relationship): ${w.compositeFks.join(", ")}`);
65
65
  if (w.joinTablesDetected.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,7 +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 |
1035
- | foreignKeys | entity | A second foreign key on a column, as \`{ name, column, to, onDelete?, validate? }\`. A database constraint only; \`apso import\` writes it when a column has two keys. 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 |
1036
1039
 
1037
1040
  In \`indexes\` and \`uniques\`, a foreign key may be named by its relationship (\`patient\`), its id property (\`patientId\`) or its column (\`patient_id\`).
1038
1041
  `;
@@ -94,22 +94,25 @@ 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
@@ -119,17 +122,19 @@ export declare const fkType: (target?: Entity) => string;
119
122
  * An entity's "foreignKeys" entries with the table and key column each one
120
123
  * references.
121
124
  * @param {Entity} e - The entity.
122
- * @param {Map<string, Entity>} byName - Every entity by name.
125
+ * @param {SchemaInput} schema - The schema the entity is in.
123
126
  * @returns {Array} One resolved entry per key.
124
127
  */
125
- export declare const extraForeignKeys: (e: Entity, byName: Map<string, Entity>) => {
128
+ export declare const extraForeignKeys: (e: Entity, schema: SchemaInput) => {
126
129
  target: string;
127
130
  targetTable: string;
128
131
  targetColumn: string;
129
132
  name: string;
130
133
  column: string;
131
134
  to: string;
132
- onDelete?: "CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION" | undefined;
135
+ onDelete?: import("../types/relationship").OnDelete | undefined;
136
+ onUpdate?: import("../types/relationship").OnDelete | undefined;
137
+ deferrable?: import("../types/relationship").Deferrable | undefined;
133
138
  validate?: boolean | undefined;
134
139
  }[];
135
140
  export declare const relationColumn: (r: RelationshipForTemplate) => string;
@@ -143,7 +148,7 @@ export declare const relationColumn: (r: RelationshipForTemplate) => string;
143
148
  */
144
149
  export declare const relationColumns: (relationships: RelationshipForTemplate[]) => Map<string, string>;
145
150
  /** The join table of an owning ManyToMany and its two key columns. */
146
- export declare const joinTableOf: (e: Entity, r: RelationshipForTemplate, target: Entity) => {
151
+ export declare const joinTableOf: (e: Entity, r: RelationshipForTemplate, target: Entity, schema?: SchemaInput) => {
147
152
  name: string;
148
153
  ownCol: string;
149
154
  otherCol: string;
@@ -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,7 +254,7 @@ 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:
@@ -238,21 +265,21 @@ exports.fkType = fkType;
238
265
  * An entity's "foreignKeys" entries with the table and key column each one
239
266
  * references.
240
267
  * @param {Entity} e - The entity.
241
- * @param {Map<string, Entity>} byName - Every entity by name.
268
+ * @param {SchemaInput} schema - The schema the entity is in.
242
269
  * @returns {Array} One resolved entry per key.
243
270
  */
244
- const extraForeignKeys = (e, byName) => {
271
+ const extraForeignKeys = (e, schema) => {
245
272
  var _a;
246
273
  return ((_a = e.foreignKeys) !== null && _a !== void 0 ? _a : []).map((k) => {
247
274
  var _a;
248
- const target = byName.get(k.to);
275
+ const target = schema.entities.find((x) => x.name === k.to);
249
276
  if (!k.name || !k.column || !target)
250
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.`);
251
278
  return {
252
279
  ...k,
253
280
  target: target.name,
254
281
  targetTable: (0, exports.tableName)(target),
255
- targetColumn: (0, exports.pkColumn)(target),
282
+ targetColumn: (0, exports.pkColumn)(target, schema),
256
283
  };
257
284
  });
258
285
  };
@@ -282,20 +309,21 @@ const relationColumns = (relationships) => {
282
309
  };
283
310
  exports.relationColumns = relationColumns;
284
311
  /** The join table of an owning ManyToMany and its two key columns. */
285
- const joinTableOf = (e, r, target) => {
312
+ const joinTableOf = (e, r, target, schema) => {
286
313
  const table = (0, exports.tableName)(e);
287
314
  const targetTable = (0, exports.tableName)(target);
288
315
  return {
289
316
  name: r.joinTableName ||
290
317
  typeormCase.snakeCase(`${table}_${r.pluralizedRelationshipName}_${targetTable}`),
291
- ownCol: r.joinColumnName || typeormCase.camelCase(`${table}_${(0, exports.pkColumn)(e)}`),
318
+ ownCol: r.joinColumnName ||
319
+ typeormCase.camelCase(`${table}_${(0, exports.pkColumn)(e, schema)}`),
292
320
  otherCol: r.inverseJoinColumnName ||
293
- typeormCase.camelCase(`${targetTable}_${(0, exports.pkColumn)(target)}`),
321
+ typeormCase.camelCase(`${targetTable}_${(0, exports.pkColumn)(target, schema)}`),
294
322
  };
295
323
  };
296
324
  exports.joinTableOf = joinTableOf;
297
325
  function schemaModel(input) {
298
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
326
+ var _a, _b, _c, _d, _e, _f, _g, _h;
299
327
  const { entities, relationshipMap } = input;
300
328
  const byName = new Map(entities.map((e) => [e.name, e]));
301
329
  const model = {
@@ -447,22 +475,22 @@ function schemaModel(input) {
447
475
  const onDelete = oneToOne ? "CASCADE" : (_g = (0, relationship_1.onDeleteOf)(r)) !== null && _g !== void 0 ? _g : "NO ACTION";
448
476
  if (r.type === "ManyToOne" || (oneToOne && r.joinTable)) {
449
477
  const col = (0, exports.relationColumn)(r);
450
- 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));
451
479
  if (oneToOne)
452
480
  unique(table, [col], exports.constraintName.relation(table, [col]));
453
481
  if (r.type === "ManyToOne" && r.index)
454
482
  index(table, [col]);
455
- foreignKey(table, col, targetTable, (0, exports.pkColumn)(target),
483
+ foreignKey(table, col, targetTable, (0, exports.pkColumn)(target, input),
456
484
  // NOT VALID exists only on a key added by ALTER TABLE, as these are.
457
- `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);
458
486
  }
459
487
  if (r.type === "ManyToMany" && r.joinTable) {
460
- const { name: join, ownCol, otherCol } = (0, exports.joinTableOf)(e, r, target);
488
+ const { name: join, ownCol, otherCol } = (0, exports.joinTableOf)(e, r, target, input);
461
489
  joinTables.push({
462
490
  name: join,
463
491
  columns: [
464
- column(ownCol, (0, exports.fkType)(e), true),
465
- 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),
466
494
  ],
467
495
  });
468
496
  primaryKey(join, [ownCol, otherCol]);
@@ -470,20 +498,20 @@ function schemaModel(input) {
470
498
  index(join, [otherCol]);
471
499
  // TypeORM cascades the inverse key only when no inverse relation exists.
472
500
  const inverse = r.biDirectional ? "NO ACTION" : "CASCADE";
473
- foreignKey(join, ownCol, table, (0, exports.pkColumn)(e), "ON DELETE CASCADE ON UPDATE CASCADE");
474
- 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}`);
475
503
  }
476
504
  }
477
- for (const k of (0, exports.extraForeignKeys)(e, byName)) {
505
+ for (const k of (0, exports.extraForeignKeys)(e, input)) {
478
506
  if (!t.columns.some((c) => c.name === k.column))
479
507
  throw new Error(`${e.name} "foreignKeys" entry "${k.name}" names column "${k.column}", which ${e.name} does not have.`);
480
508
  if (foreignKeys.some((c) => c.table === table && c.name === k.name))
481
509
  throw new Error(`${e.name} "foreignKeys" entry "${k.name}" repeats the name of another foreign key on ${e.name}.`);
482
- foreignKey(table, k.column, k.targetTable, k.targetColumn, `ON DELETE ${(_h = k.onDelete) !== null && _h !== void 0 ? _h : "NO ACTION"} ON UPDATE NO ACTION${k.validate === false ? " NOT VALID" : ""}`, k.name, `fk:${table}:${k.name}`);
510
+ foreignKey(table, k.column, k.targetTable, k.targetColumn, (0, relationship_1.keyRulesSql)(k.onDelete, k), k.name, `fk:${table}:${k.name}`);
483
511
  }
484
512
  const keyColumns = customPk
485
513
  ? [
486
- ...((_j = e.fields) !== null && _j !== void 0 ? _j : []).filter((f) => f.primary).map((f) => f.name),
514
+ ...((_h = e.fields) !== null && _h !== void 0 ? _h : []).filter((f) => f.primary).map((f) => f.name),
487
515
  ...relationKeys,
488
516
  ]
489
517
  : ["id"];
@@ -132,7 +132,22 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
132
132
  ...c,
133
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; }),
134
134
  }));
135
- const foreignKeys = (0, ddl_1.extraForeignKeys)(entity, new Map(allEntities.map((e) => [e.name, e])));
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
+ }));
136
151
  const data = {
137
152
  name,
138
153
  foreignKeys,
@@ -160,11 +175,15 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
160
175
  : c),
161
176
  associations: [...new Set(relationshipsForTemplate)].map((r) => {
162
177
  // A foreign key column copies the type of the key it references.
163
- 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);
164
179
  return {
165
180
  ...r,
166
- onDeleteRule: (0, relationship_1.onDeleteOf)(r),
167
- 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
+ : ""),
168
187
  fkTsType: key.ts,
169
188
  };
170
189
  }),
@@ -333,10 +352,14 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
333
352
  const relationshipsTemplate = (0, relationships_1.getRelationshipForTemplate)(entityName, relationships);
334
353
  // Add foreign key columns for ManyToOne relationships
335
354
  relationshipsTemplate.forEach((rel) => {
355
+ var _a;
336
356
  if (rel.type === "ManyToOne") {
337
357
  const fkName = (0, casing_1.camelCase)(rel.referenceName || rel.name) + "Id";
338
358
  const referencedEntity = allEntities === null || allEntities === void 0 ? void 0 : allEntities.find((e) => e.name === rel.name);
339
- 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;
340
363
  const fkType = fkDataType === "string" ? "text" : "integer";
341
364
  if (!columns.some((col) => col.name === fkName)) {
342
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,13 +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.confupdtype, con.condeferrable,
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,
167
168
  con.convalidated, ord.n AS key_index
168
169
  FROM pg_constraint con
169
170
  JOIN pg_class cl ON cl.oid = con.conrelid
170
171
  JOIN pg_namespace ns ON ns.oid = cl.relnamespace
171
172
  JOIN pg_class clf ON clf.oid = con.confrelid
173
+ JOIN pg_namespace nsf ON nsf.oid = clf.relnamespace
172
174
  JOIN LATERAL unnest(con.conkey) WITH ORDINALITY AS ord(attnum, n) ON true
173
175
  JOIN pg_attribute att ON att.attrelid = con.conrelid AND att.attnum = ord.attnum
174
176
  JOIN pg_attribute attf ON attf.attrelid = con.confrelid AND attf.attnum = con.confkey[ord.n]
@@ -254,7 +256,7 @@ const SCHEMAS_SQL = `SELECT schema_name FROM information_schema.schemata`;
254
256
  * the DB connection) so it can be unit-tested with fixture rows.
255
257
  */
256
258
  function buildSchema(schema, raw) {
257
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
259
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
258
260
  // Enums
259
261
  const enumMap = new Map();
260
262
  for (const row of raw.enumRows) {
@@ -320,24 +322,35 @@ function buildSchema(schema, raw) {
320
322
  table: row.table_name,
321
323
  columns: [row.column_name],
322
324
  refTable: row.referenced_table,
325
+ ...(row.referenced_schema &&
326
+ row.referenced_schema !== schema && {
327
+ refSchema: row.referenced_schema,
328
+ }),
323
329
  refColumns: [row.referenced_column],
324
330
  confdeltype: row.confdeltype,
325
- lossy: ((_j = row.confupdtype) !== null && _j !== void 0 ? _j : "a") !== "a" || row.condeferrable === true,
331
+ onUpdate: CONFDELTYPE_TO_ACTION[row.confupdtype],
332
+ ...(row.condeferrable === true && {
333
+ deferrable: row.condeferred
334
+ ? "INITIALLY DEFERRED"
335
+ : "INITIALLY IMMEDIATE",
336
+ }),
326
337
  notValid: row.convalidated === false,
327
338
  });
328
339
  }
329
340
  }
330
341
  const fksByTable = new Map();
331
342
  for (const fk of fkByConstraint.values()) {
332
- const list = (_k = fksByTable.get(fk.table)) !== null && _k !== void 0 ? _k : [];
343
+ const list = (_j = fksByTable.get(fk.table)) !== null && _j !== void 0 ? _j : [];
333
344
  list.push({
334
345
  name: fk.name,
335
346
  ...(fk.notValid && { notValid: true }),
336
- ...(fk.lossy && { otherActions: true }),
347
+ ...(fk.onUpdate && fk.onUpdate !== "NO ACTION" && { onUpdate: fk.onUpdate }),
348
+ ...(fk.deferrable && { deferrable: fk.deferrable }),
337
349
  columns: fk.columns,
338
350
  referencedTable: fk.refTable,
351
+ ...(fk.refSchema && { referencedSchema: fk.refSchema }),
339
352
  referencedColumns: fk.refColumns,
340
- onDelete: (_l = CONFDELTYPE_TO_ACTION[fk.confdeltype]) !== null && _l !== void 0 ? _l : "NO ACTION",
353
+ onDelete: (_k = CONFDELTYPE_TO_ACTION[fk.confdeltype]) !== null && _k !== void 0 ? _k : "NO ACTION",
341
354
  });
342
355
  fksByTable.set(fk.table, list);
343
356
  }
@@ -355,14 +368,14 @@ function buildSchema(schema, raw) {
355
368
  }
356
369
  const uniquesByTable = new Map();
357
370
  for (const [name, uc] of uniqueByConstraint.entries()) {
358
- const list = (_m = uniquesByTable.get(uc.table)) !== null && _m !== void 0 ? _m : [];
371
+ const list = (_l = uniquesByTable.get(uc.table)) !== null && _l !== void 0 ? _l : [];
359
372
  list.push({ name, columns: uc.columns });
360
373
  uniquesByTable.set(uc.table, list);
361
374
  }
362
375
  // Indexes (grouped by index name)
363
376
  const indexByName = new Map();
364
377
  for (const row of raw.indexRows) {
365
- const idx = (_o = indexByName.get(row.index_name)) !== null && _o !== void 0 ? _o : {
378
+ const idx = (_m = indexByName.get(row.index_name)) !== null && _m !== void 0 ? _m : {
366
379
  table: row.table_name,
367
380
  name: row.index_name,
368
381
  columns: [],
@@ -385,7 +398,7 @@ function buildSchema(schema, raw) {
385
398
  }
386
399
  const indexesByTable = new Map();
387
400
  for (const { table, ...idx } of indexByName.values()) {
388
- indexesByTable.set(table, [...((_p = indexesByTable.get(table)) !== null && _p !== void 0 ? _p : []), idx]);
401
+ indexesByTable.set(table, [...((_o = indexesByTable.get(table)) !== null && _o !== void 0 ? _o : []), idx]);
389
402
  }
390
403
  const tables = baseTables.map((name) => {
391
404
  var _a, _b, _c, _d, _e, _f;
@@ -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 {
@@ -71,7 +72,10 @@ export interface ApsorcImportRelationshipOutput {
71
72
  nullable?: boolean;
72
73
  bi_directional?: boolean;
73
74
  cascadeDelete?: boolean;
74
- onDelete?: "SET NULL" | "RESTRICT";
75
+ onDelete?: OnDelete;
76
+ onUpdate?: OnDelete;
77
+ deferrable?: KeyRules["deferrable"];
78
+ joinColumnDefault?: string;
75
79
  foreignKeyName?: string;
76
80
  primary?: boolean;
77
81
  validate?: boolean;
@@ -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, _d, _e;
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,36 +549,18 @@ 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
555
  // column (usually an exact duplicate) is kept as a constraint only.
544
556
  if (keyed.has(sourceColumn)) {
545
- const known = ["CASCADE", "SET NULL", "RESTRICT"];
546
- const onDelete = known.find((rule) => rule === fk.onDelete);
547
- // An entry references the target's primary key and states ON DELETE
548
- // only. A key it cannot state exactly is reported, not written.
549
- const target = schema.tables.find((t) => t.name === fk.referencedTable);
550
- const targetKey = target === null || target === void 0 ? void 0 : target.primaryKey;
551
- if ((targetKey === null || targetKey === void 0 ? void 0 : targetKey.length) !== 1 ||
552
- targetKey[0] !== fk.referencedColumns[0] ||
553
- (
554
- // A key that is itself a foreign key belongs to a relationship.
555
- target === null || target === void 0 ? void 0 : target.foreignKeys.some((k) => k.columns.includes(targetKey[0]))) ||
556
- fk.onDelete === "SET DEFAULT" ||
557
- fk.otherActions) {
558
- report.warnings.foreignKeysNotCarried.push(`${table.name}.${fk.name} (${sourceColumn} -> ${fk.referencedTable})`);
559
- continue;
560
- }
561
557
  // Postgres names every constraint, so the name is always there.
562
558
  ((_d = entity.foreignKeys) !== null && _d !== void 0 ? _d : (entity.foreignKeys = [])).push({
563
559
  name: (_e = fk.name) !== null && _e !== void 0 ? _e : "",
564
560
  column: sourceColumn,
565
561
  to: fk.referencedTable,
566
- ...(onDelete && { onDelete }),
567
- ...(fk.notValid && { validate: false }),
562
+ ...(fk.onDelete !== "NO ACTION" && { onDelete: fk.onDelete }),
563
+ ...keyRules(fk),
568
564
  });
569
565
  continue;
570
566
  }
@@ -586,15 +582,17 @@ function pgToApsorc(schema) {
586
582
  rel.foreignKeyName = fk.name;
587
583
  if (pkSet.has(sourceColumn))
588
584
  rel.primary = true;
589
- // Migrations keep the key NOT VALID. A database built by TypeORM's own
590
- // schema sync has it validated, which only matters on an empty one.
591
- if (fk.notValid)
592
- 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;
593
591
  if (col === null || col === void 0 ? void 0 : col.nullable)
594
592
  rel.nullable = true;
595
593
  if (fk.onDelete === "CASCADE")
596
594
  rel.cascadeDelete = true;
597
- else if (fk.onDelete === "SET NULL" || fk.onDelete === "RESTRICT")
595
+ else if (fk.onDelete !== "NO ACTION")
598
596
  rel.onDelete = fk.onDelete;
599
597
  relationships.push(rel);
600
598
  }
@@ -612,6 +610,20 @@ function pgToApsorc(schema) {
612
610
  };
613
611
  }
614
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
+ });
615
627
  /**
616
628
  * Invariant guard: every emitted field type must be a recognized `.apsorc`
617
629
  * column type, so code generation never silently falls back to varchar.
@@ -36,11 +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 has an ON UPDATE action or is DEFERRABLE; .apsorc states neither. */
40
- otherActions?: boolean;
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";
41
43
  /** Local column(s) participating in the FK. */
42
44
  columns: string[];
43
45
  referencedTable: string;
46
+ /** The referenced table's schema, when it is not the imported one. */
47
+ referencedSchema?: string;
44
48
  referencedColumns: string[];
45
49
  onDelete: OnDeleteAction;
46
50
  }
@@ -120,8 +124,9 @@ export interface ImportReport {
120
124
  /** "table.column" arrays whose element type is unknown, imported as text[]. */
121
125
  arraysLossy: string[];
122
126
  /**
123
- * "table.constraint (column -> target)" for a second foreign key on a
124
- * column that a "foreignKeys" entry cannot state. Left out of .apsorc.
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.
125
130
  */
126
131
  foreignKeysNotCarried: string[];
127
132
  /** "table.constraint" for CHECK constraints marked NOT VALID in the source. */
@@ -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);
@@ -62,7 +62,7 @@ const { CREATE, UPDATE } = CrudValidationGroups;
62
62
  @Check(<% if (check.name) { %><%~ JSON.stringify(check.name) %>, <% } %><%~ JSON.stringify(check.expression) %>)
63
63
  <% }) %>
64
64
  <% it.foreignKeys.forEach((key) => { %>
65
- @ForeignKey(() => <%= key.target %>, [<%~ JSON.stringify(key.column) %>], [<%~ JSON.stringify(key.targetColumn) %>], { name: <%~ JSON.stringify(key.name) %><% if (key.onDelete) { %>, onDelete: "<%= key.onDelete %>"<% } %> })
65
+ @ForeignKey(() => <%= key.target %>, [<%~ JSON.stringify(key.column) %>], [<%~ JSON.stringify(key.targetColumn) %>], { <%~ key.options %> })
66
66
  <% }) %>
67
67
  <% it.uniques.forEach((unique) => { %>
68
68
  @Unique(<% if (unique.name) {%> "<%= unique.name %>", <%} %>[<%~ unique.fields.map((field) => `"${field}"`).join(', ') %>])
@@ -136,7 +136,7 @@ const columnCode = includeFile(`./entities/entity-col-${field.type}`, { field })
136
136
  <% if (assoc.index) { %>
137
137
  @Index()
138
138
  <% } %>
139
- @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 %> }<% } %>)
140
140
  @JoinColumn({ name: '<%= assoc.joinColumnName || assoc.camelCasedId %>'<% if (assoc.foreignKeyName) { %>, foreignKeyConstraintName: '<%= assoc.foreignKeyName %>'<% } %> })
141
141
  <%= assoc.relationshipName %>: <%= assoc.name %>;
142
142
 
@@ -1,3 +1,4 @@
1
+ import { Deferrable, OnDelete } from "./relationship";
1
2
  export interface Unique {
2
3
  fields: string[];
3
4
  name?: string;
@@ -25,7 +26,11 @@ export interface ExtraForeignKey {
25
26
  column: string;
26
27
  /** The entity it references, by its primary key. */
27
28
  to: string;
28
- onDelete?: "CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION";
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;
29
34
  /** False keeps the key NOT VALID in migrations, as on a relationship. */
30
35
  validate?: boolean;
31
36
  }
@@ -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.55.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.55.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.55.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.55.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",