@apso/cli 0.51.0 → 0.53.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/generate.js +3 -2
- package/dist/commands/import/supabase.js +31 -6
- package/dist/commands/init.d.ts +9 -0
- package/dist/commands/init.js +31 -1
- package/dist/commands/mcp/serve.js +23 -2
- package/dist/lib/apsorc-parser.d.ts +13 -1
- package/dist/lib/apsorc-parser.js +47 -4
- package/dist/lib/ddl/catalog.js +5 -2
- package/dist/lib/ddl/change.js +13 -2
- package/dist/lib/ddl/index.d.ts +62 -3
- package/dist/lib/ddl/index.js +211 -40
- package/dist/lib/generators/go.js +17 -3
- package/dist/lib/generators/python.js +17 -3
- package/dist/lib/generators/typescript.d.ts +2 -1
- package/dist/lib/generators/typescript.js +87 -13
- package/dist/lib/import/copy-data.js +4 -0
- package/dist/lib/import/introspect.d.ts +40 -0
- package/dist/lib/import/introspect.js +137 -49
- package/dist/lib/import/pg-to-apsorc.d.ts +62 -0
- package/dist/lib/import/pg-to-apsorc.js +248 -37
- package/dist/lib/import/types.d.ts +48 -3
- package/dist/lib/migrate/sandbox.js +23 -6
- package/dist/lib/migrate/snapshot.d.ts +5 -0
- package/dist/lib/plan/index.d.ts +4 -1
- package/dist/lib/plan/index.js +9 -3
- package/dist/lib/templates/entities/entity-col-array.eta +2 -1
- package/dist/lib/templates/entities/entity-col-bigint.eta +2 -2
- package/dist/lib/templates/entities/entity-col-bigserial.eta +2 -2
- package/dist/lib/templates/entities/entity-col-boolean.eta +1 -1
- package/dist/lib/templates/entities/entity-col-bytea.eta +2 -2
- package/dist/lib/templates/entities/entity-col-char.eta +4 -3
- package/dist/lib/templates/entities/entity-col-date.eta +6 -2
- package/dist/lib/templates/entities/entity-col-datetime.eta +8 -1
- package/dist/lib/templates/entities/entity-col-decimal.eta +2 -2
- package/dist/lib/templates/entities/entity-col-double.eta +2 -2
- package/dist/lib/templates/entities/entity-col-float.eta +1 -1
- package/dist/lib/templates/entities/entity-col-geography.eta +1 -1
- package/dist/lib/templates/entities/entity-col-geometry.eta +1 -1
- package/dist/lib/templates/entities/entity-col-geometrycollection.eta +1 -1
- package/dist/lib/templates/entities/entity-col-inet.eta +2 -2
- package/dist/lib/templates/entities/entity-col-int4range.eta +1 -1
- package/dist/lib/templates/entities/entity-col-integer.eta +2 -2
- package/dist/lib/templates/entities/entity-col-interval.eta +2 -2
- package/dist/lib/templates/entities/entity-col-json-plain.eta +1 -1
- package/dist/lib/templates/entities/entity-col-json.eta +1 -1
- package/dist/lib/templates/entities/entity-col-jsonb.eta +1 -1
- package/dist/lib/templates/entities/entity-col-linestring.eta +1 -1
- package/dist/lib/templates/entities/entity-col-money.eta +2 -2
- package/dist/lib/templates/entities/entity-col-multilinestring.eta +1 -1
- package/dist/lib/templates/entities/entity-col-multipoint.eta +1 -1
- package/dist/lib/templates/entities/entity-col-multipolygon.eta +1 -1
- package/dist/lib/templates/entities/entity-col-numeric.eta +2 -2
- package/dist/lib/templates/entities/entity-col-point.eta +1 -1
- package/dist/lib/templates/entities/entity-col-polygon.eta +1 -1
- package/dist/lib/templates/entities/entity-col-real.eta +2 -2
- package/dist/lib/templates/entities/entity-col-serial.eta +2 -2
- package/dist/lib/templates/entities/entity-col-smallint.eta +2 -2
- package/dist/lib/templates/entities/entity-col-smallserial.eta +2 -2
- package/dist/lib/templates/entities/entity-col-string.eta +2 -2
- package/dist/lib/templates/entities/entity-col-text.eta +4 -3
- package/dist/lib/templates/entities/entity-col-time.eta +2 -2
- package/dist/lib/templates/entities/entity-col-timestamp.eta +8 -1
- package/dist/lib/templates/entities/entity-col-timestamptz.eta +8 -1
- package/dist/lib/templates/entities/entity-col-timetz.eta +2 -2
- package/dist/lib/templates/entities/entity-col-tsvector.eta +2 -2
- package/dist/lib/templates/entities/entity-col-uuid.eta +5 -2
- package/dist/lib/templates/entities/entity-col-varchar.eta +4 -3
- package/dist/lib/templates/entities/entity-col-xml.eta +2 -2
- package/dist/lib/templates/entities/entity.eta +30 -18
- package/dist/lib/templates/go/models/model.eta +3 -3
- package/dist/lib/templates/python/models/model.eta +1 -1
- package/dist/lib/templates/rest/controller-rest.eta +25 -7
- package/dist/lib/templates/rest/dto-rest.eta +2 -2
- package/dist/lib/templates/rest/index-module-rest.eta +10 -0
- package/dist/lib/templates/rest/schema-extras-module.eta +24 -0
- package/dist/lib/types/constraints.d.ts +13 -0
- package/dist/lib/types/entity.d.ts +67 -2
- package/dist/lib/types/entity.js +39 -1
- package/dist/lib/types/field.d.ts +20 -2
- package/dist/lib/types/generator.d.ts +16 -0
- package/dist/lib/types/index.d.ts +1 -1
- package/dist/lib/types/indices.d.ts +21 -0
- package/dist/lib/types/relationship.d.ts +33 -0
- package/dist/lib/types/relationship.js +13 -0
- package/dist/lib/utils/field.d.ts +22 -0
- package/dist/lib/utils/field.js +62 -3
- package/dist/lib/utils/relationships/index.d.ts +1 -1
- package/dist/lib/utils/relationships/index.js +2 -1
- package/dist/lib/utils/relationships/parse.d.ts +11 -0
- package/dist/lib/utils/relationships/parse.js +44 -1
- package/dist/lib/utils/template.d.ts +3 -3
- package/dist/lib/utils/template.js +4 -4
- package/dist/lib/verify/crud-plan.d.ts +2 -0
- package/dist/lib/verify/crud-plan.js +19 -5
- package/dist/lib/verify/index.js +32 -3
- package/npm-shrinkwrap.json +72 -87
- package/oclif.manifest.json +7 -1
- package/package.json +3 -2
|
@@ -5,6 +5,20 @@ const tslib_1 = require("tslib");
|
|
|
5
5
|
const path = tslib_1.__importStar(require("path"));
|
|
6
6
|
const Eta = tslib_1.__importStar(require("eta"));
|
|
7
7
|
const base_1 = require("./base");
|
|
8
|
+
const entity_1 = require("../types/entity");
|
|
9
|
+
// The options of @CreateDateColumn / @UpdateDateColumn: empty for the default
|
|
10
|
+
// (timestamp, NOT NULL), so entities generated before these settings are unchanged.
|
|
11
|
+
const timestampArgs = (entity, column) => {
|
|
12
|
+
const args = [
|
|
13
|
+
...((0, entity_1.timestampTypeOf)(entity, column) === "timestamptz"
|
|
14
|
+
? ["type: 'timestamptz'"]
|
|
15
|
+
: []),
|
|
16
|
+
...((0, entity_1.timestampNullableOf)(entity, column) ? ["nullable: true"] : []),
|
|
17
|
+
];
|
|
18
|
+
return args.length > 0 ? `{ ${args.join(", ")} }` : "";
|
|
19
|
+
};
|
|
20
|
+
const relationship_1 = require("../types/relationship");
|
|
21
|
+
const ddl_1 = require("../ddl");
|
|
8
22
|
// Utilities available for future use: createFile from "../utils/file-system"
|
|
9
23
|
const field_1 = require("../utils/field");
|
|
10
24
|
const relationships_1 = require("../utils/relationships");
|
|
@@ -75,40 +89,72 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
|
|
|
75
89
|
return this.createValidationResult(errors, warnings);
|
|
76
90
|
}
|
|
77
91
|
async generateEntity(options) {
|
|
92
|
+
var _a, _b;
|
|
78
93
|
const { entity, relationships, allEntities, apiType } = options;
|
|
79
94
|
const { name, fields = [], indexes, uniques } = entity;
|
|
80
|
-
const columns = (0, field_1.getFieldForTemplate)(fields, name)
|
|
81
|
-
|
|
95
|
+
const columns = (0, field_1.getFieldForTemplate)(fields, name).map((c) => c.defaultSql === undefined
|
|
96
|
+
? c
|
|
97
|
+
: { ...c, defaultSql: (0, field_1.typeormDefault)(c.defaultSql) });
|
|
82
98
|
const createdAt = entity.created_at;
|
|
83
99
|
const updatedAt = entity.updated_at;
|
|
84
100
|
const primaryKeyType = entity.primaryKeyType || "serial";
|
|
85
101
|
const relationshipsForTemplate = (0, relationships_1.getRelationshipForTemplate)(name, relationships, allEntities);
|
|
86
102
|
const entitiesToImport = (0, relationships_1.getRelationshipsForImport)(name, relationshipsForTemplate);
|
|
103
|
+
// No generated id when a field, or a foreign key, is the primary key.
|
|
104
|
+
const createPrimaryKey = !columns.some((column) => column.primary === true) &&
|
|
105
|
+
!relationshipsForTemplate.some((r) => r.primary);
|
|
87
106
|
// A OneToOne's FK column has no property of its own on the entity, so
|
|
88
107
|
// @Index/@Unique name the relation property; TypeORM resolves it to the
|
|
89
108
|
// join column (workspaceId -> workspace).
|
|
90
109
|
const oneToOneColumns = new Map(relationshipsForTemplate
|
|
91
110
|
.filter((r) => r.type === "OneToOne" && r.joinTable)
|
|
92
|
-
.
|
|
111
|
+
.flatMap((r) => [r.camelCasedId, r.joinColumnName]
|
|
112
|
+
.filter(Boolean)
|
|
113
|
+
.map((column) => [column, r.relationshipName])));
|
|
114
|
+
// A ManyToOne's "joinColumnName" is a database name; @Index and @Unique
|
|
115
|
+
// take the property that maps to it (patient_id -> patientId).
|
|
116
|
+
const joinColumns = new Map(relationshipsForTemplate
|
|
117
|
+
.filter((r) => r.type === "ManyToOne" && r.joinColumnName)
|
|
118
|
+
.map((r) => [r.joinColumnName, r.camelCasedId]));
|
|
119
|
+
const fieldNames = new Set(columns.map((c) => c.name));
|
|
93
120
|
const toProperties = (list = []) => list.map((c) => ({
|
|
94
121
|
...c,
|
|
95
|
-
fields: c.fields.map((f) => { var _a; return (_a = oneToOneColumns.get(f)) !== null && _a !== void 0 ? _a : f; }),
|
|
122
|
+
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; }),
|
|
96
123
|
}));
|
|
97
124
|
const data = {
|
|
98
125
|
name,
|
|
99
126
|
indexes: toProperties(indexes),
|
|
100
127
|
uniques: toProperties(uniques),
|
|
128
|
+
checks: (_a = entity.checks) !== null && _a !== void 0 ? _a : [],
|
|
129
|
+
sqlIndexes: (_b = entity.sqlIndexes) !== null && _b !== void 0 ? _b : [],
|
|
101
130
|
createPrimaryKey,
|
|
102
131
|
primaryKeyType,
|
|
132
|
+
primaryKeyName: entity.primaryKeyName,
|
|
133
|
+
primaryKeyDefault: entity.primaryKeyDefault,
|
|
134
|
+
primaryKeyGenerated: (0, field_1.isUuidGenerator)(entity.primaryKeyDefault),
|
|
103
135
|
snakeCasedName: (0, casing_1.snakeCase)(name),
|
|
104
136
|
// Honor an explicit per-entity `table` override; otherwise derive from
|
|
105
137
|
// the entity name. See apsoai/cli#98.
|
|
106
138
|
tableName: entity.table || (0, casing_1.snakeCase)(name),
|
|
107
139
|
createdAt,
|
|
108
140
|
updatedAt,
|
|
141
|
+
createdAtArgs: timestampArgs(entity, "created_at"),
|
|
142
|
+
updatedAtArgs: timestampArgs(entity, "updated_at"),
|
|
109
143
|
pluralizedName: (0, casing_1.camelCase)((0, pluralize_1.default)(name)),
|
|
110
|
-
|
|
111
|
-
|
|
144
|
+
// Every column of a named primary key carries the name (TypeORM requires it).
|
|
145
|
+
columns: columns.map((c) => c.primary && entity.primaryKeyName
|
|
146
|
+
? { ...c, primaryKeyName: entity.primaryKeyName }
|
|
147
|
+
: c),
|
|
148
|
+
associations: [...new Set(relationshipsForTemplate)].map((r) => {
|
|
149
|
+
// A foreign key column copies the type of the key it references.
|
|
150
|
+
const key = (0, ddl_1.keyColumn)(allEntities.find((e) => e.name === r.name));
|
|
151
|
+
return {
|
|
152
|
+
...r,
|
|
153
|
+
onDeleteRule: (0, relationship_1.onDeleteOf)(r),
|
|
154
|
+
fkColumnOptions: key.options,
|
|
155
|
+
fkTsType: key.ts,
|
|
156
|
+
};
|
|
157
|
+
}),
|
|
112
158
|
entitiesToImport,
|
|
113
159
|
importEnums: (0, field_1.typeExistsInEntity)(entity, "enum") !== -1,
|
|
114
160
|
apiType,
|
|
@@ -125,7 +171,7 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
|
|
|
125
171
|
];
|
|
126
172
|
}
|
|
127
173
|
async generateController(options) {
|
|
128
|
-
var _a;
|
|
174
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
|
|
129
175
|
const { entity, relationships, relationshipMap, auth } = options;
|
|
130
176
|
const { name: entityName } = entity;
|
|
131
177
|
// Auth entities are for service callers only, so no other entity's
|
|
@@ -162,12 +208,25 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
|
|
|
162
208
|
bypassRoles: scoped.bypassRoles,
|
|
163
209
|
};
|
|
164
210
|
const mcp = (0, guards_1.mcpOperations)(entity);
|
|
211
|
+
// The :id route parameter maps to the entity's own key: a primary field,
|
|
212
|
+
// or the id property of a foreign key that is the primary key. A
|
|
213
|
+
// composite key has no single field, so it keeps the default.
|
|
214
|
+
const keyFields = [
|
|
215
|
+
...((_b = entity.fields) !== null && _b !== void 0 ? _b : []).filter((f) => f.primary).map((f) => f.name),
|
|
216
|
+
...relationshipsForTemplate
|
|
217
|
+
.filter((r) => r.primary)
|
|
218
|
+
.map((r) => r.camelCasedId),
|
|
219
|
+
];
|
|
165
220
|
const data = {
|
|
166
221
|
svcName,
|
|
167
222
|
ctrlName,
|
|
168
223
|
entityName,
|
|
169
224
|
pluralEntityName,
|
|
170
225
|
primaryKeyType,
|
|
226
|
+
generatedFields: ((_c = entity.fields) !== null && _c !== void 0 ? _c : [])
|
|
227
|
+
.filter((f) => f.generated)
|
|
228
|
+
.map((f) => f.name),
|
|
229
|
+
keyField: keyFields.length === 1 ? keyFields[0] : "id",
|
|
171
230
|
associations: [...new Set(relationshipsForTemplate)],
|
|
172
231
|
nestedJoinsFile,
|
|
173
232
|
// scopeBy fields @CrudAuth adds to every query once a caller is
|
|
@@ -183,6 +242,10 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
|
|
|
183
242
|
mcp,
|
|
184
243
|
mcpName: (0, casing_1.snakeCase)(entityName),
|
|
185
244
|
mcpPluralName: (0, casing_1.snakeCase)(pluralEntityName),
|
|
245
|
+
dialects: (_e = (_d = options.query) === null || _d === void 0 ? void 0 : _d.dialects) !== null && _e !== void 0 ? _e : ["postgrest"],
|
|
246
|
+
dialectList: ((_g = (_f = options.query) === null || _f === void 0 ? void 0 : _f.dialects) !== null && _g !== void 0 ? _g : ["postgrest"]).map((d) => `'${d}'`).join(", "),
|
|
247
|
+
limit: (_j = (_h = options.query) === null || _h === void 0 ? void 0 : _h.limit) !== null && _j !== void 0 ? _j : 25,
|
|
248
|
+
alwaysPaginate: (_l = (_k = options.query) === null || _k === void 0 ? void 0 : _k.alwaysPaginate) !== null && _l !== void 0 ? _l : false,
|
|
186
249
|
};
|
|
187
250
|
const controllerContent = await this.renderTemplate("./rest/controller-rest", data);
|
|
188
251
|
const specContent = await this.renderTemplate("./rest/controller-rest-spec", data);
|
|
@@ -258,14 +321,14 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
|
|
|
258
321
|
if (rel.type === "ManyToOne") {
|
|
259
322
|
const fkName = (0, casing_1.camelCase)(rel.referenceName || rel.name) + "Id";
|
|
260
323
|
const referencedEntity = allEntities === null || allEntities === void 0 ? void 0 : allEntities.find((e) => e.name === rel.name);
|
|
261
|
-
const
|
|
262
|
-
const
|
|
263
|
-
const fkType = referencedPrimaryKeyType === "uuid" ? "text" : "integer";
|
|
324
|
+
const fkDataType = (0, ddl_1.keyColumn)(referencedEntity).ts;
|
|
325
|
+
const fkType = fkDataType === "string" ? "text" : "integer";
|
|
264
326
|
if (!columns.some((col) => col.name === fkName)) {
|
|
265
327
|
columns.push({
|
|
266
328
|
name: fkName,
|
|
267
329
|
dataType: fkDataType,
|
|
268
330
|
type: fkType,
|
|
331
|
+
...(rel.primary && { primary: true }),
|
|
269
332
|
});
|
|
270
333
|
}
|
|
271
334
|
}
|
|
@@ -355,15 +418,26 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
|
|
|
355
418
|
},
|
|
356
419
|
];
|
|
357
420
|
}
|
|
358
|
-
async generateIndexModule(entities, apiType,
|
|
421
|
+
async generateIndexModule(entities, apiType, opts) {
|
|
359
422
|
// Listing GuardsModule is what turns the global guards on; every service
|
|
360
|
-
// has at least the API key check.
|
|
361
|
-
|
|
423
|
+
// has at least the API key check. `.apsorc` "guards": false leaves it out.
|
|
424
|
+
// "sqlIndexes" are created by a generated module, after TypeORM's sync.
|
|
425
|
+
const statements = entities.flatMap((e) => (0, ddl_1.sqlIndexStatements)(e));
|
|
426
|
+
const schemaExtras = apiType === "rest" && statements.length > 0;
|
|
427
|
+
const content = await this.renderTemplate(`./${apiType}/index-module-${apiType}`, { entities, schemaExtras, guards: (opts === null || opts === void 0 ? void 0 : opts.guards) !== false });
|
|
362
428
|
return [
|
|
363
429
|
{
|
|
364
430
|
path: "index.ts",
|
|
365
431
|
content,
|
|
366
432
|
},
|
|
433
|
+
...(schemaExtras
|
|
434
|
+
? [
|
|
435
|
+
{
|
|
436
|
+
path: "schema-extras.module.ts",
|
|
437
|
+
content: await this.renderTemplate("./rest/schema-extras-module", { statements }),
|
|
438
|
+
},
|
|
439
|
+
]
|
|
440
|
+
: []),
|
|
367
441
|
];
|
|
368
442
|
}
|
|
369
443
|
async generateGuards(entities, auth, relationshipMap) {
|
|
@@ -116,6 +116,10 @@ function planCopy(source, targetColumnsByTable, tableFilter) {
|
|
|
116
116
|
const keptSource = [];
|
|
117
117
|
const keptTarget = [];
|
|
118
118
|
for (const m of mapping) {
|
|
119
|
+
// An import keeps foreign key column names ("joinColumnName"); a project
|
|
120
|
+
// imported by an older CLI has the generated camelCase name instead.
|
|
121
|
+
if (targetColumns.has(m.sourceColumn))
|
|
122
|
+
m.targetColumn = m.sourceColumn;
|
|
119
123
|
if (targetColumns.has(m.targetColumn)) {
|
|
120
124
|
keptSource.push(m.sourceColumn);
|
|
121
125
|
keptTarget.push(m.targetColumn);
|
|
@@ -14,6 +14,12 @@ import { IntrospectedSchema, Introspector } from "./types";
|
|
|
14
14
|
export declare const SYSTEM_SCHEMAS: Set<string>;
|
|
15
15
|
/** Strip credentials from a connection string for safe display in errors. */
|
|
16
16
|
export declare function redactConnectionString(input: string): string;
|
|
17
|
+
interface QueryClient {
|
|
18
|
+
query(sql: string, params?: unknown[]): Promise<{
|
|
19
|
+
rows: any[];
|
|
20
|
+
}>;
|
|
21
|
+
end(): Promise<void>;
|
|
22
|
+
}
|
|
17
23
|
/**
|
|
18
24
|
* Reads schema metadata from a Postgres database via a connection string.
|
|
19
25
|
* SSL is enabled by default (Supabase requires it).
|
|
@@ -24,6 +30,39 @@ export declare class PgIntrospector implements Introspector {
|
|
|
24
30
|
private connect;
|
|
25
31
|
introspect(schema: string): Promise<IntrospectedSchema>;
|
|
26
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
* Read a schema through an open client. Separate from the connection so the
|
|
35
|
+
* round-trip test can read an in-process database.
|
|
36
|
+
*
|
|
37
|
+
* @param {object} client - Anything with pg's query(sql, params).
|
|
38
|
+
* @param {string} schema - The database schema to read.
|
|
39
|
+
* @returns {Promise<IntrospectedSchema>} The schema's tables, keys, indexes and enums.
|
|
40
|
+
*/
|
|
41
|
+
export declare function introspectClient(client: Pick<QueryClient, "query">, schema: string): Promise<IntrospectedSchema>;
|
|
42
|
+
/**
|
|
43
|
+
* The expression of a check constraint from pg_get_constraintdef's
|
|
44
|
+
* "CHECK (<expression>) [NOT VALID]".
|
|
45
|
+
*
|
|
46
|
+
* Postgres prints a value list on a varchar column as
|
|
47
|
+
* (col)::text = ANY ((ARRAY['a'::character varying, ...])::text[]), and
|
|
48
|
+
* prints that text differently when it is parsed again. Written back as
|
|
49
|
+
* col IN ('a', ...), it parses to the form the source has.
|
|
50
|
+
*
|
|
51
|
+
* @param {string} definition - pg_get_constraintdef's output.
|
|
52
|
+
* @returns {string} The expression to store in .apsorc.
|
|
53
|
+
*/
|
|
54
|
+
export declare function checkExpression(definition: string): string;
|
|
55
|
+
/**
|
|
56
|
+
* Postgres prints a value list on a varchar column as
|
|
57
|
+
* (col)::text = ANY ((ARRAY['a'::character varying, ...])::text[]), and
|
|
58
|
+
* prints that text differently when it is parsed again. Written back as
|
|
59
|
+
* col IN ('a', ...), it parses to the form the source has. Used for check
|
|
60
|
+
* expressions and for the WHERE condition of a partial index.
|
|
61
|
+
*
|
|
62
|
+
* @param {string} sql - An expression as Postgres prints it.
|
|
63
|
+
* @returns {string} The same expression with value lists written as IN.
|
|
64
|
+
*/
|
|
65
|
+
export declare function valueLists(sql: string): string;
|
|
27
66
|
interface RawRows {
|
|
28
67
|
tableRows: any[];
|
|
29
68
|
columnRows: any[];
|
|
@@ -33,6 +72,7 @@ interface RawRows {
|
|
|
33
72
|
indexRows: any[];
|
|
34
73
|
enumRows: any[];
|
|
35
74
|
schemaRows: any[];
|
|
75
|
+
checkRows?: any[];
|
|
36
76
|
}
|
|
37
77
|
/**
|
|
38
78
|
* Assemble raw query rows into an IntrospectedSchema. Exported (separate from
|
|
@@ -34,7 +34,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
|
|
|
34
34
|
return result;
|
|
35
35
|
};
|
|
36
36
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
37
|
-
exports.buildSchema = exports.PgIntrospector = exports.redactConnectionString = exports.SYSTEM_SCHEMAS = void 0;
|
|
37
|
+
exports.buildSchema = exports.valueLists = exports.checkExpression = exports.introspectClient = exports.PgIntrospector = exports.redactConnectionString = exports.SYSTEM_SCHEMAS = void 0;
|
|
38
38
|
/** Supabase- and Postgres-managed schemas we never import from. */
|
|
39
39
|
exports.SYSTEM_SCHEMAS = new Set([
|
|
40
40
|
"auth",
|
|
@@ -93,26 +93,7 @@ class PgIntrospector {
|
|
|
93
93
|
let client;
|
|
94
94
|
try {
|
|
95
95
|
client = await this.connect();
|
|
96
|
-
|
|
97
|
-
await client.query(TABLES_SQL, [schema]),
|
|
98
|
-
await client.query(COLUMNS_SQL, [schema]),
|
|
99
|
-
await client.query(PRIMARY_KEYS_SQL, [schema]),
|
|
100
|
-
await client.query(FOREIGN_KEYS_SQL, [schema]),
|
|
101
|
-
await client.query(UNIQUE_SQL, [schema]),
|
|
102
|
-
await client.query(INDEXES_SQL, [schema]),
|
|
103
|
-
await client.query(ENUMS_SQL, [schema]),
|
|
104
|
-
await client.query(SCHEMAS_SQL),
|
|
105
|
-
];
|
|
106
|
-
return buildSchema(schema, {
|
|
107
|
-
tableRows: tableRows.rows,
|
|
108
|
-
columnRows: columnRows.rows,
|
|
109
|
-
pkRows: pkRows.rows,
|
|
110
|
-
fkRows: fkRows.rows,
|
|
111
|
-
uniqueRows: uniqueRows.rows,
|
|
112
|
-
indexRows: indexRows.rows,
|
|
113
|
-
enumRows: enumRows.rows,
|
|
114
|
-
schemaRows: schemaRows.rows,
|
|
115
|
-
});
|
|
96
|
+
return await introspectClient(client, schema);
|
|
116
97
|
}
|
|
117
98
|
catch (error) {
|
|
118
99
|
const message = error instanceof Error ? error.message : String(error);
|
|
@@ -125,6 +106,39 @@ class PgIntrospector {
|
|
|
125
106
|
}
|
|
126
107
|
}
|
|
127
108
|
exports.PgIntrospector = PgIntrospector;
|
|
109
|
+
/**
|
|
110
|
+
* Read a schema through an open client. Separate from the connection so the
|
|
111
|
+
* round-trip test can read an in-process database.
|
|
112
|
+
*
|
|
113
|
+
* @param {object} client - Anything with pg's query(sql, params).
|
|
114
|
+
* @param {string} schema - The database schema to read.
|
|
115
|
+
* @returns {Promise<IntrospectedSchema>} The schema's tables, keys, indexes and enums.
|
|
116
|
+
*/
|
|
117
|
+
async function introspectClient(client, schema) {
|
|
118
|
+
const [tableRows, columnRows, pkRows, fkRows, uniqueRows, indexRows, enumRows, schemaRows, checkRows,] = [
|
|
119
|
+
await client.query(TABLES_SQL, [schema]),
|
|
120
|
+
await client.query(COLUMNS_SQL, [schema]),
|
|
121
|
+
await client.query(PRIMARY_KEYS_SQL, [schema]),
|
|
122
|
+
await client.query(FOREIGN_KEYS_SQL, [schema]),
|
|
123
|
+
await client.query(UNIQUE_SQL, [schema]),
|
|
124
|
+
await client.query(INDEXES_SQL, [schema]),
|
|
125
|
+
await client.query(ENUMS_SQL, [schema]),
|
|
126
|
+
await client.query(SCHEMAS_SQL),
|
|
127
|
+
await client.query(CHECKS_SQL, [schema]),
|
|
128
|
+
];
|
|
129
|
+
return buildSchema(schema, {
|
|
130
|
+
tableRows: tableRows.rows,
|
|
131
|
+
columnRows: columnRows.rows,
|
|
132
|
+
pkRows: pkRows.rows,
|
|
133
|
+
fkRows: fkRows.rows,
|
|
134
|
+
uniqueRows: uniqueRows.rows,
|
|
135
|
+
indexRows: indexRows.rows,
|
|
136
|
+
enumRows: enumRows.rows,
|
|
137
|
+
schemaRows: schemaRows.rows,
|
|
138
|
+
checkRows: checkRows.rows,
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
exports.introspectClient = introspectClient;
|
|
128
142
|
const TABLES_SQL = `
|
|
129
143
|
SELECT table_name, table_type
|
|
130
144
|
FROM information_schema.tables
|
|
@@ -133,12 +147,12 @@ const TABLES_SQL = `
|
|
|
133
147
|
const COLUMNS_SQL = `
|
|
134
148
|
SELECT table_name, column_name, udt_name, data_type, is_nullable,
|
|
135
149
|
column_default, character_maximum_length, numeric_precision,
|
|
136
|
-
numeric_scale, ordinal_position
|
|
150
|
+
numeric_scale, ordinal_position, is_generated, generation_expression
|
|
137
151
|
FROM information_schema.columns
|
|
138
152
|
WHERE table_schema = $1
|
|
139
153
|
ORDER BY table_name, ordinal_position`;
|
|
140
154
|
const PRIMARY_KEYS_SQL = `
|
|
141
|
-
SELECT cl.relname AS table_name, att.attname AS column_name, ord.n AS key_index
|
|
155
|
+
SELECT con.conname, cl.relname AS table_name, att.attname AS column_name, ord.n AS key_index
|
|
142
156
|
FROM pg_constraint con
|
|
143
157
|
JOIN pg_class cl ON cl.oid = con.conrelid
|
|
144
158
|
JOIN pg_namespace ns ON ns.oid = cl.relnamespace
|
|
@@ -149,7 +163,7 @@ const PRIMARY_KEYS_SQL = `
|
|
|
149
163
|
const FOREIGN_KEYS_SQL = `
|
|
150
164
|
SELECT con.conname, cl.relname AS table_name, att.attname AS column_name,
|
|
151
165
|
clf.relname AS referenced_table, attf.attname AS referenced_column,
|
|
152
|
-
con.confdeltype, ord.n AS key_index
|
|
166
|
+
con.confdeltype, con.convalidated, ord.n AS key_index
|
|
153
167
|
FROM pg_constraint con
|
|
154
168
|
JOIN pg_class cl ON cl.oid = con.conrelid
|
|
155
169
|
JOIN pg_namespace ns ON ns.oid = cl.relnamespace
|
|
@@ -168,15 +182,62 @@ const UNIQUE_SQL = `
|
|
|
168
182
|
JOIN pg_attribute att ON att.attrelid = con.conrelid AND att.attnum = ord.attnum
|
|
169
183
|
WHERE con.contype = 'u' AND ns.nspname = $1
|
|
170
184
|
ORDER BY con.conname, ord.n`;
|
|
185
|
+
/**
|
|
186
|
+
* The expression of a check constraint from pg_get_constraintdef's
|
|
187
|
+
* "CHECK (<expression>) [NOT VALID]".
|
|
188
|
+
*
|
|
189
|
+
* Postgres prints a value list on a varchar column as
|
|
190
|
+
* (col)::text = ANY ((ARRAY['a'::character varying, ...])::text[]), and
|
|
191
|
+
* prints that text differently when it is parsed again. Written back as
|
|
192
|
+
* col IN ('a', ...), it parses to the form the source has.
|
|
193
|
+
*
|
|
194
|
+
* @param {string} definition - pg_get_constraintdef's output.
|
|
195
|
+
* @returns {string} The expression to store in .apsorc.
|
|
196
|
+
*/
|
|
197
|
+
function checkExpression(definition) {
|
|
198
|
+
const expression = definition
|
|
199
|
+
.replace(/\s+NOT VALID$/, "")
|
|
200
|
+
.replace(/^CHECK \((.*)\)$/s, "$1");
|
|
201
|
+
return valueLists(expression);
|
|
202
|
+
}
|
|
203
|
+
exports.checkExpression = checkExpression;
|
|
204
|
+
/**
|
|
205
|
+
* Postgres prints a value list on a varchar column as
|
|
206
|
+
* (col)::text = ANY ((ARRAY['a'::character varying, ...])::text[]), and
|
|
207
|
+
* prints that text differently when it is parsed again. Written back as
|
|
208
|
+
* col IN ('a', ...), it parses to the form the source has. Used for check
|
|
209
|
+
* expressions and for the WHERE condition of a partial index.
|
|
210
|
+
*
|
|
211
|
+
* @param {string} sql - An expression as Postgres prints it.
|
|
212
|
+
* @returns {string} The same expression with value lists written as IN.
|
|
213
|
+
*/
|
|
214
|
+
function valueLists(sql) {
|
|
215
|
+
return sql.replace(/\((\w+)\)::text (=|<>) (ANY|ALL) \(\(ARRAY\[((?:'(?:[^']|'')*'::character varying(?:, )?)+)]\)::text\[]\)/g, (_all, column, op, quantifier, list) => (op === "=" && quantifier === "ANY") || (op === "<>" && quantifier === "ALL")
|
|
216
|
+
? `${column} ${op === "=" ? "IN" : "NOT IN"} (${list.replace(/::character varying/g, "")})`
|
|
217
|
+
: _all);
|
|
218
|
+
}
|
|
219
|
+
exports.valueLists = valueLists;
|
|
220
|
+
const CHECKS_SQL = `
|
|
221
|
+
SELECT cl.relname AS table_name, con.conname, con.convalidated,
|
|
222
|
+
pg_get_constraintdef(con.oid) AS definition
|
|
223
|
+
FROM pg_constraint con
|
|
224
|
+
JOIN pg_class cl ON cl.oid = con.conrelid
|
|
225
|
+
JOIN pg_namespace ns ON ns.oid = cl.relnamespace
|
|
226
|
+
WHERE con.contype = 'c' AND ns.nspname = $1
|
|
227
|
+
ORDER BY cl.relname, con.conname`;
|
|
171
228
|
const INDEXES_SQL = `
|
|
172
229
|
SELECT tc.relname AS table_name, ic.relname AS index_name,
|
|
173
|
-
a.attname AS column_name, ix.indisunique, k.n AS ord
|
|
230
|
+
a.attname AS column_name, ix.indisunique, k.n AS ord,
|
|
231
|
+
ix.indpred IS NOT NULL AS partial,
|
|
232
|
+
pg_get_expr(ix.indpred, ix.indrelid) AS predicate,
|
|
233
|
+
(ix.indoption[k.n - 1] & 1) = 1 AS descending,
|
|
234
|
+
pg_get_indexdef(ix.indexrelid) AS definition
|
|
174
235
|
FROM pg_index ix
|
|
175
236
|
JOIN pg_class ic ON ic.oid = ix.indexrelid
|
|
176
237
|
JOIN pg_class tc ON tc.oid = ix.indrelid
|
|
177
238
|
JOIN pg_namespace ns ON ns.oid = tc.relnamespace
|
|
178
239
|
JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, n) ON true
|
|
179
|
-
JOIN pg_attribute a ON a.attrelid = tc.oid AND a.attnum = k.attnum
|
|
240
|
+
LEFT JOIN pg_attribute a ON a.attrelid = tc.oid AND a.attnum = k.attnum
|
|
180
241
|
WHERE ns.nspname = $1 AND ix.indisprimary = false
|
|
181
242
|
ORDER BY tc.relname, ic.relname, k.n`;
|
|
182
243
|
const ENUMS_SQL = `
|
|
@@ -192,7 +253,7 @@ const SCHEMAS_SQL = `SELECT schema_name FROM information_schema.schemata`;
|
|
|
192
253
|
* the DB connection) so it can be unit-tested with fixture rows.
|
|
193
254
|
*/
|
|
194
255
|
function buildSchema(schema, raw) {
|
|
195
|
-
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
|
|
256
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
|
|
196
257
|
// Enums
|
|
197
258
|
const enumMap = new Map();
|
|
198
259
|
for (const row of raw.enumRows) {
|
|
@@ -222,19 +283,25 @@ function buildSchema(schema, raw) {
|
|
|
222
283
|
numericPrecision: (_d = row.numeric_precision) !== null && _d !== void 0 ? _d : null,
|
|
223
284
|
numericScale: (_e = row.numeric_scale) !== null && _e !== void 0 ? _e : null,
|
|
224
285
|
ordinal: row.ordinal_position,
|
|
286
|
+
...(row.is_generated === "ALWAYS" && {
|
|
287
|
+
generated: (_f = row.generation_expression) !== null && _f !== void 0 ? _f : "",
|
|
288
|
+
}),
|
|
225
289
|
isEnum,
|
|
226
290
|
enumTypeName: isEnum ? row.udt_name : undefined,
|
|
227
291
|
};
|
|
228
|
-
const list = (
|
|
292
|
+
const list = (_g = columnsByTable.get(row.table_name)) !== null && _g !== void 0 ? _g : [];
|
|
229
293
|
list.push(col);
|
|
230
294
|
columnsByTable.set(row.table_name, list);
|
|
231
295
|
}
|
|
232
296
|
// Primary keys
|
|
233
297
|
const pkByTable = new Map();
|
|
298
|
+
const pkNameByTable = new Map();
|
|
234
299
|
for (const row of raw.pkRows) {
|
|
235
|
-
const list = (
|
|
300
|
+
const list = (_h = pkByTable.get(row.table_name)) !== null && _h !== void 0 ? _h : [];
|
|
236
301
|
list.push(row.column_name);
|
|
237
302
|
pkByTable.set(row.table_name, list);
|
|
303
|
+
if (row.conname)
|
|
304
|
+
pkNameByTable.set(row.table_name, row.conname);
|
|
238
305
|
}
|
|
239
306
|
// Foreign keys (grouped by constraint name to handle composite keys)
|
|
240
307
|
const fkByConstraint = new Map();
|
|
@@ -251,17 +318,20 @@ function buildSchema(schema, raw) {
|
|
|
251
318
|
refTable: row.referenced_table,
|
|
252
319
|
refColumns: [row.referenced_column],
|
|
253
320
|
confdeltype: row.confdeltype,
|
|
321
|
+
notValid: row.convalidated === false,
|
|
254
322
|
});
|
|
255
323
|
}
|
|
256
324
|
}
|
|
257
325
|
const fksByTable = new Map();
|
|
258
|
-
for (const fk of fkByConstraint.
|
|
259
|
-
const list = (
|
|
326
|
+
for (const [name, fk] of fkByConstraint.entries()) {
|
|
327
|
+
const list = (_j = fksByTable.get(fk.table)) !== null && _j !== void 0 ? _j : [];
|
|
260
328
|
list.push({
|
|
329
|
+
name,
|
|
330
|
+
...(fk.notValid && { notValid: true }),
|
|
261
331
|
columns: fk.columns,
|
|
262
332
|
referencedTable: fk.refTable,
|
|
263
333
|
referencedColumns: fk.refColumns,
|
|
264
|
-
onDelete: (
|
|
334
|
+
onDelete: (_k = CONFDELTYPE_TO_ACTION[fk.confdeltype]) !== null && _k !== void 0 ? _k : "NO ACTION",
|
|
265
335
|
});
|
|
266
336
|
fksByTable.set(fk.table, list);
|
|
267
337
|
}
|
|
@@ -279,38 +349,56 @@ function buildSchema(schema, raw) {
|
|
|
279
349
|
}
|
|
280
350
|
const uniquesByTable = new Map();
|
|
281
351
|
for (const [name, uc] of uniqueByConstraint.entries()) {
|
|
282
|
-
const list = (
|
|
352
|
+
const list = (_l = uniquesByTable.get(uc.table)) !== null && _l !== void 0 ? _l : [];
|
|
283
353
|
list.push({ name, columns: uc.columns });
|
|
284
354
|
uniquesByTable.set(uc.table, list);
|
|
285
355
|
}
|
|
286
356
|
// Indexes (grouped by index name)
|
|
287
357
|
const indexByName = new Map();
|
|
288
358
|
for (const row of raw.indexRows) {
|
|
289
|
-
const
|
|
290
|
-
|
|
291
|
-
|
|
359
|
+
const idx = (_m = indexByName.get(row.index_name)) !== null && _m !== void 0 ? _m : {
|
|
360
|
+
table: row.table_name,
|
|
361
|
+
name: row.index_name,
|
|
362
|
+
columns: [],
|
|
363
|
+
unique: row.indisunique,
|
|
364
|
+
};
|
|
365
|
+
// A null column is an expression such as lower(email).
|
|
366
|
+
if (row.column_name === null)
|
|
367
|
+
idx.expression = true;
|
|
292
368
|
else
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
369
|
+
idx.columns.push(row.column_name);
|
|
370
|
+
if (row.partial)
|
|
371
|
+
idx.partial = true;
|
|
372
|
+
if (row.predicate)
|
|
373
|
+
idx.predicate = valueLists(row.predicate);
|
|
374
|
+
if (row.descending)
|
|
375
|
+
idx.descending = true;
|
|
376
|
+
if (row.definition)
|
|
377
|
+
idx.definition = row.definition;
|
|
378
|
+
indexByName.set(row.index_name, idx);
|
|
298
379
|
}
|
|
299
380
|
const indexesByTable = new Map();
|
|
300
|
-
for (const
|
|
301
|
-
|
|
302
|
-
list.push({ name, columns: idx.columns, unique: idx.unique });
|
|
303
|
-
indexesByTable.set(idx.table, list);
|
|
381
|
+
for (const { table, ...idx } of indexByName.values()) {
|
|
382
|
+
indexesByTable.set(table, [...((_o = indexesByTable.get(table)) !== null && _o !== void 0 ? _o : []), idx]);
|
|
304
383
|
}
|
|
305
384
|
const tables = baseTables.map((name) => {
|
|
306
|
-
var _a, _b, _c, _d, _e;
|
|
385
|
+
var _a, _b, _c, _d, _e, _f;
|
|
307
386
|
return ({
|
|
308
387
|
name,
|
|
309
388
|
columns: (_a = columnsByTable.get(name)) !== null && _a !== void 0 ? _a : [],
|
|
310
389
|
primaryKey: (_b = pkByTable.get(name)) !== null && _b !== void 0 ? _b : [],
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
390
|
+
primaryKeyName: pkNameByTable.get(name),
|
|
391
|
+
checks: ((_c = raw.checkRows) !== null && _c !== void 0 ? _c : [])
|
|
392
|
+
.filter((row) => row.table_name === name)
|
|
393
|
+
.map((row) => ({
|
|
394
|
+
name: row.conname,
|
|
395
|
+
// pg_get_constraintdef prints CHECK (<expression>) [NOT VALID].
|
|
396
|
+
expression: checkExpression(String(row.definition)),
|
|
397
|
+
...(row.convalidated === false && { notValid: true }),
|
|
398
|
+
})),
|
|
399
|
+
foreignKeys: (_d = fksByTable.get(name)) !== null && _d !== void 0 ? _d : [],
|
|
400
|
+
uniqueConstraints: (_e = uniquesByTable.get(name)) !== null && _e !== void 0 ? _e : [],
|
|
401
|
+
indexes: (_f = indexesByTable.get(name)) !== null && _f !== void 0 ? _f : [],
|
|
314
402
|
});
|
|
315
403
|
});
|
|
316
404
|
const systemSchemas = raw.schemaRows
|