keystonejs / keystone

The most powerful headless CMS for Node.js — built with GraphQL and React
https://keystonejs.com
MIT License
8.98k stars 1.13k forks source link

Clarification on how to handle migrations #9127

Closed pc-erin closed 2 months ago

pc-erin commented 2 months ago

I was wondering what the standard way to handle migrations is meant to be.

As I recall, migrations used to be generated automatically when I made schema changes, but it seems like that's no longer the case.

Now, I use keystone dev but no new migrations appear. So I tried using keystone prisma migrate dev, but that says that because the DB has drifted, it needs to reset the entire thing, which will delete all my dev data.

Am I supposed to reset the database on every migration, or is there some other way this is meant to work? Can I just create a migration that would bring the previous migration into line with the current schema/DB state, but not apply it locally?

It seems like there should be a simple way to do this.

stuible commented 2 months ago

I am also struggling with this issue. Would love to see some improvements in the documentation around this area!

pc-erin commented 2 months ago

I know you can use prisma's seeding feature to inject database entries. Maybe we're supposed to put all our dev data in a seed file? If so it would be good to have the docs mention that.

It might still be an issue for projects where you need to constantly be changing data during development and testing. Same for projects that involve file/image uploads since I'm not sure how you'd put those in a seed file.

I've been reading through the docs, and the only other way I can see to do migrations is to change your dev script to keystone dev --no-db-push, which doesn't make any database changes, so you have to manually run keystone prisma migrate dev each time you change the schema.

I also tried to figure out a way to get back to a working state after using the default push behavior, without deleting all the dev data.

You can use:

keystone prisma migrate diff --from-migrations migrations --to-schema-datasource schema.prisma --script --shadow-database-url='[SHADOW_DATABASE_URL]' > migrations/[migration_number_and_name]/migration.sql

To create the missing migration.

Then run keystone prisma migrate resolve --applied [migration_number_and_name], to tell the database that the missing migration has already been applied.

After that the database should be fully up to date with the migrations, and you can switch over to using the --no-db-push manual migration mode.

Not sure if that's how it's intended to be done, but those are my workarounds so far.