Factories and seeding
A factory makes rows for one table, with believable fake values. Use one to fill a development database, or to make a few rows of a known shape. The values come from a seeded generator, so two runs make the same rows.
Factories are part of @hamur/db. The samples use the todos table of that page.
Write a factory
A factory is a file in server/db/factories/, named after the table. Its default export is defineFactory. The function you give it makes one row. It gets n, which counts from 1, and fake, the generator:
import { defineFactory } from "@hamur/db/server"
export default defineFactory<"todos">((_n, fake) => ({
title: fake.sentence(),
done: fake.bool(0.3) ? 1 : 0,
}))
Write the table name as the type argument, defineFactory<"todos">. Then the compiler checks each row against Insert<"todos">: a column that is not in the table, or a required column you forgot, is a type error. Without it the row is checked against every table at once, so a mistake can slip through.
- A factory for another connection goes in
server/db/factories/<connection>/<table>.ts, as migrations do. - The build reads the app's folder and each layer's. When both have a file for one table, the app's wins.
- The build reads
.ts,.mts,.jsand.mjsfiles, except those that end in.d.ts,.test.<ext>or.spec.<ext>and names that start with_or.. Use_helpers.tsfor code the factories share.
The build checks the folder and fails with HAMUR_E5525 when it finds a mistake: a file for a table that the migrations do not create, a folder that is not a connection, or two files for one table. The message names the file, and offers the nearest table:
server/db/factories/todo.ts: db "default" has no table "todo" (did you mean "todos"?)
Make rows
factory(table) gives the two things a factory does:
import { factory } from "@hamur/db/server"
export async function examples() {
const todos = factory("todos")
const drafts = todos.make(3)
const rows = await todos.create(5, { done: 1 })
const numbered = await todos.create(2, (n) => ({ title: `Task ${n}` }))
return { drafts, rows, numbered }
}
make(count?, overrides?)returnscountrows (default 1) and touches no database.create(count?, overrides?)inserts the rows and returns them as the database stored them, so you get the ids and the defaults it filled. All rows go in onebatch: if one fails, none stays.overridesis an object that replaces keys in every row, or a function ofnthat gives the keys for one row.- A key whose value is
undefinedis left out of theINSERT, so the column's default applies. A row with no keys at all insertsDEFAULT VALUES.
n counts per factory(table) value, across make and create: the first row is 1, the next 2. Keep the value in a variable to carry on counting. A second call of factory("todos") starts again at 1 and makes the same rows as the first. That is what a seed is for, but it also means two factory("users").create(3) calls in a row insert the same three emails.
On Postgres and SQLite create uses RETURNING *. MySQL has none, so it reads the rows back by the column id, from the row's own id or from lastInsertId. A MySQL table without an id column, or a row that has no id of its own, fails with factory("users").create: row 1 has no id to select it by; give it an id.
Other errors say what to change:
| Mistake | Error |
|---|---|
factory("users") with no file | No factory for "users" in db "default"; write server/db/factories/users.ts |
the file does not export defineFactory(...) | server/db/factories/users.ts must export default defineFactory(...) |
count that is not a whole number from 0 | factory("users") count must be an integer from 0 |
| a key that is not a column name | factory("users"): "a"b" is not a column name |
For a table of another connection, pass it: factory("events", { connection: "analytics" }).
What fake gives
| Method | Gives |
|---|---|
name(), firstName(), lastName() | a name |
email(n?) | <word><n>@example.com; without n, <word>@example.com |
word(), words(k) | a word, or k words |
sentence(), paragraph() | a sentence, or 3 to 6 sentences |
slug(), url() | three words joined by -; an https://example.com/ URL |
int(min, max) | a whole number, both ends included |
float(min, max) | a number from min up to, not including, max |
bool(p?) | true with probability p, 0.5 when you leave it out |
pick(list) | one item of a list |
date({ from, to }) | a Date between two dates; each end is a Date, a string or milliseconds |
uuid() | a version 4 UUID |
The words are English. Only email(n) is made unique by a number you give it. For another unique column, put n in it: `${fake.slug()}-${n}`.
The seed is the environment variable HAMUR_FAKE_SEED, a whole number, 1 when it is not set. Another value makes other rows, the same on every run. A value that is not a whole number fails: HAMUR_FAKE_SEED must be an integer (got "abc"). Each factory has its own stream, made from the seed, the connection and the table, so adding a factory or running them in another order does not change the rows of the others.
The word lists are in a server bundle only when its code imports factory. A production server that never calls it carries none.
Seed a database
Seeding is a task. Write server/tasks/db/seed.ts and call your factories in it:
import { defineTask } from "hamur/server"
import { factory, useDatabase } from "@hamur/db/server"
export default defineTask({
description: "Fill an empty dev database with sample todos",
async run() {
const existing = await useDatabase().first<{ n: number }>`select count(*) as n from todos`
if (existing && existing.n > 0) return { seeded: 0 }
const todos = await factory("todos").create(25)
return { seeded: todos.length }
},
})
Run it by name:
hamur db migrate
hamur task run db:seed
# {"seeded":25}
hamur task run db:seed
# {"seeded":0}
The seed is the same every time, so a second run would insert the same rows again, and fail on a column that must be unique. Make the task safe to run twice, as the sample does by checking for rows first.
To seed the development database each time hamur dev starts, list the task in tasks.runOnStart of the $development block. A start task runs after the server's plugins, which apply the pending migrations in development, so the tables exist (Database). The block keeps it out of hamur build:
import { defineConfig } from "hamur"
export default defineConfig({
framework: "react",
$development: { tasks: { runOnStart: ["db:seed"] } },
})
There is no hamur db seed command: hamur task run db:seed is the one way, and the task is the same one a schedule or runTask("db:seed") calls.
The signatures are in the @hamur/db API reference.