Skip to content

Steps to change primary key and preserve data in migration #3329

Closed Answered by simolus3
realth000 asked this question in Q&A
Discussion options

You must be logged in to vote

Is this way correct to "change the primary key of table while reserving most data"?

Using UserEntity.fromJson is not a reliable tool here: That class will always reflect the current columns of your schema, so you'll get these null cast errors after adding a new non-nullable column to the table in any subsequent migration.
The good news is that drift's TableMigration API can take care of all of these steps, while also avoiding some common pitfalls by doing the transformation between the two tables in SQL.

Under the assumption that no two users in the old table have the same value in someId, you can just do this:

await m.alterTable(TableMigration(users));

That's it! If you can't guarantee…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by realth000
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants