日本語

How to Read and Write SQLite with bun:sqlite in Bun

​​Bun​SQLite,TypeScript

Bun includes a SQLite driver built in. You can use it by just importing from bun:sqlite. There is no need to install a package from npm.

It fits cases where you want a single-file local database: storing CLI tool settings or history, a data store for a small web app, or test data. This article covers the basic pattern for creating a table and reading and writing it, the pitfalls that are easy to hit (forgotten parameters, transactions and async, type conversion), and the time it took to write 10,000 rows, all confirmed with actual output.

Note

The test environment was Ubuntu 24.04 (x86_64) with Bun 1.4.4. The SQLite bundled with Bun was 3.53.4. I wrote the code in TypeScript and ran it with bun filename.ts. I did not test concurrent writes from multiple processes, loading extensions (loadExtension), combining with an ORM, or Windows and macOS. For the official documentation, I checked the source files at the tag used for testing (bun-v1.4.4) on GitHub, and the links point there.

Create a Table, then Insert, Query, Update, and Delete

With the following basic.ts, I created a table that stores cat names and ages and ran through the basic operations.

ts
import { Database } from "bun:sqlite";

// The file is created if it does not exist
const db = new Database("cats.sqlite");

db.run(`CREATE TABLE IF NOT EXISTS cats (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL UNIQUE,
  age INTEGER
)`);

// Insert: pass values to $name and $age
const insert = db.query("INSERT INTO cats (name, age) VALUES ($name, $age)");
console.log(insert.run({ $name: "たま", $age: 3 }));
console.log(insert.run({ $name: "みけ", $age: 5 }));
console.log(insert.run({ $name: "くろ", $age: 1 }));

// Fetch one row
const byName = db.query("SELECT * FROM cats WHERE name = ?");
console.log(byName.get("みけ"));
console.log(byName.get("しろ"));

// Fetch all rows
console.log(db.query("SELECT * FROM cats WHERE age >= ? ORDER BY age").all(2));

// Fetch as an array of arrays
console.log(db.query("SELECT name, age FROM cats ORDER BY id").values());

// Update and delete also use run(), which returns the number of changed rows
console.log(db.query("UPDATE cats SET age = age + 1").run());
console.log(db.query("DELETE FROM cats WHERE name = ?").run("くろ"));

console.log(db.query("SELECT sqlite_version() AS version").get());
db.close();

new Database("cats.sqlite") creates the file if it does not exist. After running the script, cats.sqlite was created. If you want to use the database only in memory, write new Database(":memory:") (official documentation on how to open a database).

All APIs are synchronous, so you don't need await. You compile SQL with db.query() and run it with the methods on the returned Statement. Each method returns a different shape of result.

Method Returns
run() The number of changed rows (changes) and the ID of the last inserted row (lastInsertRowid)
get() The first row as an object. null if there are no rows
all() All rows as an array of objects
values() All rows as an array of arrays

When I ran it, the output was as follows (I added blank lines between outputs for readability).

text
{
  changes: 1,
  lastInsertRowid: 1,
}
{
  changes: 1,
  lastInsertRowid: 2,
}
{
  changes: 1,
  lastInsertRowid: 3,
}

{
  id: 2,
  name: "みけ",
  age: 5,
}
null

[
  {
    id: 1,
    name: "たま",
    age: 3,
  }, {
    id: 2,
    name: "みけ",
    age: 5,
  }
]

[
  [ "たま", 3 ], [ "みけ", 5 ], [ "くろ", 1 ]
]

{
  changes: 3,
  lastInsertRowid: 3,
}
{
  changes: 1,
  lastInsertRowid: 3,
}

{
  version: "3.53.4",
}

For the INSERT run() calls, lastInsertRowid held the id of the inserted row. Calling get() with a name that does not exist (shiro) returned null. The UPDATE affected every row, so changes was 3. The DELETE removed one row, so changes was 1. For UPDATE and DELETE, lastInsertRowid stayed at 3, the ID of the last INSERTed row.

db.query() reuses a prepared Statement when the SQL string is the same. What is reused is only the compiled SQL, not the query results. Values are passed on each execution, so as with byName above, you can run one Statement many times with different values (official documentation on query() caching).

A Forgotten Parameter Becomes NULL by Default

When putting values into SQL, don't concatenate strings. Use ? or $name parameters instead. A $name value can be passed with a $ in the key, as in { $name: "たま" }, or without it, as in { name: "たま" } (official documentation on named parameter keys).

The point to watch is when you forget to pass a parameter value. By default, no error is raised and NULL is inserted (official documentation on strict mode). The following params.ts compares the case of typing $age as $agee with and without strict.

ts
import { Database } from "bun:sqlite";

