Changing schema in existing project via Ecto

I have an existing user schema containing name ,email . I have some users as the application had been running.

How do I introduce a new field phone_num for all users?

It can be ensured for new users. How do I handle those already in the db?

Can I just run an ecto migration over db after changing schema (manually)? Is there a better way?

Your Ecto schema doesn’t have to track 1:1 with the table columns, if you have a column that is not defined in Ecto it should ignore it. So the order should be to first run the schema migration to add phone_num, ensure the db and app are still happy, then commit and deploy the code that uses the new column.

You do have to understand how your specific database version handles the type of migration you want to do. For example in postgres < v11 if you add a column with a default value it will lock the entire table while it runs the transaction and if you’re changing a very large table in production your app may become unstable for a few minutes while the operation completes. In that case you’d have to split into a number of steps that prevent full locks, or at least makes them run as quickly as possible.

This article talks about that a bit Running a safe database migration using Postgres in the “backfill” section.

Martin Fowler goes into a lot of detail on the subject Evolutionary Database Design

2 Likes