Created
September 28, 2025 17:28
-
-
Save kbsali/a19b362997bf38cbbfb3ea4b4f9ede9b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import db from "./SQLITE-DB-FILE-PATH.db" with { type: "sqlite" }; | |
| const sqliteToTsType: Record<string, string> = { | |
| // numeric | |
| INT: "number", | |
| INTEGER: "number", | |
| TINYINT: "number", | |
| SMALLINT: "number", | |
| MEDIUMINT: "number", | |
| BIGINT: "number", | |
| "UNSIGNED BIG INT": "number", | |
| INT2: "number", | |
| INT8: "number", | |
| // real | |
| REAL: "number", | |
| DOUBLE: "number", | |
| "DOUBLE PRECISION": "number", | |
| FLOAT: "number", | |
| NUMERIC: "number", | |
| DECIMAL: "number", | |
| // text | |
| TEXT: "string", | |
| CHARACTER: "string", | |
| VARCHAR: "string", | |
| "VARYING CHARACTER": "string", | |
| NCHAR: "string", | |
| "NATIVE CHARACTER": "string", | |
| NVARCHAR: "string", | |
| CLOB: "string", | |
| // date/time | |
| DATE: "string", | |
| DATETIME: "string", | |
| // blob | |
| BLOB: "Buffer", | |
| // null | |
| NULL: "null", | |
| }; | |
| export function mapSqliteTypeToTs(type: string): string { | |
| const normalized = type.trim().toUpperCase(); | |
| for (const key in sqliteToTsType) { | |
| if (normalized.includes(key)) { | |
| return sqliteToTsType[key] ?? "any"; | |
| } | |
| } | |
| return "any"; | |
| } | |
| const generateSqliteTableDefinitions = async () => { | |
| const tables = await db | |
| .query("select name from sqlite_master where type='table'") | |
| .all(); | |
| const types = await Promise.all( | |
| tables.map(async (table) => { | |
| const columns = await db | |
| .query(`pragma table_info('${table.name}')`) | |
| .all(); | |
| const cols = columns | |
| .map((column) => ` ${column.name}: ${mapSqliteTypeToTs(column.type)};`) | |
| .join("\n"); | |
| return [`export type ${table.name}_table = {`, cols, "}"].join("\n"); | |
| }) | |
| ); | |
| await Bun.write("types.ts", types.join("\n")); | |
| console.log("Done!"); | |
| }; | |
| generateSqliteTableDefinitions(); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Generate your typescript sqlite database types with Bun
$ bun sqlite-to-types.ts Done!Original script by @BrianDouglasIE : https://briandouglas.ie/generate-sqlite-table-types-bun/