@apso/cli 0.54.0 → 0.55.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(` - 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(", ")}`);
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)
@@ -1032,6 +1032,7 @@ is tracked separately.
1032
1032
  | primary | field | The field is the primary key, or part of it |
1033
1033
  | elementType | field | Element type of an \`array\` field, e.g. \`uuid\` |
1034
1034
  | generated | field | The SQL expression of a stored generated column, e.g. \`(quantity * price)\`. Postgres computes it; create and update requests do not accept the field. TypeScript only |
1035
+ | 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 |
1035
1036
 
1036
1037
  In \`indexes\` and \`uniques\`, a foreign key may be named by its relationship (\`patient\`), its id property (\`patientId\`) or its column (\`patient_id\`).
1037
1038
  `;
@@ -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
  }
@@ -115,6 +115,23 @@ export declare const fkType: (target?: Entity) => string;
115
115
  * "joinColumnName" when the .apsorc sets one (an imported database keeps its
116
116
  * own column names), else the name TypeORM derives.
117
117
  */
118
+ /**
119
+ * An entity's "foreignKeys" entries with the table and key column each one
120
+ * references.
121
+ * @param {Entity} e - The entity.
122
+ * @param {Map<string, Entity>} byName - Every entity by name.
123
+ * @returns {Array} One resolved entry per key.
124
+ */
125
+ export declare const extraForeignKeys: (e: Entity, byName: Map<string, Entity>) => {
126
+ target: string;
127
+ targetTable: string;
128
+ targetColumn: string;
129
+ name: string;
130
+ column: string;
131
+ to: string;
132
+ onDelete?: "CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION" | undefined;
133
+ validate?: boolean | undefined;
134
+ }[];
118
135
  export declare const relationColumn: (r: RelationshipForTemplate) => string;
119
136
  /**
120
137
  * Every name an "indexes" or "uniques" entry may use for a foreign key, mapped
@@ -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
  *
@@ -234,6 +234,29 @@ exports.fkType = fkType;
234
234
  * "joinColumnName" when the .apsorc sets one (an imported database keeps its
235
235
  * own column names), else the name TypeORM derives.
236
236
  */
237
+ /**
238
+ * An entity's "foreignKeys" entries with the table and key column each one
239
+ * references.
240
+ * @param {Entity} e - The entity.
241
+ * @param {Map<string, Entity>} byName - Every entity by name.
242
+ * @returns {Array} One resolved entry per key.
243
+ */
244
+ const extraForeignKeys = (e, byName) => {
245
+ var _a;
246
+ return ((_a = e.foreignKeys) !== null && _a !== void 0 ? _a : []).map((k) => {
247
+ var _a;
248
+ const target = byName.get(k.to);
249
+ if (!k.name || !k.column || !target)
250
+ 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
+ return {
252
+ ...k,
253
+ target: target.name,
254
+ targetTable: (0, exports.tableName)(target),
255
+ targetColumn: (0, exports.pkColumn)(target),
256
+ };
257
+ });
258
+ };
259
+ exports.extraForeignKeys = extraForeignKeys;
237
260
  const relationColumn = (r) => r.joinColumnName ||
