@apso/cli 0.52.0 → 0.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/dist/commands/import/supabase.js +31 -6
  2. package/dist/commands/init.d.ts +9 -0
  3. package/dist/commands/init.js +31 -1
  4. package/dist/commands/mcp/serve.js +20 -0
  5. package/dist/commands/schema/validate.js +18 -1
  6. package/dist/lib/apsorc-parser.js +7 -3
  7. package/dist/lib/base-command.js +14 -3
  8. package/dist/lib/config/types.d.ts +5 -0
  9. package/dist/lib/ddl/catalog.js +5 -2
  10. package/dist/lib/ddl/change.js +13 -2
  11. package/dist/lib/ddl/index.d.ts +62 -3
  12. package/dist/lib/ddl/index.js +211 -40
  13. package/dist/lib/generators/go.js +17 -3
  14. package/dist/lib/generators/python.js +17 -3
  15. package/dist/lib/generators/typescript.js +85 -15
  16. package/dist/lib/import/copy-data.js +4 -0
  17. package/dist/lib/import/introspect.d.ts +40 -0
  18. package/dist/lib/import/introspect.js +137 -49
  19. package/dist/lib/import/pg-to-apsorc.d.ts +62 -0
  20. package/dist/lib/import/pg-to-apsorc.js +248 -37
  21. package/dist/lib/import/types.d.ts +48 -3
  22. package/dist/lib/migrate/sandbox.js +23 -6
  23. package/dist/lib/migrate/snapshot.d.ts +5 -0
  24. package/dist/lib/plan/index.d.ts +4 -1
  25. package/dist/lib/plan/index.js +9 -3
  26. package/dist/lib/telemetry/error-utils.d.ts +74 -0
  27. package/dist/lib/telemetry/error-utils.js +221 -0
  28. package/dist/lib/telemetry/internal-constants.d.ts +27 -0
  29. package/dist/lib/telemetry/internal-constants.js +32 -0
  30. package/dist/lib/telemetry/internal-detection.d.ts +37 -0
  31. package/dist/lib/telemetry/internal-detection.js +78 -0
  32. package/dist/lib/telemetry/telemetry.d.ts +11 -0
  33. package/dist/lib/telemetry/telemetry.js +197 -3
  34. package/dist/lib/templates/entities/entity-col-array.eta +2 -1
  35. package/dist/lib/templates/entities/entity-col-bigint.eta +2 -2
  36. package/dist/lib/templates/entities/entity-col-bigserial.eta +2 -2
  37. package/dist/lib/templates/entities/entity-col-boolean.eta +1 -1
  38. package/dist/lib/templates/entities/entity-col-bytea.eta +2 -2
  39. package/dist/lib/templates/entities/entity-col-char.eta +4 -3
  40. package/dist/lib/templates/entities/entity-col-date.eta +6 -2
  41. package/dist/lib/templates/entities/entity-col-datetime.eta +8 -1
  42. package/dist/lib/templates/entities/entity-col-decimal.eta +2 -2
  43. package/dist/lib/templates/entities/entity-col-double.eta +2 -2
  44. package/dist/lib/templates/entities/entity-col-float.eta +1 -1
  45. package/dist/lib/templates/entities/entity-col-geography.eta +1 -1
  46. package/dist/lib/templates/entities/entity-col-geometry.eta +1 -1
  47. package/dist/lib/templates/entities/entity-col-geometrycollection.eta +1 -1
  48. package/dist/lib/templates/entities/entity-col-inet.eta +2 -2
  49. package/dist/lib/templates/entities/entity-col-int4range.eta +1 -1
  50. package/dist/lib/templates/entities/entity-col-integer.eta +2 -2
  51. package/dist/lib/templates/entities/entity-col-interval.eta +2 -2
  52. package/dist/lib/templates/entities/entity-col-json-plain.eta +1 -1
  53. package/dist/lib/templates/entities/entity-col-json.eta +1 -1
  54. package/dist/lib/templates/entities/entity-col-jsonb.eta +1 -1
  55. package/dist/lib/templates/entities/entity-col-linestring.eta +1 -1
  56. package/dist/lib/templates/entities/entity-col-money.eta +2 -2
  57. package/dist/lib/templates/entities/entity-col-multilinestring.eta +1 -1
  58. package/dist/lib/templates/entities/entity-col-multipoint.eta +1 -1
  59. package/dist/lib/templates/entities/entity-col-multipolygon.eta +1 -1
  60. package/dist/lib/templates/entities/entity-col-numeric.eta +2 -2
  61. package/dist/lib/templates/entities/entity-col-point.eta +1 -1
  62. package/dist/lib/templates/entities/entity-col-polygon.eta +1 -1
  63. package/dist/lib/templates/entities/entity-col-real.eta +2 -2
  64. package/dist/lib/templates/entities/entity-col-serial.eta +2 -2
  65. package/dist/lib/templates/entities/entity-col-smallint.eta +2 -2
  66. package/dist/lib/templates/entities/entity-col-smallserial.eta +2 -2
  67. package/dist/lib/templates/entities/entity-col-string.eta +2 -2
  68. package/dist/lib/templates/entities/entity-col-text.eta +4 -3
  69. package/dist/lib/templates/entities/entity-col-time.eta +2 -2
  70. package/dist/lib/templates/entities/entity-col-timestamp.eta +8 -1
  71. package/dist/lib/templates/entities/entity-col-timestamptz.eta +8 -1
  72. package/dist/lib/templates/entities/entity-col-timetz.eta +2 -2
  73. package/dist/lib/templates/entities/entity-col-tsvector.eta +2 -2
  74. package/dist/lib/templates/entities/entity-col-uuid.eta +5 -2
  75. package/dist/lib/templates/entities/entity-col-varchar.eta +4 -3
  76. package/dist/lib/templates/entities/entity-col-xml.eta +2 -2
  77. package/dist/lib/templates/entities/entity.eta +30 -18
  78. package/dist/lib/templates/go/models/model.eta +3 -3
  79. package/dist/lib/templates/python/models/model.eta +1 -1
  80. package/dist/lib/templates/rest/controller-rest.eta +16 -5
  81. package/dist/lib/templates/rest/dto-rest.eta +2 -2
  82. package/dist/lib/templates/rest/index-module-rest.eta +6 -0
  83. package/dist/lib/templates/rest/schema-extras-module.eta +24 -0
  84. package/dist/lib/types/constraints.d.ts +13 -0
  85. package/dist/lib/types/entity.d.ts +67 -2
  86. package/dist/lib/types/entity.js +39 -1
  87. package/dist/lib/types/field.d.ts +20 -2
  88. package/dist/lib/types/indices.d.ts +21 -0
  89. package/dist/lib/types/relationship.d.ts +33 -0
  90. package/dist/lib/types/relationship.js +13 -0
  91. package/dist/lib/upgrade.d.ts +5 -6
  92. package/dist/lib/upgrade.js +12 -23
  93. package/dist/lib/utils/field.d.ts +22 -0
  94. package/dist/lib/utils/field.js +62 -3
  95. package/dist/lib/utils/relationships/index.d.ts +1 -1
  96. package/dist/lib/utils/relationships/index.js +2 -1
  97. package/dist/lib/utils/relationships/parse.d.ts +11 -0
  98. package/dist/lib/utils/relationships/parse.js +44 -1
  99. package/dist/lib/utils/template.d.ts +3 -3
  100. package/dist/lib/utils/template.js +4 -4
  101. package/dist/lib/verify/crud-plan.d.ts +2 -0
  102. package/dist/lib/verify/crud-plan.js +19 -5
  103. package/dist/lib/verify/index.js +32 -3
  104. package/npm-shrinkwrap.json +77 -91
  105. package/oclif.manifest.json +7 -1
  106. package/package.json +4 -2
