Skip to content

Commit efc2c91

Browse files
committed
fix(codegen-ts): a read-only projection keyed on a non-id field addresses its own key (FR-044)
The read-only mounts address a row by `idColumn`, which defaults to `id`. The routes templates never passed it, so a projection whose identity is on another field (say `code`) mounted `GET /:id` against a column the view does not have. The mount then ran the query with no WHERE and answered with the view's first row. Generators: the Fastify and Hono routes templates, and their reference copies, emit `idColumn: "<field>"` in the read-only mount options when the by-id field is not `id`. It is the field `find<Name>ById` reads, through a new `itemRouteField` (`hasItemRoute` is now "it is defined"). A projection keyed on `id` keeps its bytes; no golden moved. Runtime: both read-only mounts answer `404 not_found` when the view declares columns and has none under `idColumn`, instead of an unfiltered row. That also makes an owned routes generator that predates the option fail safe. Owned copies under test-generators and examples are re-synced.
1 parent 735ab76 commit efc2c91

16 files changed

Lines changed: 370 additions & 40 deletions

File tree

‎examples/advanced-modeling/codegen/generators/routes.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,8 @@ import {
7272
isProjection,
7373
isWriteThrough,
7474
isReport,
75-
hasItemRoute,
75+
itemRouteField,
76+
DEFAULT_ID_FIELD,
7677
servesReadApi,
7778
formatTs,
7879
renderRoutesIndex,
@@ -141,15 +142,22 @@ function renderRoutes(
141142
const camelName = entityName.charAt(0).toLowerCase() + entityName.slice(1);
142143
// A keyless read-only object (a projection with no identity and no `id` column, and
143144
// every report: FR-044) has no row to address, so it mounts GET list and the collection 405
144-
// and no `/:id` route of any verb. Both keys are absent for a keyed projection, which
145+
// and no `/:id` route of any verb. Every key is absent for a projection keyed on `id`, which
145146
// keeps its output byte-identical.
146-
const keyless = !hasItemRoute(entity);
147+
const idField = itemRouteField(entity);
148+
const keyless = idField === undefined;
147149
const report = isReport(entity);
148150
const noun = report ? "report" : "projection";
149151
const exposes = keyless
150152
? "Exposes GET list only. POST returns 405."
151153
: "Exposes GET list + GET :id only. POST/PATCH/DELETE return 405.";
154+
// The mount addresses `id` by default. A projection keyed on another field names it
155+
// (the view's key for that column, which is the field name), so `GET /:id` reads the
156+
// same column the by-id query does. Absent for `id`, which keeps that output's bytes.
152157
const keylessOpts = (indent: string): string =>
158+
(idField !== undefined && idField !== DEFAULT_ID_FIELD
159+
? `\n${indent}idColumn: ${JSON.stringify(idField)},`
160+
: "") +
153161
(keyless ? `\n${indent}itemRoutes: false,` : "") +
154162
(report ? `\n${indent}resource: "report",` : "");
155163
const FastifyInstanceSym = imp("t:FastifyInstance@fastify");

‎examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-read-only.ts‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,15 @@ export interface MountReadOnlyOptions {
2020
readonly filterAllowlist: FilterAllowlist;
2121
readonly sortAllowlist: SortAllowlist;
2222
readonly dialect: SqlDialect;
23-
/** Override default ID column name (defaults to "id"). */
23+
/**
24+
* The column `GET /:id` addresses a row by: the KEY of that column in the Drizzle view
25+
* (the field name), not its physical name. Defaults to "id". For a view declared with
26+
* no columns (the raw-SQL path) it is the physical column name instead, because there
27+
* is no key to look up.
28+
*
29+
* A view that declares columns and has none under this key has no row to address, so
30+
* `GET /:id` answers `404 not_found` for every id.
31+
*/
2432
readonly idColumn?: string;
2533
/**
2634
* Fastify route-level hooks applied to every route this mounts — the same option
@@ -229,15 +237,18 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void {
229237
}
230238
// biome-ignore lint/suspicious/noExplicitAny: Drizzle table/view column ref
231239
const colRef = (view as any)[idCol];
240+
// No column under `idColumn`: there is nothing to compare the id against, and a query
241+
// with no WHERE would answer with the view's first row. No row is addressable.
242+
if (colRef === undefined) {
243+
return reply.code(404).send({ error: "not_found" });
244+
}
232245
// Compare against the PK's real type — a uuid/text key must NOT go through Number().
233246
const idValue = coerceIdForColumn(colRef, id);
234247
if (idValue === undefined) {
235248
return reply.code(400).send({ error: "invalid_id" });
236249
}
237250
// Await + first row rather than `.get()` (libsql/better-sqlite3-only).
238-
const rows = await db.select().from(view).where(
239-
colRef !== undefined ? eq(colRef, idValue) : undefined
240-
).limit(1);
251+
const rows = await db.select().from(view).where(eq(colRef, idValue)).limit(1);
241252
const row = (rows as unknown[])[0];
242253
return row ? toWire(row) : reply.code(404).send({ error: "not_found" });
243254
});

‎examples/showcase/codegen/generators/routes.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,8 @@ import {
7272
isProjection,
7373
isWriteThrough,
7474
isReport,
75-
hasItemRoute,
75+
itemRouteField,
76+
DEFAULT_ID_FIELD,
7677
servesReadApi,
7778
formatTs,
7879
renderRoutesIndex,
@@ -141,15 +142,22 @@ function renderRoutes(
141142
const camelName = entityName.charAt(0).toLowerCase() + entityName.slice(1);
142143
// A keyless read-only object (a projection with no identity and no `id` column, and
143144
// every report: FR-044) has no row to address, so it mounts GET list and the collection 405
144-
// and no `/:id` route of any verb. Both keys are absent for a keyed projection, which
145+
// and no `/:id` route of any verb. Every key is absent for a projection keyed on `id`, which
145146
// keeps its output byte-identical.
146-
const keyless = !hasItemRoute(entity);
147+
const idField = itemRouteField(entity);
148+
const keyless = idField === undefined;
147149
const report = isReport(entity);
148150
const noun = report ? "report" : "projection";
149151
const exposes = keyless
150152
? "Exposes GET list only. POST returns 405."
151153
: "Exposes GET list + GET :id only. POST/PATCH/DELETE return 405.";
154+
// The mount addresses `id` by default. A projection keyed on another field names it
155+
// (the view's key for that column, which is the field name), so `GET /:id` reads the
156+
// same column the by-id query does. Absent for `id`, which keeps that output's bytes.
152157
const keylessOpts = (indent: string): string =>
158+
(idField !== undefined && idField !== DEFAULT_ID_FIELD
159+
? `\n${indent}idColumn: ${JSON.stringify(idField)},`
160+
: "") +
153161
(keyless ? `\n${indent}itemRoutes: false,` : "") +
154162
(report ? `\n${indent}resource: "report",` : "");
155163
const FastifyInstanceSym = imp("t:FastifyInstance@fastify");

‎examples/showcase/codegen/runtime/drizzle-fastify/mount-read-only.ts‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,15 @@ export interface MountReadOnlyOptions {
2020
readonly filterAllowlist: FilterAllowlist;
2121
readonly sortAllowlist: SortAllowlist;
2222
readonly dialect: SqlDialect;
23-
/** Override default ID column name (defaults to "id"). */
23+
/**
24+
* The column `GET /:id` addresses a row by: the KEY of that column in the Drizzle view
25+
* (the field name), not its physical name. Defaults to "id". For a view declared with
26+
* no columns (the raw-SQL path) it is the physical column name instead, because there
27+
* is no key to look up.
28+
*
29+
* A view that declares columns and has none under this key has no row to address, so
30+
* `GET /:id` answers `404 not_found` for every id.
31+
*/
2432
readonly idColumn?: string;
2533
/**
2634
* Fastify route-level hooks applied to every route this mounts — the same option
@@ -229,15 +237,18 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void {
229237
}
230238
// biome-ignore lint/suspicious/noExplicitAny: Drizzle table/view column ref
231239
const colRef = (view as any)[idCol];
240+
// No column under `idColumn`: there is nothing to compare the id against, and a query
241+
// with no WHERE would answer with the view's first row. No row is addressable.
242+
if (colRef === undefined) {
243+
return reply.code(404).send({ error: "not_found" });
244+
}
232245
// Compare against the PK's real type — a uuid/text key must NOT go through Number().
233246
const idValue = coerceIdForColumn(colRef, id);
234247
if (idValue === undefined) {
235248
return reply.code(400).send({ error: "invalid_id" });
236249
}
237250
// Await + first row rather than `.get()` (libsql/better-sqlite3-only).
238-
const rows = await db.select().from(view).where(
239-
colRef !== undefined ? eq(colRef, idValue) : undefined
240-
).limit(1);
251+
const rows = await db.select().from(view).where(eq(colRef, idValue)).limit(1);
241252
const row = (rows as unknown[])[0];
242253
return row ? toWire(row) : reply.code(404).send({ error: "not_found" });
243254
});

‎server/typescript/packages/codegen-ts/src/api-surface.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,12 +79,26 @@ export function servesReadApi(entity: MetaObject): boolean {
7979
* Only the read-only templates ask. The writable surface emits item routes unconditionally.
8080
*/
8181
export function hasItemRoute(entity: MetaObject): boolean {
82-
if (isReport(entity)) return false;
82+
return itemRouteField(entity) !== undefined;
83+
}
84+
85+
/**
86+
* The field a read-only object's item routes address a row by, or `undefined` when it has
87+
* none (`hasItemRoute` is exactly "this is defined"). It is `getPkInfo`'s field, so the
88+
* by-id query and the mounted `GET /:id` read the same column.
89+
*
90+
* The read-only mount addresses `id` unless told otherwise, so a routes template passes
91+
* this as the mount's `idColumn` whenever it is not `id`. Without that, a projection keyed
92+
* on `code` mounted a `/:id` route that compared nothing and answered with the view's
93+
* first row.
94+
*/
95+
export function itemRouteField(entity: MetaObject): string | undefined {
96+
if (isReport(entity)) return undefined;
8397
// ADR-0039: resolving. `getPkFields` reads `primaryIdentity()` and `findField` reads
8498
// `fields()`, both of which walk the super chain; a projection's identity and its `id`
8599
// field are typically inherited from its base entity.
86100
const idField = getPkFields(entity)[0] ?? DEFAULT_ID_FIELD;
87-
return entity.findField(idField) !== undefined;
101+
return entity.findField(idField) !== undefined ? idField : undefined;
88102
}
89103

90104
/**

‎server/typescript/packages/codegen-ts/src/index.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ export type { DocPageNode, DocPagePlacement } from "./docs-paths.js";
131131
export { isProjection, isWriteThrough } from "./projection/projection-detector.js";
132132
export { isAbstract, emitsInstanceArtifacts, emitsWriteArtifacts } from "./instance-artifacts.js";
133133
// The UI tier asks THESE — "is there an endpoint?" — never the storage predicates.
134-
export { hasGeneratedForm, hasItemRoute, restPath, servesClientTier, servesReadApi, servesWriteApi } from "./api-surface.js";
134+
export { hasGeneratedForm, hasItemRoute, itemRouteField, restPath, servesClientTier, servesReadApi, servesWriteApi } from "./api-surface.js";
135135
// #356 — every emitter selects a field's view by the SURFACE it renders, never by
136136
// declaration position. An owned generator (FR-040) composing the render layer must
137137
// use this too, or it reinstates the order-dependence in its own copy.
@@ -207,6 +207,10 @@ export {
207207
renderReverseFinderFns,
208208
reverseFksFor,
209209
getPkInfo,
210+
// The by-id field of an object that declares no primary identity. Public because an
211+
// owned routes generator compares `itemRouteField` against it to decide whether the
212+
// read-only mount needs an `idColumn`.
213+
DEFAULT_ID_FIELD,
210214
} from "./templates/queries.js";
211215
export { hasAutoSetFields } from "./templates/zod-validators.js";
212216

‎server/typescript/packages/codegen-ts/src/reference/routes-hono.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,8 @@ import {
5757
isProjection,
5858
isWriteThrough,
5959
isReport,
60-
hasItemRoute,
60+
itemRouteField,
61+
DEFAULT_ID_FIELD,
6162
servesReadApi,
6263
formatTs,
6364
renderRoutesIndex,
@@ -122,15 +123,22 @@ function renderRoutesHono(
122123
const camelName = entityName.charAt(0).toLowerCase() + entityName.slice(1);
123124
// A keyless read-only object (a projection with no identity and no `id` column, and
124125
// every report: FR-044) has no row to address, so it mounts GET list and the collection 405
125-
// and no `/:id` route of any verb. Both keys are absent for a keyed projection, which
126+
// and no `/:id` route of any verb. Every key is absent for a projection keyed on `id`, which
126127
// keeps its output byte-identical.
127-
const keyless = !hasItemRoute(entity);
128+
const idField = itemRouteField(entity);
129+
const keyless = idField === undefined;
128130
const report = isReport(entity);
129131
const noun = report ? "report" : "projection";
130132
const exposes = keyless
131133
? "Exposes GET list only. POST returns 405."
132134
: "Exposes GET list + GET :id only. POST/PATCH/DELETE return 405.";
135+
// The mount addresses `id` by default. A projection keyed on another field names it
136+
// (the view's key for that column, which is the field name), so `GET /:id` reads the
137+
// same column the by-id query does. Absent for `id`, which keeps that output's bytes.
133138
const keylessOpts = (indent: string): string =>
139+
(idField !== undefined && idField !== DEFAULT_ID_FIELD
140+
? `\n${indent}idColumn: ${JSON.stringify(idField)},`
141+
: "") +
134142
(keyless ? `\n${indent}itemRoutes: false,` : "") +
135143
(report ? `\n${indent}resource: "report",` : "");
136144
const HonoSym = imp("t:Hono@hono");

‎server/typescript/packages/codegen-ts/src/reference/routes.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,8 @@ import {
7272
isProjection,
7373
isWriteThrough,
7474
isReport,
75-
hasItemRoute,
75+
itemRouteField,
76+
DEFAULT_ID_FIELD,
7677
servesReadApi,
7778
formatTs,
7879
renderRoutesIndex,
@@ -141,15 +142,22 @@ function renderRoutes(
141142
const camelName = entityName.charAt(0).toLowerCase() + entityName.slice(1);
142143
// A keyless read-only object (a projection with no identity and no `id` column, and
143144
// every report: FR-044) has no row to address, so it mounts GET list and the collection 405
144-
// and no `/:id` route of any verb. Both keys are absent for a keyed projection, which
145+
// and no `/:id` route of any verb. Every key is absent for a projection keyed on `id`, which
145146
// keeps its output byte-identical.
146-
const keyless = !hasItemRoute(entity);
147+
const idField = itemRouteField(entity);
148+
const keyless = idField === undefined;
147149
const report = isReport(entity);
148150
const noun = report ? "report" : "projection";
149151
const exposes = keyless
150152
? "Exposes GET list only. POST returns 405."
151153
: "Exposes GET list + GET :id only. POST/PATCH/DELETE return 405.";
154+
// The mount addresses `id` by default. A projection keyed on another field names it
155+
// (the view's key for that column, which is the field name), so `GET /:id` reads the
156+
// same column the by-id query does. Absent for `id`, which keeps that output's bytes.
152157
const keylessOpts = (indent: string): string =>
158+
(idField !== undefined && idField !== DEFAULT_ID_FIELD
159+
? `\n${indent}idColumn: ${JSON.stringify(idField)},`
160+
: "") +
153161
(keyless ? `\n${indent}itemRoutes: false,` : "") +
154162
(report ? `\n${indent}resource: "report",` : "");
155163
const FastifyInstanceSym = imp("t:FastifyInstance@fastify");

‎server/typescript/packages/codegen-ts/src/templates/routes-file-hono.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@ import { entityModuleSpecifier } from "../import-path.js";
3131
import { GENERATED_HEADER, GENERATED_EDIT_NOTE, sidecarLine } from "../constants.js";
3232
import { isProjection, isWriteThrough } from "../projection/projection-detector.js";
3333
import { isReport } from "../source-detect.js";
34-
import { hasItemRoute } from "../api-surface.js";
34+
import { itemRouteField } from "../api-surface.js";
35+
import { DEFAULT_ID_FIELD } from "./queries.js";
3536
import { authSeamJsDoc, type CrudVerb, exposeLine } from "../routes-expose.js";
3637
import { effectivePackage } from "../docs-paths.js";
3738
import { httpRuntimeSpecifier } from "../owned-runtime.js";
@@ -81,15 +82,22 @@ export function renderRoutesFileHono(
8182
const camelName = entityName.charAt(0).toLowerCase() + entityName.slice(1);
8283
// A keyless read-only object (a projection with no identity and no `id` column, and
8384
// every report: FR-044) has no row to address, so it mounts GET list and the collection 405
84-
// and no `/:id` route of any verb. Both keys are absent for a keyed projection, which
85+
// and no `/:id` route of any verb. Every key is absent for a projection keyed on `id`, which
8586
// keeps its output byte-identical.
86-
const keyless = !hasItemRoute(entity);
87+
const idField = itemRouteField(entity);
88+
const keyless = idField === undefined;
8789
const report = isReport(entity);
8890
const noun = report ? "report" : "projection";
8991
const exposes = keyless
9092
? "Exposes GET list only. POST returns 405."
9193
: "Exposes GET list + GET :id only. POST/PATCH/DELETE return 405.";
94+
// The mount addresses `id` by default. A projection keyed on another field names it
95+
// (the view's key for that column, which is the field name), so `GET /:id` reads the
96+
// same column the by-id query does. Absent for `id`, which keeps that output's bytes.
9297
const keylessOpts = (indent: string): string =>
98+
(idField !== undefined && idField !== DEFAULT_ID_FIELD
99+
? `\n${indent}idColumn: ${JSON.stringify(idField)},`
100+
: "") +
93101
(keyless ? `\n${indent}itemRoutes: false,` : "") +
94102
(report ? `\n${indent}resource: "report",` : "");
95103
const HonoSym = imp("t:Hono@hono");

‎server/typescript/packages/codegen-ts/src/templates/routes-file.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,8 @@ import { GENERATED_HEADER, GENERATED_EDIT_NOTE, sidecarLine } from "../constants
2929
import { routesHandlerName } from "../naming.js";
3030
import { isProjection, isWriteThrough } from "../projection/projection-detector.js";
3131
import { isReport } from "../source-detect.js";
32-
import { hasItemRoute } from "../api-surface.js";
32+
import { itemRouteField } from "../api-surface.js";
33+
import { DEFAULT_ID_FIELD } from "./queries.js";
3334
import type { RelationEntry } from "../relation-resolver.js";
3435
import { isTphDiscriminatorBase, tphPlan } from "./tph-discriminator.js";
3536
import { authSeamJsDoc, type CrudVerb, exposeLine, intersectExpose, TPH_POLYMORPHIC_VERBS } from "../routes-expose.js";
@@ -80,15 +81,22 @@ export function renderRoutesFile(
8081
const camelName = entityName.charAt(0).toLowerCase() + entityName.slice(1);
8182
// A keyless read-only object (a projection with no identity and no `id` column, and
8283
// every report: FR-044) has no row to address, so it mounts GET list and the collection 405
83-
// and no `/:id` route of any verb. Both keys are absent for a keyed projection, which
84+
// and no `/:id` route of any verb. Every key is absent for a projection keyed on `id`, which
8485
// keeps its output byte-identical.
85-
const keyless = !hasItemRoute(entity);
86+
const idField = itemRouteField(entity);
87+
const keyless = idField === undefined;
8688
const report = isReport(entity);
8789
const noun = report ? "report" : "projection";
8890
const exposes = keyless
8991
? "Exposes GET list only. POST returns 405."
9092
: "Exposes GET list + GET :id only. POST/PATCH/DELETE return 405.";
93+
// The mount addresses `id` by default. A projection keyed on another field names it
94+
// (the view's key for that column, which is the field name), so `GET /:id` reads the
95+
// same column the by-id query does. Absent for `id`, which keeps that output's bytes.
9196
const keylessOpts = (indent: string): string =>
97+
(idField !== undefined && idField !== DEFAULT_ID_FIELD
98+
? `\n${indent}idColumn: ${JSON.stringify(idField)},`
99+
: "") +
92100
(keyless ? `\n${indent}itemRoutes: false,` : "") +
93101
(report ? `\n${indent}resource: "report",` : "");
94102
const FastifyInstanceSym = imp("t:FastifyInstance@fastify");

0 commit comments

Comments
 (0)