DatabaseSeeding & Factories

IX · Database

Seeding & Factories

On this page

Introduction

A factory knows how to make a believable row of one table: every required column with a value. Tests use factories to create the rows they need, and mail previews to build sample data. A seeder fills a database with the rows a developer wants to find, such as an account to sign in with, and uses factories to make them.

modules/auth/factories/UserFactory.ts
import { defineFactory } from '@marmeon/database';

export const FACTORY_PASSWORD_HASH = '$argon2id$v=19$m=1024,t=1,p=1$4Xhubcoo37TNJTsjeD4YIg$tLK1IR1zuYLJNCVRYJaBxiXR+EuI6aAXP5Wt1Ha2xlQ';

export const UserFactory = defineFactory(
  'users',
  ({ sequence, now }) => {
    const verified = now().toISOString();
    return {
      name: `User ${sequence}`,
      email: `user${sequence}@example.com`,
      password: FACTORY_PASSWORD_HASH,
      email_verified_at: verified,
      first_verified_at: verified,
    };
  },
  { states: { unverified: { email_verified_at: null, first_verified_at: null } } },
);

factory(UserFactory).count(3).create() inserts three users and returns them as stored. This is the starter kit's factory, and marmeon migrate:fresh --seed runs its seeder.

Defining factories

defineFactory(table, definition, { states }) takes the table, a function that returns one row's values, and named states. The values are typed against the table's insert type. A new NOT NULL column without a default therefore makes every factory that misses it a compile error, and you find them all at once.

marmeon make:factory Note --module=notes writes the file into factories/ (--table names the table when it is not the plural of the name) and registers nothing: a factory is imported where it is used. The definition it writes is empty, and the compiler lists the columns it still has to set.

The definition gets a context:

  • sequence counts the rows this factory has made in this app: 1, 2, 3 and on. Use it for values that must be unique, such as an address. Each app counts on its own, so two test apps never share a counter.
  • now() is the app's time, a new Date on each call. It is the time app.travel() moves, and the one that stamps created_at of a row the factory creates, so a date a definition sets (now().toISOString()) follows the same clock. See time.
  • factory(Other) stands for a row of another table. Put it where a foreign key goes, and the related row is created first:
modules/notes/factories/NoteFactory.ts
import { defineFactory } from '@marmeon/database';
import { UserFactory } from '#modules/auth';

export const NoteFactory = defineFactory(
  'notes',
  ({ sequence, factory }) => ({
    user_id: factory(UserFactory),
    title: `Note ${sequence}`,
    slug: `note-${sequence}`,
    body: 'A note to read later.',
  }),
  { states: { shared: { shared: true }, published: ({ now }) => ({ published_at: now().toISOString() }) } },
);

A state is a set of values that replaces the definition's, or a function of the context that returns them. A state as a function gets a fresh value each time, such as the current time from now().

A column that oneOf() holds to a list is typed as the union of its values, and a value from the list in a definition, a state or an override needs no as const: { role: 'admin' } stays 'admin'. A value outside the list is a compile error. A value built elsewhere (a const, Array.from(…), a string parameter) is a string; type it as Row<'memberships'>['role']. Moving a value from one oneOf() column into another whose list is shorter needs Kysely's $castTo<'admin' | 'member'>() (the target column's union) at that expression: the compiler cannot see the where that makes it true, and the check constraint still refuses a wrong value.

Deriving a column from the row

A column's value can be a function of the row. It runs after the definition, the states and the overrides are merged and every other column is worked out, so it sees what the call sets, and a column the call names replaces the function, which then does not run:

modules/events/factories/ResourceFactory.ts
import { defineFactory } from '@marmeon/database';
import { EventFactory } from './EventFactory.ts';
import { ResourceGroupFactory } from './ResourceGroupFactory.ts';

export const ResourceFactory = defineFactory('resources', ({ sequence, factory }) => ({
  event_id: factory(EventFactory),
  resource_group_id: (row) => factory(ResourceGroupFactory).state({ event_id: row.event_id }),
  name: `Resource ${sequence}`,
}));

factory(ResourceFactory).create() makes one event, and the resource and its group both lie in it. create({ event_id }) makes no event, and the group lies in the one you name. count(3) gives each row an event of its own.

  • row holds the other columns' values with their types. In create() a related column is already the created row's id; in make() it is still the factory, so row.event_id is number | PendingFactory and the same code compiles for both. A column the table does not have is a compile error.
  • Several derived columns run in the order of the definition. A derived column can read every column that is not derived, and the derived columns before it. Reading one that comes later, or itself, throws an error that names both columns. It throws before the row is inserted, but the related rows of the plain columns (event_id: factory(EventFactory)) may exist by then.
  • A secret column may be set by a factory, but is not in row: the type refuses a read, so a derived value cannot copy it into a column that is not secret. create() also throws, naming the derived and the secret column, when a function reads one anyway, and refuses a derived column on a connection that does not know the schema, such as an infrastructure connection; make() checks the type only.
  • A derived column returns a value or a factory, never a function or a promise: it is synchronous. A state may hold a derived column too.

Password hashes

Hashing a password is slow on purpose, and count(50) would hash fifty times. So the starter kit's factory stores one hash, made once with the low costs of .env.test, and every factory user signs in with the password password. A seeder hashes with the app's configured costs instead, as the next section shows. The hashing page explains the costs.

Using factories

A factory is used through factory(Definition), which a seeder gets in its context and a test from its app.

