K
Kysely2y ago
bun

What's the pattern for writing migrations exactly?

I'm not familiar with SQL migrations, so my question is how do we create the migration files, what rules should it follow ? As seen in the kysely's GitHub repo example, the migration files have dates, but those files aren't generated, so where did the dates come from ? Well, let's say I don't want the migration files to have dates then I just create separate files for migrations and name them whatever? Ok, then how do I run them? Do I run them everytime the program starts ? Just help me out here, the docs doesn't mention anything about migrations I think it just assumes you are familiar with them already..
8 Replies
ohmi
ohmi2y ago
Migrations | Kysely
Migration files should look like this:
bun
bunOP2y ago
yeah
ohmi
ohmi2y ago
you specify the directory where the migrations are held, and they're executed in alphabetical order. theres no specific convention on how to name them, but ISO 8601 makes sure that they're in alphabetical-chronological order i name them iso8601timestamp-some-description.ts as for running them, the docs have a section on the code for that but the tldr is you run some code to migrate to the latest migration. kysely will keep an internal database table to keep track of which migrations have alreadyt been run. migrateToLatest will only run the migrations that havent been run yet
koskimas
koskimas2y ago
Only thing I'd add here is that migrations should never ever change because they are never run again. Migrations also shouldn't contain any references to the types or other source code since that can (and will) change. While you are not in production and don't have any data you need to keep, it's completely ok to only have one migration and keep modifying it, but running it again requires you to completely clear your database including the kysely migration tables.
bun
bunOP2y ago
wouldn't it be an expensive computation if im running serverless? like for it to try to create the tables if they dont exist everytime a request hits on my aws lambda
koskimas
koskimas2y ago
You definitely shouldn't run migrations on every run You should only run them when there's something to change. In your CI preferably.
bun
bunOP2y ago
I'm thinking of creating a /migrations folder and an index.ts file that will include the run migration code, while there will be the migration files in the same folder. Following the iso8601timestamp-some-description.ts then run them using a package.json script locally
Igal
Igal2y ago
aside from running it, which is not a good idea in serverless. another thing about this, is that migrations folder is quite heavy - getting filled over time, you don't want to bundle that with your lambda, your cold starts will become very lengthy.
Want results from more Discord servers?
Add your server