Type-safe schema generator, part IV
Well, it's good enough for my current needs.
I can generate typed CRUD operations for the style of queries that I'm writing.
Supports SELECT, UPDATE, INSERT, and DELETE, with JOINs (automatically makes fields nullable for OUTER JOINs). Aliased columns, COUNT, SELECT * ... and RETURNING.
Uses nominal types for primary and foreign keys.
For the following query
INSERT INTO
users AS u (
telegram_id,
first_name,
last_name,
username,
photo_url
)
VALUES
(
$telegram_id,
$first_name,
$last_name,
$username,
$photo_url
)
ON CONFLICT(telegram_id) DO
UPDATE
SET
first_name = excluded.first_name,
last_name = excluded.last_name,
username = excluded.username,
photo_url = excluded.photo_url
RETURNING *;
Output looks roughly like this
import type { Brand } from "../../brand.ts";
import Database from "bun:sqlite";
// This file is automatically generated and should not be edited by hand
type MakeBunHappy = Record<string, never>;
export type UserUserId = Brand<number, 'user:user_id'>;
export interface UpsertUserInput {
readonly $telegram_id: number;
readonly $first_name: string;
readonly $last_name: string;
readonly $username: string;
readonly $photo_url: string;
}
export interface UpsertUserOutput {
readonly user_id: UserUserId;
readonly telegram_id: number;
readonly first_name: string;
readonly last_name: string;
readonly username: string;
readonly photo_url: string;
readonly approved: number;
}
export function getUpsertUserQuery(connection: Database) {
return connection.query<UpsertUserOutput, UpsertUserInput & MakeBunHappy>(`... query text here ...`);
}
❯ cloc .
11 text files.
11 unique files.
0 files ignored.
github.com/AlDanial/cloc v 1.90 T=0.02 s (603.6 files/s, 44449.2 lines/s)
-------------------------------------------------------------------------------
Language files blank comment code
-------------------------------------------------------------------------------
TypeScript 11 79 4 727
-------------------------------------------------------------------
Not too bad...
It's too crusty to be published – but if you're interested drop me a line.