Skip to content

A SQLite database

Goal: a table, a migration that creates it, and handlers that read and write it, with no server to run in development. This is what Nitro's useDatabase and NuxtHub's database give a Nuxt app.

  1. Add the package and the module:
sh
bun add @hamur/db
hamur db new create_notes
hamur db migrate
hamur db status
ts
import { defineConfig } from "hamur"
import db from "@hamur/db"

export default defineConfig({
  framework: "react",
  modules: [db],
  db: { migrate: "start" },
})

With no db.connections.default, the module gives you the database of the preset: bun-sqlite at .data/db.sqlite on bun, static and under hamur dev, node-sqlite on node, and a D1 binding named DB on cloudflare. db.migrate: "start" applies the pending files before the server listens.

  1. Write the table in the file hamur db new create_notes made in server/db/migrations/. A migration is plain SQL, applied once, in number order:
sql
create table notes (
  id integer primary key,
  body text not null,
  created_at text not null default (datetime('now'))
);
  1. Keep the queries in functions that take the Database. Every ${value} in a tagged query is a bound parameter, so there is nothing to escape:
ts
import type { Database } from "@hamur/db"
import { createError } from "hamur/server"

export interface Note {
  id: number
  body: string
  created_at: string
}

export const addNote = (db: Database, body: string) =>
  db.first<Note>`insert into notes (body) values (${body}) returning *`

export const listNotes = (db: Database) => db.sql<Note>`select * from notes order by id desc`

export async function removeNote(db: Database, id: number): Promise<void> {
  const { changes } = await db.run`delete from notes where id = ${id}`
  if (changes === 0) throw createError({ status: 404, message: "Note not found" })
}
  1. Call them from handlers with useDatabase(). A query is awaitable, so a handler can return it:
ts
import { useDatabase } from "@hamur/db/server"
import { defineHandler, type StandardSchemaV1 } from "hamur/server"
import { addNote, listNotes, removeNote } from "./database-notes.ts"

const bodyInput: StandardSchemaV1<unknown, { body: string }> = {
  "~standard": {
    version: 1,
    vendor: "docs",
    validate(value) {
      const body = (value as { body?: unknown } | undefined)?.body
      return typeof body === "string" && body.trim()
        ? { value: { body: body.trim() } }
        : { issues: [{ message: "Write something", path: ["body"] }] }
    },
  },
}

export const notes = defineHandler({
  route: "/api/notes",
  method: "GET",
  handler: () => listNotes(useDatabase()),
})

export const createNote = defineHandler({
  route: "/api/notes",
  method: "POST",
  input: bodyInput,
  handler: ({ body }: { body: string }) => addNote(useDatabase(), body),
})

export const deleteNote = defineHandler({
  route: "/api/notes/:id",
  method: "DELETE",
  async handler({ id }: { id: string }) {
    await removeNote(useDatabase(), Number(id))
    return { ok: true }
  },
})

On vercel and netlify the build fails until you give default a connection, because their file systems do not keep files. For Postgres or MySQL from bun use the bun-sql connector with url: env("DATABASE_URL"); for any other driver, a client file.

See also: Database, @hamur/db reference, Deploy to Cloudflare.