sqlite-zod-orm · The Plain Web Stack · diadem.fun
The Plain Web Stack4 / 15

sqlite-zod-orm

Source: https://github.com/7flash/sqlite-zod-orm · bun add sqlite-zod-orm

One schema language#

import { Database, z } from "sqlite-zod-orm";
export const db = new Database("data/app.db", {
  users: z.object({ email: z.string(), passwordHash: z.string() }),
  notes: z.object({ text: z.string().max(4000), userId: z.number() }),
}, {
  relations: { notes: { userId: "users" } },
  cascade: { users: ["notes"] },
  timestamps: true,
  softDeletes: true,
});

The tables are created from these schemas and migrated when they change. Columns are added, and renamed with the renames option. Changes that would lose or resurrect data are refused at startup with an explanation.

Typed reads, exact writes#

You write You get
db.notes.select().where({ userId, text: { $like: "%milk%" } }).orderBy("id", "desc").paginate(1, 20) typed rows, a total count and the number of pages
db.users.select().with("notes").all() each user with a typed notes array, loaded in one batched query
db.notes.insert({ text, userId }) the stored row, with id, createdAt and updatedAt
note.text = "new" the change written to the database; the entity shows what was stored
db.notes.update({ done: true }).where({ userId }).exec() the exact number of rows changed
db.users.delete(id) a soft delete that cascades to notes; restore(id) brings both back

Hooks that respect transactions#

beforeInsert, beforeUpdate and beforeDelete run inside the write and can refuse it. After-hooks run once the outermost transaction commits, and never for rolled-back work. So an email sent from afterInsert is never sent for a row that does not exist.

Live changes across processes#

db.notes.on("insert", (note) => notify(note.userId));

Triggers log every write to a small journal, which keeps the last 10,000 changes. Every connection and every process on the same file sees every change, in order. Next: chapter 5, logging.