for (const strict of [false, true]) {
  const db = new Database(":memory:", { strict });
  db.run("CREATE TABLE cats (name TEXT, age INTEGER)");
  const insert = db.query("INSERT INTO cats (name, age) VALUES ($name, $age)");
  console.log(`--- strict: ${strict}`);
  try {
    // Written without the $ prefix
    insert.run({ name: "たま", age: 3 });
    // Forgot age (mistyped as agee)
    insert.run({ $name: "みけ", $agee: 5 });
  } catch (e) {
    console.log(`${(e as Error).name}: ${(e as Error).message}`);
  }
  console.log(db.query("SELECT * FROM cats").all());
}
text
--- strict: false
[
  {
    name: "たま",
    age: 3,
  }, {
    name: "みけ",
    age: null,
  }
]
--- strict: true
Error: Missing parameter "age"
[
  {
    name: "たま",
    age: 3,
  }
]

Without strict, the mistyped row was inserted silently, with age set to null. With strict: true, it raised Missing parameter "age", and that row was not inserted. In new code, passing new Database("cats.sqlite", { strict: true }) lets you catch typos right away.

Group Multiple Writes in a Transaction

Passing a function to db.transaction() returns a function that runs it inside a transaction. If an exception occurs inside, the writes made up to that point are rolled back (official documentation on transactions). In the following tx.ts, I inserted a duplicate name as the third item into a table with a UNIQUE constraint on name.

ts
import { Database } from "bun:sqlite";

const db = new Database(":memory:");
db.run("CREATE TABLE cats (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE)");
const insert = db.query("INSERT INTO cats (name) VALUES (?)");

const insertCats = db.transaction((names: string[]) => {
  for (const name of names) insert.run(name);
  return names.length;
});

console.log(`追加: ${insertCats(["たま", "みけ"])}件`);

try {
  // "tama" already exists, so the third insert violates the UNIQUE constraint
  insertCats(["くろ", "しろ", "たま"]);
} catch (e) {
  console.log(`${(e as Error).name}: ${(e as Error).message}`);
}
console.log(db.query("SELECT name FROM cats ORDER BY id").values());

// Doing the same thing without a transaction leaves the rows inserted before the failure
try {
  for (const name of ["くろ", "しろ", "たま"]) insert.run(name);
} catch (e) {
  console.log(`${(e as Error).name}: ${(e as Error).message}`);
}
console.log(db.query("SELECT name FROM cats ORDER BY id").values());
text
追加: 2件
SQLiteError: UNIQUE constraint failed: cats.name
[
  [ "たま" ], [ "みけ" ]
]
SQLiteError: UNIQUE constraint failed: cats.name
[
  [ "たま" ], [ "みけ" ], [ "くろ" ], [ "しろ" ]
]

When the transaction failed, the rows for kuro and shiro that had been inserted first were also rolled back, leaving just the 2 original rows. Without a transaction, the run() calls kept the 2 rows inserted before the failure.

Writing 10,000 Rows: Grouping in a Transaction Cut the Time from 8 Seconds to 7.6 ms

Grouping writes in a transaction also changes the speed a lot. I wrote bench.ts, which inserts 10,000 rows into a file-based database, and measured the time with performance.now(), both for calling run() once per row and for the same work grouped in a transaction. I changed the journal settings in three ways and ran each setup three times.

ts
measure("1行ずつ", (db) => {
  const insert = db.query("INSERT INTO logs (message, at) VALUES (?, ?)");
  for (let i = 0; i < N; i++) insert.run(`message ${i}`, i);
});

measure("transaction でまとめる", (db) => {
  const insert = db.query("INSERT INTO logs (message, at) VALUES (?, ?)");
  const insertAll = db.transaction(() => {
    for (let i = 0; i < N; i++) insert.run(`message ${i}`, i);
  });
  insertAll();
});
Setting One row at a time (3 runs) Transaction (3 runs)
Default (journal_mode=delete, synchronous=2) 8,113.5 / 7,810.7 / 8,184.0 ms 7.6 / 8.5 / 6.0 ms
WAL 1,213.2 / 1,284.9 / 1,466.2 ms 5.5 / 7.0 / 8.2 ms
WAL + synchronous=NORMAL 113.2 / 119.8 / 98.9 ms 4.5 / 6.9 / 4.3 ms
Horizontal bar chart of the time taken to insert 10,000 rows. With the default settings (journal_mode=delete, synchronous=2), one row at a time took 8,113.5 ms and the transaction took 7.6 ms. With WAL, 1,284.9 ms and 7.0 ms. With WAL and synchronous=NORMAL, 113.2 ms and 4.5 ms. The labels in the image are in Japanese.
Time taken to insert 10,000 rows (median of 3 runs for each setting)

With the default settings, inserting one row at a time took around 8 seconds, while grouping in a transaction took less than 10 milliseconds. Comparing the medians, the difference is about 1,000 times. With WAL, one row at a time dropped to 1.2 to 1.5 seconds, and with synchronous = NORMAL it dropped to around 0.1 seconds. Even so, grouping in a transaction was still faster in every case. These numbers are from the disk on the test VM.

Don't Pass an async Function to a Transaction

The function passed to a transaction must be synchronous. According to the official documentation, an async function returns at its first await, and the transaction is committed at that point. Code after that runs outside the transaction, so an exception there will not roll back the writes (official documentation on functions passed to transactions). I checked this with the following tx-async.ts.

ts
import { Database } from "bun:sqlite";

const db = new Database(":memory:");
db.run("CREATE TABLE cats (name TEXT)");
const insert = db.query("INSERT INTO cats (name) VALUES (?)");

