ilbertt/bun-sqlgen: Types generator for your Bun.sql queries ยท GitHub

๐Ÿ”ฅ Explore this trending post from Hacker News ๐Ÿ“–

๐Ÿ“‚ **Category**:

๐Ÿ“Œ **What Youโ€™ll Learn**:

Type-safe SQL for Bun, no ORM โ€” raw Bun.sql,
live-checked against your schema.

Tag a query with a name โ€” sql.GetUser`...` โ€” and its fully-typed, null-safe
row appears right at the call site: no ORM, no generics, no hand-written types.
Codegen plans every query against a real Postgres or SQLite database (no Docker
needed), so wrong columns and bad SQL fail the build, not production โ€” fast enough
to rerun on every save. The runtime stays 100% Bun-native.

Published as @ilbertt/bun-sqlgen โ€”
its README is the full guide: both dialects,
nullability overrides, transactions, and configuration.

bun add @ilbertt/bun-sqlgen
  1. Migrations are the source of truth for your 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
    );
  2. Wrap your client with withTypes and tag each query with its name:

    import  id: string; email: string; display_name: string  from '@ilbertt/bun-sqlgen';
    import ๐Ÿ’ฌ 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 = $โšก
      `;
      return user; // typed  null 
    }
  3. Generate the types:

    bun bun-sqlgen generate 'src/**/*.ts' --migrations db/migrations

    This writes src/queries.gen.d.ts โ€” commit it. With it in place, user.emial is
    a compile error and user.display_name.length is flagged as possibly-null, all by
    plain tsc.

Runnable projects live in the examples/ folder.

Development setup and conventions are in CONTRIBUTING.md.

โšก **Whatโ€™s your take?**
Share your thoughts in the comments below!

#๏ธโƒฃ **#ilberttbunsqlgen #Types #generator #Bun.sql #queries #GitHub**

๐Ÿ•’ **Posted on**: 1782227527

๐ŸŒŸ **Want more?** Click here for more info! ๐ŸŒŸ

By

Leave a Reply

Your email address will not be published. Required fields are marked *