@buntok/orm
v0.1.0
Published
TypeScript ORM for Bun - SQLite, PostgreSQL, and MySQL with migrations and Studio GUI
Maintainers
Readme
Buntok ORM
Type-safe ORM for Bun with SQLite, PostgreSQL, and MySQL support, migration system, and Studio GUI.
Why Buntok ORM?
- Type safety - autocomplete for table names, columns, where operators, and orderBy
- Prisma-like DX - familiar if you've used Prisma before
- Multi database - one codebase works across PostgreSQL, SQLite, and MySQL
- Migration system - generate SQL from schema, automatic tracking
- Studio GUI - view, insert, edit, delete data visually from your browser
Prerequisites
- Bun v1.0 or newer
- One of: PostgreSQL, SQLite, or MySQL
Installation
bun add @buntok/ormThen install the database driver you need:
# PostgreSQL
bun add pg && bun add -D @types/pg
# MySQL
bun add mysql2
# SQLite - nothing to install (built-in)Quick Start
1. Initialize
bunx buntok initPick your provider when prompted, and you'll get:
your-project/
buntok/
schema.ts ← table definitions
buntok.config.ts ← configuration
.env ← DATABASE_URL2. Define Tables
Edit buntok/schema.ts:
import { table, col } from "@buntok/orm";
export const users = table("users", {
id: col.serial().primaryKey(),
name: col.varchar(100).notNull(),
email: col.varchar(200).notNull().unique(),
role: col.enum("Role", ["ADMIN", "USER"] as const).default("USER"),
age: col.integer(),
active: col.boolean().default(true),
createdAt: col.timestamp().notNull().default("now()"),
});
export const posts = table("posts", {
id: col.serial().primaryKey(),
title: col.varchar(200).notNull(),
content: col.text(),
published: col.boolean().default(false),
authorId: col.integer().notNull().references(users, "id", "cascade"),
createdAt: col.timestamp().notNull().default("now()"),
});3. Generate Migration
buntok generate4. Run Migration
buntok migrate5. Open Studio
buntok studioOpen http://localhost:3434 in your browser to view and manage data visually.
Typed Database (Prisma-like DX)
Pass schema to createDb() for full type safety - autocomplete on table names, columns, where operators, and orderBy:
import { createDb } from "@buntok/orm";
import { users, posts } from "./buntok/schema";
const db = await createDb({
provider: "sqlite",
databaseUrl: "./dev.db",
schema: { users, posts }, // ← pass schema for type safety
});
// Full autocomplete: db.users, db.posts, db.tx_items, ...
// Full autocomplete on where: { name: "Alice", age: { gte: 18 } }
// Full autocomplete on orderBy: { name: "asc", createdAt: "desc" }
const adults = await db.users.findMany({
where: { age: { gte: 18 } },
orderBy: { name: "asc" },
select: { id: true, name: true }, // ← return type: { id: number, name: string }[]
});Typed Select (Return Type Projection)
When select is used, the return type only contains the selected columns:
// Without select → full type
const users = await db.users.findMany();
// { id: number, name: string, email: string, age: number | null, ... }[]
// With select → projected type
const users = await db.users.findMany({ select: { id: true, name: true } });
// { id: number, name: string }[]
// findFirst also supports it
const user = await db.users.findFirst({ select: { email: true } });
// { email: string } | nullTyped Where (Enum Literal Support)
Use as const on enums so the type is a literal union, not just string:
const items = table("items", {
id: col.serial().primaryKey(),
role: col.enum("Role", ["ADMIN", "USER"] as const).notNull(),
status: col.enum("Status", ["ACTIVE", "INACTIVE"] as const),
});
const db = await createDb({ schema: { items } });
// Autocomplete only accepts "ADMIN" | "USER"
await db.items.findMany({ where: { role: "ADMIN" } }); // ✅
await db.items.findMany({ where: { role: "SUPER_ADMIN" } }); // ❌ TypeScript errorRepository Pattern
Use the Repository class for a more structured approach:
import { Repository, type BuntokAdapter } from "@buntok/orm";
import { users } from "./buntok/schema";
import { db } from "./config/db";
class UserRepository extends Repository<typeof users> {
constructor() {
super(db, users);
}
async findByEmail(email: string) {
return this.findFirst({ email });
}
async findActiveAdmins() {
return this.findMany({
where: { role: "ADMIN", active: true },
orderBy: { name: "asc" },
select: { id: true, name: true },
});
}
}
const userRepo = new UserRepository();
const admin = await userRepo.findByEmail("[email protected]");Transactions
db.transaction() runs all operations in a single transaction. Auto-commits on success, auto-rollbacks on error. Nested transactions are supported via savepoints.
// Simple transaction
await db.transaction(async (tx) => {
await tx.users.create({
data: { name: "Alice", email: "[email protected]" },
});
await tx.posts.create({ data: { title: "Hello", authorId: 1 } });
});
// Nested transactions (savepoints)
await db.transaction(async (outer) => {
await outer.users.create({ data: { name: "Alice" } });
await outer.transaction(async (inner) => {
await inner.users.create({ data: { name: "Bob" } });
throw new Error("Inner fails");
}); // Inner rolls back to savepoint
// Alice still exists, Bob is rolled back
});
// Outer commits AliceColumns
Data Types
| Method | PostgreSQL | SQLite | MySQL | TS Type |
| ----------------------------- | ------------------ | ------------ | --------------- | ------------------------------- |
| col.serial() | SERIAL | INTEGER | INT | number |
| col.integer() | INTEGER | INTEGER | INT | number |
| col.float() | REAL | REAL | FLOAT | number |
| col.double() | DOUBLE PRECISION | REAL | DOUBLE | number |
| col.decimal(10, 2) | NUMERIC(10,2) | TEXT | DECIMAL(10,2) | string |
| col.bigint() | BIGINT | INTEGER | BIGINT | bigint |
| col.varchar(100) | VARCHAR(100) | TEXT | VARCHAR(100) | string |
| col.text() | TEXT | TEXT | TEXT | string |
| col.boolean() | BOOLEAN | INTEGER | TINYINT(1) | boolean |
| col.timestamp() | TIMESTAMP | TEXT | DATETIME | string |
| col.date() | DATE | TEXT | DATE | string |
| col.json() | JSONB | TEXT | JSON | any |
| col.uuid() | UUID | TEXT | CHAR(36) | string |
| col.cuid() | TEXT | TEXT | VARCHAR(255) | string |
| col.ulid() | TEXT | TEXT | VARCHAR(26) | string |
| col.enum("Name", ["A","B"]) | CREATE TYPE | TEXT CHECK | ENUM(...) | literal union (with as const) |
Why does
col.decimal()returnstring? To avoid floating point precision issues. Same as Prisma Decimal. Convert to number manually if needed.
Enum Columns
// Without as const → type is string
role: col.enum("Role", ["ADMIN", "USER"]);
// With as const → type is literal union
role: col.enum("Role", ["ADMIN", "USER"] as const);
// TS type: "ADMIN" | "USER" | nullModifiers
All columns are nullable by default. Use modifiers to change behavior:
col.text().notNull(); // required
col.text().nullable(); // nullable (default)
col.text().unique(); // unique constraint
col.text().default("abc"); // default value
col.text().primaryKey(); // primary keyPrimary Key
col.serial().primaryKey(); // auto-increment (most common)
col.uuid().primaryKey(); // UUID v4, auto-generated
col.cuid().primaryKey(); // CUID, auto-generated
col.ulid().primaryKey(); // ULID, auto-generatedForeign Key
// Type-safe - direct reference to Table object
col.integer().references(users, "id", "cascade");
// onDelete: "cascade" | "restrict" | "set null"Default Values
col.timestamp().default("now()"); // current timestamp
col.uuid().default("gen_random_uuid()"); // UUID
col.text().default("draft"); // string literal
col.integer().default(0); // number
col.boolean().default(true); // boolean
col.enum("Role", ["USER"] as const).default("USER"); // enum defaultType Inference
import type { InferSelectModel, InferInsertModel } from "@buntok/orm";
// Type for SELECT (all columns present)
type User = InferSelectModel<typeof users>;
// { id: number; name: string; email: string; role: string | null; ... }
// Type for INSERT (columns with defaults become optional)
type NewUser = InferInsertModel<typeof users>;
// { name: string; email: string; role?: string | null; age?: number | null; ... }Query API
findMany
await db.users.findMany(); // all rows
await db.users.findMany({ where: { age: { gte: 18 } } }); // with filter
await db.users.findMany({ orderBy: { name: "asc" } }); // sorting
await db.users.findMany({ select: { id: true, name: true } }); // select specific columns
await db.users.findMany({ take: 10, skip: 20 }); // paginationfindFirst
await db.users.findFirst({ where: { email: "[email protected]" } });
await db.users.findFirst({ select: { id: true, name: true } });findUnique
await db.users.findUnique({ where: { id: 1 } });
await db.users.findUnique({ where: { id: 1 }, select: { id: true, name: true } });findUniqueOrThrow / findFirstOrThrow
Same as findUnique/findFirst, but throws an error if no record is found instead of returning null.
const user = await db.users.findUniqueOrThrow({ where: { id: 1 } });
// throws Error if not found
const admin = await db.users.findFirstOrThrow({
where: { role: "ADMIN" },
});create / createMany
await db.users.create({ data: { name: "Alice", email: "[email protected]" } });
await db.users.createMany({
data: [
{ name: "Bob", email: "[email protected]" },
{ name: "Charlie", email: "[email protected]" },
],
});update / updateMany
await db.users.update({ where: { id: 1 }, data: { name: "Alice Updated" } });
await db.users.updateMany({ where: { active: true }, data: { role: "ADMIN" } });delete / deleteMany
await db.users.delete({ where: { id: 1 } });
await db.users.deleteMany({ where: { active: false } });count / exists
const total = await db.users.count();
const hasAdmins = await db.users.exists({ where: { role: "ADMIN" } });upsert
Insert a row, or update it if it already exists (based on conflict columns — primary key by default).
// PostgreSQL / SQLite: INSERT ... ON CONFLICT DO UPDATE
// MySQL: INSERT ... ON DUPLICATE KEY UPDATE
const user = await db.users.upsert({
where: { email: "[email protected]" },
create: { name: "Alice", email: "[email protected]", role: "USER" },
update: { name: "Alice Updated" },
});groupBy
Group rows by columns and apply aggregate functions.
const results = await db.posts.groupBy({
by: ["authorId"],
where: { published: true },
_count: true,
_avg: { /* no numeric columns in posts example */ },
orderBy: { authorId: "asc" },
});
// [{ authorId: 1, _count: 5 }, { authorId: 2, _count: 3 }, ...]Supported aggregates: _count, _sum, _avg, _min, _max. Use _count: true for COUNT(*), or _count: { columnName: true } for COUNT(column).
aggregate
Run aggregate queries without grouping.
const stats = await db.orders.aggregate({
where: { status: "completed" },
_count: true,
_sum: { total: true },
_avg: { total: true },
_min: { total: true },
_max: { total: true },
});
// { _count: 42, _sum_total: "15000.00", _avg_total: "357.14", _min_total: "10.00", _max_total: "999.99" }Where Operators
// Basic
{ name: "Alice" } // equals
{ name: { equals: "Alice" } } // equals (explicit)
{ name: { not: "Bob" } } // not equals
// Comparison
{ age: { gt: 18 } } // greater than
{ age: { gte: 18 } } // greater than or equal
{ age: { lt: 65 } } // less than
{ age: { lte: 65 } } // less than or equal
// Array
{ role: { in: ["ADMIN", "USER"] } } // in list
{ role: { notIn: ["BANNED"] } } // not in list
// String (only for string columns)
{ name: { contains: "Ali" } } // LIKE '%Ali%'
{ name: { startsWith: "A" } } // LIKE 'A%'
{ name: { endsWith: "e" } } // LIKE '%e'
// Logical
{ OR: [{ role: "ADMIN" }, { age: { lt: 20 } }] }
{ AND: [{ active: true }, { role: "USER" }] }
{ NOT: [{ name: "Banned" }] }SQL Injection Safety
Buntok ORM is designed with security in mind:
- Prepared statements - all values use parameterized queries (
$1,$2for PostgreSQL;?for MySQL/SQLite) - Identifier escaping - table and column names are properly escaped by doubling internal quote characters (
"→"",`→``) - LIKE wildcard escaping -
%and_characters are automatically escaped incontains,startsWith,endsWith, and Studio search - Studio API - field names from request bodies are validated against the schema (whitelist), CORS restricted to localhost, path traversal protection on static files
Note:
db.raw()accepts raw SQL. Use it carefully and always use parameterized queries when dealing with user input.
CLI Commands
| Command | Description |
| ----------------------- | ---------------------------------------------- |
| buntok init | Initialize a new project |
| buntok generate | Generate SQL migration file from schema |
| buntok migrate | Run pending migrations |
| buntok migrate status | View migration status |
| buntok migrate reset | Reset all migrations |
| buntok db:push | Push schema directly to DB (no migration file) |
| buntok studio | Open Studio GUI |
Configuration
// buntok.config.ts
import type { BuntokConfig } from "@buntok/orm";
const config: BuntokConfig = {
provider: "postgresql", // "postgresql" | "sqlite" | "mysql"
schema: "./buntok/schema.ts",
out: "./buntok",
databaseUrl: "postgresql://...", // optional, defaults to DATABASE_URL env
};
export default config;Connection String
# PostgreSQL
DATABASE_URL="postgresql://user:password@localhost:5432/mydb"
# SQLite
DATABASE_URL="file:./buntok/dev.db"
# MySQL
DATABASE_URL="mysql://user:password@localhost:3306/mydb"Migration System
Workflow
schema.ts → buntok generate → buntok/migrations/*.sql → buntok migrate → database- Edit
schema.ts buntok generate- create.sqlfile- Review the generated
.sqlfile buntok migrate- run against database
Folder Structure
buntok/
snapshot.json ← last schema snapshot
migrations/
2026-07-30T13-34-33-993Z_migration.sql
2026-07-31T10-00-00-000Z_migration.sqlTracking
Every time migrate runs, the .sql filename is recorded in the _buntok_migrations table. Already-run migrations won't be executed again.
Reset
buntok migrate resetDeletes all tables + _buntok_migrations + snapshot. Start fresh.
Studio GUI
buntok studioOpen http://localhost:3434 in your browser.
Features
- View all tables and their data
- Insert, edit, delete rows from the GUI
- Search with autocomplete
- Foreign key dropdowns (shows all columns from referenced table)
- Date/timestamp input with datetime picker
- Auto-generate primary key on insert
- Enum columns with dropdowns
REST API
Studio also provides a REST API if you need to access data from code:
| Endpoint | Method | Description |
| ------------------------------- | ------ | --------------------------------------------- |
| /api/schema | GET | Get all table definitions |
| /api/tables/:name/rows | GET | List data (pagination: ?page=1&pageSize=50) |
| /api/tables/:name/rows | POST | Insert new row |
| /api/tables/:name/rows/:id | PATCH | Update row |
| /api/tables/:name/rows/:id | DELETE | Delete row |
| /api/tables/:name/rows/search | GET | Search (?q=keyword&column=name&limit=20) |
Full Example
Schema with All Features
import { table, col } from "@buntok/orm";
export const users = table("users", {
id: col.serial().primaryKey(),
name: col.varchar(100).notNull(),
email: col.varchar(200).notNull().unique(),
role: col.enum("Role", ["ADMIN", "USER"] as const).default("USER"),
age: col.integer(),
salary: col.decimal(12, 2),
bio: col.text().nullable(),
active: col.boolean().default(true),
createdAt: col.timestamp().notNull().default("now()"),
});
export const posts = table("posts", {
id: col.serial().primaryKey(),
title: col.varchar(200).notNull(),
content: col.text().notNull(),
published: col.boolean().notNull().default(false),
authorId: col.integer().notNull().references(users, "id", "cascade"),
createdAt: col.timestamp().notNull().default("now()"),
});Typed Database Usage
import { createDb } from "@buntok/orm";
import { users, posts } from "./buntok/schema";
const db = await createDb({
provider: "sqlite",
databaseUrl: "./dev.db",
schema: { users, posts },
});
// Prisma-like queries with full type safety
const admin = await db.users.findFirst({
where: { role: "ADMIN" },
select: { id: true, name: true },
});
// Upsert
const user = await db.users.upsert({
where: { email: "[email protected]" },
create: { name: "Alice", email: "[email protected]" },
update: { name: "Alice Updated" },
});
// Or throw if not found
const bob = await db.users.findFirstOrThrow({ where: { name: "Bob" } });
// Aggregates
const stats = await db.posts.aggregate({
where: { published: true },
_count: true,
});
// Group by
const byAuthor = await db.posts.groupBy({
by: ["authorId"],
_count: true,
});
// Transactions
await db.transaction(async (tx) => {
const user = await tx.users.create({
data: { name: "Alice", email: "[email protected]", role: "ADMIN" },
});
await tx.posts.create({
data: { title: "Hello World", content: "My first post", authorId: user.id },
});
});
await db.destroy();Repository Pattern
import { Repository } from "@buntok/orm";
import { db } from "./config/db";
import { users } from "./buntok/schema";
class UserRepository extends Repository<typeof users> {
constructor() {
super(db, users);
}
async findByEmail(email: string) {
return this.findFirst({ email });
}
async findActiveAdmins() {
return this.findMany({
where: { role: "ADMIN", active: true },
orderBy: { name: "asc" },
select: { id: true, name: true },
});
}
async findOrCreate(email: string, name: string) {
return this.upsert({
where: { email },
create: { email, name },
update: { name },
});
}
}
const userRepo = new UserRepository();
const admin = await userRepo.findByEmail("[email protected]");
const bob = await userRepo.findByIdOrThrow(2); // throws if not foundFAQ
Q: What's the difference between generate and migrate?
generate creates SQL files from your schema. migrate runs those SQL files against the database. generate doesn't need a database connection.
Q: What's the difference between migrate and db:push?
migrate creates a migration file and records it in the tracking table. db:push pushes directly to the database without a file or tracking. Use db:push for quick development, migrate for production.
Q: How do I add a new column?
Edit schema.ts, add the column you want, then run buntok generate && buntok migrate.
Q: Can I switch providers?
Yes, change provider in buntok.config.ts and update DATABASE_URL in .env. But the generated DDL will differ between providers.
Q: How do I completely reset the database?
buntok migrate reset drops all tables, tracking, and snapshots. Then buntok migrate to rebuild from scratch.
Q: Why does col.decimal() return string?
To avoid floating point precision issues. Same as Prisma Decimal. Convert to number manually if needed.
Q: How do nested transactions work?
They use savepoints. Each transaction() inside another transaction creates a savepoint. If the inner transaction rolls back, only the inner one rolls back - the outer can still commit.
Q: How does upsert work across databases?
PostgreSQL and SQLite use ON CONFLICT ... DO UPDATE SET ... = EXCLUDED.*. MySQL uses ON DUPLICATE KEY UPDATE ... = VALUES(*). The conflict column defaults to the primary key.
Q: What aggregates are supported in groupBy and aggregate?
_count (boolean or per-column), _sum, _avg, _min, _max (per-column). All return typed results.
Q: What's the difference between findFirstOrThrow and findFirst?
findFirst returns null when no record matches. findFirstOrThrow throws an Error instead. Same for findUniqueOrThrow.
Tech Stack
- Bun - runtime
- TypeScript - strict mode
- PostgreSQL / SQLite / MySQL - database drivers
- React + Vite + Tailwind - Studio UI
License
MIT