const insertAsync = db.transaction(async (names: string[]) => {
  insert.run(names[0]);
  await Promise.resolve(); // The function returns here and the transaction is committed
  insert.run(names[1]);
  throw new Error("2件目のあとで失敗");
});

try {
  await insertAsync(["たま", "みけ"]);
} catch (e) {
  console.log(`${(e as Error).name}: ${(e as Error).message}`);
}
console.log(`inTransaction: ${db.inTransaction}`);
console.log(db.query("SELECT name FROM cats").values());
text
Error: 2件目のあとで失敗
inTransaction: false
[
  [ "たま" ], [ "みけ" ]
]

The exception reached the caller, but both rows remained. When saving data fetched from an API, for example, finish the work that needs await first, then pass the collected values to a synchronous transaction function.

With WAL, Two Extra Files Exist While the Database Is Open

The official documentation recommends WAL mode for most apps. Adding PRAGMA synchronous = NORMAL makes the WAL file sync to disk at checkpoints instead of at every commit. The trade-off is that a power loss may lose the last few commits, but the database is not corrupted (official documentation on WAL mode).

With WAL, -wal and -shm files are created next to the database file. The following files.ts compares the directory while the database is open and after close(). It also tries the option to open read-only and the option to not create the file when it is missing.

ts
import { Database } from "bun:sqlite";
import { mkdirSync, readdirSync, rmSync } from "node:fs";

rmSync("memo", { recursive: true, force: true });
mkdirSync("memo");
const db = new Database("memo/app.sqlite");
console.log(db.query("PRAGMA journal_mode = WAL;").get());
db.run("CREATE TABLE notes (body TEXT)");
db.run("INSERT INTO notes VALUES ('hello')");
console.log("開いている間:", readdirSync("memo"));
db.close();
console.log("close() のあと:", readdirSync("memo"));

try {
  new Database("memo/nothing.sqlite", { create: false });
} catch (e) {
  console.log(`${(e as Error).name}: ${(e as Error).message}`);
}
const ro = new Database("memo/app.sqlite", { readonly: true });
try {
  ro.run("INSERT INTO notes VALUES ('x')");
} catch (e) {
  console.log(`${(e as Error).name}: ${(e as Error).message}`);
}
console.log(ro.query("SELECT * FROM notes").all());
text
{
  journal_mode: "wal",
}
開いている間: [ "app.sqlite", "app.sqlite-shm", "app.sqlite-wal" ]
close() のあと: [ "app.sqlite" ]
SQLiteError: unable to open database file
SQLiteError: attempt to write a readonly database
[
  {
    body: "hello",
  }
]

On the test environment (Ubuntu), the -wal and -shm files disappeared after close(), leaving only app.sqlite. According to the official documentation, Bun on macOS uses the SQLite provided by Apple, so these two files remain even after close(). The explanation of cleaning up WAL files also describes how to remove them.

With { create: false }, opening a missing file did not create it and instead raised unable to open database file. Writing to a database opened with { readonly: true } raised attempt to write a readonly database, while reading still worked.

Warning

Do not back up a WAL database by copying only the .sqlite file while it is still open. In the test environment, I copied the file right after writing 3 rows, while it was still open. The copy did not contain the notes table at all, and opening it raised no such table: notes. The copy made after close() contained all 3 rows.

Type Conversion Between JavaScript Values and SQLite Types

I also checked the types of values passed in and read out with the following types.ts.

ts
import { Database } from "bun:sqlite";

const db = new Database(":memory:");
db.run("CREATE TABLE t (b, blob, big, d)");
db.query("INSERT INTO t VALUES (?, ?, ?, ?)").run(
  true,
  new Uint8Array([1, 2, 3]),
  2n ** 53n + 1n,
  new Date("2026-11-14T00:00:00Z").toISOString(),
);
console.log(db.query("SELECT b, typeof(b) AS b_type, blob, big, d FROM t").get());

const safe = new Database(":memory:", { safeIntegers: true });
console.log(safe.query("SELECT ? AS big").get(2n ** 53n + 1n));

try {
  db.query("SELECT ?").get(new Date() as any);
} catch (e) {
  console.log(`${(e as Error).name}: ${(e as Error).message}`);
}
text
{
  b: 1,
  b_type: "integer",
  blob: Uint8Array(3) [ 1, 2, 3 ],
  big: 9007199254740992,
  d: "2026-11-14T00:00:00.000Z",
}
{
  big: 9007199254740993n,
}
TypeError: Binding expected string, TypedArray, boolean, number, bigint or null

The output shows the following:

  • true was stored as the integer 1, and reading it back did not return true.
  • A Date cannot be passed as is and raised a TypeError. Convert it to an ISO-format string first, as shown above.
  • Integers above 2^53 are returned as number by default, so 9007199254740993 changed to 9007199254740992. With safeIntegers: true, they are returned as bigint and the value was preserved.

The correspondence between the types you can pass and SQLite types is summarized in the official type conversion table. For how integers are handled, see the section on integers. When reading large integer IDs, use safeIntegers so they are not rounded.

​Posted by 86