Behind factory is the Factories service of @marmeon/database, which the container builds like any other: a class that is not a seeder takes it in its constructor, or asks make(Factories), and factories.for(Definition) is the same call as factory(Definition). A mail preview does exactly that.

CallEffect
.create(overrides?)Inserts one row and returns it as stored, with its id and defaults. Secret columns, such as password, are not in it.
.make(overrides?)Returns the values without inserting anything. A related factory is not created either: its column keeps the factory itself, not an id, and its type says so (number | PendingFactory) unless an override sets the column.
.count(n)n rows instead of one: create() and make() return a list.
.state('shared')Applies a named state. Several states apply in the order you call them.
.state({ title: 'Draft' })Applies values directly.
.using(trx)Inserts through this connection or transaction.

Overrides apply last, after the states:

const ada = await factory(UserFactory).create({ name: 'Ada Lovelace', email: 'ada@example.com' });
const notes = await factory(NoteFactory).count(3).state('shared').create({ user_id: ada.id });

Every factory(Other) of a definition creates a row of its own, so a factory with two foreign keys makes two parent rows. When the keys have to agree, as a resource's event_id and the event of its resource_group_id, derive one from the other, as above, or create the shared parent once and pass every column that points to it:

const event = await factory(EventFactory).create();
const group = await factory(ResourceGroupFactory).create({ event_id: event.id });
const resource = await factory(ResourceFactory).create({ event_id: event.id, resource_group_id: group.id });

Without the derived column, ResourceFactory.create() would make an event for the resource and another for its group. A column an override sets creates no parent. Where a factory does not derive the columns, say in its JSDoc which a caller has to name together.

Each call returns a new pending factory, so you can keep one and use it twice. A state the definition does not have throws, with the states it knows. create() inserts the rows one after the other, each related row first.

Writing seeders

A seeder is a class with a handle() method. The container builds it, so its constructor gets what it needs. handle() receives factory and db, the default connection:

modules/auth/seeders/UserSeeder.ts
import { Hasher } from '@marmeon/auth';
import { environment } from '@marmeon/core';
import type { SeedContext } from '@marmeon/database';
import { UserFactory } from '../factories/UserFactory.ts';

export class UserSeeder {
  readonly #hasher: Hasher;

  constructor(hasher: Hasher) {
    this.#hasher = hasher;
  }

  async handle({ factory }: SeedContext) {
    // A known password: never where the app is protected, whatever `--force` says.
    if (environment.isProtected()) throw new Error('UserSeeder runs only in development and tests (NODE_ENV=development or test).');
    await factory(UserFactory).create({ name: 'Test User', email: 'test@example.com', password: await this.#hasher.make('password') });
  }
}

What a seeder returns from handle() is dropped. To tell the person running marmeon db:seed or migrate:fresh --seed what it made, write to output in the context:

async handle({ factory, output }: SeedContext) {
  const notes = await factory(NoteFactory).count(5).create();
  output?.info(`Made ${notes.length} notes.`);
  output?.table(['Title'], notes.map((note) => [note.title]));
}

output has line(), info(), warn() and table(), like the console's Output. The lines appear at once, ahead of the Seeded … line the command writes when the seeder is done, so a seeder that fails afterwards still shows what it printed. It is optional: a test that builds the context by hand (handle({ factory, db })) has none, which is why you write output?.info(…). Under createTestApp({ seed: true }) it is silent.

The framework prints nothing from the context itself; only the seeder decides. Print a generated password or token only from a seeder that guards itself with environment.isProtected(), like the UserSeeder above: migrate:fresh --seed runs in deployments too, and its output ends up in their logs. Alternatively, a command can call a method of the same seeder class and print what it returns; the seeder then takes Factories in its constructor, since the command has no SeedContext.

A module lists its seeders in its definition, and they run in that order:

modules/auth/index.ts
import { defineModule } from '@marmeon/core';
import { UserSeeder } from './seeders/UserSeeder.ts';

export default defineModule({
  name: 'auth',
  migrations: new URL('./migrations/', import.meta.url),
  seeders: [UserSeeder],
});

Generating a seeder

marmeon make:seeder Demo --module=auth writes modules/auth/seeders/DemoSeeder.ts and adds it to the module's seeders. The seeders run in the order of that list, and the generator cannot know which rows a new seeder needs first, so it appends the seeder last and says so. Move it up when it must run earlier. When the module's seeders is not a list written out in index.ts, or with --no-register, the command prints the lines to add instead.

Running seeders

pnpm marmeon db:seed
pnpm marmeon db:seed --module=auth
pnpm marmeon db:seed --class=UserSeeder
pnpm marmeon migrate:fresh --seed

db:seed runs every seeder of every module, the modules in the order of modules: [...] in bootstrap/app.ts. --module runs one module's seeders, and --class one seeder by its class name. An unknown module or class ends the command with an error that names it. migrate:fresh --seed drops every table, migrates and then seeds: the way back to a known database in development.

Seeders do not run in a transaction. A seeder that fails stops the command, and the rows inserted before it stay. Run the seeders on a fresh database, or write them so that running them twice does no harm.

Where the app is protected, in production, staging or without NODE_ENV, db:seed asks for --force like migrate does. The migrations page explains it.

Testing

A test app has the same factories: app.factory(UserFactory).create(). With seed: true, createTestApp() also runs the seeders for every test. The database testing page explains both, and the mail page shows make() building a preview's sample data.