@apso/cli 0.55.0 → 0.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/commands/import/data.d.ts +1 -0
  2. package/dist/commands/import/data.js +8 -3
  3. package/dist/commands/import/{supabase.d.ts → index.d.ts} +4 -1
  4. package/dist/commands/import/{supabase.js → index.js} +20 -11
  5. package/dist/commands/mcp/serve.js +5 -2
  6. package/dist/commands/schema/validate.js +5 -0
  7. package/dist/lib/access/cases.js +1 -2
  8. package/dist/lib/access/rules.json +1 -1
  9. package/dist/lib/api/services.js +15 -1
  10. package/dist/lib/base-command.d.ts +6 -0
  11. package/dist/lib/base-command.js +14 -0
  12. package/dist/lib/ddl/index.d.ts +12 -7
  13. package/dist/lib/ddl/index.js +50 -22
  14. package/dist/lib/generators/go.d.ts +18 -0
  15. package/dist/lib/generators/go.js +40 -18
  16. package/dist/lib/generators/python.js +6 -7
  17. package/dist/lib/generators/typescript.js +76 -14
  18. package/dist/lib/guards.d.ts +43 -5
  19. package/dist/lib/guards.js +148 -18
  20. package/dist/lib/import/copy-data.js +4 -2
  21. package/dist/lib/import/introspect.js +23 -10
  22. package/dist/lib/import/pg-to-apsorc.d.ts +5 -1
  23. package/dist/lib/import/pg-to-apsorc.js +44 -32
  24. package/dist/lib/import/types.d.ts +9 -4
  25. package/dist/lib/migrate/sandbox.js +4 -0
  26. package/dist/lib/templates/entities/entity.eta +2 -2
  27. package/dist/lib/templates/go/middleware/auth.eta +136 -7
  28. package/dist/lib/templates/go/services/service.eta +29 -1
  29. package/dist/lib/templates/guards/permission.guard.eta +15 -0
  30. package/dist/lib/templates/guards/scope.guard.eta +9 -5
  31. package/dist/lib/templates/python/auth.eta +100 -2
  32. package/dist/lib/templates/python/services/service.eta +19 -0
  33. package/dist/lib/templates/rest/controller-rest.eta +17 -2
  34. package/dist/lib/templates/rest/dto-rest.eta +20 -8
  35. package/dist/lib/templates/rest/index-module-rest.eta +5 -1
  36. package/dist/lib/types/constraints.d.ts +6 -1
  37. package/dist/lib/types/relationship.d.ts +40 -1
  38. package/dist/lib/types/relationship.js +34 -1
  39. package/dist/lib/utils/relationships/parse.js +25 -0
  40. package/npm-shrinkwrap.json +2 -2
  41. package/oclif.manifest.json +23 -14
  42. package/package.json +1 -1
