Vasili's Blog

bun

So, I've gotten to a point where the generator is able to produce a schema typescript file that is compatible with my current database.

The code can be found here.

It currently runs on Bun, but can be trivially adapted for Node (w/ better-sqlite3).

It will likely require additional changes to handle other cases my schema might end up with, but for now I'll be enjoying type-safe queries that would break the build if the schema changes.

#codegen #ast #bun #sqlite #schema #typesafe

Started working on a type-safe schema generator based off the sqlite schema.

I'm pulling out the database schema using #bun's native sqlite driver with a simple query:

SELECT
   tbl_name,
   name,
   type,
   sql
 FROM
   sqlite_schema
 WHERE
   1=1
   AND type = 'table'
   AND sql IS NOT NULL
   AND name != 'sqlite_sequence'

Then aggregating all the SQL statements, passing them through sql-parser-cst, walking the AST collecting tables, columns, primary keys, etc...

Then passing it through ts-morph to emit typescript source code with all the types. Could potentially scan queries, and try to derive parameter types based on schema, that would be pretty sweet.

In plans:

  • Nominally-typed ID's, with Brand types. No more accidentally passing UserId into a ProductId.
  • Could leverage runtypes to produce contracts...

Maybe even create contracts and derive types from that instead... Not a bad idea...

Will post a gist once done.

#codegen #bun #sqlite #schema #typesafe