238
261
  (r.type === "ManyToOne"
239
262
  ? r.camelCasedId
@@ -272,7 +295,7 @@ const joinTableOf = (e, r, target) => {
272
295
  };
273
296
  exports.joinTableOf = joinTableOf;
274
297
  function schemaModel(input) {
275
- var _a, _b, _c, _d, _e, _f, _g, _h;
298
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
276
299
  const { entities, relationshipMap } = input;
277
300
  const byName = new Map(entities.map((e) => [e.name, e]));
278
301
  const model = {
@@ -323,8 +346,8 @@ function schemaModel(input) {
323
346
  columns,
324
347
  body: `PRIMARY KEY (${cols(columns)})`,
325
348
  });
326
- const foreignKey = (table, col, target, targetCol, actions, name = exports.constraintName.foreignKey(table, [col])) => foreignKeys.push({
327
- key: `fk:${table}(${col})->${target}`,
349
+ const foreignKey = (table, col, target, targetCol, actions, name = exports.constraintName.foreignKey(table, [col]), key = `fk:${table}(${col})->${target}`) => foreignKeys.push({
350
+ key,
328
351
  name,
329
352
  table,
330
353
  kind: "fk",
@@ -451,9 +474,16 @@ function schemaModel(input) {
451
474
  foreignKey(join, otherCol, targetTable, (0, exports.pkColumn)(target), `ON DELETE ${inverse} ON UPDATE ${inverse}`);
452
475
  }
453
476
  }
477
+ for (const k of (0, exports.extraForeignKeys)(e, byName)) {
478
+ if (!t.columns.some((c) => c.name === k.column))
479
+ throw new Error(`${e.name} "foreignKeys" entry "${k.name}" names column "${k.column}", which ${e.name} does not have.`);
480
+ if (foreignKeys.some((c) => c.table === table && c.name === k.name))
481
+ 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}`);
483
+ }
454
484
  const keyColumns = customPk
455
485
  ? [
456
- ...((_h = e.fields) !== null && _h !== void 0 ? _h : []).filter((f) => f.primary).map((f) => f.name),
486
+ ...((_j = e.fields) !== null && _j !== void 0 ? _j : []).filter((f) => f.primary).map((f) => f.name),
457
487
  ...relationKeys,
458
488
  ]
459
489
  : ["id"];
@@ -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,10 @@ 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 foreignKeys = (0, ddl_1.extraForeignKeys)(entity, new Map(allEntities.map((e) => [e.name, e])));
124
136
  const data = {
125
137
  name,
138
+ foreignKeys,
126
139
  indexes: toProperties(indexes),
127
140
  uniques: toProperties(uniques),
128
141
  checks: (_a = entity.checks) !== null && _a !== void 0 ? _a : [],
@@ -155,7 +168,9 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
155
168
  fkTsType: key.ts,
156
169
  };
157
170
  }),
158
- entitiesToImport,
171
+ entitiesToImport: [
172
+ ...new Set([...entitiesToImport, ...foreignKeys.map((k) => k.target)]),
173
+ ].filter((other) => other !== name),
159
174
  importEnums: (0, field_1.typeExistsInEntity)(entity, "enum") !== -1,
160
175
  apiType,
161
176
  };
@@ -163,7 +163,8 @@ const PRIMARY_KEYS_SQL = `
163
163
  const FOREIGN_KEYS_SQL = `
164
164
  SELECT con.conname, cl.relname AS table_name, att.attname AS column_name,
165
165
  clf.relname AS referenced_table, attf.attname AS referenced_column,
166
- con.confdeltype, con.convalidated, ord.n AS key_index
166
+ con.confdeltype, con.confupdtype, con.condeferrable,
167
+ con.convalidated, ord.n AS key_index
167
168
  FROM pg_constraint con
168
169
  JOIN pg_class cl ON cl.oid = con.conrelid
169
170
  JOIN pg_namespace ns ON ns.oid = cl.relnamespace
@@ -253,7 +254,7 @@ const SCHEMAS_SQL = `SELECT schema_name FROM information_schema.schemata`;
253
254
  * the DB connection) so it can be unit-tested with fixture rows.
254
255
  */
255
256
  function buildSchema(schema, raw) {
256
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
257
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
257
258
  // Enums
258
259
  const enumMap = new Map();
259
260
  for (const row of raw.enumRows) {
@@ -303,35 +304,40 @@ function buildSchema(schema, raw) {
303
304
  if (row.conname)
304
305
  pkNameByTable.set(row.table_name, row.conname);
305
306
  }
306
- // Foreign keys (grouped by constraint name to handle composite keys)
307
+ // Foreign keys, grouped by table and constraint name to handle composite
308
+ // keys. Postgres keeps a key's name unique per table, not per schema.
307
309
  const fkByConstraint = new Map();
308
310
  for (const row of raw.fkRows) {
309
- const existing = fkByConstraint.get(row.conname);
311
+ const id = JSON.stringify([row.table_name, row.conname]);
312
+ const existing = fkByConstraint.get(id);
310
313
  if (existing) {
311
314
  existing.columns.push(row.column_name);
312
315
  existing.refColumns.push(row.referenced_column);
313
316
  }
314
317
  else {
315
- fkByConstraint.set(row.conname, {
318
+ fkByConstraint.set(id, {
319
+ name: row.conname,
316
320
  table: row.table_name,
317
321
  columns: [row.column_name],
318
322
  refTable: row.referenced_table,
319
323
  refColumns: [row.referenced_column],
320
324
  confdeltype: row.confdeltype,
325
+ lossy: ((_j = row.confupdtype) !== null && _j !== void 0 ? _j : "a") !== "a" || row.condeferrable === true,
321
326
  notValid: row.convalidated === false,
322
327
  });
323
328
  }
324
329
  }
325
330
  const fksByTable = new Map();
326
- for (const [name, fk] of fkByConstraint.entries()) {
327
- const list = (_j = fksByTable.get(fk.table)) !== null && _j !== void 0 ? _j : [];
331
+ for (const fk of fkByConstraint.values()) {
332
+ const list = (_k = fksByTable.get(fk.table)) !== null && _k !== void 0 ? _k : [];
328
333
  list.push({
329
- name,
334
+ name: fk.name,
330
335
  ...(fk.notValid && { notValid: true }),
336
+ ...(fk.lossy && { otherActions: true }),
331
337
  columns: fk.columns,
332
338
  referencedTable: fk.refTable,
333
339
  referencedColumns: fk.refColumns,
334
- onDelete: (_k = CONFDELTYPE_TO_ACTION[fk.confdeltype]) !== null && _k !== void 0 ? _k : "NO ACTION",
340
+ onDelete: (_l = CONFDELTYPE_TO_ACTION[fk.confdeltype]) !== null && _l !== void 0 ? _l : "NO ACTION",
335
341
  });
336
342
  fksByTable.set(fk.table, list);
337
343
  }
@@ -349,14 +355,14 @@ function buildSchema(schema, raw) {
349
355
  }
350
356
  const uniquesByTable = new Map();
351
357
  for (const [name, uc] of uniqueByConstraint.entries()) {
352
- const list = (_l = uniquesByTable.get(uc.table)) !== null && _l !== void 0 ? _l : [];
358
+ const list = (_m = uniquesByTable.get(uc.table)) !== null && _m !== void 0 ? _m : [];
353
359
  list.push({ name, columns: uc.columns });
354
360
  uniquesByTable.set(uc.table, list);
355
361
  }
356
362
  // Indexes (grouped by index name)
357
363
  const indexByName = new Map();
358
364
  for (const row of raw.indexRows) {
359
- const idx = (_m = indexByName.get(row.index_name)) !== null && _m !== void 0 ? _m : {
365
+ const idx = (_o = indexByName.get(row.index_name)) !== null && _o !== void 0 ? _o : {
360
366
  table: row.table_name,
361
367
  name: row.index_name,
362
368
  columns: [],
@@ -379,7 +385,7 @@ function buildSchema(schema, raw) {
379
385
  }
380
386
  const indexesByTable = new Map();
381
387
  for (const { table, ...idx } of indexByName.values()) {
382
- indexesByTable.set(table, [...((_o = indexesByTable.get(table)) !== null && _o !== void 0 ? _o : []), idx]);
388
+ indexesByTable.set(table, [...((_p = indexesByTable.get(table)) !== null && _p !== void 0 ? _p : []), idx]);
383
389
  }
384
390
  const tables = baseTables.map((name) => {
385
391
  var _a, _b, _c, _d, _e, _f;
@@ -48,6 +48,7 @@ export interface ApsorcImportEntityOutput {
48
48
  expression: string;
49
49
  validate?: boolean;
50
50
  }>;
51
+ foreignKeys?: Entity["foreignKeys"];
51
52
  timestampDefault?: Entity["timestampDefault"];
52
53
  sqlIndexes?: Array<{
53
54
  name: string;
@@ -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,7 +274,7 @@ 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;
278
278
  const report = emptyReport(schema);
279
279
  const enumLabels = new Map(schema.enums.map((e) => [e.name, e.labels]));
280
280
  const entities = [];
@@ -540,9 +540,32 @@ function pgToApsorc(schema) {
540
540
  continue; // composite FK handled above
541
541
  const sourceColumn = fk.columns[0];
542
542
  // A relationship holds one key per column. A second key on the same
543
- // column (usually an exact duplicate) is left out and reported.
543
+ // column (usually an exact duplicate) is kept as a constraint only.
544
544
  if (keyed.has(sourceColumn)) {
545
- report.warnings.foreignKeysNotCarried.push(`${table.name}.${fk.name} (${sourceColumn} -> ${fk.referencedTable})`);
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
+ // Postgres names every constraint, so the name is always there.
562
+ ((_d = entity.foreignKeys) !== null && _d !== void 0 ? _d : (entity.foreignKeys = [])).push({
563
+ name: (_e = fk.name) !== null && _e !== void 0 ? _e : "",
564
+ column: sourceColumn,
565
+ to: fk.referencedTable,
566
+ ...(onDelete && { onDelete }),
567
+ ...(fk.notValid && { validate: false }),
568
+ });
546
569
  continue;
547
570
  }
548
571
  keyed.add(sourceColumn);
@@ -36,6 +36,8 @@ 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
41
  /** Local column(s) participating in the FK. */
40
42
  columns: string[];
41
43
  referencedTable: string;
@@ -117,6 +119,11 @@ export interface ImportReport {
117
119
  warnings: {
118
120
  /** "table.column" arrays whose element type is unknown, imported as text[]. */
119
121
  arraysLossy: string[];
122
+ /**
123
+ * "table.constraint (column -> target)" for a second foreign key on a
124
+ * column that a "foreignKeys" entry cannot state. Left out of .apsorc.
125
+ */
126
+ foreignKeysNotCarried: string[];
120
127
  /** "table.constraint" for CHECK constraints marked NOT VALID in the source. */
121
128
  checksNotValid: string[];
122
129
  /**
@@ -129,11 +136,6 @@ export interface ImportReport {
129
136
  * the table has a column of that name. The column itself is unchanged.
130
137
  */
131
138
  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
139
  /**
138
140
  * Indexes .apsorc cannot express, as Postgres defines them: an expression
139
141
  * or DESC index that is not a btree. They are left out.
@@ -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) %>], { name: <%~ JSON.stringify(key.name) %><% if (key.onDelete) { %>, onDelete: "<%= key.onDelete %>"<% } %> })
66
+ <% }) %>
61
67
  <% it.uniques.forEach((unique) => { %>
62
68
  @Unique(<% if (unique.name) {%> "<%= unique.name %>", <%} %>[<%~ unique.fields.map((field) => `"${field}"`).join(', ') %>])
63
69
  <% }) %>
@@ -15,3 +15,17 @@ export interface Check {
15
15
  */
16
16
  validate?: boolean;
17
17
  }
18
+ /**
19
+ * A foreign key beyond the one a relationship makes, for a column that has
20
+ * more than one. It is a database constraint only: no relation property.
21
+ */
22
+ export interface ExtraForeignKey {
23
+ name: string;
24
+ /** The column's database name. */
25
+ column: string;
26
+ /** The entity it references, by its primary key. */
27
+ to: string;
28
+ onDelete?: "CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION";
29
+ /** False keeps the key NOT VALID in migrations, as on a relationship. */
30
+ validate?: boolean;
31
+ }
@@ -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,12 +1,12 @@
1
1
  {
2
2
  "name": "@apso/cli",
3
- "version": "0.54.0",
3
+ "version": "0.55.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.55.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.55.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.55.0",
4
4
  "mcpName": "io.github.apsoai/apso",
5
5
  "description": "Apso CLI",
6
6
  "author": "Apso by Mavric - @mavric",