@@ -6,6 +6,7 @@ export declare function resolveTargetConnectionString(flagValue: string | undefi
6
6
  /** Render a copy result (or dry-run plan) as a human-readable summary. */
7
7
  export declare function formatCopyResult(result: CopyResult): string;
8
8
  export default class ImportData extends BaseCommand {
9
+ protected reportErrorText: boolean;
9
10
  static description: string;
10
11
  static examples: string[];
11
12
  static flags: {
@@ -6,7 +6,7 @@ const core_1 = require("@oclif/core");
6
6
  const inquirer_1 = tslib_1.__importDefault(require("inquirer"));
7
7
  const base_command_1 = tslib_1.__importDefault(require("../../lib/base-command"));
8
8
  const import_1 = require("../../lib/import");
9
- const supabase_1 = require("./supabase");
9
+ const index_1 = require("./index");
10
10
  /** Resolve the target connection string from flag/env, else undefined. */
11
11
  function resolveTargetConnectionString(flagValue, env = process.env) {
12
12
  return flagValue || env.TARGET_DATABASE_URL || env.APSO_DATABASE_URL || undefined;
@@ -41,6 +41,11 @@ function formatCopyResult(result) {
41
41
  }
42
42
  exports.formatCopyResult = formatCopyResult;
43
43
  class ImportData extends base_command_1.default {
44
+ constructor() {
45
+ super(...arguments);
46
+ // Errors here can name the database host, so the text stays on this machine.
47
+ this.reportErrorText = false;
48
+ }
44
49
  async promptConnection(role) {
45
50
  const answer = await inquirer_1.default.prompt([
46
51
  {
@@ -55,7 +60,7 @@ class ImportData extends base_command_1.default {
55
60
  }
56
61
  async run() {
57
62
  const { flags } = await this.parse(ImportData);
58
- const sourceConn = (0, supabase_1.resolveConnectionString)(flags.source) ||
63
+ const sourceConn = (0, index_1.resolveConnectionString)(flags.source) ||
59
64
  (await this.promptConnection("Source"));
60
65
  const targetConn = resolveTargetConnectionString(flags.target) ||
61
66
  (await this.promptConnection("Target"));
@@ -122,7 +127,7 @@ class ImportData extends base_command_1.default {
122
127
  }
123
128
  }
124
129
  }
125
- ImportData.description = "Copy table data from a source Supabase (Postgres) database into the target database rebuilt from the imported schema. Reads the source read-only; inserts into empty target tables.";
130
+ ImportData.description = "Copy table data from a source Postgres database (Supabase, Neon, RDS, or any other) into the target database rebuilt from the imported schema. Reads the source read-only; inserts into empty target tables.";
126
131
  ImportData.examples = [
127
132
  `$ apso import data -s "postgresql://...source..." -t "postgresql://...target..."`,
128
133
  `$ apso import data --dry-run`,
@@ -26,9 +26,11 @@ export declare function formatReport(report: ImportReport): string;
26
26
  export declare function writeApsorcFile(apsorc: ApsorcImportOutput, outPath: string): {
27
27
  backupPath?: string;
28
28
  };
29
- export default class ImportSupabase extends BaseCommand {
29
+ export default class Import extends BaseCommand {
30
30
  static description: string;
31
31
  static examples: string[];
32
+ static aliases: string[];
33
+ static deprecateAliases: boolean;
32
34
  static flags: {
33
35
  "connection-string": import("@oclif/core/lib/interfaces").OptionFlag<string | undefined, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
34
36
  schema: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
@@ -36,6 +38,7 @@ export default class ImportSupabase extends BaseCommand {
36
38
  "dry-run": import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
37
39
  yes: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
38
40
  };
41
+ protected reportErrorText: boolean;
39
42
  /** Overridable for testing. */
40
43
  protected makeIntrospector(connectionString: string): Introspector;
41
44
  run(): Promise<void>;
@@ -59,7 +59,7 @@ function formatReport(report) {
59
59
  if (w.noPrimaryKey.length > 0)
60
60
  review.push(` - Tables with no primary key: ${w.noPrimaryKey.join(", ")}`);
61
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(", ")}`);
62
+ review.push(` - Foreign keys left out; the column itself is kept (the key points at a table that was not imported, or at a column that is not that table's primary key): ${w.foreignKeysNotCarried.join(", ")}`);
63
63
  if (w.compositeFks.length > 0)
64
64
  review.push(` - Composite foreign keys (kept as columns, no relationship): ${w.compositeFks.join(", ")}`);
65
65
  if (w.joinTablesDetected.length > 0)
@@ -111,14 +111,19 @@ function writeApsorcFile(apsorc, outPath) {
111
111
  return { backupPath };
112
112
  }
113
113
  exports.writeApsorcFile = writeApsorcFile;
114
- class ImportSupabase extends base_command_1.default {
114
+ class Import extends base_command_1.default {
115
+ constructor() {
116
+ super(...arguments);
117
+ // Errors here can name the database host, so the text stays on this machine.
118
+ this.reportErrorText = false;
119
+ }
115
120
  /** Overridable for testing. */
116
121
  makeIntrospector(connectionString) {
117
122
  return new import_1.PgIntrospector(connectionString);
118
123
  }
119
124
  async run() {
120
125
  var _a, _b;
121
- const { flags } = await this.parse(ImportSupabase);
126
+ const { flags } = await this.parse(Import);
122
127
  let connectionString = resolveConnectionString(flags["connection-string"]);
123
128
  if (!connectionString) {
124
129
  const answer = await inquirer_1.default.prompt([
@@ -126,7 +131,7 @@ class ImportSupabase extends base_command_1.default {
126
131
  type: "password",
127
132
  name: "connectionString",
128
133
  mask: "*",
129
- message: "Supabase Postgres connection string:",
134
+ message: "Postgres connection string:",
130
135
  validate: (input) => input.trim().length > 0 || "A connection string is required",
131
136
  },
132
137
  ]);
@@ -189,13 +194,17 @@ class ImportSupabase extends base_command_1.default {
189
194
  }
190
195
  }
191
196
  }
192
- ImportSupabase.description = "Introspect an existing Supabase (Postgres) database and generate a local .apsorc schema. Read-only: it never writes to the source database.";
193
- ImportSupabase.examples = [
194
- `$ apso import supabase`,
195
- `$ apso import supabase -c "postgresql://postgres:[pw]@db.[ref].supabase.co:5432/postgres"`,
196
- `$ SUPABASE_DB_URL="postgresql://..." apso import supabase --dry-run`,
197
+ Import.description = "Introspect an existing Postgres database (Supabase, Neon, RDS, or any Postgres you can reach with a connection string) and generate a local .apsorc schema. Runs on your machine and is read-only: it never writes to the source database.";
198
+ Import.examples = [
199
+ `$ apso import`,
200
+ `$ apso import -c "postgresql://user:[pw]@host:5432/dbname"`,
201
+ `$ apso import -c "postgresql://postgres:[pw]@db.[ref].supabase.co:5432/postgres"`,
202
+ `$ DATABASE_URL="postgresql://..." apso import --dry-run`,
197
203
  ];
198
- ImportSupabase.flags = {
204
+ // "apso import supabase" was the first name of this command. It still works.
205
+ Import.aliases = ["import:supabase"];
206
+ Import.deprecateAliases = true;
207
+ Import.flags = {
199
208
  "connection-string": core_1.Flags.string({
200
209
  char: "c",
201
210
  description: "Postgres connection string. Falls back to SUPABASE_DB_URL or DATABASE_URL, then prompts.",
@@ -218,4 +227,4 @@ ImportSupabase.flags = {
218
227
  default: false,
219
228
  }),
220
229
  };
221
- exports.default = ImportSupabase;
230
+ exports.default = Import;
@@ -1022,7 +1022,10 @@ is tracked separately.
1022
1022
  |---------|----|---------|
1023
1023
  | joinColumnName | relationship | The foreign key column's own name, e.g. \`patient_id\`. The property stays \`patientId\`. TypeScript only |
1024
1024
  | foreignKeyName | relationship | The foreign key constraint's name. TypeScript only |
1025
- | onDelete | relationship | CASCADE, SET NULL, RESTRICT or NO ACTION. \`cascadeDelete: true\` is CASCADE |
1025
+ | onDelete | relationship | CASCADE, SET NULL, SET DEFAULT, RESTRICT or NO ACTION. \`cascadeDelete: true\` is CASCADE. SET DEFAULT is TypeScript only |
1026
+ | onUpdate | relationship | The same rules for a change to the referenced key. Defaults to NO ACTION. TypeScript only |
1027
+ | joinColumnDefault | relationship | The foreign key column's DEFAULT, as a SQL expression. TypeScript only |
1028
+ | deferrable | relationship | \`INITIALLY DEFERRED\` or \`INITIALLY IMMEDIATE\`: the key is DEFERRABLE and checked at commit or per statement. TypeScript only |
1026
1029
  | primary | relationship | The foreign key column is the entity's primary key. No \`id\` is generated. TypeScript only |
1027
1030
  | primaryKeyName | entity | The primary key constraint's name. TypeScript only |
1028
1031
  | timestampType | entity | \`timestamp\` (default) or \`timestamptz\` for created_at and updated_at: one value, or \`{ "created_at": ..., "updated_at": ... }\` |
@@ -1032,7 +1035,7 @@ is tracked separately.
1032
1035
  | primary | field | The field is the primary key, or part of it |
1033
1036
  | elementType | field | Element type of an \`array\` field, e.g. \`uuid\` |
1034
1037
  | 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 |
1038
+ | foreignKeys | entity | A second foreign key on a column, as \`{ name, column, to, onDelete?, onUpdate?, deferrable?, validate? }\`. A database constraint only; \`apso import\` writes it when a column has two keys. TypeScript only |
1036
1039
 
1037
1040
  In \`indexes\` and \`uniques\`, a foreign key may be named by its relationship (\`patient\`), its id property (\`patientId\`) or its column (\`patient_id\`).
1038
1041
  `;
@@ -10,6 +10,7 @@ const services_1 = require("../../lib/api/services");
10
10
  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
+ const ddl_1 = require("../../lib/ddl");
13
14
  const schema_convert_1 = require("../../lib/utils/schema-convert");
14
15
  /**
15
16
  * A validation error that includes the individual error messages.
@@ -55,6 +56,10 @@ async function accessRuleErrors(parsed) {
55
56
  };
56
57
  // auth and permissions for every language; mcp for Python and Go.
57
58
  await attempt(() => generator.generateGuards(entities, auth, relationshipMap));
59
+ // Python and Go build the database with the DDL writer, which refuses a
60
+ // field type it cannot write. apso generate fails on the same schema.
61
+ if (config.language !== "typescript")
62
+ await attempt(async () => (0, ddl_1.schemaModel)({ entities, relationshipMap }));
58
63
  // mcp in TypeScript is checked where the controller is generated.
59
64
  if (config.language === "typescript")
60
65
  for (const entity of entities)
@@ -85,8 +85,7 @@ function buildModel(entities, relationships, language, auth) {
85
85
  }));
86
86
  const config = scoped.find((s) => s.name === entity.name);
87
87
  const direct = config === null || config === void 0 ? void 0 : config.scopes.find((s) => s.direct && s.contextKey !== "userId" && s.contextKey !== "email");
88
- // Only TypeScript enforces a path through a parent; Python and Go refuse it at generate.
89
- const nested = language === "typescript" ? config === null || config === void 0 ? void 0 : config.scopes.find((s) => s.fkField) : undefined;
88
+ const nested = config === null || config === void 0 ? void 0 : config.scopes.find((s) => s.fkField);
90
89
  let scope;
91
90
  if (config && direct) {
92
91
  scope = { field: direct.field, bypassRoles: config.bypassRoles };
@@ -49,7 +49,7 @@
49
49
  "group": "Tenant scope",
50
50
  "rule": "A user caller reads and changes only rows of their own tenant.",
51
51
  "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" },
52
- "note": "A scopeBy path through a parent (project.organizationId) is enforced in TypeScript and refused at generate in Python and Go. The scope covers every operation: `apso generate` refuses `scopeOptions.enforceOn`."
52
+ "note": "A scopeBy path through a parent (project.organizationId) is enforced in every language: the foreign key must name a parent in the caller's tenant. The scope covers every operation: `apso generate` refuses `scopeOptions.enforceOn`."
53
53
  },
54
54
  {
55
55
  "id": "R7",
@@ -158,10 +158,24 @@ exports.servicesApi = {
158
158
  return match;
159
159
  },
160
160
  async create(workspaceId, data) {
161
+ var _a;
161
162
  const headers = workspaceId
162
163
  ? { "X-Workspace-Id": String(workspaceId) }
163
164
  : undefined;
164
- const raw = await client_1.api.post("/api/services", { name: data.name }, { headers });
165
+ // Send the body the web app sends. workspaceUserId is the caller's own
166
+ // membership in the workspace: the id of their row in GET /api/workspaces.
167
+ // Without it the platform does not record the creator as the service's
168
+ // Owner. A failed lookup must not stop the create.
169
+ const rows = workspaceId
170
+ ? await client_1.api.get("/api/workspaces").catch(() => null)
171
+ : null;
172
+ const memberships = Array.isArray(rows) ? rows : (_a = rows === null || rows === void 0 ? void 0 : rows.data) !== null && _a !== void 0 ? _a : [];
173
+ const membership = memberships.find((m) => { var _a, _b; return String((_b = (_a = m === null || m === void 0 ? void 0 : m.workspace) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : m === null || m === void 0 ? void 0 : m.workspaceId) === String(workspaceId); });
174
+ const raw = await client_1.api.post("/api/services", {
175
+ name: data.name,
176
+ workspaceId: Number(workspaceId) || undefined,
177
+ workspaceUserId: membership === null || membership === void 0 ? void 0 : membership.id,
178
+ }, { headers });
165
179
  return adaptService(raw);
166
180
  },
167
181
  async update(_workspaceSlug, serviceSlugOrId, data) {
@@ -6,6 +6,12 @@ import { Command } from "@oclif/core";
6
6
  */
7
7
  export declare function isUserError(err: unknown): boolean;
8
8
  export default abstract class BaseCommand extends Command {
9
+ /**
10
+ * Whether a failure's message is sent with the cli_command_failed event.
11
+ * Commands that connect to the user's own database set this to false: their
12
+ * error text can name the database host.
13
+ */
14
+ protected reportErrorText: boolean;
9
15
  /**
10
16
  * Report failures to Sentry + PostHog before oclif exits. The postrun hook
11
17
  * does not fire on error, so the flush has to happen here.
@@ -19,6 +19,15 @@ function isUserError(err) {
19
19
  }
20
20
  exports.isUserError = isUserError;
21
21
  class BaseCommand extends core_1.Command {
22
+ constructor() {
23
+ super(...arguments);
24
+ /**
25
+ * Whether a failure's message is sent with the cli_command_failed event.
26
+ * Commands that connect to the user's own database set this to false: their
27
+ * error text can name the database host.
28
+ */
29
+ this.reportErrorText = true;
30
+ }
22
31
  /**
23
32
  * Report failures to Sentry + PostHog before oclif exits. The postrun hook
24
33
  * does not fire on error, so the flush has to happen here.
@@ -43,6 +52,11 @@ class BaseCommand extends core_1.Command {
43
52
  (0, telemetry_1.capturePostHogException)(err, { command: this.id });
44
53
  // Extract detailed error properties for the cli_command_failed event
45
54
  const errorProps = (0, error_utils_1.extractErrorProperties)(err);
55
+ if (!this.reportErrorText) {
56
+ // Commands that connect to the user's own database: the message can name the host.
57
+ delete errorProps.error_message;
58
+ delete errorProps.error_messages;
59
+ }
46
60
  // Track the failure event with structured error properties
47
61
  (0, telemetry_1.track)("cli_command_failed", {
48
62
  command: this.id,
@@ -94,22 +94,25 @@ export interface Model {
94
94
  constraints: ModelConstraint[];
95
95
  indexes: ModelIndex[];
96
96
  }
97
- export declare const pkColumn: (e: Entity) => string;
97
+ export declare const pkColumn: (e: Entity, schema?: SchemaInput) => string;
98
98
  /**
99
99
  * The primary key column of an entity, as a foreign key onto it must copy it:
100
100
  * its SQL type, the matching TypeORM column options and the TypeScript type.
101
101
  * A key declared as a field (varchar(100), text, bigint) keeps that type
102
102
  * instead of falling back to integer.
103
103
  *
104
+ * A key that is a relationship has the type of the key that one references.
105
+ *
104
106
  * @param {Entity} [target] - The referenced entity.
107
+ * @param {SchemaInput} [schema] - The schema, to follow such a key through.
105
108
  * @returns {object} sql, options and ts for the key column.
106
109
  */
107
- export declare const keyColumn: (target?: Entity) => {
110
+ export declare const keyColumn: (target?: Entity, schema?: SchemaInput) => {
108
111
  sql: string;
109
112
  options: string;
110
113
  ts: "string" | "number";
111
114
  };
112
- export declare const fkType: (target?: Entity) => string;
115
+ export declare const fkType: (target?: Entity, schema?: SchemaInput) => string;
113
116
  /**
114
117
  * The foreign key column of a ManyToOne or an owning OneToOne:
115
118
  * "joinColumnName" when the .apsorc sets one (an imported database keeps its
@@ -119,17 +122,19 @@ export declare const fkType: (target?: Entity) => string;
119
122
  * An entity's "foreignKeys" entries with the table and key column each one
120
123
  * references.
121
124
  * @param {Entity} e - The entity.
122
- * @param {Map<string, Entity>} byName - Every entity by name.
125
+ * @param {SchemaInput} schema - The schema the entity is in.
123
126
  * @returns {Array} One resolved entry per key.
124
127
  */
125
- export declare const extraForeignKeys: (e: Entity, byName: Map<string, Entity>) => {
128
+ export declare const extraForeignKeys: (e: Entity, schema: SchemaInput) => {
126
129
  target: string;
127
130
  targetTable: string;
128
131
  targetColumn: string;
129
132
  name: string;
130
133
  column: string;
131
134
  to: string;
132
- onDelete?: "CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION" | undefined;
135
+ onDelete?: import("../types/relationship").OnDelete | undefined;
136
+ onUpdate?: import("../types/relationship").OnDelete | undefined;
137
+ deferrable?: import("../types/relationship").Deferrable | undefined;
133
138
  validate?: boolean | undefined;
134
139
  }[];
135
140
  export declare const relationColumn: (r: RelationshipForTemplate) => string;
@@ -143,7 +148,7 @@ export declare const relationColumn: (r: RelationshipForTemplate) => string;
143
148
  */
144
149
  export declare const relationColumns: (relationships: RelationshipForTemplate[]) => Map<string, string>;
145
150
  /** The join table of an owning ManyToMany and its two key columns. */
146
- export declare const joinTableOf: (e: Entity, r: RelationshipForTemplate, target: Entity) => {
151
+ export declare const joinTableOf: (e: Entity, r: RelationshipForTemplate, target: Entity, schema?: SchemaInput) => {
147
152
  name: string;
148
153
  ownCol: string;
149
154
  otherCol: string;
@@ -192,7 +192,28 @@ const column = (name, type, notNull, def, serial, generated) => ({
192
192
  serial,
193
193
  generated,
194
194
  });
195
- const pkColumn = (e) => { var _a, _b, _c; return (_c = (_b = ((_a = e.fields) !== null && _a !== void 0 ? _a : []).find((f) => f.primary)) === null || _b === void 0 ? void 0 : _b.name) !== null && _c !== void 0 ? _c : "id"; };
195
+ /**
196
+ * The relationship that is an entity's whole primary key ("primary": true and
197
+ * no primary field): a table keyed by the row it extends.
198
+ *
199
+ * @param {Entity} e - The entity.
200
+ * @param {SchemaInput} [schema] - The schema, to look its relationships up in.
201
+ * @returns {RelationshipForTemplate | undefined} The relationship, if one is the key.
202
+ */
203
+ const keyRelationship = (e, schema) => {
204
+ var _a;
205
+ if (!schema || ((_a = e.fields) !== null && _a !== void 0 ? _a : []).some((f) => f.primary))
206
+ return;
207
+ const keys = (0, relationships_1.getRelationshipForTemplate)(e.name, schema.relationshipMap[e.name] || [], schema.entities).filter((r) => r.primary && ownsColumn(r) && r.name !== e.name);
208
+ return keys.length === 1 ? keys[0] : undefined;
209
+ };
210
+ const pkColumn = (e, schema) => {
211
+ var _a, _b, _c;
212
+ const r = keyRelationship(e, schema);
213
+ return r
214
+ ? (0, exports.relationColumn)(r)
215
+ : (_c = (_b = ((_a = e.fields) !== null && _a !== void 0 ? _a : []).find((f) => f.primary)) === null || _b === void 0 ? void 0 : _b.name) !== null && _c !== void 0 ? _c : "id";
216
+ };
196
217
  exports.pkColumn = pkColumn;
197
218
  /**
198
219
  * The primary key column of an entity, as a foreign key onto it must copy it:
@@ -200,11 +221,17 @@ exports.pkColumn = pkColumn;
200
221
  * A key declared as a field (varchar(100), text, bigint) keeps that type
201
222
  * instead of falling back to integer.
202
223
  *
224
+ * A key that is a relationship has the type of the key that one references.
225
+ *
203
226
  * @param {Entity} [target] - The referenced entity.
227
+ * @param {SchemaInput} [schema] - The schema, to follow such a key through.
204
228
  * @returns {object} sql, options and ts for the key column.
205
229
  */
206
- const keyColumn = (target) => {
230
+ const keyColumn = (target, schema) => {
207
231
  var _a, _b;
232
+ const through = target && keyRelationship(target, schema);
233
+ if (through)
234
+ return (0, exports.keyColumn)(schema.entities.find((e) => e.name === through.name), schema);
208
235
  const keys = ((_a = target === null || target === void 0 ? void 0 : target.fields) !== null && _a !== void 0 ? _a : []).filter((f) => f.primary);
209
236
  if (target && keys.length === 1) {
210
237
  const [f] = (0, field_1.getFieldForTemplate)(keys, target.name);
@@ -227,7 +254,7 @@ const keyColumn = (target) => {
227
254
  return { sql: "integer", options: 'type: "integer"', ts: "number" };
228
255
  };
229
256
  exports.keyColumn = keyColumn;
230
- const fkType = (target) => (0, exports.keyColumn)(target).sql;
257
+ const fkType = (target, schema) => (0, exports.keyColumn)(target, schema).sql;
231
258
  exports.fkType = fkType;
232
259
  /**
233
260
  * The foreign key column of a ManyToOne or an owning OneToOne:
@@ -238,21 +265,21 @@ exports.fkType = fkType;
238
265
  * An entity's "foreignKeys" entries with the table and key column each one
239
266
  * references.
240
267
  * @param {Entity} e - The entity.
241
- * @param {Map<string, Entity>} byName - Every entity by name.
268
+ * @param {SchemaInput} schema - The schema the entity is in.
242
269
  * @returns {Array} One resolved entry per key.
243
270
  */
244
- const extraForeignKeys = (e, byName) => {
271
+ const extraForeignKeys = (e, schema) => {
245
272
  var _a;
246
273
  return ((_a = e.foreignKeys) !== null && _a !== void 0 ? _a : []).map((k) => {
247
274
  var _a;
248
- const target = byName.get(k.to);
275
+ const target = schema.entities.find((x) => x.name === k.to);
249
276
  if (!k.name || !k.column || !target)
250
277
  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
278
  return {
252
279
  ...k,
253
280
  target: target.name,
254
281
  targetTable: (0, exports.tableName)(target),
255
- targetColumn: (0, exports.pkColumn)(target),
282
+ targetColumn: (0, exports.pkColumn)(target, schema),
256
283
  };
257
284
  });
258
285
  };
@@ -282,20 +309,21 @@ const relationColumns = (relationships) => {
282
309
  };
283
310
  exports.relationColumns = relationColumns;
284
311
  /** The join table of an owning ManyToMany and its two key columns. */
285
- const joinTableOf = (e, r, target) => {
312
+ const joinTableOf = (e, r, target, schema) => {
286
313
  const table = (0, exports.tableName)(e);
287
314
  const targetTable = (0, exports.tableName)(target);
288
315
  return {
289
316
  name: r.joinTableName ||
290
317
  typeormCase.snakeCase(`${table}_${r.pluralizedRelationshipName}_${targetTable}`),
291
- ownCol: r.joinColumnName || typeormCase.camelCase(`${table}_${(0, exports.pkColumn)(e)}`),
318
+ ownCol: r.joinColumnName ||
319
+ typeormCase.camelCase(`${table}_${(0, exports.pkColumn)(e, schema)}`),
292
320
  otherCol: r.inverseJoinColumnName ||
293
- typeormCase.camelCase(`${targetTable}_${(0, exports.pkColumn)(target)}`),
321
+ typeormCase.camelCase(`${targetTable}_${(0, exports.pkColumn)(target, schema)}`),
294
322
  };
295
323
  };
296
324
  exports.joinTableOf = joinTableOf;
297
325
  function schemaModel(input) {
298
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
326
+ var _a, _b, _c, _d, _e, _f, _g, _h;
299
327
  const { entities, relationshipMap } = input;
300
328
  const byName = new Map(entities.map((e) => [e.name, e]));
301
329
  const model = {
@@ -447,22 +475,22 @@ function schemaModel(input) {
447
475
  const onDelete = oneToOne ? "CASCADE" : (_g = (0, relationship_1.onDeleteOf)(r)) !== null && _g !== void 0 ? _g : "NO ACTION";
448
476
  if (r.type === "ManyToOne" || (oneToOne && r.joinTable)) {
449
477
  const col = (0, exports.relationColumn)(r);
450
- t.columns.push(column(col, (0, exports.fkType)(target), !(r.nullable || oneToOne)));
478
+ t.columns.push(column(col, (0, exports.fkType)(target, input), !(r.nullable || oneToOne), r.joinColumnDefault));
451
479
  if (oneToOne)
452
480
  unique(table, [col], exports.constraintName.relation(table, [col]));
453
481
  if (r.type === "ManyToOne" && r.index)
454
482
  index(table, [col]);
455
- foreignKey(table, col, targetTable, (0, exports.pkColumn)(target),
483
+ foreignKey(table, col, targetTable, (0, exports.pkColumn)(target, input),
456
484
  // NOT VALID exists only on a key added by ALTER TABLE, as these are.
457
- `ON DELETE ${onDelete} ON UPDATE NO ACTION${r.validate === false ? " NOT VALID" : ""}`, r.foreignKeyName || undefined);
485
+ (0, relationship_1.keyRulesSql)(onDelete, r), r.foreignKeyName || undefined);
458
486
  }
459
487
  if (r.type === "ManyToMany" && r.joinTable) {
460
- const { name: join, ownCol, otherCol } = (0, exports.joinTableOf)(e, r, target);
488
+ const { name: join, ownCol, otherCol } = (0, exports.joinTableOf)(e, r, target, input);
461
489
  joinTables.push({
462
490
  name: join,
463
491
  columns: [
464
- column(ownCol, (0, exports.fkType)(e), true),
465
- column(otherCol, (0, exports.fkType)(target), true),
492
+ column(ownCol, (0, exports.fkType)(e, input), true),
493
+ column(otherCol, (0, exports.fkType)(target, input), true),
466
494
  ],
467
495
  });
468
496
  primaryKey(join, [ownCol, otherCol]);
@@ -470,20 +498,20 @@ function schemaModel(input) {
470
498
  index(join, [otherCol]);
471
499
  // TypeORM cascades the inverse key only when no inverse relation exists.
472
500
  const inverse = r.biDirectional ? "NO ACTION" : "CASCADE";
473
- foreignKey(join, ownCol, table, (0, exports.pkColumn)(e), "ON DELETE CASCADE ON UPDATE CASCADE");
474
- foreignKey(join, otherCol, targetTable, (0, exports.pkColumn)(target), `ON DELETE ${inverse} ON UPDATE ${inverse}`);
501
+ foreignKey(join, ownCol, table, (0, exports.pkColumn)(e, input), "ON DELETE CASCADE ON UPDATE CASCADE");
502
+ foreignKey(join, otherCol, targetTable, (0, exports.pkColumn)(target, input), `ON DELETE ${inverse} ON UPDATE ${inverse}`);
475
503
  }
476
504
  }
477
- for (const k of (0, exports.extraForeignKeys)(e, byName)) {
505
+ for (const k of (0, exports.extraForeignKeys)(e, input)) {
478
506
  if (!t.columns.some((c) => c.name === k.column))
479
507
  throw new Error(`${e.name} "foreignKeys" entry "${k.name}" names column "${k.column}", which ${e.name} does not have.`);
480
508
  if (foreignKeys.some((c) => c.table === table && c.name === k.name))
481
509
  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}`);
510
+ foreignKey(table, k.column, k.targetTable, k.targetColumn, (0, relationship_1.keyRulesSql)(k.onDelete, k), k.name, `fk:${table}:${k.name}`);
483
511
  }
484
512
  const keyColumns = customPk
485
513
  ? [
486
- ...((_j = e.fields) !== null && _j !== void 0 ? _j : []).filter((f) => f.primary).map((f) => f.name),
514
+ ...((_h = e.fields) !== null && _h !== void 0 ? _h : []).filter((f) => f.primary).map((f) => f.name),
487
515
  ...relationKeys,
488
516
  ]
489
517
  : ["id"];
@@ -1,6 +1,22 @@
1
1
  import { BaseGenerator } from "./base";
2
2
  import { TargetLanguage, GeneratedFile, ValidationResult, GeneratorConfig, EntityGenerationOptions, ControllerGenerationOptions, ServiceGenerationOptions, DtoGenerationOptions, MigrationGenerationOptions, Entity, AuthConfig } from "../types";
3
+ import { NestedScopeData } from "../guards";
3
4
  import { RelationshipMap } from "../types";
5
+ /**
6
+ * A scopeBy path through parents as SQL names: the entity's foreign key column,
7
+ * each parent's table with its foreign key column to the next, and the tenant
8
+ * column on the last parent. Columns are the .apsorc names, as the DDL writer
9
+ * names them.
10
+ */
11
+ export declare function goNestedScopes(nested: NestedScopeData[], entities: Entity[]): {
12
+ column: string;
13
+ parents: {
14
+ table: string;
15
+ column: string;
16
+ }[];
17
+ tenantColumn: string;
18
+ source: "email" | "userId" | "tenant";
19
+ }[];
4
20
  /**
5
21
  * Go/Gin generator that produces GORM models, DTOs, Gin handlers,
6
22
  * and service layer code.
@@ -66,6 +82,8 @@ export declare class GoGenerator extends BaseGenerator {
66
82
  * Scope data for a Go service: each direct scopeBy field's struct field and
67
83
  * column (the .apsorc name, as the DDL writer names it). A field declared on the entity is
68
84
  * pascalCase; a relation's foreign key (organizationId) is OrganizationID.
85
+ * A path through a parent (task.workspaceId) carries the foreign key the
86
+ * service reads from a write, to check the parent is the caller's.
69
87
  */
70
88
  private goScope;
71
89
  /**