@apso/cli 0.56.0 → 0.57.1
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/data.d.ts +1 -0
- package/dist/commands/import/data.js +8 -3
- package/dist/commands/import/{supabase.d.ts → index.d.ts} +4 -1
- package/dist/commands/import/{supabase.js → index.js} +19 -10
- package/dist/commands/schema/validate.js +5 -0
- package/dist/lib/access/cases.js +1 -2
- package/dist/lib/access/rules.json +1 -1
- package/dist/lib/api/services.js +15 -1
- package/dist/lib/base-command.d.ts +6 -0
- package/dist/lib/base-command.js +14 -0
- package/dist/lib/generators/go.d.ts +18 -0
- package/dist/lib/generators/go.js +40 -18
- package/dist/lib/generators/python.js +6 -7
- package/dist/lib/generators/typescript.js +48 -9
- package/dist/lib/guards.d.ts +43 -5
- package/dist/lib/guards.js +148 -18
- package/dist/lib/import/copy-data.d.ts +23 -5
- package/dist/lib/import/copy-data.js +45 -7
- package/dist/lib/import/index.d.ts +1 -1
- package/dist/lib/import/index.js +2 -1
- package/dist/lib/import/pg-data.d.ts +1 -1
- package/dist/lib/import/pg-data.js +10 -5
- package/dist/lib/templates/go/middleware/auth.eta +136 -7
- package/dist/lib/templates/go/services/service.eta +29 -1
- package/dist/lib/templates/guards/permission.guard.eta +15 -0
- package/dist/lib/templates/guards/scope.guard.eta +9 -5
- package/dist/lib/templates/python/auth.eta +100 -2
- package/dist/lib/templates/python/services/service.eta +19 -0
- package/dist/lib/templates/rest/controller-rest.eta +17 -2
- package/dist/lib/templates/rest/dto-rest.eta +20 -8
- package/dist/lib/templates/rest/index-module-rest.eta +5 -1
- package/npm-shrinkwrap.json +2 -2
- package/oclif.manifest.json +23 -14
- package/package.json +1 -1
package/dist/lib/guards.d.ts
CHANGED
|
@@ -108,18 +108,46 @@ export interface DirectScopeField {
|
|
|
108
108
|
/** userId and email map to the caller's own; anything else is the tenant. */
|
|
109
109
|
source: "userId" | "email" | "tenant";
|
|
110
110
|
}
|
|
111
|
+
/**
|
|
112
|
+
* One scopeBy path through parents (task.project.organizationId), resolved to
|
|
113
|
+
* the foreign keys it follows, for services that filter in SQL (Go, Python).
|
|
114
|
+
*/
|
|
115
|
+
export interface NestedScopeData {
|
|
116
|
+
/** The entity's foreign key to the first parent, as .apsorc names it (taskId). */
|
|
117
|
+
field: string;
|
|
118
|
+
/**
|
|
119
|
+
* Each parent on the way to the tenant, nearest first: the entity, and its
|
|
120
|
+
* foreign key to the next parent (none on the last).
|
|
121
|
+
*/
|
|
122
|
+
parents: {
|
|
123
|
+
entity: string;
|
|
124
|
+
field?: string;
|
|
125
|
+
}[];
|
|
126
|
+
/** The field on the last parent that holds the tenant. */
|
|
127
|
+
tenantField: string;
|
|
128
|
+
/** userId and email map to the caller's own; anything else is the tenant. */
|
|
129
|
+
source: "userId" | "email" | "tenant";
|
|
130
|
+
}
|
|
111
131
|
/** What Go and Python services need to scope one entity. */
|
|
112
132
|
export interface EntityScopeData {
|
|
113
133
|
fields: DirectScopeField[];
|
|
134
|
+
/** Paths through a parent; empty unless the relationship map was given. */
|
|
135
|
+
nested: NestedScopeData[];
|
|
114
136
|
bypassRoles: string[];
|
|
115
137
|
}
|
|
138
|
+
/**
|
|
139
|
+
* The scopeBy paths of an entity that run through parents, each resolved hop
|
|
140
|
+
* by hop. Every step before the last must be a many-to-one relationship: its
|
|
141
|
+
* foreign key is what the SQL filter follows.
|
|
142
|
+
*/
|
|
143
|
+
export declare function nestedScopes(entity: Entity, relationshipMap: RelationshipMap): NestedScopeData[];
|
|
116
144
|
/**
|
|
117
145
|
* The direct scopeBy fields of an entity, for services that filter in their
|
|
118
146
|
* own queries (Go, Python). Undefined without auth: with no caller identity
|
|
119
|
-
* there is no tenant to scope by.
|
|
120
|
-
*
|
|
147
|
+
* there is no tenant to scope by. Paths through a parent (task.workspaceId)
|
|
148
|
+
* are resolved only when the relationship map is given.
|
|
121
149
|
*/
|
|
122
|
-
export declare function entityScope(entity: Entity, hasAuth: boolean): EntityScopeData | undefined;
|
|
150
|
+
export declare function entityScope(entity: Entity, hasAuth: boolean, relationshipMap?: RelationshipMap): EntityScopeData | undefined;
|
|
123
151
|
/** One entity in the relation table every generated service checks. */
|
|
124
152
|
export interface RelationScope {
|
|
125
153
|
/** Set when the entity's reads are tenant-scoped: the roles that skip its scope. */
|
|
@@ -154,8 +182,6 @@ export interface RelationScope {
|
|
|
154
182
|
* Undefined without auth or when no entity is scoped.
|
|
155
183
|
*/
|
|
156
184
|
export declare function relationScopes(entities: Entity[], relationshipMap: RelationshipMap | undefined, hasAuth: boolean): Record<string, RelationScope> | undefined;
|
|
157
|
-
/** Entities whose scopeBy uses a nested path, which Go and Python cannot enforce. */
|
|
158
|
-
export declare function nestedScopeEntities(entities: Entity[]): string[];
|
|
159
185
|
/**
|
|
160
186
|
* One warning per provider that maps no tenant claim while entities are
|
|
161
187
|
* tenant-scoped: its users would get 403 on every one of those entities.
|
|
@@ -169,3 +195,15 @@ export declare function tenantClaimWarnings(entities: Entity[], auth?: AuthConfi
|
|
|
169
195
|
* the caller.
|
|
170
196
|
*/
|
|
171
197
|
export declare function scopedReferences(entity: Entity, foreignKeys: [field: string, target: string][], scopes: Record<string, RelationScope> | undefined): Record<string, string>;
|
|
198
|
+
/**
|
|
199
|
+
* One operation's role rule as a sentence, for its OpenAPI description:
|
|
200
|
+
* "Requires role: manager (from the token's `o.rol` claim). Other callers get 403."
|
|
201
|
+
*/
|
|
202
|
+
export declare function roleRuleText(rule: PermissionRule, auth?: AuthConfig): string;
|
|
203
|
+
/** Each guarded operation of an entity and its rule, from .apsorc permissions. */
|
|
204
|
+
export declare function entityRoleRules(entity: Entity): Partial<Record<PermissionOperation, PermissionRule>>;
|
|
205
|
+
/**
|
|
206
|
+
* The OpenAPI info.description: who signs callers in, how records are scoped
|
|
207
|
+
* and which operations need which role, in plain words.
|
|
208
|
+
*/
|
|
209
|
+
export declare function accessSummary(entities: Entity[], auth?: AuthConfig): string;
|
package/dist/lib/guards.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.
|
|
3
|
+
exports.accessSummary = exports.entityRoleRules = exports.roleRuleText = exports.scopedReferences = exports.tenantClaimWarnings = exports.relationScopes = exports.entityScope = exports.nestedScopes = exports.getPermissionConfig = exports.hasPermissions = exports.mcpToolNames = exports.authEntityRoutes = exports.hidesRelation = exports.authEntityNames = exports.mcpOperations = exports.hasScopedEntities = exports.getScopedEntities = exports.toRouteName = exports.removedScopeOptionErrors = void 0;
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
5
|
const types_1 = require("./types");
|
|
6
6
|
const pluralize_1 = tslib_1.__importDefault(require("pluralize"));
|
|
@@ -280,28 +280,58 @@ function getPermissionConfig(entities, relationshipMap, auth) {
|
|
|
280
280
|
return { routes, joins, grants: resolveGrants(entities, auth) };
|
|
281
281
|
}
|
|
282
282
|
exports.getPermissionConfig = getPermissionConfig;
|
|
283
|
+
const scopeSource = (contextKey) => contextKey === "userId" || contextKey === "email" ? contextKey : "tenant";
|
|
284
|
+
/**
|
|
285
|
+
* The scopeBy paths of an entity that run through parents, each resolved hop
|
|
286
|
+
* by hop. Every step before the last must be a many-to-one relationship: its
|
|
287
|
+
* foreign key is what the SQL filter follows.
|
|
288
|
+
*/
|
|
289
|
+
function nestedScopes(entity, relationshipMap) {
|
|
290
|
+
if (!entity.scopeBy)
|
|
291
|
+
return [];
|
|
292
|
+
return parseScopeBy(entity.scopeBy)
|
|
293
|
+
.filter((s) => !s.direct && s.path)
|
|
294
|
+
.map((s) => {
|
|
295
|
+
const steps = s.path.split(".");
|
|
296
|
+
const tenantField = steps.pop();
|
|
297
|
+
let from = entity.name;
|
|
298
|
+
const hops = steps.map((step) => {
|
|
299
|
+
var _a;
|
|
300
|
+
const relation = ((_a = relationshipMap[from]) !== null && _a !== void 0 ? _a : []).find((r) => r.type === "ManyToOne" && (0, parse_1.getRelationshipName)(r) === step);
|
|
301
|
+
if (!relation)
|
|
302
|
+
throw new Error(`${entity.name}.scopeBy "${s.path}": "${step}" must be a many-to-one relationship of ${from}`);
|
|
303
|
+
const hop = { entity: relation.name, field: (0, parse_1.getRelationshipIdField)(relation) };
|
|
304
|
+
from = relation.name;
|
|
305
|
+
return hop;
|
|
306
|
+
});
|
|
307
|
+
return {
|
|
308
|
+
field: hops[0].field,
|
|
309
|
+
parents: hops.map((h, i) => { var _a; return ({ entity: h.entity, field: (_a = hops[i + 1]) === null || _a === void 0 ? void 0 : _a.field }); }),
|
|
310
|
+
tenantField,
|
|
311
|
+
source: scopeSource(tenantField),
|
|
312
|
+
};
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
exports.nestedScopes = nestedScopes;
|
|
283
316
|
/**
|
|
284
317
|
* The direct scopeBy fields of an entity, for services that filter in their
|
|
285
318
|
* own queries (Go, Python). Undefined without auth: with no caller identity
|
|
286
|
-
* there is no tenant to scope by.
|
|
287
|
-
*
|
|
319
|
+
* there is no tenant to scope by. Paths through a parent (task.workspaceId)
|
|
320
|
+
* are resolved only when the relationship map is given.
|
|
288
321
|
*/
|
|
289
|
-
function entityScope(entity, hasAuth) {
|
|
322
|
+
function entityScope(entity, hasAuth, relationshipMap) {
|
|
290
323
|
if (!hasAuth || !entity.scopeBy)
|
|
291
324
|
return undefined;
|
|
292
325
|
const [config] = getScopedEntities([entity]);
|
|
293
326
|
const fields = config.scopes
|
|
294
327
|
.filter((s) => s.direct)
|
|
295
|
-
.map((s) => ({
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
? s.contextKey
|
|
299
|
-
: "tenant",
|
|
300
|
-
}));
|
|
301
|
-
if (fields.length === 0)
|
|
328
|
+
.map((s) => ({ field: s.field, source: scopeSource(s.contextKey) }));
|
|
329
|
+
const nested = relationshipMap ? nestedScopes(entity, relationshipMap) : [];
|
|
330
|
+
if (fields.length === 0 && nested.length === 0)
|
|
302
331
|
return undefined;
|
|
303
332
|
return {
|
|
304
333
|
fields,
|
|
334
|
+
nested,
|
|
305
335
|
bypassRoles: config.bypassRoles,
|
|
306
336
|
};
|
|
307
337
|
}
|
|
@@ -364,13 +394,6 @@ function relationScopes(entities, relationshipMap, hasAuth) {
|
|
|
364
394
|
return table;
|
|
365
395
|
}
|
|
366
396
|
exports.relationScopes = relationScopes;
|
|
367
|
-
/** Entities whose scopeBy uses a nested path, which Go and Python cannot enforce. */
|
|
368
|
-
function nestedScopeEntities(entities) {
|
|
369
|
-
return getScopedEntities(entities)
|
|
370
|
-
.filter((e) => e.scopes.some((s) => !s.direct))
|
|
371
|
-
.map((e) => e.name);
|
|
372
|
-
}
|
|
373
|
-
exports.nestedScopeEntities = nestedScopeEntities;
|
|
374
397
|
/**
|
|
375
398
|
* One warning per provider that maps no tenant claim while entities are
|
|
376
399
|
* tenant-scoped: its users would get 403 on every one of those entities.
|
|
@@ -402,3 +425,110 @@ function scopedReferences(entity, foreignKeys, scopes) {
|
|
|
402
425
|
return Object.fromEntries(foreignKeys.filter(([field, target]) => { var _a; return !own.has(field) && ((_a = scopes === null || scopes === void 0 ? void 0 : scopes[target]) === null || _a === void 0 ? void 0 : _a.bypassRoles) !== undefined; }));
|
|
403
426
|
}
|
|
404
427
|
exports.scopedReferences = scopedReferences;
|
|
428
|
+
/*
|
|
429
|
+
* Access text for the OpenAPI contract (/_docs-json). An app builder reading
|
|
430
|
+
* the contract should leave these rules to the API instead of copying them
|
|
431
|
+
* into the browser: matching users to roles by email, sending the tenant on a
|
|
432
|
+
* write, hiding a delete button as the only check.
|
|
433
|
+
*/
|
|
434
|
+
const PROVIDER_NAMES = {
|
|
435
|
+
"better-auth": "Better Auth",
|
|
436
|
+
auth0: "Auth0",
|
|
437
|
+
clerk: "Clerk",
|
|
438
|
+
cognito: "Amazon Cognito",
|
|
439
|
+
jwt: "a JWT issuer",
|
|
440
|
+
};
|
|
441
|
+
const KEY_ONLY_DESCRIPTION = "Every request needs the service API key in the `x-api-key` header; without it the API answers 401. " +
|
|
442
|
+
"The key is for server-side callers only. Never put it in a browser app: a browser app calls its own backend, which calls this API.";
|
|
443
|
+
/** "the token's `o.rol` claim", naming each provider's claim when they differ. */
|
|
444
|
+
function claimText(providers, pick) {
|
|
445
|
+
const names = [...new Set(providers.map((p) => pick(p)).filter((n) => Boolean(n)))];
|
|
446
|
+
if (names.length === 0)
|
|
447
|
+
return undefined;
|
|
448
|
+
return `the token's ${names.map((n) => `\`${n}\``).join(" or ")} claim`;
|
|
449
|
+
}
|
|
450
|
+
const tenantClaim = (p) => { var _a; return (_a = p.claims.workspaceId) !== null && _a !== void 0 ? _a : p.claims.organizationId; };
|
|
451
|
+
const joinWords = (words, last = "and") => words.length <= 1 ? words.join("") : `${words.slice(0, -1).join(", ")} ${last} ${words[words.length - 1]}`;
|
|
452
|
+
/**
|
|
453
|
+
* One operation's role rule as a sentence, for its OpenAPI description:
|
|
454
|
+
* "Requires role: manager (from the token's `o.rol` claim). Other callers get 403."
|
|
455
|
+
*/
|
|
456
|
+
function roleRuleText(rule, auth) {
|
|
457
|
+
const providers = (0, types_1.resolveJwtProviders)(auth);
|
|
458
|
+
const roles = claimText(providers, (p) => p.claims.roles);
|
|
459
|
+
const perms = claimText(providers, (p) => p.claims.permissions);
|
|
460
|
+
return (`Requires role: ${joinWords(rule.roles, "or")}${roles ? ` (from ${roles})` : " (from the token)"}` +
|
|
461
|
+
`${perms ? `, or \`${rule.permission}\` in ${perms}` : ""}. Other signed-in users get 403. ` +
|
|
462
|
+
"The API checks this; a client app must not re-implement it.");
|
|
463
|
+
}
|
|
464
|
+
exports.roleRuleText = roleRuleText;
|
|
465
|
+
/** Each guarded operation of an entity and its rule, from .apsorc permissions. */
|
|
466
|
+
function entityRoleRules(entity) {
|
|
467
|
+
var _a;
|
|
468
|
+
return Object.fromEntries(Object.entries((_a = entity.permissions) !== null && _a !== void 0 ? _a : {}).map(([op, roles]) => [
|
|
469
|
+
op,
|
|
470
|
+
{ permission: `${permissionKey(entity.name)}:${op}`, roles: roles !== null && roles !== void 0 ? roles : [] },
|
|
471
|
+
]));
|
|
472
|
+
}
|
|
473
|
+
exports.entityRoleRules = entityRoleRules;
|
|
474
|
+
/**
|
|
475
|
+
* The OpenAPI info.description: who signs callers in, how records are scoped
|
|
476
|
+
* and which operations need which role, in plain words.
|
|
477
|
+
*/
|
|
478
|
+
function accessSummary(entities, auth) {
|
|
479
|
+
var _a, _b, _c, _d, _e, _f;
|
|
480
|
+
const providers = (0, types_1.resolveJwtProviders)(auth);
|
|
481
|
+
if (providers.length === 0)
|
|
482
|
+
return KEY_ONLY_DESCRIPTION;
|
|
483
|
+
const lines = [
|
|
484
|
+
"**Access rules.** This API enforces every rule below on every request. A client app must not re-implement them: " +
|
|
485
|
+
"do not look users up to decide their role, do not send the tenant field, and do not treat a hidden button as the check.",
|
|
486
|
+
"",
|
|
487
|
+
`- **Sign-in:** ${joinWords([...new Set(providers.map((p) => (p.provider === "jwt" ? `a JWT issuer (${p.issuer})` : PROVIDER_NAMES[p.provider])))], "or")}. Send the signed-in user's token as \`Authorization: Bearer <token>\`. Without a valid token the API answers 401.`,
|
|
488
|
+
];
|
|
489
|
+
const tenant = (_a = claimText(providers, tenantClaim)) !== null && _a !== void 0 ? _a : "the token's tenant claim";
|
|
490
|
+
const user = (_b = claimText(providers, (p) => p.claims.userId)) !== null && _b !== void 0 ? _b : "the token's `sub` claim";
|
|
491
|
+
// Entities by scope sentence, so a schema scoped by one field reads as one line.
|
|
492
|
+
const byScope = new Map();
|
|
493
|
+
for (const { name, scopes, bypassRoles } of getScopedEntities(entities)) {
|
|
494
|
+
const parts = scopes.map((s) => s.direct
|
|
495
|
+
? `\`${s.field}\` is taken from ${s.contextKey === "userId" ? user : s.contextKey === "email" ? "the token's email claim" : tenant}`
|
|
496
|
+
: `rows are limited through \`${s.path}\` to the caller's tenant (${tenant})`);
|
|
497
|
+
const bypass = bypassRoles.length > 0 ? ` Callers with role ${joinWords(bypassRoles, "or")} see every tenant.` : "";
|
|
498
|
+
const key = `${parts.join("; ")}.${bypass}`;
|
|
499
|
+
const group = (_c = byScope.get(key)) !== null && _c !== void 0 ? _c : { names: [], fields: scopes.filter((s) => s.direct).map((s) => `\`${s.field}\``) };
|
|
500
|
+
group.names.push(name);
|
|
501
|
+
byScope.set(key, group);
|
|
502
|
+
}
|
|
503
|
+
for (const [scope, { names, fields }] of byScope) {
|
|
504
|
+
const it = fields.length > 1 ? "them" : "it";
|
|
505
|
+
lines.push(`- **Scoped records:** ${joinWords(names)}: ${scope} Reads and lists return only the caller's records` +
|
|
506
|
+
(fields.length > 0
|
|
507
|
+
? `, and creates and updates set ${joinWords(fields)} from the token. The client must not send ${it} or filter by ${it}.`
|
|
508
|
+
: "."));
|
|
509
|
+
}
|
|
510
|
+
const guarded = entities.filter((e) => e.permissions && Object.keys(e.permissions).length > 0);
|
|
511
|
+
if (guarded.length > 0) {
|
|
512
|
+
const roles = (_d = claimText(providers, (p) => p.claims.roles)) !== null && _d !== void 0 ? _d : "the token";
|
|
513
|
+
const perms = claimText(providers, (p) => p.claims.permissions);
|
|
514
|
+
lines.push(`- **Roles** come from ${roles}${perms ? ` (a permission such as \`${permissionKey(guarded[0].name)}:delete\` in ${perms} also passes)` : ""}. ` +
|
|
515
|
+
"A caller without the role gets 403. Operations not listed are open to any signed-in user:");
|
|
516
|
+
for (const entity of guarded) {
|
|
517
|
+
// Operations that need the same roles share a clause.
|
|
518
|
+
const byRoles = new Map();
|
|
519
|
+
for (const op of types_1.PERMISSION_OPERATIONS) {
|
|
520
|
+
const roles = (_e = entity.permissions) === null || _e === void 0 ? void 0 : _e[op];
|
|
521
|
+
if (!roles)
|
|
522
|
+
continue;
|
|
523
|
+
const key = joinWords(roles, "or");
|
|
524
|
+
byRoles.set(key, [...((_f = byRoles.get(key)) !== null && _f !== void 0 ? _f : []), op]);
|
|
525
|
+
}
|
|
526
|
+
const clauses = [...byRoles].map(([roles, ops]) => `${joinWords(ops)} need${ops.length === 1 ? "s" : ""} ${roles}`);
|
|
527
|
+
lines.push(` - ${entity.name}: ${clauses.join("; ")}.`);
|
|
528
|
+
}
|
|
529
|
+
lines.push("- To show only the actions a user may take, read the role from the same token, and still handle 403.");
|
|
530
|
+
}
|
|
531
|
+
lines.push("- **API key:** server-side callers may send the service key in `x-api-key` instead of a token. It is not limited to one tenant or role. Never put it in a browser app.");
|
|
532
|
+
return lines.join("\n");
|
|
533
|
+
}
|
|
534
|
+
exports.accessSummary = accessSummary;
|
|
@@ -11,6 +11,11 @@
|
|
|
11
11
|
* - target table name = snakeCase(entity name) = snakeCase(source table name)
|
|
12
12
|
* - single-column FK = renamed to the platform's camelCase `<ref>Id`
|
|
13
13
|
* - every other column = copied under its original name
|
|
14
|
+
*
|
|
15
|
+
* Values travel as the text Postgres prints for them and are parsed again by
|
|
16
|
+
* the target column, so an array, a timestamp's microseconds, an interval or a
|
|
17
|
+
* bytea arrive as they left. Reading them into JavaScript values first lost
|
|
18
|
+
* the microseconds and broke every array column.
|
|
14
19
|
*/
|
|
15
20
|
import { IntrospectedSchema, IntrospectedTable } from "./types";
|
|
16
21
|
export interface ColumnMapping {
|
|
@@ -24,6 +29,8 @@ export interface TableCopyPlan {
|
|
|
24
29
|
sourceColumns: string[];
|
|
25
30
|
/** Target column names, parallel to sourceColumns. */
|
|
26
31
|
targetColumns: string[];
|
|
32
|
+
/** The SQL that reads each source column as text, parallel to sourceColumns. */
|
|
33
|
+
sourceExpressions?: string[];
|
|
27
34
|
/** Source PK column used to order paged reads (null when there is no PK). */
|
|
28
35
|
orderBy: string | null;
|
|
29
36
|
/** Target PK column whose sequence to reset after copy (null if not serial). */
|
|
@@ -60,9 +67,18 @@ export declare function topoSortTables(tables: IntrospectedTable[]): {
|
|
|
60
67
|
* column is missing are dropped (and reported); source tables with no target
|
|
61
68
|
* table are skipped entirely.
|
|
62
69
|
*/
|
|
63
|
-
export declare function planCopy(source: IntrospectedSchema, targetColumnsByTable: Map<string, Set<string>>, tableFilter?: string[]): CopyPlan;
|
|
64
|
-
/**
|
|
70
|
+
export declare function planCopy(source: IntrospectedSchema, targetColumnsByTable: Map<string, Set<string> | Map<string, string>>, tableFilter?: string[]): CopyPlan;
|
|
71
|
+
/**
|
|
72
|
+
* Coerce a value into something safe to bind on insert. The copy reads every
|
|
73
|
+
* column as text, so it sees strings and nulls; the other branches serve a
|
|
74
|
+
* reader that returns JavaScript values.
|
|
75
|
+
*/
|
|
65
76
|
export declare function coerceValue(value: unknown): unknown;
|
|
77
|
+
/**
|
|
78
|
+
* Build the paged SELECT that reads a batch of source rows. Each column comes
|
|
79
|
+
* back under its own name; `expressions` says how to read it.
|
|
80
|
+
*/
|
|
81
|
+
export declare function buildSelectSql(table: string, columns: string[], orderBy: string | null, schema?: string, expressions?: string[]): string;
|
|
66
82
|
/** Build a parameterized multi-row INSERT statement for a batch. */
|
|
67
83
|
export declare function buildInsertSql(table: string, columns: string[], rows: unknown[][], schema?: string): {
|
|
68
84
|
text: string;
|
|
@@ -70,7 +86,9 @@ export declare function buildInsertSql(table: string, columns: string[], rows: u
|
|
|
70
86
|
};
|
|
71
87
|
export interface SourceReader {
|
|
72
88
|
totalRows(table: string): Promise<number>;
|
|
73
|
-
readBatch(table: string, columns: string[], orderBy: string | null, offset: number, limit: number
|
|
89
|
+
readBatch(table: string, columns: string[], orderBy: string | null, offset: number, limit: number,
|
|
90
|
+
/** The SQL that reads each column, parallel to columns. Defaults to the column itself. */
|
|
91
|
+
expressions?: string[]): Promise<unknown[][]>;
|
|
74
92
|
}
|
|
75
93
|
export interface TargetWriter {
|
|
76
94
|
rowCount(table: string): Promise<number>;
|
|
@@ -102,5 +120,5 @@ export interface ExecuteOptions {
|
|
|
102
120
|
* on the target, so a failure rolls everything back.
|
|
103
121
|
*/
|
|
104
122
|
export declare function executeCopy(plan: CopyPlan, source: SourceReader, target: TargetWriter, options?: ExecuteOptions): Promise<CopyResult>;
|
|
105
|
-
/** Build the target
|
|
106
|
-
export declare function targetColumnsFromSchema(target: IntrospectedSchema): Map<string,
|
|
123
|
+
/** Build the target lookup used by planCopy from an introspected target: each table's columns and their types. */
|
|
124
|
+
export declare function targetColumnsFromSchema(target: IntrospectedSchema): Map<string, Map<string, string>>;
|
|
@@ -12,9 +12,14 @@
|
|
|
12
12
|
* - target table name = snakeCase(entity name) = snakeCase(source table name)
|
|
13
13
|
* - single-column FK = renamed to the platform's camelCase `<ref>Id`
|
|
14
14
|
* - every other column = copied under its original name
|
|
15
|
+
*
|
|
16
|
+
* Values travel as the text Postgres prints for them and are parsed again by
|
|
17
|
+
* the target column, so an array, a timestamp's microseconds, an interval or a
|
|
18
|
+
* bytea arrive as they left. Reading them into JavaScript values first lost
|
|
19
|
+
* the microseconds and broke every array column.
|
|
15
20
|
*/
|
|
16
21
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.targetColumnsFromSchema = exports.executeCopy = exports.buildInsertSql = exports.coerceValue = exports.planCopy = exports.topoSortTables = exports.buildColumnMapping = exports.targetTableName = void 0;
|
|
22
|
+
exports.targetColumnsFromSchema = exports.executeCopy = exports.buildInsertSql = exports.buildSelectSql = exports.coerceValue = exports.planCopy = exports.topoSortTables = exports.buildColumnMapping = exports.targetTableName = void 0;
|
|
18
23
|
const casing_1 = require("../utils/casing");
|
|
19
24
|
const relationships_1 = require("../utils/relationships");
|
|
20
25
|
const pg_to_apsorc_1 = require("./pg-to-apsorc");
|
|
@@ -98,7 +103,7 @@ exports.topoSortTables = topoSortTables;
|
|
|
98
103
|
* table are skipped entirely.
|
|
99
104
|
*/
|
|
100
105
|
function planCopy(source, targetColumnsByTable, tableFilter) {
|
|
101
|
-
var _a;
|
|
106
|
+
var _a, _b;
|
|
102
107
|
const filter = tableFilter && tableFilter.length > 0 ? new Set(tableFilter) : null;
|
|
103
108
|
const consideredTables = source.tables.filter((t) => !filter || filter.has(t.name));
|
|
104
109
|
const { order, cyclic } = topoSortTables(consideredTables);
|
|
@@ -117,6 +122,8 @@ function planCopy(source, targetColumnsByTable, tableFilter) {
|
|
|
117
122
|
const mapping = buildColumnMapping(table);
|
|
118
123
|
const keptSource = [];
|
|
119
124
|
const keptTarget = [];
|
|
125
|
+
const expressions = [];
|
|
126
|
+
const sourceTypes = new Map(table.columns.map((c) => [c.name, c.udtName]));
|
|
120
127
|
for (const m of mapping) {
|
|
121
128
|
// An import keeps foreign key column names ("joinColumnName"); a project
|
|
122
129
|
// imported by an older CLI has the generated camelCase name instead.
|
|
@@ -125,6 +132,14 @@ function planCopy(source, targetColumnsByTable, tableFilter) {
|
|
|
125
132
|
if (targetColumns.has(m.targetColumn)) {
|
|
126
133
|
keptSource.push(m.sourceColumn);
|
|
127
134
|
keptTarget.push(m.targetColumn);
|
|
135
|
+
// An array whose target column is json (the field was changed to
|
|
136
|
+
// jsonb after the import) is sent as a JSON array.
|
|
137
|
+
const targetType = targetColumns instanceof Map ? targetColumns.get(m.targetColumn) : "";
|
|
138
|
+
const arrayToJson = ((_a = sourceTypes.get(m.sourceColumn)) === null || _a === void 0 ? void 0 : _a.startsWith("_")) &&
|
|
139
|
+
(targetType === "json" || targetType === "jsonb");
|
|
140
|
+
expressions.push(arrayToJson
|
|
141
|
+
? `to_jsonb("${m.sourceColumn}")::text`
|
|
142
|
+
: `"${m.sourceColumn}"::text`);
|
|
128
143
|
}
|
|
129
144
|
else {
|
|
130
145
|
skippedColumns.push({
|
|
@@ -141,7 +156,7 @@ function planCopy(source, targetColumnsByTable, tableFilter) {
|
|
|
141
156
|
const pkCol = table.primaryKey[0];
|
|
142
157
|
orderBy = pkCol;
|
|
143
158
|
const pk = table.columns.find((c) => c.name === pkCol);
|
|
144
|
-
const targetPk = (
|
|
159
|
+
const targetPk = (_b = mapping.find((m) => m.sourceColumn === pkCol)) === null || _b === void 0 ? void 0 : _b.targetColumn;
|
|
145
160
|
if (pk && targetPk && INTEGER_PK_UDTS.has(pk.udtName)) {
|
|
146
161
|
serialPkColumn = targetPk;
|
|
147
162
|
}
|
|
@@ -151,6 +166,7 @@ function planCopy(source, targetColumnsByTable, tableFilter) {
|
|
|
151
166
|
targetTable,
|
|
152
167
|
sourceColumns: keptSource,
|
|
153
168
|
targetColumns: keptTarget,
|
|
169
|
+
sourceExpressions: expressions,
|
|
154
170
|
orderBy,
|
|
155
171
|
serialPkColumn,
|
|
156
172
|
});
|
|
@@ -158,7 +174,11 @@ function planCopy(source, targetColumnsByTable, tableFilter) {
|
|
|
158
174
|
return { tables, skippedColumns, missingTargetTables, cyclicTables: cyclic };
|
|
159
175
|
}
|
|
160
176
|
exports.planCopy = planCopy;
|
|
161
|
-
/**
|
|
177
|
+
/**
|
|
178
|
+
* Coerce a value into something safe to bind on insert. The copy reads every
|
|
179
|
+
* column as text, so it sees strings and nulls; the other branches serve a
|
|
180
|
+
* reader that returns JavaScript values.
|
|
181
|
+
*/
|
|
162
182
|
function coerceValue(value) {
|
|
163
183
|
if (value === null || value === undefined)
|
|
164
184
|
return null;
|
|
@@ -171,6 +191,21 @@ function coerceValue(value) {
|
|
|
171
191
|
return value;
|
|
172
192
|
}
|
|
173
193
|
exports.coerceValue = coerceValue;
|
|
194
|
+
/**
|
|
195
|
+
* Build the paged SELECT that reads a batch of source rows. Each column comes
|
|
196
|
+
* back under its own name; `expressions` says how to read it.
|
|
197
|
+
*/
|
|
198
|
+
function buildSelectSql(table, columns, orderBy, schema, expressions) {
|
|
199
|
+
const tableRef = schema ? `"${schema}"."${table}"` : `"${table}"`;
|
|
200
|
+
const cols = columns
|
|
201
|
+
.map((c, i) => { var _a; return `${(_a = expressions === null || expressions === void 0 ? void 0 : expressions[i]) !== null && _a !== void 0 ? _a : `"${c}"`} AS "${c}"`; })
|
|
202
|
+
.join(", ");
|
|
203
|
+
// Qualified, so the order is the column's own (and its index is used), not
|
|
204
|
+
// the text alias of the same name: as text, id 10 sorts before id 9.
|
|
205
|
+
const order = orderBy ? ` ORDER BY ${tableRef}."${orderBy}"` : "";
|
|
206
|
+
return `SELECT ${cols} FROM ${tableRef}${order} OFFSET $1 LIMIT $2`;
|
|
207
|
+
}
|
|
208
|
+
exports.buildSelectSql = buildSelectSql;
|
|
174
209
|
/** Build a parameterized multi-row INSERT statement for a batch. */
|
|
175
210
|
function buildInsertSql(table, columns, rows, schema) {
|
|
176
211
|
const tableRef = schema ? `"${schema}"."${table}"` : `"${table}"`;
|
|
@@ -233,7 +268,7 @@ async function executeCopy(plan, source, target, options = {}) {
|
|
|
233
268
|
// eslint-disable-next-line no-constant-condition
|
|
234
269
|
while (true) {
|
|
235
270
|
// eslint-disable-next-line no-await-in-loop
|
|
236
|
-
const rows = await source.readBatch(t.sourceTable, t.sourceColumns, t.orderBy, offset, batchSize);
|
|
271
|
+
const rows = await source.readBatch(t.sourceTable, t.sourceColumns, t.orderBy, offset, batchSize, t.sourceExpressions);
|
|
237
272
|
if (rows.length === 0)
|
|
238
273
|
break;
|
|
239
274
|
// eslint-disable-next-line no-await-in-loop
|
|
@@ -265,8 +300,11 @@ async function executeCopy(plan, source, target, options = {}) {
|
|
|
265
300
|
};
|
|
266
301
|
}
|
|
267
302
|
exports.executeCopy = executeCopy;
|
|
268
|
-
/** Build the target
|
|
303
|
+
/** Build the target lookup used by planCopy from an introspected target: each table's columns and their types. */
|
|
269
304
|
function targetColumnsFromSchema(target) {
|
|
270
|
-
return new Map(target.tables.map((t) => [
|
|
305
|
+
return new Map(target.tables.map((t) => [
|
|
306
|
+
t.name,
|
|
307
|
+
new Map(t.columns.map((c) => [c.name, c.udtName])),
|
|
308
|
+
]));
|
|
271
309
|
}
|
|
272
310
|
exports.targetColumnsFromSchema = targetColumnsFromSchema;
|
|
@@ -2,6 +2,6 @@ export * from "./types";
|
|
|
2
2
|
export { pgToApsorc, findUnknownEmittedTypes } from "./pg-to-apsorc";
|
|
3
3
|
export type { ApsorcImportOutput, ApsorcImportEntityOutput, ApsorcImportFieldOutput, ApsorcImportRelationshipOutput, } from "./pg-to-apsorc";
|
|
4
4
|
export { PgIntrospector, redactConnectionString, buildSchema, SYSTEM_SCHEMAS } from "./introspect";
|
|
5
|
-
export { planCopy, executeCopy, buildColumnMapping, topoSortTables, targetTableName, targetColumnsFromSchema, buildInsertSql, coerceValue, } from "./copy-data";
|
|
5
|
+
export { planCopy, executeCopy, buildColumnMapping, topoSortTables, targetTableName, targetColumnsFromSchema, buildInsertSql, buildSelectSql, coerceValue, } from "./copy-data";
|
|
6
6
|
export type { CopyPlan, CopyResult, TableCopyPlan, ColumnMapping, SourceReader, TargetWriter, ExecuteOptions, } from "./copy-data";
|
|
7
7
|
export { PgSourceReader, PgTargetWriter } from "./pg-data";
|
package/dist/lib/import/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.PgTargetWriter = exports.PgSourceReader = exports.coerceValue = exports.buildInsertSql = exports.targetColumnsFromSchema = exports.targetTableName = exports.topoSortTables = exports.buildColumnMapping = exports.executeCopy = exports.planCopy = exports.SYSTEM_SCHEMAS = exports.buildSchema = exports.redactConnectionString = exports.PgIntrospector = exports.findUnknownEmittedTypes = exports.pgToApsorc = void 0;
|
|
3
|
+
exports.PgTargetWriter = exports.PgSourceReader = exports.coerceValue = exports.buildSelectSql = exports.buildInsertSql = exports.targetColumnsFromSchema = exports.targetTableName = exports.topoSortTables = exports.buildColumnMapping = exports.executeCopy = exports.planCopy = exports.SYSTEM_SCHEMAS = exports.buildSchema = exports.redactConnectionString = exports.PgIntrospector = exports.findUnknownEmittedTypes = exports.pgToApsorc = void 0;
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
5
|
tslib_1.__exportStar(require("./types"), exports);
|
|
6
6
|
var pg_to_apsorc_1 = require("./pg-to-apsorc");
|
|
@@ -19,6 +19,7 @@ Object.defineProperty(exports, "topoSortTables", { enumerable: true, get: functi
|
|
|
19
19
|
Object.defineProperty(exports, "targetTableName", { enumerable: true, get: function () { return copy_data_1.targetTableName; } });
|
|
20
20
|
Object.defineProperty(exports, "targetColumnsFromSchema", { enumerable: true, get: function () { return copy_data_1.targetColumnsFromSchema; } });
|
|
21
21
|
Object.defineProperty(exports, "buildInsertSql", { enumerable: true, get: function () { return copy_data_1.buildInsertSql; } });
|
|
22
|
+
Object.defineProperty(exports, "buildSelectSql", { enumerable: true, get: function () { return copy_data_1.buildSelectSql; } });
|
|
22
23
|
Object.defineProperty(exports, "coerceValue", { enumerable: true, get: function () { return copy_data_1.coerceValue; } });
|
|
23
24
|
var pg_data_1 = require("./pg-data");
|
|
24
25
|
Object.defineProperty(exports, "PgSourceReader", { enumerable: true, get: function () { return pg_data_1.PgSourceReader; } });
|
|
@@ -14,7 +14,7 @@ export declare class PgSourceReader implements SourceReader {
|
|
|
14
14
|
private constructor();
|
|
15
15
|
static connect(connectionString: string, schema: string): Promise<PgSourceReader>;
|
|
16
16
|
totalRows(table: string): Promise<number>;
|
|
17
|
-
readBatch(table: string, columns: string[], orderBy: string | null, offset: number, limit: number): Promise<unknown[][]>;
|
|
17
|
+
readBatch(table: string, columns: string[], orderBy: string | null, offset: number, limit: number, expressions?: string[]): Promise<unknown[][]>;
|
|
18
18
|
close(): Promise<void>;
|
|
19
19
|
}
|
|
20
20
|
/** Writes rows into the target database within a single transaction. */
|
|
@@ -53,16 +53,21 @@ class PgSourceReader {
|
|
|
53
53
|
this.schema = schema;
|
|
54
54
|
}
|
|
55
55
|
static async connect(connectionString, schema) {
|
|
56
|
-
|
|
56
|
+
const client = await createClient(connectionString);
|
|
57
|
+
// Values are read as text, so the text must mean the same on the target:
|
|
58
|
+
// ISO dates whatever the source's DateStyle (with "SQL, DMY" the day and
|
|
59
|
+
// month would swap), and every digit of a float.
|
|
60
|
+
await client.query("SET datestyle = 'ISO'");
|
|
61
|
+
await client.query("SET extra_float_digits = 3");
|
|
62
|
+
return new PgSourceReader(client, schema);
|
|
57
63
|
}
|
|
58
64
|
async totalRows(table) {
|
|
59
65
|
const res = await this.client.query(`SELECT count(*)::int AS n FROM ${qualified(this.schema, table)}`);
|
|
60
66
|
return res.rows[0].n;
|
|
61
67
|
}
|
|
62
|
-
async readBatch(table, columns, orderBy, offset, limit) {
|
|
63
|
-
const
|
|
64
|
-
const
|
|
65
|
-
const res = await this.client.query(`SELECT ${cols} FROM ${qualified(this.schema, table)}${order} OFFSET $1 LIMIT $2`, [offset, limit]);
|
|
68
|
+
async readBatch(table, columns, orderBy, offset, limit, expressions) {
|
|
69
|
+
const { buildSelectSql } = await Promise.resolve().then(() => __importStar(require("./copy-data")));
|
|
70
|
+
const res = await this.client.query(buildSelectSql(table, columns, orderBy, this.schema, expressions), [offset, limit]);
|
|
66
71
|
return res.rows.map((row) => columns.map((c) => row[c]));
|
|
67
72
|
}
|
|
68
73
|
async close() {
|