Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/commands/import/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion src/lib/access/cases.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
7 changes: 6 additions & 1 deletion src/lib/generators/typescript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
];
Expand Down Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions src/lib/templates/rest/controller-rest-spec.eta
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
11 changes: 11 additions & 0 deletions src/lib/templates/rest/controller-rest.eta
Original file line number Diff line number Diff line change
Expand Up @@ -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 %>',
Expand Down Expand Up @@ -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')) { %>
Expand All @@ -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 }) */ %>
Expand Down Expand Up @@ -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')) { %>
Expand Down Expand Up @@ -274,5 +284,6 @@ export class <%= it.ctrlName %> implements CrudController<<%= it.entityName %>>{
) {
return this.base.deleteOneBase(req);
}
<% } %>
}

20 changes: 16 additions & 4 deletions src/lib/verify/crud-plan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"] = [];
Expand All @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion src/lib/verify/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>();
Expand Down
67 changes: 67 additions & 0 deletions test/lib/generators/typescript.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'");
});
});
20 changes: 20 additions & 0 deletions test/lib/verify/crud-plan.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"]);
});
});
Loading