kysely-org / kysely-ctl

Command-line tool for Kysely
MIT License
46 stars 1 forks source link

How to use the "seeds" feature? #39

Closed shoooe closed 2 weeks ago

shoooe commented 3 weeks ago

There doesn't seem to be any mention of what the seed files are supposed to contain. Is there maybe some documentation I'm missing where it explains what the structure of these files are, how to async/await in these files or how to connect to the database (e.g. it's passed in like for migrations vs we should import the connection).

Thanks in advance and thanks for this awesome library!

igalklebanov commented 3 weeks ago

Hey 👋

Database seeding is populating a database with an initial set of data. It is common to load seed data such as initial user accounts or dummy data upon initial setup of an application. wikipedia.

e.g. populating a test environment's database before e2e tests. populating a demo environment for presentations. populating a local development environment, so the frontend allows logging in and renders some data in a table.

The current template for generated seeds (kysely seed make <seed_name>) is:

import type { Kysely } from 'kysely'

export async function seed(db: Kysely<any>): Promise<void> {
    // seed code goes here...
    // note: this function is mandatory. you must implement this function.
}

https://github.com/kysely-org/kysely-ctl/blob/main/src/templates/seed-template.ts

As you can see, you get a kysely instance, just like with migrations' functions. There's only one direction, "seed" which is like "up" in a sense. You can run all seed files with kysely seed run, or pick specific ones using the --specific flag. Seed files are run in natural file system order.

Unlike migrations, there is no state stored in the database. You can't revert a seed, or continue where you left off.

Unlike migrations that should be frozen in time, seed scripts are something you have to maintain over time, and they should evolve as the database schema evolves. So I'm not so happy with the template right now - it should support Kysely<Database> somehow.

shoooe commented 1 week ago

@igalklebanov Awesome thanks. Just one question: is there anything blocking me from importing Database (the database schema type) and using Kysely<Database>?

Thanks for the quick response.

igalklebanov commented 1 week ago

There's nothing blocking you from doing that.