惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

MongoDB | Blog
MongoDB | Blog
罗磊的独立博客
美团技术团队
B
Blog
量子位
The Cloudflare Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
aimingoo的专栏
aimingoo的专栏
The GitHub Blog
The GitHub Blog
博客园 - 聂微东
P
Proofpoint News Feed
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
D
DataBreaches.Net
博客园 - 三生石上(FineUI控件)
Y
Y Combinator Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Vercel News
Vercel News
Blog — PlanetScale
Blog — PlanetScale
云风的 BLOG
云风的 BLOG
Microsoft Azure Blog
Microsoft Azure Blog
有赞技术团队
有赞技术团队
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
阮一峰的网络日志
阮一峰的网络日志
S
SegmentFault 最新的问题

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
# I built a type-safe SQL library for Bun — no ORM, no co...
phonemyatt · 2026-05-22 · via DEV Community

phonemyatt

I've been using Bun for a while and kept running into the same problem: every SQL library either requires Node.js internals, leans heavily on an ORM abstraction I don't want, or generates types from a schema file at build time.

So I built squn — a lightweight, type-safe SQL query library that works natively with Bun's built-in database clients.

The core idea

Every query goes through a tagged template literal called sql. Interpolated values always become bound parameters — they are never concatenated into the SQL string. SQL injection is structurally impossible by design.

import { createDb, PostgresAdapter, sql } from "@phonemyatt/squn";

const db = createDb(new PostgresAdapter({
  url: "postgresql://user:password@localhost:5432/mydb",
}));

interface User {
  id: number;
  name: string;
  age: number | null;
}

// Values become $1, $2 parameters — never string-concatenated
const users = await db.query<User>(sql`SELECT * FROM users WHERE age > ${18}`);

Enter fullscreen mode Exit fullscreen mode

No schema file. No code generation step. No build-time magic. You write SQL, get back typed results.

Four databases, one API

squn supports all four databases you're likely to use with Bun:

Database Driver
SQLite bun:sqlite (built-in)
PostgreSQL Bun's native Postgres
MySQL Bun's native MySQL
MSSQL mssql npm package

The same query code works across all four — only the adapter construction changes.

// Switch databases by swapping the adapter
const db = createDb(new SqliteAdapter({ filename: ":memory:" }));
const db = createDb(new PostgresAdapter({ url: process.env.PG_URL }));
const db = createDb(new MysqlAdapter({ url: process.env.MYSQL_URL }));
const db = createDb(new MssqlAdapter({ host: "localhost", ... }));

Enter fullscreen mode Exit fullscreen mode

Query methods that match what you actually need

// All rows
const users = await db.query<User>(sql`SELECT * FROM users`);

// First row or null — no throw
const user = await db.queryFirst<User>(sql`SELECT * FROM users WHERE id = ${1}`);

// Exactly one row — throws if 0 or 2+ rows returned
const user = await db.querySingle<User>(sql`SELECT * FROM users WHERE id = ${1}`);

// Scalar — first column of first row
const count = await db.queryScalar<number>(sql`SELECT COUNT(*) FROM users`);

Enter fullscreen mode Exit fullscreen mode

Composable SQL fragments

Fragments compose. Nested fragments merge inline and placeholders are renumbered automatically.

const minAge = 18;
const activeOnly = true;

const conditions = [
  sqlIf(minAge !== undefined, sql`age >= ${minAge}`),
  sqlIf(activeOnly, sql`active = ${true}`),
];

const where = sqlJoin(conditions, " AND ");
const q = sql`SELECT * FROM users WHERE ${where} ORDER BY name`;
// → SELECT * FROM users WHERE age >= $1 AND active = $2 ORDER BY name
// params → [18, true]

Enter fullscreen mode Exit fullscreen mode

No string concatenation. No injection risk. Full composability.

Transactions that don't leak

atomically wraps your callback in BEGIN/COMMIT and rolls back automatically on error:

await db.atomically(async (q) => {
  await q.execute(sql`UPDATE accounts SET balance = balance - ${100} WHERE id = ${from}`);
  await q.execute(sql`UPDATE accounts SET balance = balance + ${100} WHERE id = ${to}`);
  // if either throws, both updates are rolled back
});

Enter fullscreen mode Exit fullscreen mode

Transaction also implements Symbol.asyncDispose — so await using gives you guaranteed cleanup:

await using tx = new Transaction(await adapter.beginTransaction());
await tx.execute(sql`UPDATE users SET active = ${false} WHERE id = ${42}`);
await tx.commit();
// if commit throws or you return early, rollback happens automatically

Enter fullscreen mode Exit fullscreen mode

Batch inserts with a single prepared statement

await db.executeBatch(
  sql`INSERT INTO users (name, age) VALUES (@name, @age)`,
  [
    { name: "Alice", age: 30 },
    { name: "Bob",   age: 25 },
    { name: "Carol", age: 35 },
  ],
);

Enter fullscreen mode Exit fullscreen mode

One prepared statement, all rows bound in a loop. Much faster than individual inserts.

Type inference from table definitions

Define your table schema once, get insert/select/update types inferred automatically:

import { col, defineTable, InferSelect, InferInsert } from "@phonemyatt/squn";

const Users = defineTable({
  id:   col("integer").primaryKey().notNull(),
  name: col("text").notNull(),
  age:  col("integer").nullable(),
});

type UserRow    = InferSelect<typeof Users>;  // { id: number; name: string; age: number | null }
type UserInsert = InferInsert<typeof Users>;  // { name: string; age?: number | null }

Enter fullscreen mode Exit fullscreen mode

Multi-connection and read replicas

const db = createConnections({
  connections: {
    primary: new PostgresAdapter({ url: process.env.PRIMARY }),
    replica: new PostgresAdapter({ url: process.env.REPLICA }),
  },
  default: "primary",
});

// Route reads to replica
const users = await db.query<User>(sql`SELECT * FROM users`, { connection: "replica" });

// Scoped helper — no connection option needed per call
const replica = db.use("replica");

// Typed concurrent queries
const [users, roles] = await db.concurrent(
  db.query<User>(sql`SELECT * FROM users`),
  db.query<Role>(sql`SELECT * FROM roles`),
);

Enter fullscreen mode Exit fullscreen mode

Try it

bun add @phonemyatt/squn

Enter fullscreen mode Exit fullscreen mode

Feedback welcome — especially from anyone using it with MySQL or MSSQL in production.


Built with TypeScript 5.9 strict mode, zero any, and tested against real databases in Docker.