Database
Drivers, migrations, seeding, and the query builder
Drivers
There are three drivers: sqlite, postgres(pg is an accepted alias) and turso. Anything else throwsUnknown database driver when the connection is opened. Configure the one you want in basicben.config.js, or leave driver out and it is read from the URL: postgres:// is Postgres,libsql:// (or a TURSO_URL) is Turso, and anything else is a SQLite file.
The default. Uses Node's built-in node:sqlite, so there is nothing to install — but it needs Node 24 or newer.
Uses pg, an optional dependency. Run npm install pgif it is not already present.
Talks to Turso over HTTP with fetch, so there is nothing to install and it runs on serverless hosts. Reads TURSO_URL andTURSO_AUTH_TOKEN.
export default {
db: {
driver: 'sqlite',
url: './database.sqlite'
}
}export default {
db: {
driver: 'postgres',
url: process.env.DATABASE_URL,
poolSize: 10 // optional, defaults to 10
}
}The connection string is taken from db.url, thenprocess.env.DATABASE_URL, then ./database.sqlite. Leavingdb out of the config entirely gives you a local SQLite file, which is why a new project works before you have configured anything.
The connection is a single cached instance for the life of the process. The first call opens it; every later call reuses it.
Hosted Databases
Turso has its own driver. For the rest, what works is decided by wire protocol, not by branding.
Neon speaks the Postgres wire protocol, so usedriver: 'postgres' with the connection string Neon gives you. Setting driver: 'neon' throws.
Same as Neon: driver: 'postgres' and their connection string.
driver: 'turso', or set TURSO_URL and the driver is picked for you. The token comes from TURSO_AUTH_TOKEN or theauthToken option. Transactions work; each holds its stream for its duration.
PlanetScale is MySQL. There is no MySQL driver, and MySQL is not a goal.
export default {
db: {
driver: 'postgres',
url: process.env.DATABASE_URL
}
}Migrations
A migration is a file in db/migrations/ that exports up anddown. Both receive the database adapter and run raw SQL throughdb.exec(). There is no schema builder — you write the SQL your database understands.
npm run make:migration create_posts # Creates: db/migrations/<timestamp>_create_posts.js
export const up = async (db) => {
await db.exec(`
CREATE TABLE posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
title TEXT NOT NULL,
content TEXT,
published INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
)
`)
}
export const down = async (db) => {
await db.exec('DROP TABLE IF EXISTS posts')
}Files run in filename order, and each run is recorded in a _migrationstable along with a batch number. A rollback undoes the whole last batch in reverse order, so if one migrate applied five files, one rollback removes all five.
Each file runs in its own transaction, together with the row recording that it ran — both commit or neither does. A migration that creates two tables and throws between them used to leave the first one behind with nothing recorded, so the next migrate failed on table already exists and there was nothing to roll back. The database is now either before the migration or after it.
Some statements cannot run inside a transaction: Postgres refuses CREATE INDEX CONCURRENTLY and VACUUM, and SQLite ignores PRAGMA foreign_keys there — the table-rebuild pattern that turns constraints off needs it outside. A migration that needs one opts out with export const transaction = false, and then runs without the wrapper, in both directions. A migration that opens its own db.transaction() is fine without opting out: it joins the one already open rather than starting a second, which both drivers refuse.
export const transaction = false
export const up = (db) =>
db.exec('CREATE INDEX CONCURRENTLY IF NOT EXISTS posts_slug ON posts (slug)')
export const down = (db) =>
db.exec('DROP INDEX CONCURRENTLY IF EXISTS posts_slug')Nothing is undone if an opted-out migration fails halfway, so write it to be safe to run twice: IF NOT EXISTS and friends.
migrate, migrate:rollback and migrate:fresh hold a lock, so two replicas deploying at once cannot both apply a migration. The second waits for the first, up to 10 minutes, and then finds nothing left to do. On Postgres the lock is a session advisory lock, which the server releases if the process dies. On SQLite it is a row in a _migrations_lock table; a run that crashes leaves the row behind, the next run times out naming the holder, and npx basicben migrate:unlock clears it.
Postgres falls back to the lock row when an advisory lock would misbehave: with poolSize: 1, where the lock would hold the only connection, and behind what looks like a transaction-mode pooler (a Neon -pooler host, or port 6432 for PgBouncer), where the lock and the unlock can land on different server sessions. To choose outright, set migrationLock in basicben.config.js to 'auto' (the default), 'advisory', 'table', or false for no lock. Behind a pooler on any other address, set 'table'.
npm run migrateRun pending migrations
npm run migrate:rollbackUndo the last batch
npm run migrate:freshDrop every table and migrate again
npm run migrate:statusShow which files have run
npx basicben migrate:unlockClear a lock row left by a crashed run
The generated stub and the migrations that ship with a new project are written in SQLite dialect. If you are targeting Postgres, translate as you go:INTEGER PRIMARY KEY AUTOINCREMENT becomes SERIAL PRIMARY KEY orGENERATED ALWAYS AS IDENTITY, and DATETIME becomesTIMESTAMP. Nothing rewrites SQL for you.
Seeding
Seeds populate a database with starting data. Each file in db/seeds/exports a seed function (a default export also works), and files run in filename order, which is why they are usually numbered.
import { db } from '@basicbenframework/core/db'
import { hashPassword } from '@basicbenframework/core/auth'
import { ROLES } from '@basicbenframework/core/auth/permissions'
export async function seed() {
const password = await hashPassword('password123')
await (await db.table('users')).only('name', 'email', 'password', 'role').insert({
name: 'Admin User',
email: '[email protected]',
password,
role: ROLES.ADMIN
})
console.log('Seeded 1 user')
}Seed a password through hashPassword rather than writing a literal, and setrole explicitly. The column defaults to subscriber, and the migration that promotes the first account runs before any seeder, against an empty table — so a seeded user named “Admin User” without a role is a subscriber that cannot reach anything the admin area gates.
import { db } from '@basicbenframework/core/db'
export async function seed() {
const user = await (await db.table('users')).first()
await (await db.table('posts')).only('user_id', 'title', 'content', 'published').insert({
user_id: user.id,
title: 'Welcome to BasicBen',
content: 'Your first post.',
published: 1
})
}npm run seedRun every seed file
npx basicben seed 01_usersRun one file, named without the extension
npx basicben make:seed usersGenerate db/seeds/users.js
npx basicben db:seedAlias for seed
Seeds are not tracked the way migrations are, so running them twice runs them twice. Against a table with a unique constraint the second run fails, which is usually what you want to notice.
Query Builder
query(table) and db.table(table) both return a builder, and both are async because they open the connection first. That is where the double await in these examples comes from: the outer one waits for the query, the inner one waits for the builder.
import { db, query } from '@basicbenframework/core/db'
// Every row
const users = await (await query('users')).get()
// One row by id, or undefined
const user = await (await query('users')).find(1)
// Two arguments mean equals
const admins = await (await query('users'))
.where('is_admin', 1)
.get()
// Three arguments take an operator
const recent = await (await query('posts'))
.where('published', 1)
.where('id', '>', 100)
.orderBy('created_at', 'DESC')
.limit(10)
.get()
// first() adds LIMIT 1 and returns the row itself
const latest = await (await query('posts'))
.orderBy('created_at', 'DESC')
.first()
// db.table() is the same builder under a different name
const drafts = await (await db.table('posts')).where('published', 0).get()// IN and NOT IN take an array. An empty IN list matches nothing;
// an empty NOT IN list matches everything.
const some = await (await query('users')).whereIn('id', [1, 2, 3]).get()
const rest = await (await query('users')).whereNotIn('role', ['admin']).get()
// orWhere joins with OR. AND binds tighter, as in SQL:
// where(a).orWhere(b).where(c) is a OR (b AND c)
const flagged = await (await query('posts'))
.where('published', 0)
.orWhere('title', 'LIKE', '%draft%')
.get()
// A callback adds a parenthesised group
const visible = await (await query('posts'))
.where('user_id', userId)
.where(q => q.where('published', 1).orWhereNull('deleted_at'))
.get()
// ... WHERE user_id = ? AND (published = ? OR deleted_at IS NULL)
// A literal null compares with IS NULL / IS NOT NULL
await (await query('users')).where('reset_token', null).get() // IS NULL
await (await query('users')).where('reset_token', '!=', null).get() // IS NOT NULLOnly a literal null means IS NULL. Any other comparison with null, such as '<', throws. An undefined value in where, orWhere, a group, or a whereIn list throws an error with code: 'UNDEFINED_VALUE': it is almost always a missing input, and where('reset_token', req.query.token) with no token must not match every row that has no token.
const posts = await (await query('posts'))
.select('posts.*', 'users.name as author')
.join('users', 'users.id', '=', 'posts.user_id')
.where('posts.published', 1)
.orderBy('posts.created_at', 'DESC')
.limit(5)
.get()
// The operator may be left out, and a table may be aliased
await (await query('posts'))
.select('posts.title', 'u.name as author')
.leftJoin('users as u', 'u.id', 'posts.user_id')
.get()Columns can be qualified (posts.title, posts.*) and aliased with as. update() and delete() refuse a builder that has a join, because the dialects disagree on the syntax.
import { query, escapeLike } from '@basicbenframework/core/db'
// Matches 'Hello', 'HELLO' and 'hello' on every driver
const hits = await (await query('posts'))
.where('title', 'LIKE', `%${escapeLike(req.query.q)}%`)
.get()LIKE and NOT LIKE ignore case on every dialect, the same way: the builder emits LOWER(col) LIKE LOWER(?) ESCAPE '\'. SQLite folds ASCII letters only. escapeLike() escapes %, _ and backslash, so user input matches literally instead of as a pattern. The LOWER() call means a plain index on the column is not used; on a large table, search with an index on the lowered column or with raw SQL.
// Every insert and update names the columns it may write
const result = await (await query('posts'))
.only('user_id', 'title', 'content')
.insert({
user_id: 1,
title: 'My Post',
content: 'Hello world'
})
result.lastInsertRowid // id of the new row
result.changes // 1
await (await query('posts'))
.only('title')
.where('id', postId)
.update({ title: 'Updated Title' })
await (await query('posts'))
.where('id', postId)
.delete()On Postgres, insert() appends RETURNING id solastInsertRowid is filled in there too. A hand-writtenINSERT without that clause returns null instead, which is a good reason to insert through the builder.
A key whose value is undefined is left out of an insert or update rather than written as NULL. An update no longer clears a column because an input was missing, and an insert gets the column’s default. Pass null to write NULL. An update whose only values are undefined throws No valid columns to update.
const total = await (await query('posts'))
.where('published', 1)
.count()
const taken = await (await query('users'))
.where('email', '[email protected]')
.exists()
const page = await (await query('posts'))
.orderBy('created_at', 'DESC')
.paginate(1, 15)
// { data, total, page, perPage, totalPages }The full method list is short by design.
select(...cols)Columns to return; defaults to *. Qualify and alias with as
join / leftJoin(table, a, op, b)INNER or LEFT JOIN; op defaults to =
where(col, val)Equality shorthand; a null value is IS NULL
where(col, op, val)=, !=, <>, <, >, <=, >=, LIKE, NOT LIKE, IN, NOT IN
where(q => ...)A parenthesised group
orWhere(...)Same arguments as where(), joined with OR
whereIn / whereNotIn(col, arr)IN and NOT IN
orWhereIn(col, arr)IN, joined with OR
whereNull / whereNotNull(col)IS NULL and IS NOT NULL
orWhereNull / orWhereNotNull(col)The same, joined with OR
orderBy(col, dir)ASC or DESC
limit(n) / offset(n)Slice the result
get() / first()All rows, or the first one
find(id)Shorthand for where('id', id).first()
insert(data)Returns { lastInsertRowid, changes }
update(data) / delete()Return { lastInsertRowid, changes }
count() / exists()A number, and whether it is above zero
paginate(page, perPage)Rows plus the totals to render a pager
only(...) / except(...) / unguarded()Mass assignment rules, below
toSql()The SELECT this builder would run
Multiple where calls are joined with AND, and orWhere calls with OR. Table and column names, including each part of a qualified name, are validated against [a-zA-Z_][a-zA-Z0-9_]* and quoted, and every value goes in as a bound parameter, so user input cannot become SQL.
Booleans on SQLite
node:sqlite refuses to bind JavaScript booleans. Passingtrue or false as a value throwsProvided value cannot be bound to SQLite parameter, whether it came from an insert or a where clause. Store flags as integers and convert at the edge.
// Throws on SQLite
await (await query('posts')).only('title', 'published').insert({ title: 'Draft', published: false })
await (await query('posts')).where('published', true).get()
// Works
await (await query('posts')).only('title', 'published').insert({ title: 'Draft', published: 0 })
await (await query('posts')).where('published', 1).get()
// Convert where the value arrives, not everywhere it is used
await (await query('posts')).only('title', 'published').insert({
title: req.body.title,
published: req.body.published ? 1 : 0
})Mass Assignment Protection
Since 0.9, every insert() and update() must say which columns it may write. A chain that calls neither only() nor unguarded() throws an error with code: 'MASS_ASSIGNMENT' before anything reaches the database. Raw db.run() is not affected.
only() lists the columns a write may touch — the model’s fillable list. Keys outside it are dropped silently rather than raising, so a request body with extra fields still succeeds, minus the fields it should not have set.
await (await query('users'))
.only('name', 'email', 'bio')
.insert(req.body)
// Given { name: 'Bob', email: '[email protected]', is_admin: 1 }
// the row is written without is_admin
// Neither only() nor unguarded(): throws MASS_ASSIGNMENT
await (await query('users')).insert(req.body)except() narrows a write further: its columns are dropped even when only() lists them. On its own it no longer permits a write. It also replaces the default guard, which is id, so name id again when you list other columns.
const FILLABLE = ['name', 'email', 'bio', 'role']
// Users may edit their own profile, but not their role
await (await query('users'))
.only(...FILLABLE)
.except('id', 'role')
.where('id', userId)
.update(req.body)unguarded() writes every key it is given, except guarded ones — the 0.8 behaviour, said out loud. Use it for rows your own code built, never for a request body.
await (await query('audit_log')).unguarded().insert({
user_id: user.id,
action: 'login',
created_at: new Date().toISOString()
})id stays guarded by default either way: it is dropped even if only() lists it, unless an except() call replaces the guard. Prefer only(). A whitelist stays correct when someone adds a column later; a blacklist quietly stops covering everything.
What the Builder Does Not Do
The list above is all of it. There is no groupBy, no having, no distinct, no right or full join, no whereBetween, and no aggregate beyond count(). An update or delete cannot use a join. This is deliberate: a builder that covers every query ends up as large as the SQL it hides. When you need more, write SQL.
import { db } from '@basicbenframework/core/db'
const counts = await db.all(
`SELECT users.name, COUNT(posts.id) AS post_count
FROM users
JOIN posts ON posts.user_id = users.id
WHERE posts.published = ?
GROUP BY users.id, users.name
ORDER BY post_count DESC`,
[1]
)Pass values separately as parameters, never by interpolating them into the SQL.
Raw Queries
The adapter is available directly for anything the builder does not cover.
import { db } from '@basicbenframework/core/db'
// Many rows
const posts = await db.all(
'SELECT * FROM posts WHERE user_id = ? AND published = ?',
[userId, 1]
)
// One row, or undefined
const user = await db.get('SELECT * FROM users WHERE email = ?', [email])
// Writes: { lastInsertRowid, changes }
const result = await db.run(
'INSERT INTO posts (title, user_id) VALUES (?, ?)',
[title, userId]
)
// Statements with no parameters, such as DDL
await db.exec('CREATE INDEX idx_posts_user ON posts (user_id)')Raw SQL reaches the driver exactly as written, so the placeholder style is yours to get right: ? on SQLite, $1, $2 on Postgres. The builder handles that difference for you, which is one more reason to use it for ordinary queries and save raw SQL for the queries that need it.
Transactions
db.transaction() wraps the callback in BEGIN andCOMMIT, rolls back if it throws, and returns whatever the callback returns. The callback receives a transaction-scoped adapter, and its result is awaited before the commit, so async work inside is safe.
const remaining = await db.transaction(async (tx) => {
await tx.run(
'UPDATE accounts SET balance = balance - ? WHERE id = ?',
[100, fromId]
)
await tx.run(
'UPDATE accounts SET balance = balance + ? WHERE id = ?',
[100, toId]
)
const row = await tx.get('SELECT balance FROM accounts WHERE id = ?', [fromId])
return row.balance
})Use tx inside the callback rather than db. On Postgres the transaction holds one pooled client, and a statement sent through dbtakes a different connection — it would commit on its own and survive the rollback. The tx object exposes run, get,all and exec; the query builder does not accept it, so transactional work is written in SQL.
Models
A model here is a plain object that groups the queries for one table. There is no base class to extend, no active record, no relations, and no lazy loading — a model has exactly the methods you write.
npx basicben make:model Post scaffolds one with afillable list and all, find,create, update and destroy built on the query builder. Check the import at the top of anything you generate: it should read@basicbenframework/core/db. Older scaffolds import from'basicben', which is not a published package and will not resolve.
import { getDb, query } from '@basicbenframework/core/db'
// Columns update() may write. Without this, passing req.body straight
// through would let a caller set any column at all.
const UPDATABLE = ['title', 'content', 'published']
export const Post = {
async find(id) {
const db = await getDb()
return db.get('SELECT * FROM posts WHERE id = ?', [id])
},
// The join lives on the model rather than being reassembled at
// every call site.
async findPublished() {
return (await query('posts'))
.select('posts.*', 'users.name as author_name')
.join('users', 'users.id', 'posts.user_id')
.where('posts.published', 1)
.orderBy('posts.created_at', 'DESC')
.get()
},
async create(data) {
// Through the builder so Postgres gets RETURNING id and the new
// id comes back.
const posts = await query('posts')
const result = await posts.only('user_id', 'title', 'content', 'published').insert({
user_id: data.user_id,
title: data.title,
content: data.content,
published: data.published ? 1 : 0
})
return { id: result.lastInsertRowid, ...data }
},
async update(id, data) {
const fields = Object.keys(data).filter(k => UPDATABLE.includes(k))
if (fields.length === 0) return this.find(id)
return (await query('posts'))
.only(...UPDATABLE)
.where('id', id)
.update(data)
}
}Controllers then call Post.create(...) instead of assembling queries themselves, which keeps the column list in one file.
Validating Against the Database
Two validation rules query the database. Both are async, so thevalidate call must be awaited like any other.
import { validate, rules } from '@basicbenframework/core/validation'
const result = await validate(req.body, {
// No other row in users has this email
email: [rules.required, rules.email, rules.unique('users')],
// Check a named column instead of the field name
slug: [rules.unique('categories', 'slug')],
// The referenced row must exist
user_id: [rules.required, rules.exists('users')]
})// Without the third argument, a user saving their profile without
// changing their email would collide with themselves.
email: [rules.required, rules.email, rules.unique('users', 'email', currentUserId)]