diff --git a/src/commands/import/index.ts b/src/commands/import/index.ts index 3b80bff..990a84d 100644 --- a/src/commands/import/index.ts +++ b/src/commands/import/index.ts @@ -76,7 +76,7 @@ export function formatReport(report: ImportReport): string { const w = report.warnings; const review: string[] = []; if (w.compositePks.length > 0) - review.push(` - Composite primary keys (review): ${w.compositePks.join(", ")}`); + review.push(` - Composite primary keys (the table and its key are kept; the API lists and creates rows and has no route for one row, so read one with a filter on its key columns): ${w.compositePks.join(", ")}`); if (w.nonStandardPks.length > 0) review.push(` - Non-"id" primary keys (kept as fields): ${w.nonStandardPks.join(", ")}`); if (w.noPrimaryKey.length > 0) diff --git a/src/lib/access/cases.ts b/src/lib/access/cases.ts index 60f4461..e491b06 100644 --- a/src/lib/access/cases.ts +++ b/src/lib/access/cases.ts @@ -121,7 +121,7 @@ export function buildModel( language: Language, auth?: { permissionEntity?: string } ): AccessModel { - const plan = planCrud(entities, relationships); + const plan = planCrud(entities, relationships, language); const skipped = [...plan.skipped]; const scoped = auth ? getScopedEntities(entities, relationships) : []; let tenantRoot: string | undefined; diff --git a/src/lib/generators/typescript.ts b/src/lib/generators/typescript.ts index 8ca382e..319887f 100644 --- a/src/lib/generators/typescript.ts +++ b/src/lib/generators/typescript.ts @@ -362,9 +362,11 @@ export class TypeScriptGenerator extends BaseGenerator { // The :id route parameter maps to the entity's own key: a primary field, // or the id property of a foreign key that is the primary key. A // composite key has no single field, so it keeps the default. + // Counted over every relationship: one onto an auth entity is not + // joinable, but its column is still part of the key. const keyFields = [ ...(entity.fields ?? []).filter((f) => f.primary).map((f) => f.name), - ...relationshipsForTemplate + ...getRelationshipForTemplate(entityName, relationships) .filter((r) => r.primary) .map((r) => r.camelCasedId), ]; @@ -394,6 +396,9 @@ export class TypeScriptGenerator extends BaseGenerator { .filter((f) => f.generated) .map((f) => f.name), keyField: keyFields.length === 1 ? keyFields[0] : "id", + // A composite key has no single value to put in /:id, so the routes + // that address one row are left out (apsoai/cli#250). + compositeKey: keyFields.length > 1, associations: [...new Set(relationshipsForTemplate)], nestedJoinsFile, // scopeBy fields @CrudAuth adds to every query once a caller is diff --git a/src/lib/templates/rest/controller-rest-spec.eta b/src/lib/templates/rest/controller-rest-spec.eta index 04282f7..0fe526f 100644 --- a/src/lib/templates/rest/controller-rest-spec.eta +++ b/src/lib/templates/rest/controller-rest-spec.eta @@ -49,11 +49,13 @@ describe('<%= it.ctrlName%>', () => { expect(controller).toBeDefined(); }); +<% if (!it.compositeKey) { %> it('should call <%= it.ctrlName%> get method', () => { const req: CrudRequest = { ...baseRequest } expect(controller.get(req)).not.toEqual(null); expect(spyService.getOne).toHaveBeenCalled(); }); +<% } %> it('should call <%= it.ctrlName%> create method', () => { const req: CrudRequest = { ...baseRequest } diff --git a/src/lib/templates/rest/controller-rest.eta b/src/lib/templates/rest/controller-rest.eta index b41f0ce..13541cf 100644 --- a/src/lib/templates/rest/controller-rest.eta +++ b/src/lib/templates/rest/controller-rest.eta @@ -75,6 +75,13 @@ const skipScope = (req: any) => { // Query syntaxes accepted, from .apsorc "query.dialects". <% } %> dialects: [<%~ it.dialectList %>], +<% if (it.compositeKey) { %> + // The primary key is more than one column, so no route addresses one row + // by /:id. Read a row with a list filter on its key columns. + routes: { + exclude: ['getOneBase', 'updateOneBase', 'replaceOneBase', 'deleteOneBase', 'recoverOneBase'], + }, +<% } %> params: { id: { field: '<%= it.keyField %>', @@ -193,6 +200,7 @@ export class <%= it.ctrlName %> implements CrudController<<%= it.entityName %>>{ return this.base.getManyBase(req); } +<% if (!it.compositeKey) { %> @Override('getOneBase') @ApiOperation({ summary: 'Retrieve a single <%= it.entityName %>' }) <% if (it.mcp.includes('read')) { %> @@ -204,6 +212,7 @@ export class <%= it.ctrlName %> implements CrudController<<%= it.entityName %>>{ return this.base.getOneBase(req); } +<% } %> @Override('createOneBase') @ApiOperation({ summary: 'Create a single <%= it.entityName %>' }) <% /* @ApiResponse({ status: 200, description: 'description goes here', schema: <%= it.entityName %>Create }) */ %> @@ -243,6 +252,7 @@ export class <%= it.ctrlName %> implements CrudController<<%= it.entityName %>>{ return this.base.createManyBase(req, <%~ it.generatedFields.length ? '{ ...dto, bulk: dto.bulk.map((row) => writable(row)) }' : 'dto' %> as unknown as CreateManyDto<<%= it.entityName %>>); } +<% if (!it.compositeKey) { %> @Override('updateOneBase') @ApiOperation({ summary: 'Update a single <%= it.entityName %>' }) <% if (it.mcp.includes('update')) { %> @@ -274,5 +284,6 @@ export class <%= it.ctrlName %> implements CrudController<<%= it.entityName %>>{ ) { return this.base.deleteOneBase(req); } +<% } %> } \ No newline at end of file diff --git a/src/lib/verify/crud-plan.ts b/src/lib/verify/crud-plan.ts index 9cd9538..e293c12 100644 --- a/src/lib/verify/crud-plan.ts +++ b/src/lib/verify/crud-plan.ts @@ -75,7 +75,8 @@ export interface CrudPlan { export function planCrud( entities: Entity[], - relationships: RelationshipMap + relationships: RelationshipMap, + language = "typescript" ): CrudPlan { const pending: PlannedEntity[] = []; const skipped: CrudPlan["skipped"] = []; @@ -97,14 +98,25 @@ export function planCrud( const manyToOne = (relationships[entity.name] || []).filter( (r) => r.type === "ManyToOne" ); - const parents = manyToOne - .filter((r) => !r.nullable) - .map((r) => ({ property: getRelationshipIdField(r), entity: r.name })); // The same rule as the generated controller's id parameter. const keys = [ ...(entity.fields || []).filter((f) => f.primary).map((f) => f.name), ...manyToOne.filter((r) => r.primary).map((r) => getRelationshipIdField(r)), ]; + // A TypeScript service has no one-row routes for a composite key. Python + // and Go services still declare them, so their rows are tried as before. + if (keys.length > 1 && language === "typescript") { + skipped.push({ + name: entity.name, + reason: `its primary key is ${keys.length} columns (${keys.join( + ", " + )}), so the service has no route that reads or deletes one row`, + }); + continue; + } + const parents = manyToOne + .filter((r) => !r.nullable) + .map((r) => ({ property: getRelationshipIdField(r), entity: r.name })); pending.push({ name: entity.name, key: keys.length === 1 ? keys[0] : "id", diff --git a/src/lib/verify/index.ts b/src/lib/verify/index.ts index 854f6ac..ddea868 100644 --- a/src/lib/verify/index.ts +++ b/src/lib/verify/index.ts @@ -648,7 +648,7 @@ async function checkEndpoints( }); } - const plan = planCrud(entities, relationships); + const plan = planCrud(entities, relationships, language); for (const s of plan.skipped) done({ name: `skip ${s.name}`, ok: true, output: s.reason }); const ids = new Map(); diff --git a/test/lib/generators/typescript.test.ts b/test/lib/generators/typescript.test.ts index 9b13fb6..c49c666 100644 --- a/test/lib/generators/typescript.test.ts +++ b/test/lib/generators/typescript.test.ts @@ -1158,3 +1158,70 @@ describe("key types and enum names kept from an import", () => { expect(() => schemaDdl({ entities: [ledger, note], relationshipMap })).toThrow('uses the enum type "review_state" with values that differ'); }); }); + +const specOf = async (entity: Entity) => { + const files = await new TypeScriptGenerator(createConfig([entity])).generateController({ entity, allEntities: [entity], relationshipMap: {}, relationships: [], apiType: "rest" } as never); + return files.find((f) => f.path.endsWith(".controller.spec.ts"))!.content; +}; + +// apsoai/cli#250 +describe("a composite primary key", () => { + const controllerOf = async (entity: Entity) => { + const files = await new TypeScriptGenerator(createConfig([entity])).generateController({ entity, allEntities: [entity], relationshipMap: {}, relationships: [], apiType: "rest" } as never); + return files.find((f) => f.path.endsWith(".controller.ts"))!.content; + }; + const limit: Entity = { + name: "RateLimit", + mcp: true, + fields: [ + { name: "bucket", type: "text", primary: true }, + { name: "window_start", type: "timestamptz", primary: true }, + { name: "hits", type: "integer" }, + ], + } as Entity; + + test("has list and create routes, and none that address one row", async () => { + const controller = await controllerOf(limit); + expect(controller).toContain("exclude: ['getOneBase', 'updateOneBase', 'replaceOneBase', 'deleteOneBase', 'recoverOneBase']"); + for (const kept of ["getManyBase", "createOneBase", "createManyBase"]) expect(controller).toContain(`@Override('${kept}')`); + for (const gone of ["getOneBase", "updateOneBase", "replaceOneBase", "deleteOneBase"]) expect(controller).not.toContain(`@Override('${gone}')`); + // The MCP tools follow the routes. + expect(controller).toContain("list_rate_limits"); + expect(controller).toContain("create_rate_limit"); + expect(controller).not.toContain("get_rate_limit"); + expect(controller).not.toContain("delete_rate_limit"); + }); + + test("the generated spec does not call a handler that is gone", async () => { + expect(await specOf(limit)).not.toContain("controller.get("); + expect(await specOf({ ...limit, fields: [limit.fields![0], limit.fields![2]] })).toContain("controller.get("); + }); + + test("a key column that references an auth entity still counts", async () => { + const user: Entity = { name: "User", fields: [{ name: "email", type: "text" }] }; + const post: Entity = { name: "Post", fields: [{ name: "title", type: "text" }] }; + const favorite: Entity = { name: "Favorite", fields: [{ name: "note", type: "text", nullable: true }] }; + const relationshipMap = parseRelationships([ + { from: "Favorite", to: "User", type: "ManyToOne", primary: true, bi_directional: false }, + { from: "Favorite", to: "Post", type: "ManyToOne", primary: true, bi_directional: false }, + ]); + const files = await new TypeScriptGenerator(createConfig([user, post, favorite], relationshipMap)).generateController({ + entity: favorite, + allEntities: [user, post, favorite], + relationshipMap, + relationships: relationshipMap.Favorite, + apiType: "rest", + auth: { provider: "better-auth", url: "https://app.example.com/api/auth" }, + } as never); + const controller = files.find((f) => f.path.endsWith(".controller.ts"))!.content; + expect(controller).toContain("exclude: ['getOneBase'"); + expect(controller).not.toContain("@Override('deleteOneBase')"); + }); + + test("a single key keeps every route", async () => { + const controller = await controllerOf({ ...limit, fields: [limit.fields![0], limit.fields![2]] }); + expect(controller).not.toContain("exclude:"); + expect(controller).toContain("@Override('deleteOneBase')"); + expect(controller).toContain("field: 'bucket'"); + }); +}); diff --git a/test/lib/verify/crud-plan.test.ts b/test/lib/verify/crud-plan.test.ts index 3c50144..36302c1 100644 --- a/test/lib/verify/crud-plan.test.ts +++ b/test/lib/verify/crud-plan.test.ts @@ -113,3 +113,23 @@ describe("a uuid id with no default", () => { ]); }); }); + +describe("a composite primary key", () => { + test("is skipped, with the reason", () => { + const limit: Entity = { + name: "RateLimit", + fields: [ + { name: "bucket", type: "text", primary: true }, + { name: "window_start", type: "timestamptz", primary: true }, + ], + }; + const plan = planCrud([limit], parseRelationships([])); + expect(plan.order).toEqual([]); + expect(plan.skipped).toEqual([ + { name: "RateLimit", reason: "its primary key is 2 columns (bucket, window_start), so the service has no route that reads or deletes one row" }, + ]); + // Python and Go services still declare one-row routes, so they are tried. + for (const language of ["python", "go"]) + expect(planCrud([limit], parseRelationships([]), language).order.map((p) => p.name)).toEqual(["RateLimit"]); + }); +});