Seeding
Database seeding is the initial seeding of a database with data. It is a form of initial database population, intended for use during development, testing, or production database initialization.
Deepkit ORM has no special seeding API. A seed is a regular function that receives a Database and inserts entities with database.persist() or a session. This makes the same seed usable in a CLI command, at application startup, and in tests.
Seed Function
The following entities are used in the examples of this page:
import { AutoIncrement, entity, PrimaryKey, Reference, Unique } from '@deepkit/type'; @entity.name('author') export class Author { id: number & PrimaryKey & AutoIncrement = 0; constructor(public username: string & Unique) { } } @entity.name('book') export class Book { id: number & PrimaryKey & AutoIncrement = 0; constructor(public title: string, public author: Author & Reference) { } }
A seed function adds all entities to a session and commits them at once. The unit of work sorts the inserts by their dependencies, so the author is inserted before the books that reference it, and the auto-increment ID of the author is assigned to the books automatically.
import { Database } from '@deepkit/orm'; export async function seed(database: Database) { const session = database.createSession(); const peter = new Author('peter'); session.add(peter); for (let i = 1; i <= 3; i++) { session.add(new Book(`Book ${i}`, peter)); } await session.commit(); }
For a few unrelated entities database.persist() is enough:
await database.persist(new Author('peter'), new Author('marie'));
Idempotent Seeding
A seed that is executed more than once (e.g. on every start of a development server) should not insert the same data twice or fail with a unique constraint error. Check whether the data already exists before inserting it:
export async function seed(database: Database) { const exists = await database.query(Author).filter({ username: 'peter' }).has(); if (exists) return; const session = database.createSession(); const peter = new Author('peter'); session.add(peter, new Book('Book 1', peter)); await session.commit(); }
To start from a clean state instead, delete the existing records first. Delete entities that reference others before the referenced ones:
await database.query(Book).deleteMany(); await database.query(Author).deleteMany();
If the seed must be applied either completely or not at all, run it in a transaction with database.transaction(async (session) => { ... }).
CLI Command
In a Deepkit application, seeding is typically done in a CLI command. The database class is injected via dependency injection like any other service. See CLI for more information about commands.
import { App, cli, Flag } from '@deepkit/app'; import { FrameworkModule } from '@deepkit/framework'; import { Logger } from '@deepkit/logger'; import { Database } from '@deepkit/orm'; import { SQLiteDatabaseAdapter } from '@deepkit/sqlite'; class AppDatabase extends Database { constructor() { super(new SQLiteDatabaseAdapter('./app.sqlite'), [Author, Book]); } } @cli.controller('db:seed', { description: 'Seed the database with initial data', }) class SeedCommand { constructor( protected database: AppDatabase, protected logger: Logger, ) { } async execute(reset: boolean & Flag = false) { if (reset) { await this.database.query(Book).deleteMany(); await this.database.query(Author).deleteMany(); } await seed(this.database); this.logger.log(`Database seeded, ${await this.database.query(Book).count()} books.`); } } new App({ providers: [AppDatabase], controllers: [SeedCommand], imports: [new FrameworkModule()], }).run();
$ ts-node app.ts db:seed
$ ts-node app.ts db:seed --resetThe tables have to exist before seeding. Create them with migrations (or database.migrate() / migrateOnStartup during prototyping).
Fixture Data
Seed data does not need to be generated by a fake data library. Plain object literals in a fixture file are easier to read and produce the same data on every run, which makes tests deterministic. Use cast from @deepkit/type to convert them into entity instances. cast also validates the data, so invalid fixtures fail early.
import { cast } from '@deepkit/type'; const authorFixtures = [ { username: 'peter' }, { username: 'marie' }, ]; await database.persist(...authorFixtures.map(v => cast<Author>(v)));
For larger amounts of data, generate it with a simple loop:
const session = database.createSession(); for (let i = 0; i < 1000; i++) { session.add(new Author(`user${i}`)); } await session.commit();
Seeding in Tests
In tests, use the MemoryDatabaseAdapter from @deepkit/orm. It needs no running database server and no migration, and every test gets a fresh, isolated database.
import { expect, test } from '@jest/globals'; import { Database, MemoryDatabaseAdapter } from '@deepkit/orm'; test('books by author', async () => { const database = new Database(new MemoryDatabaseAdapter(), [Author, Book]); await seed(database); const peter = await database.query(Author).filter({ username: 'peter' }).findOne(); const books = await database.query(Book).filter({ author: peter }).find(); expect(books.map(book => book.title)).toEqual(['Book 1', 'Book 2', 'Book 3']); });
When you test a Deepkit application with createTestingApp, pass the entities as the second argument. This registers a Database with a MemoryDatabaseAdapter that you can seed before running the test. See Testing.
import { createTestingApp } from '@deepkit/framework'; import { Database } from '@deepkit/orm'; test('seeded app', async () => { const testing = createTestingApp({ controllers: [BookController] }, [Author, Book]); await seed(testing.app.get(Database)); // ... });
The memory adapter does not support joins and does not execute SQL. For tests that depend on joins or database-specific behavior (constraints, collations, raw SQL), use new SQLiteDatabaseAdapter(':memory:') from @deepkit/sqlite (call database.migrate() before seeding) or your real database adapter.