@apso/cli 0.53.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.
- package/dist/commands/import/supabase.js +2 -2
- package/dist/commands/mcp/serve.js +1 -0
- package/dist/commands/schema/validate.js +18 -1
- package/dist/lib/base-command.js +14 -3
- package/dist/lib/config/types.d.ts +5 -0
- package/dist/lib/ddl/change.js +11 -4
- package/dist/lib/ddl/index.d.ts +17 -0
- package/dist/lib/ddl/index.js +35 -5
- package/dist/lib/generators/go.js +5 -2
- package/dist/lib/generators/python.js +5 -2
- package/dist/lib/generators/typescript.js +17 -2
- package/dist/lib/import/introspect.js +18 -12
- package/dist/lib/import/pg-to-apsorc.d.ts +1 -0
- package/dist/lib/import/pg-to-apsorc.js +27 -4
- package/dist/lib/import/types.d.ts +7 -5
- package/dist/lib/telemetry/error-utils.d.ts +74 -0
- package/dist/lib/telemetry/error-utils.js +221 -0
- package/dist/lib/telemetry/internal-constants.d.ts +27 -0
- package/dist/lib/telemetry/internal-constants.js +32 -0
- package/dist/lib/telemetry/internal-detection.d.ts +37 -0
- package/dist/lib/telemetry/internal-detection.js +78 -0
- package/dist/lib/telemetry/telemetry.d.ts +11 -0
- package/dist/lib/telemetry/telemetry.js +197 -3
- package/dist/lib/templates/entities/entity.eta +6 -0
- package/dist/lib/types/constraints.d.ts +14 -0
- package/dist/lib/types/entity.d.ts +3 -1
- package/dist/lib/upgrade.d.ts +5 -6
- package/dist/lib/upgrade.js +12 -23
- package/npm-shrinkwrap.json +7 -6
- package/oclif.manifest.json +1 -1
- package/package.json +2 -1
|
@@ -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
|
`;
|
|
@@ -11,6 +11,18 @@ const schema_tools_1 = require("@apso/schema-tools");
|
|
|
11
11
|
const apsorc_parser_1 = require("../../lib/apsorc-parser");
|
|
12
12
|
const generators_1 = require("../../lib/generators");
|
|
13
13
|
const schema_convert_1 = require("../../lib/utils/schema-convert");
|
|
14
|
+
/**
|
|
15
|
+
* A validation error that includes the individual error messages.
|
|
16
|
+
* This allows telemetry to extract and report the specific validation failures.
|
|
17
|
+
*/
|
|
18
|
+
class ValidationError extends Error {
|
|
19
|
+
constructor(message, errors) {
|
|
20
|
+
super(message);
|
|
21
|
+
this.userError = true;
|
|
22
|
+
this.name = "ValidationError";
|
|
23
|
+
this.errorMessages = errors;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
14
26
|
/**
|
|
15
27
|
* What `apso generate` would stop on: its configuration checks and the auth,
|
|
16
28
|
* permissions and mcp rules. It runs the generator's own checks
|
|
@@ -149,7 +161,12 @@ class SchemaValidate extends base_command_1.default {
|
|
|
149
161
|
for (const err of errors) {
|
|
150
162
|
this.log(` - ${err}`);
|
|
151
163
|
}
|
|
152
|
-
this.error(
|
|
164
|
+
// Use this.error() to maintain oclif's exit code 2 and formatting.
|
|
165
|
+
// Attach the error list so telemetry can still extract individual messages.
|
|
166
|
+
const validationError = new ValidationError(`Validation failed with ${errors.length} error(s).`, errors);
|
|
167
|
+
// this.error() will trigger base-command's catch(), which will extract
|
|
168
|
+
// errorMessages from the ValidationError and send them to telemetry.
|
|
169
|
+
this.error(validationError);
|
|
153
170
|
}
|
|
154
171
|
else {
|
|
155
172
|
this.log("Validation passed.");
|
package/dist/lib/base-command.js
CHANGED
|
@@ -6,6 +6,7 @@ const core_1 = require("@oclif/core");
|
|
|
6
6
|
const child_process_1 = require("child_process");
|
|
7
7
|
const os_1 = tslib_1.__importDefault(require("os"));
|
|
8
8
|
const telemetry_1 = require("./telemetry/telemetry");
|
|
9
|
+
const error_utils_1 = require("./telemetry/error-utils");
|
|
9
10
|
/**
|
|
10
11
|
* True for errors oclif raised deliberately (this.error, this.exit, parse
|
|
11
12
|
* errors) and for errors that mark themselves `userError` (problems in the
|
|
@@ -28,16 +29,26 @@ class BaseCommand extends core_1.Command {
|
|
|
28
29
|
// and arg parse failures) with an `oclif` property. Those are messages
|
|
29
30
|
// we chose to show the user, e.g. "No entity named X", not crashes, so
|
|
30
31
|
// they go to PostHog only. Everything else is a real bug for Sentry.
|
|
31
|
-
|
|
32
|
+
//
|
|
33
|
+
// Config and validation errors (ApsorcNamingError, validation failures)
|
|
34
|
+
// are also user errors, not CLI bugs.
|
|
35
|
+
const isOclifError = isUserError(err);
|
|
36
|
+
const isConfigError = (0, error_utils_1.isConfigOrValidationError)(err);
|
|
37
|
+
const userError = isOclifError || isConfigError;
|
|
38
|
+
// Sentry: only real bugs (not user errors)
|
|
32
39
|
if (!userError) {
|
|
33
40
|
(0, telemetry_1.captureException)(err, { command: this.id });
|
|
34
41
|
}
|
|
42
|
+
// PostHog: capture the exception with full context
|
|
43
|
+
(0, telemetry_1.capturePostHogException)(err, { command: this.id });
|
|
44
|
+
// Extract detailed error properties for the cli_command_failed event
|
|
45
|
+
const errorProps = (0, error_utils_1.extractErrorProperties)(err);
|
|
46
|
+
// Track the failure event with structured error properties
|
|
35
47
|
(0, telemetry_1.track)("cli_command_failed", {
|
|
36
48
|
command: this.id,
|
|
37
49
|
duration_ms: (0, telemetry_1.elapsedMs)(),
|
|
38
|
-
error: err === null || err === void 0 ? void 0 : err.message,
|
|
39
|
-
error_code: err === null || err === void 0 ? void 0 : err.code,
|
|
40
50
|
user_error: userError,
|
|
51
|
+
...errorProps,
|
|
41
52
|
});
|
|
42
53
|
await (0, telemetry_1.shutdownTelemetry)();
|
|
43
54
|
}
|
|
@@ -137,6 +137,11 @@ export interface GlobalConfigFile {
|
|
|
137
137
|
* User id this install's anonymous telemetry id was last aliased to.
|
|
138
138
|
*/
|
|
139
139
|
telemetryAliasedUserId?: string;
|
|
140
|
+
/**
|
|
141
|
+
* Mark this machine as internal (Apso team/system). Set via `apso config set internal true`.
|
|
142
|
+
* When true, all telemetry events are tagged as internal.
|
|
143
|
+
*/
|
|
144
|
+
internal?: boolean;
|
|
140
145
|
}
|
|
141
146
|
/**
|
|
142
147
|
* Project link stored in .apso/link.json
|
package/dist/lib/ddl/change.js
CHANGED
|
@@ -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
|
-
|
|
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 (
|
|
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
|
}
|
package/dist/lib/ddl/index.d.ts
CHANGED
|
@@ -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
|
package/dist/lib/ddl/index.js
CHANGED
|
@@ -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
|
|
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
|
-
...((
|
|
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 (
|
|
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 (
|
|
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.
|
|
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
|
|
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
|
|
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(
|
|
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
|
|
327
|
-
const list = (
|
|
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: (
|
|
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 = (
|
|
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 = (
|
|
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, [...((
|
|
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;
|
|
@@ -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
|
|
543
|
+
// column (usually an exact duplicate) is kept as a constraint only.
|
|
544
544
|
if (keyed.has(sourceColumn)) {
|
|
545
|
-
|
|
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.
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error extraction and redaction utilities for telemetry.
|
|
3
|
+
*
|
|
4
|
+
* Extracts useful error properties (class, normalized message, code, entity,
|
|
5
|
+
* field) while redacting sensitive data: file contents, secrets, tokens, env
|
|
6
|
+
* values, and absolute paths. Home-directory paths are redacted.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Maximum number of error messages to include in an array.
|
|
10
|
+
*/
|
|
11
|
+
export declare const MAX_ERROR_MESSAGES = 10;
|
|
12
|
+
/**
|
|
13
|
+
* Redact sensitive information from a string.
|
|
14
|
+
*/
|
|
15
|
+
export declare function redactSensitiveData(str: string): string;
|
|
16
|
+
/**
|
|
17
|
+
* Truncate a string to a maximum length, adding ellipsis if truncated.
|
|
18
|
+
*/
|
|
19
|
+
export declare function truncate(str: string, maxLength?: number): string;
|
|
20
|
+
/**
|
|
21
|
+
* Normalize an error message by redacting sensitive data and truncating.
|
|
22
|
+
*/
|
|
23
|
+
export declare function normalizeErrorMessage(message: string): string;
|
|
24
|
+
/**
|
|
25
|
+
* Extract the error class name from an error object.
|
|
26
|
+
*/
|
|
27
|
+
export declare function getErrorClass(err: unknown): string | undefined;
|
|
28
|
+
/**
|
|
29
|
+
* Extract the error code from an error object (if present).
|
|
30
|
+
*/
|
|
31
|
+
export declare function getErrorCode(err: unknown): string | undefined;
|
|
32
|
+
/**
|
|
33
|
+
* Extract entity name from an error object (for schema/config errors).
|
|
34
|
+
*/
|
|
35
|
+
export declare function getErrorEntity(err: unknown): string | undefined;
|
|
36
|
+
/**
|
|
37
|
+
* Extract field name from an error object (for schema/config errors).
|
|
38
|
+
*/
|
|
39
|
+
export declare function getErrorField(err: unknown): string | undefined;
|
|
40
|
+
/**
|
|
41
|
+
* Extract error messages array from a validation error.
|
|
42
|
+
* Used for errors that carry multiple individual messages (e.g. ValidationError).
|
|
43
|
+
*/
|
|
44
|
+
export declare function getErrorMessages(err: unknown): string[] | undefined;
|
|
45
|
+
/**
|
|
46
|
+
* Extract structured error properties for telemetry.
|
|
47
|
+
*
|
|
48
|
+
* @param err - The error object
|
|
49
|
+
* @returns Object with error properties suitable for telemetry
|
|
50
|
+
*/
|
|
51
|
+
export declare function extractErrorProperties(err: unknown): {
|
|
52
|
+
error_class?: string;
|
|
53
|
+
error_message?: string;
|
|
54
|
+
error_code?: string;
|
|
55
|
+
entity?: string;
|
|
56
|
+
field?: string;
|
|
57
|
+
error_messages?: string[];
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* Extract an array of error messages from multiple errors, redacted and truncated.
|
|
61
|
+
*
|
|
62
|
+
* Used for validation errors where multiple issues may be present.
|
|
63
|
+
*
|
|
64
|
+
* @param errors - Array of errors (strings or Error objects)
|
|
65
|
+
* @param maxCount - Maximum number of error messages to include
|
|
66
|
+
* @returns Array of redacted, truncated error messages
|
|
67
|
+
*/
|
|
68
|
+
export declare function extractErrorMessages(errors: Array<string | Error>, maxCount?: number): string[];
|
|
69
|
+
/**
|
|
70
|
+
* Check if an error is a config or validation error (a user error).
|
|
71
|
+
*
|
|
72
|
+
* Config and validation errors should be marked as user errors, not CLI bugs.
|
|
73
|
+
*/
|
|
74
|
+
export declare function isConfigOrValidationError(err: unknown): boolean;
|