Types generator for your
Bun.sqlqueries
You don't need an ORM to have type-safe SQL statements in your Bun application.
@ilbertt/bun-sqlgen is a codegen tool that validates your queries against your schema and generates their result types.
No running database is needed at codegen time, because your migrations run against an in-memory Wasm Postgres (PGlite).
bun add @ilbertt/bun-sqlgen-
Your migrations are the source of truth for the schema — put them in any folder:
-- db/migrations/0001_init.sql CREATE TABLE users ( id bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY, email text NOT NULL, display_name text );
-
Wrap your client with
withTypesand tag each query with its name:import { withTypes } from '@ilbertt/bun-sqlgen'; import { SQL } from 'bun'; const sql = withTypes(new SQL(Bun.env.DATABASE_URL!)); export async function getUser(id: number) { const [user] = await sql.GetUser` SELECT id, email, display_name FROM users WHERE id = ${id} `; return user; // { id: string; email: string; display_name: string | null } }
-
Generate the types:
bun bun-sqlgen generate 'src/**/*.ts' --migrations db/migrationsThis writes
src/queries.gen.d.ts— commit it. With it in place,user.whateveris a compile error anduser.display_name.lengthis flagged as possibly-null, all by plaintsc.
Runnable projects live in the examples/ folder.
Development setup and conventions are in CONTRIBUTING.md.