@@ -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 { Entity } from "../types/entity";
14
15
  import { ImportReport, IntrospectedColumn, IntrospectedSchema } from "./types";
15
16
  export interface ApsorcImportFieldOutput {
16
17
  name: string;
@@ -18,26 +19,47 @@ export interface ApsorcImportFieldOutput {
18
19
  nullable?: boolean;
19
20
  unique?: boolean;
20
21
  default?: unknown;
22
+ noDefault?: boolean;
23
+ generated?: string;
21
24
  index?: boolean;
22
25
  values?: string[];
23
26
  length?: number;
24
27
  precision?: number;
25
28
  scale?: number;
26
29
  primary?: boolean;
30
+ elementType?: string;
27
31
  }
28
32
  export interface ApsorcImportEntityOutput {
29
33
  name: string;
30
34
  primaryKeyType?: "serial" | "uuid" | "text";
35
+ primaryKeyName?: string;
36
+ primaryKeyDefault?: string;
31
37
  created_at?: boolean;
32
38
  updated_at?: boolean;
39
+ timestampType?: Entity["timestampType"];
40
+ timestampNullable?: Entity["timestampNullable"];
33
41
  fields?: ApsorcImportFieldOutput[];
34
42
  uniques?: Array<{
35
43
  fields: string[];
36
44
  name?: string;
37
45
  }>;
46
+ checks?: Array<{
47
+ name?: string;
48
+ expression: string;
49
+ validate?: boolean;
50
+ }>;
51
+ timestampDefault?: Entity["timestampDefault"];
52
+ sqlIndexes?: Array<{
53
+ name: string;
54
+ columns: string;
55
+ unique?: boolean;
56
+ where?: string;
57
+ }>;
38
58
  indexes?: Array<{
39
59
  fields: string[];
40
60
  unique?: boolean;
61
+ name?: string;
62
+ where?: string;
41
63
  }>;
42
64
  }
43
65
  export interface ApsorcImportRelationshipOutput {
@@ -48,9 +70,17 @@ export interface ApsorcImportRelationshipOutput {
48
70
  nullable?: boolean;
49
71
  bi_directional?: boolean;
50
72
  cascadeDelete?: boolean;
73
+ onDelete?: "SET NULL" | "RESTRICT";
74
+ foreignKeyName?: string;
75
+ primary?: boolean;
76
+ validate?: boolean;
77
+ index?: boolean;
78
+ joinColumnName?: string;
51
79
  }
52
80
  export interface ApsorcImportOutput {
53
81
  version: number;
82
+ /** Set when the file is written: the existing file's, else typescript. */
83
+ language?: string;
54
84
  rootFolder: string;
55
85
  apiType: string;
56
86
  entities: ApsorcImportEntityOutput[];
@@ -58,6 +88,8 @@ export interface ApsorcImportOutput {
58
88
  }
59
89
  interface TypeResolution {
60
90
  type: string;
91
+ /** Element type of an array column, when it is not text. */
92
+ elementType?: string;
61
93
  /** True when the mapping loses information (arrays, unknown types). */
62
94
  lossy?: "array" | "defaulted";
63
95
  }
@@ -77,6 +109,36 @@ export declare function parseDefault(raw: string | null, apsorcType: string): {
77
109
  value?: unknown;
78
110
  drop?: boolean;
79
111
  };
112
+ /**
113
+ * The column list of a btree index from pg_get_indexdef's
114
+ * "CREATE INDEX name ON t USING btree (<columns>) [WHERE ...]". Undefined for
115
+ * another index method, which .apsorc cannot express.
116
+ *
117
+ * @param {string} [definition] - pg_get_indexdef's output.
118
+ * @returns {string | undefined} The text between the outer parentheses.
119
+ */
120
+ export declare function indexColumnsSql(definition?: string): string | undefined;
121
+ /**
122
+ * How a single-column foreign key is written to .apsorc: the relationship
123
+ * name ("to_name" when the default would not do) and "joinColumnName" when
124
+ * the generated column would differ from the source column, so an import
125
+ * never renames a foreign key (apsoai/cli#241).
126
+ *
127
+ * A relationship named like one of the table's own columns would collide
128
+ * with that field ("facility" text beside "facility_id"), so it gets another
129
+ * name; the column is kept either way (apsoai/cli#250).
130
+ *
131
+ * @param {string} sourceColumn - The foreign key column in the source table.
132
+ * @param {string} targetTable - The table it references.
133
+ * @param {string[]} columns - The source table's column names.
134
+ * @returns {object} toName and joinColumnName when needed, and the relationship's property name.
135
+ */
136
+ export declare function foreignKeyNames(sourceColumn: string, targetTable: string, columns?: string[]): {
137
+ toName?: string;
138
+ joinColumnName?: string;
139
+ property: string;
140
+ renamed: boolean;
141
+ };
80
142
  /**
81
143
  * Derive the relationship `to_name` so the platform regenerates a FK column
82
144
  * matching the source column. Returns `undefined` when the default naming
@@ -13,10 +13,10 @@
13
13
  * (src/lib/utils/relationships/parse.ts) so imported relationships round-trip.
14
14
  */
15
15
  Object.defineProperty(exports, "__esModule", { value: true });
16
- exports.findUnknownEmittedTypes = exports.pgToApsorc = exports.deriveToName = exports.parseDefault = exports.pgTypeToApsorcType = void 0;
16
+ exports.findUnknownEmittedTypes = exports.pgToApsorc = exports.deriveToName = exports.foreignKeyNames = exports.indexColumnsSql = exports.parseDefault = exports.pgTypeToApsorcType = void 0;
17
17
  const casing_1 = require("../utils/casing");
18
18
  const field_1 = require("../utils/field");
19
- const relationships_1 = require("../utils/relationships");
19
+ const parse_1 = require("../utils/relationships/parse");
20
20
  /** Maps a Postgres udt_name to the closest `.apsorc` field type. */
21
21
  const udtToApsorcType = {
22
22
  int2: "smallint",
@@ -51,6 +51,21 @@ const udtToApsorcType = {
51
51
  geography: "geography",
52
52
  };
53
53
  const TIMESTAMP_UDTS = new Set(["timestamp", "timestamptz"]);
54
+ /** Field types whose templates write a literal default; others take SQL. */
55
+ const LITERAL_DEFAULT_TYPES = new Set([
56
+ "text",
57
+ "varchar",
58
+ "char",
59
+ "integer",
60
+ "smallint",
61
+ "bigint",
62
+ "numeric",
63
+ "decimal",
64
+ "float",
65
+ "double",
66
+ "boolean",
67
+ "enum",
68
+ ]);
54
69
  const AUTO_TIMESTAMP_DEFAULTS = new Set([
55
70
  "now()",
56
71
  "current_timestamp",
@@ -67,7 +82,13 @@ function pgTypeToApsorcType(col) {
67
82
  return { type: "enum" };
68
83
  }
69
84
  if (col.dataType === "ARRAY" || col.udtName.startsWith("_")) {
70
- return { type: "array", lossy: "array" };
85
+ // uuid[] must stay uuid[]: the element type is the udt without its "_".
86
+ const element = udtToApsorcType[col.udtName.replace(/^_/, "")];
87
+ if (!element)
88
+ return { type: "array", lossy: "array" };
89
+ return element === "text"
90
+ ? { type: "array" }
91
+ : { type: "array", elementType: element };
71
92
  }
72
93
  const mapped = udtToApsorcType[col.udtName];
73
94
  if (mapped) {
@@ -114,6 +135,73 @@ function parseDefault(raw, apsorcType) {
114
135
  return { drop: true };
115
136
  }
116
137
  exports.parseDefault = parseDefault;
138
+ /**
139
+ * The column list of a btree index from pg_get_indexdef's
140
+ * "CREATE INDEX name ON t USING btree (<columns>) [WHERE ...]". Undefined for
141
+ * another index method, which .apsorc cannot express.
142
+ *
143
+ * @param {string} [definition] - pg_get_indexdef's output.
144
+ * @returns {string | undefined} The text between the outer parentheses.
145
+ */
146
+ function indexColumnsSql(definition) {
147
+ var _a;
148
+ const start = (_a = definition === null || definition === void 0 ? void 0 : definition.indexOf(" USING btree (")) !== null && _a !== void 0 ? _a : -1;
149
+ if (!definition || start < 0)
150
+ return undefined;
151
+ const open = start + " USING btree ".length;
152
+ let depth = 0;
153
+ for (let i = open; i < definition.length; i++) {
154
+ if (definition[i] === "(")
155
+ depth++;
156
+ if (definition[i] === ")" && --depth === 0)
157
+ return definition.slice(open + 1, i);
158
+ }
159
+ return undefined;
160
+ }
161
+ exports.indexColumnsSql = indexColumnsSql;
162
+ /**
163
+ * How a single-column foreign key is written to .apsorc: the relationship
164
+ * name ("to_name" when the default would not do) and "joinColumnName" when
165
+ * the generated column would differ from the source column, so an import
166
+ * never renames a foreign key (apsoai/cli#241).
167
+ *
168
+ * A relationship named like one of the table's own columns would collide
169
+ * with that field ("facility" text beside "facility_id"), so it gets another
170
+ * name; the column is kept either way (apsoai/cli#250).
171
+ *
172
+ * @param {string} sourceColumn - The foreign key column in the source table.
173
+ * @param {string} targetTable - The table it references.
174
+ * @param {string[]} columns - The source table's column names.
175
+ * @returns {object} toName and joinColumnName when needed, and the relationship's property name.
176
+ */
177
+ function foreignKeyNames(sourceColumn, targetTable, columns = []) {
178
+ let { toName } = deriveToName(sourceColumn, targetTable);
179
+ const natural = (0, parse_1.getRelationshipName)({
180
+ name: targetTable,
181
+ type: "ManyToOne",
182
+ referenceName: toName,
183
+ });
184
+ const renamed = columns.includes(natural);
185
+ if (renamed) {
186
+ toName = `${natural}Record`;
187
+ for (let n = 2; columns.includes(toName); n++)
188
+ toName = `${natural}Record${n}`;
189
+ }
190
+ const relationship = {
191
+ name: targetTable,
192
+ type: "ManyToOne",
193
+ referenceName: toName,
194
+ };
195
+ return {
196
+ toName,
197
+ joinColumnName: (0, parse_1.getRelationshipIdField)(relationship) === sourceColumn
198
+ ? undefined
199
+ : sourceColumn,
200
+ property: (0, parse_1.getRelationshipName)(relationship),
201
+ renamed,
202
+ };
203
+ }
204
+ exports.foreignKeyNames = foreignKeyNames;
117
205
  /**
118
206
  * Derive the relationship `to_name` so the platform regenerates a FK column
119
207
  * matching the source column. Returns `undefined` when the default naming
@@ -125,7 +213,7 @@ function deriveToName(sourceColumn, targetTable) {
125
213
  // columns are typically snake_case. Compare on the camelCased form so a
126
214
  // snake_case source that is semantically identical isn't flagged as a mismatch.
127
215
  const source = (0, casing_1.camelCase)(sourceColumn);
128
- const defaultColumn = (0, relationships_1.getRelationshipIdField)({
216
+ const defaultColumn = (0, parse_1.getRelationshipIdField)({
129
217
  name: targetTable,
130
218
  type: "ManyToOne",
131
219
  });
@@ -136,7 +224,7 @@ function deriveToName(sourceColumn, targetTable) {
136
224
  const base = sourceColumn.replace(/(_id|Id)$/, "");
137
225
  if (base && base !== sourceColumn) {
138
226
  const candidate = (0, casing_1.camelCase)(base);
139
- const roundTrip = (0, relationships_1.getRelationshipIdField)({
227
+ const roundTrip = (0, parse_1.getRelationshipIdField)({
140
228
  name: targetTable,
141
229
  type: "ManyToOne",
142
230
  referenceName: candidate,
@@ -145,8 +233,7 @@ function deriveToName(sourceColumn, targetTable) {
145
233
  return { toName: candidate };
146
234
  }
147
235
  }
148
- // Best-effort: emit a reference name but flag that the generated FK column
149
- // may not match the source column exactly.
236
+ // No relationship name generates this column; "joinColumnName" keeps it.
150
237
  return { toName: (0, casing_1.camelCase)(base || sourceColumn), unmapped: true };
151
238
  }
152
239
  exports.deriveToName = deriveToName;
@@ -158,12 +245,16 @@ function emptyReport(schema) {
158
245
  systemSchemasSkipped: schema.skipped.systemSchemas,
159
246
  warnings: {
160
247
  arraysLossy: [],
248
+ checksNotValid: [],
249
+ timestampDefaultsAdded: [],
250
+ indexesNotCarried: [],
251
+ relationshipsRenamed: [],
252
+ foreignKeysNotCarried: [],
161
253
  compositePks: [],
162
254
  compositeFks: [],
163
255
  nonStandardPks: [],
164
256
  noPrimaryKey: [],
165
257
  typesDefaulted: [],
166
- fkColumnNameUnmapped: [],
167
258
  defaultsDropped: [],
168
259
  joinTablesDetected: [],
169
260
  },
@@ -183,6 +274,7 @@ function isJoinTable(table) {
183
274
  * report of everything that could not be represented losslessly.
184
275
  */
185
276
  function pgToApsorc(schema) {
277
+ var _a, _b, _c;
186
278
  const report = emptyReport(schema);
187
279
  const enumLabels = new Map(schema.enums.map((e) => [e.name, e.labels]));
188
280
  const entities = [];
@@ -193,6 +285,10 @@ function pgToApsorc(schema) {
193
285
  report.warnings.joinTablesDetected.push(table.name);
194
286
  }
195
287
  const entity = { name: table.name };
288
+ // Keep the source's constraint names, so a first migration against the
289
+ // existing database does not drop and recreate every key.
290
+ if (table.primaryKeyName)
291
+ entity.primaryKeyName = table.primaryKeyName;
196
292
  // Columns covered by a single-column FK are materialized by the
197
293
  // relationship, so they must not also be emitted as scalar fields.
198
294
  const fkColumns = new Map();
@@ -212,16 +308,26 @@ function pgToApsorc(schema) {
212
308
  const pkCol = table.columns.find((c) => c.name === pk[0]);
213
309
  if (pk[0] === "id" && pkCol) {
214
310
  const t = pgTypeToApsorcType(pkCol).type;
215
- if (t === "uuid")
216
- entity.primaryKeyType = "uuid";
217
- else if (t === "text" || t === "varchar")
218
- entity.primaryKeyType = "text";
311
+ // A varchar(n) or char(n) id is kept as a primary field, so its
312
+ // length and the columns that reference it keep theirs.
219
313
  // integer/bigint/smallint id => default serial, omit primaryKeyType.
314
+ if (t === "uuid" || t === "text")
315
+ entity.primaryKeyType = t;
316
+ // The generated uuid id uses uuid_generate_v4(); keep another function.
317
+ const idDefault = (_a = pkCol.default) === null || _a === void 0 ? void 0 : _a.trim();
318
+ if (t === "uuid" && idDefault && idDefault !== "uuid_generate_v4()")
319
+ entity.primaryKeyDefault = idDefault;
320
+ else
321
+ pkAsField = t === "varchar" || t === "char";
220
322
  }
221
323
  else {
222
- // Single, non-"id" PK: emit it as a primary field.
324
+ // Single, non-"id" PK: a primary field, or the relationship's own
325
+ // key when the column is a foreign key (a table keyed by the row it
326
+ // extends).
223
327
  pkAsField = true;
224
- report.warnings.nonStandardPks.push(table.name);
328
+ const keyIsForeignKey = table.foreignKeys.some((fk) => fk.columns.length === 1 && fk.columns[0] === pk[0]);
329
+ if (!keyIsForeignKey)
330
+ report.warnings.nonStandardPks.push(table.name);
225
331
  }
226
332
  }
227
333
  else if (pk.length > 1) {
@@ -233,36 +339,96 @@ function pgToApsorc(schema) {
233
339
  }
234
340
  // --- created_at / updated_at detection ---
235
341
  const autoTimestamps = new Set();
342
+ const stampTypes = {};
343
+ const stampNullable = {};
344
+ const stampDefault = {};
236
345
  for (const name of ["created_at", "updated_at"]) {
237
346
  const col = table.columns.find((c) => c.name === name);
238
347
  if (col && TIMESTAMP_UDTS.has(col.udtName)) {
239
348
  entity[name] = true;
240
349
  autoTimestamps.add(name);
350
+ stampTypes[name] = col.udtName;
351
+ if (col.default === null) {
352
+ stampDefault[name] = false;
353
+ report.warnings.timestampDefaultsAdded.push(`${table.name}.${name}`);
354
+ }
355
+ stampNullable[name] = col.nullable;
241
356
  }
242
357
  }
358
+ if (Object.keys(stampDefault).length > 0)
359
+ entity.timestampDefault =
360
+ autoTimestamps.size === Object.keys(stampDefault).length
361
+ ? false
362
+ : stampDefault;
363
+ const nullable = [...new Set(Object.values(stampNullable))];
364
+ if (nullable.length > 1)
365
+ entity.timestampNullable = stampNullable;
366
+ else if (nullable[0])
367
+ entity.timestampNullable = true;
368
+ // Keep the source types: one value when the columns agree (nothing when
369
+ // that is the default "timestamp"), one per column when they differ.
370
+ const stamps = [...new Set(Object.values(stampTypes))];
371
+ if (stamps.length > 1)
372
+ entity.timestampType = stampTypes;
373
+ else if (stamps[0] === "timestamptz")
374
+ entity.timestampType = "timestamptz";
243
375
  // --- Fields ---
244
376
  const uniqueSingle = new Set();
245
377
  const uniqueComposite = [];
378
+ // A foreign key column is not a field: indexes and uniques name the
379
+ // relationship that owns it, which the generators resolve to the column.
380
+ const columnNames = table.columns.map((c) => c.name);
381
+ const fkProperty = new Map();
382
+ for (const [column, fk] of fkColumns)
383
+ fkProperty.set(column, foreignKeyNames(column, fk.referencedTable, columnNames).property);
246
384
  for (const uc of table.uniqueConstraints) {
247
- if (uc.columns.length === 1)
385
+ // A field's "unique": true gets a generated name, so a constraint the
386
+ // source names goes in "uniques", which carries the name.
387
+ if (uc.columns.length === 1 && !fkColumns.has(uc.columns[0]) && !uc.name)
248
388
  uniqueSingle.add(uc.columns[0]);
249
389
  else
250
- uniqueComposite.push({ fields: uc.columns, name: uc.name });
390
+ uniqueComposite.push({
391
+ fields: uc.columns.map((c) => { var _a; return (_a = fkProperty.get(c)) !== null && _a !== void 0 ? _a : c; }),
392
+ name: uc.name,
393
+ });
251
394
  }
252
- const indexSingle = new Set();
253
- const indexComposite = [];
395
+ // Every index is an "indexes" entry with the source's name and WHERE
396
+ // condition, so it is rebuilt as it was. A field's or a relationship's
397
+ // "index": true would get a generated name.
398
+ const indexes = [];
399
+ const sqlIndexes = [];
254
400
  for (const idx of table.indexes) {
255
401
  const cols = idx.columns;
256
- // Skip indexes that merely back the PK or a unique constraint.
257
- const backsPk = cols.length === pk.length && cols.every((c) => pkSet.has(c));
258
- const backsUnique = table.uniqueConstraints.some((uc) => uc.columns.length === cols.length &&
259
- uc.columns.every((c) => cols.includes(c)));
260
- if (backsPk || backsUnique)
402
+ // Skip the index Postgres itself creates for the primary key or a
403
+ // unique constraint: it has the constraint's name. A separate index on
404
+ // the same columns is the source's own and is kept.
405
+ const backsConstraint = idx.name === table.primaryKeyName ||
406
+ table.uniqueConstraints.some((uc) => uc.name === idx.name);
407
+ if (backsConstraint)
261
408
  continue;
262
- if (cols.length === 1)
263
- indexSingle.add(cols[0]);
264
- else
265
- indexComposite.push({ fields: cols, unique: idx.unique });
409
+ // An index on an expression or with a DESC column goes in "sqlIndexes"
410
+ // with its column list as Postgres prints it (apsoai/cli#249).
411
+ if (idx.expression || idx.descending) {
412
+ const columns = indexColumnsSql(idx.definition);
413
+ if (columns === undefined) {
414
+ report.warnings.indexesNotCarried.push(`${(_b = idx.definition) !== null && _b !== void 0 ? _b : idx.name} (not imported)`);
415
+ }
416
+ else {
417
+ sqlIndexes.push({
418
+ name: idx.name,
419
+ columns,
420
+ ...(idx.unique && { unique: true }),
421
+ ...(idx.predicate && { where: idx.predicate }),
422
+ });
423
+ }
424
+ continue;
425
+ }
426
+ indexes.push({
427
+ fields: cols.map((c) => { var _a; return (_a = fkProperty.get(c)) !== null && _a !== void 0 ? _a : c; }),
428
+ ...(idx.unique && { unique: true }),
429
+ name: idx.name,
430
+ ...(idx.predicate && { where: idx.predicate }),
431
+ });
266
432
  }
267
433
  const fields = [];
268
434
  const sortedColumns = [...table.columns].sort((a, b) => a.ordinal - b.ordinal);
@@ -288,14 +454,16 @@ function pgToApsorc(schema) {
288
454
  name: col.name,
289
455
  type: resolved.type,
290
456
  };
457
+ if (resolved.elementType)
458
+ field.elementType = resolved.elementType;
291
459
  if (col.nullable)
292
460
  field.nullable = true;
293
461
  if (uniqueSingle.has(col.name))
294
462
  field.unique = true;
295
- if (indexSingle.has(col.name))
296
- field.index = true;
297
463
  if (pkSet.has(col.name) && pkAsField)
298
464
  field.primary = true;
465
+ if (col.generated)
466
+ field.generated = col.generated;
299
467
  if ((resolved.type === "varchar" || resolved.type === "char") && col.charMaxLength)
300
468
  field.length = col.charMaxLength;
301
469
  if (resolved.type === "numeric" || resolved.type === "decimal") {
@@ -312,11 +480,23 @@ function pgToApsorc(schema) {
312
480
  field.values = labels;
313
481
  }
314
482
  // Defaults (skip for PK columns — those are implicit/sequence-driven).
315
- if (!(pkSet.has(col.name) && !pkAsField)) {
483
+ if (!(pkSet.has(col.name) && !pkAsField) && !col.generated) {
316
484
  const parsed = parseDefault(col.default, resolved.type);
317
- if (parsed.drop && col.default !== null) {
485
+ const literal = "value" in parsed && LITERAL_DEFAULT_TYPES.has(resolved.type);
486
+ if (col.default === null) {
487
+ // A boolean field gets DEFAULT false unless it says otherwise.
488
+ if (resolved.type === "boolean")
489
+ field.noDefault = true;
490
+ }
491
+ else if (col.default.trim().toLowerCase().startsWith("nextval(")) {
492
+ // A sequence .apsorc does not create.
318
493
  report.warnings.defaultsDropped.push(`${table.name}.${col.name}`);
319
494
  }
495
+ else if (!literal) {
496
+ // A function call, an expression or a literal the field's template
497
+ // cannot write (json, array, date, uuid): kept as Postgres prints it.
498
+ field.default = { sql: col.default };
499
+ }
320
500
  else if ("value" in parsed) {
321
501
  if (resolved.type === "enum") {
322
502
  // Only keep an enum default that is one of the allowed labels.
@@ -338,30 +518,61 @@ function pgToApsorc(schema) {
338
518
  entity.fields = fields;
339
519
  if (uniqueComposite.length > 0)
340
520
  entity.uniques = uniqueComposite;
341
- if (indexComposite.length > 0)
342
- entity.indexes = indexComposite;
521
+ if (indexes.length > 0)
522
+ entity.indexes = indexes;
523
+ if (sqlIndexes.length > 0)
524
+ entity.sqlIndexes = sqlIndexes;
525
+ const checks = (_c = table.checks) !== null && _c !== void 0 ? _c : [];
526
+ if (checks.length > 0)
527
+ entity.checks = checks.map((c) => ({
528
+ name: c.name,
529
+ expression: c.expression,
530
+ ...(c.notValid && { validate: false }),
531
+ }));
532
+ for (const c of checks)
533
+ if (c.notValid)
534
+ report.warnings.checksNotValid.push(`${table.name}.${c.name}`);
343
535
  entities.push(entity);
344
536
  // --- Foreign keys -> ManyToOne relationships ---
537
+ const keyed = new Set();
345
538
  for (const fk of table.foreignKeys) {
346
539
  if (fk.columns.length !== 1)
347
540
  continue; // composite FK handled above
348
541
  const sourceColumn = fk.columns[0];
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.
544
+ if (keyed.has(sourceColumn)) {
545
+ report.warnings.foreignKeysNotCarried.push(`${table.name}.${fk.name} (${sourceColumn} -> ${fk.referencedTable})`);
546
+ continue;
547
+ }
548
+ keyed.add(sourceColumn);
349
549
  const col = table.columns.find((c) => c.name === sourceColumn);
350
550
  const rel = {
351
551
  from: table.name,
352
552
  to: fk.referencedTable,
353
553
  type: "ManyToOne",
354
554
  };
355
- const { toName, unmapped } = deriveToName(sourceColumn, fk.referencedTable);
555
+ const { toName, joinColumnName, property, renamed } = foreignKeyNames(sourceColumn, fk.referencedTable, columnNames);
556
+ if (renamed)
557
+ report.warnings.relationshipsRenamed.push(`${table.name}.${sourceColumn} is relationship "${property}"`);
356
558
  if (toName)
357
559
  rel.to_name = toName;
358
- if (unmapped) {
359
- report.warnings.fkColumnNameUnmapped.push(`${table.name}.${sourceColumn}`);
360
- }
560
+ if (joinColumnName)
561
+ rel.joinColumnName = joinColumnName;
562
+ if (fk.name)
563
+ rel.foreignKeyName = fk.name;
564
+ if (pkSet.has(sourceColumn))
565
+ 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;
361
570
  if (col === null || col === void 0 ? void 0 : col.nullable)
362
571
  rel.nullable = true;
363
572
  if (fk.onDelete === "CASCADE")
364
573
  rel.cascadeDelete = true;
574
+ else if (fk.onDelete === "SET NULL" || fk.onDelete === "RESTRICT")
575
+ rel.onDelete = fk.onDelete;
365
576
  relationships.push(rel);
366
577
  }
367
578
  }
@@ -23,6 +23,8 @@ export interface IntrospectedColumn {
23
23
  numericPrecision: number | null;
24
24
  numericScale: number | null;
25
25
  ordinal: number;
26
+ /** The expression of a GENERATED ALWAYS AS (...) STORED column. */
27
+ generated?: string;
26
28
  /** True when the column's type is a user-defined enum. */
27
29
  isEnum: boolean;
28
30
  /** Links to IntrospectedEnum.name when isEnum is true. */
@@ -30,6 +32,10 @@ export interface IntrospectedColumn {
30
32
  }
31
33
  /** A foreign key constraint (may be composite). */
32
34
  export interface IntrospectedFk {
35
+ /** The key is NOT VALID: existing rows were never checked against it. */
36
+ notValid?: boolean;
37
+ /** The constraint's name in the source database. */
38
+ name?: string;
33
39
  /** Local column(s) participating in the FK. */
34
40
  columns: string[];
35
41
  referencedTable: string;
@@ -44,8 +50,19 @@ export interface IntrospectedUnique {
44
50
  /** A secondary index (may be composite). */
45
51
  export interface IntrospectedIndex {
46
52
  name: string;
53
+ /** Plain columns only; an expression is flagged, not listed. */
47
54
  columns: string[];
48
55
  unique: boolean;
56
+ /** The index has a WHERE clause. */
57
+ partial?: boolean;
58
+ /** The WHERE condition, as Postgres prints it. */
59
+ predicate?: string;
60
+ /** A column is sorted DESC, which .apsorc cannot express yet. */
61
+ descending?: boolean;
62
+ /** The index covers an expression, e.g. lower(email). */
63
+ expression?: boolean;
64
+ /** pg_get_indexdef, for the import report. */
65
+ definition?: string;
49
66
  }
50
67
  /** A user-defined enum type and its labels (in sort order). */
51
68
  export interface IntrospectedEnum {
@@ -58,6 +75,14 @@ export interface IntrospectedTable {
58
75
  columns: IntrospectedColumn[];
59
76
  /** Ordered primary-key column names ([] if the table has no primary key). */
60
77
  primaryKey: string[];
78
+ /** The primary key constraint's name in the source database. */
79
+ primaryKeyName?: string;
80
+ /** CHECK constraints, with the expression as Postgres prints it. */
81
+ checks?: Array<{
82
+ name: string;
83
+ expression: string;
84
+ notValid?: boolean;
85
+ }>;
61
86
  foreignKeys: IntrospectedFk[];
62
87
  uniqueConstraints: IntrospectedUnique[];
63
88
  indexes: IntrospectedIndex[];
@@ -90,8 +115,30 @@ export interface ImportReport {
90
115
  viewsSkipped: string[];
91
116
  systemSchemasSkipped: string[];
92
117
  warnings: {
93
- /** "table.column" whose Postgres array type was reduced to text. */
118
+ /** "table.column" arrays whose element type is unknown, imported as text[]. */
94
119
  arraysLossy: string[];
120
+ /** "table.constraint" for CHECK constraints marked NOT VALID in the source. */
121
+ checksNotValid: string[];
122
+ /**
123
+ * "table.column" for a created_at or updated_at with no default in the
124
+ * source. TypeORM always gives these columns DEFAULT now().
125
+ */
126
+ timestampDefaultsAdded: string[];
127
+ /**
128
+ * Foreign keys whose relationship could not take its natural name because
129
+ * the table has a column of that name. The column itself is unchanged.
130
+ */
131
+ 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
+ /**
138
+ * Indexes .apsorc cannot express, as Postgres defines them: an expression
139
+ * or DESC index that is not a btree. They are left out.
140
+ */
141
+ indexesNotCarried: string[];
95
142
  /** Tables with composite primary keys (emitted as primary:true fields). */
96
143
  compositePks: string[];
97
144
  /** Tables with composite foreign keys (kept as scalar columns, no relationship). */
@@ -105,8 +152,6 @@ export interface ImportReport {
105
152
  column: string;
106
153
  udt: string;
107
154
  }>;
108
- /** FK columns whose name could not be round-tripped to a relationship name. */
109
- fkColumnNameUnmapped: string[];
110
155
  /** "table.column" defaults that were dropped (unsupported expressions). */
111
156
  defaultsDropped: string[];
112
157
  /** Tables that look like pure join tables (candidates for manual ManyToMany). */