Skip to content

Commit cd4421a

Browse files
rtolsmaclaude
andcommitted
feat: Strongly typed columns via enum literal unions and type overrides
Generate stricter, more expressive TypeScript types in two ways: 1. Enum types declared in the schema (previously ignored — the plugin never read the request catalog) are now emitted as string literal union types plus a runtime values array, and columns/params of that type reference the union: export type Status = "active" | "inactive" | "banned"; export const StatusValues: readonly Status[] = [...]; 2. A new `overrides` plugin option (modeled on sqlc-gen-go's overrides) maps SQL types — including domains and other custom types — or individual `table.column`s to arbitrary TypeScript type expressions, with optional type-only imports. This enables branded/nominal types and concrete JSON payload types: overrides: - db_type: "email" ts_type: "Email" import: { path: "./brands", name: "Email" } - db_type: "user_id" ts_type: 'string & { readonly __brand: "user_id" }' - column: "users.meta" ts_type: "UserMeta" import: { path: "./brands", name: "UserMeta" } Resolution order is column override > db_type override > schema enum > built-in driver mapping. Driver nullability (`| null`) and array (`T[]`) wrapping still compose on top of resolved custom types. Emitted enum declarations and imports are deduplicated per generated file and only included when actually used by that file's queries. Implemented as a CustomTypeRegistry (src/customTypes.ts) built from the GenerateRequest catalog and plugin options; each driver accepts the resolver and consults it before its built-in switch, so behavior is identical across pg, postgres, mysql2, and better-sqlite3. Output for schemas without enums or overrides is byte-for-byte unchanged (verified against all seven example configs), and generated code for the new features typechecks under `tsc --strict`. Closes #32. Addresses #37. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GFyrFwpJC2eivaBRyNBJqv
1 parent 395a0ba commit cd4421a

7 files changed

Lines changed: 393 additions & 11 deletions

File tree

‎README.md‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,86 @@ sql:
334334
driver: better-sqlite3 # npm package name
335335
```
336336

337+
## Strongly typed columns
338+
339+
### Enums
340+
341+
Enum types declared in your schema are generated as string literal union
342+
types, along with a runtime array of their values. No configuration is
343+
required.
344+
345+
```sql
346+
CREATE TYPE status AS ENUM ('active', 'inactive', 'banned');
347+
348+
CREATE TABLE users (
349+
id BIGSERIAL PRIMARY KEY,
350+
st status NOT NULL
351+
);
352+
```
353+
354+
```ts
355+
export type Status = "active" | "inactive" | "banned";
356+
357+
export const StatusValues: readonly Status[] = ["active", "inactive", "banned"];
358+
359+
export interface GetUserRow {
360+
id: string;
361+
st: Status;
362+
}
363+
```
364+
365+
### Type overrides
366+
367+
Use the `overrides` option to map SQL types (including domains and other
368+
custom types) or individual columns to your own TypeScript types. Each entry
369+
matches either a SQL type name (`db_type`) or a single column
370+
(`column: "table.column"`), and emits `ts_type` verbatim. An optional
371+
`import` adds a type-only import to files that use the override.
372+
373+
```yaml
374+
codegen:
375+
- out: db
376+
plugin: ts
377+
options:
378+
runtime: node
379+
driver: pg
380+
overrides:
381+
# Map a domain (or any SQL type) to an imported type
382+
- db_type: "email"
383+
ts_type: "Email"
384+
import:
385+
path: "./brands"
386+
name: "Email"
387+
# Inline branded/nominal types work too
388+
- db_type: "user_id"
389+
ts_type: 'string & { readonly __brand: "user_id" }'
390+
# Give a JSON column a concrete payload type
391+
- column: "users.meta"
392+
ts_type: "UserMeta"
393+
import:
394+
path: "./brands"
395+
name: "UserMeta"
396+
```
397+
398+
```ts
399+
import type { Email, UserMeta } from "./brands";
400+
401+
export interface GetUserRow {
402+
id: string & { readonly __brand: "user_id" };
403+
email: Email;
404+
meta: UserMeta | null;
405+
}
406+
```
407+
408+
Column overrides take precedence over `db_type` overrides, which take
409+
precedence over generated enum types and the built-in type mappings.
410+
Nullability and array handling still apply: a nullable overridden column is
411+
emitted as `T | null`, and an array column as `T[]`.
412+
413+
Note that overrides only change the generated *types* — converting values at
414+
runtime (for example, parsing a `numeric` string into a `Big`) is still up to
415+
your driver configuration.
416+
337417
## Development
338418

339419
If you want to build and test sqlc-gen-typescript locally, follow these steps:

‎src/app.ts‎

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
createPrinter,
1717
createSourceFile,
1818
factory,
19+
isImportDeclaration,
1920
} from "typescript";
2021

2122
import {
@@ -28,6 +29,11 @@ import {
2829
} from "./gen/plugin/codegen_pb";
2930

3031
import { argName, colName } from "./drivers/utlis";
32+
import {
33+
CustomTypeFn,
34+
CustomTypeRegistry,
35+
TypeOverride,
36+
} from "./customTypes";
3137
import { Driver as Sqlite3Driver } from "./drivers/better-sqlite3";
3238
import { Driver as PgDriver } from "./drivers/pg";
3339
import { Driver as PostgresDriver } from "./drivers/postgres";
@@ -44,6 +50,7 @@ interface Options {
4450
runtime?: string;
4551
driver?: string;
4652
mysql2?: Mysql2Options
53+
overrides?: TypeOverride[];
4754
}
4855

4956
interface Driver {
@@ -79,19 +86,22 @@ interface Driver {
7986
) => Node;
8087
}
8188

82-
function createNodeGenerator(options: Options): Driver {
89+
function createNodeGenerator(
90+
options: Options,
91+
customType: CustomTypeFn
92+
): Driver {
8393
switch (options.driver) {
8494
case "mysql2": {
85-
return new MysqlDriver(options.mysql2);
95+
return new MysqlDriver(options.mysql2, customType);
8696
}
8797
case "pg": {
88-
return new PgDriver();
98+
return new PgDriver(customType);
8999
}
90100
case "postgres": {
91-
return new PostgresDriver();
101+
return new PostgresDriver(customType);
92102
}
93103
case "better-sqlite3": {
94-
return new Sqlite3Driver();
104+
return new Sqlite3Driver(customType);
95105
}
96106
}
97107
throw new Error(`unknown driver: ${options.driver}`);
@@ -106,7 +116,8 @@ function codegen(input: GenerateRequest): GenerateResponse {
106116
options = JSON.parse(text) as Options;
107117
}
108118

109-
const driver = createNodeGenerator(options);
119+
const registry = new CustomTypeRegistry(input, options.overrides ?? []);
120+
const driver = createNodeGenerator(options, registry.resolver());
110121

111122
// TODO: Verify options, parse them from protobuf honestly
112123

@@ -122,6 +133,13 @@ function codegen(input: GenerateRequest): GenerateResponse {
122133

123134
for (const [filename, queries] of querymap.entries()) {
124135
const nodes = driver.preamble(queries);
136+
// Insert custom type imports and enum declarations after the driver's
137+
// own imports, before any other declarations
138+
let insertAt = 0;
139+
while (insertAt < nodes.length && isImportDeclaration(nodes[insertAt])) {
140+
insertAt++;
141+
}
142+
nodes.splice(insertAt, 0, ...registry.fileDecls(queries));
125143

126144
for (const query of queries) {
127145
const colmap = new Map<string, number>();

0 commit comments

Comments
 (0)