Ecto migration rollbacks: Is automatic safe rollback for schema changes supported?
0 reputation · 16 Jan 2021, 21:40 UTC
0 reputation · 16 Jan 2021, 21:40 UTC
Ensure that rolling back a schema migration does not inadvertently lose or corrupt data.
Ecto requires a down function for every migration; if omitted the migration is deemed irreversible. The alter table DSL does not automatically generate reverse operations for added columns or renamed fields, and the :force option can silently truncate data during type changes.
Whether Ecto should provide an automatic, safe rollback mechanism for column renames and type conversions remains undecided in the community. Current practice demands explicit handling, and there is no built‑in safeguard against accidental data loss.
Which Ecto migration constructs currently lack auto‑generated safe rollbacks that could protect data?
Can the :force option be used without risking silent truncation, or should it be avoided in production migrations?
34775 reputation · 16 Jan 2021, 23:52 UTC
Ecto does **not** provide an automatic, safe rollback for most schema changes. Only a narrow set of reversible edits can be auto‑generated by the change/0 callback; everything else requires an explicit down/1 implementation to avoid data loss.
change/0 callback auto‑generates reverse operations for: add/remove column, create/drop table, add/drop index, create/drop constraint.rename/3), column type changes, adding a NOT NULL constraint without a default, and dropping a column that contains data **do not** have auto‑generated safe rollbacks.:force option in alter table or type‑change clauses bypasses type checking and can silently truncate or discard data; it is not safe for production unless intentional data loss is acceptable.Ecto’s design treats migrations as explicit scripts. The change/0 helper can infer inverses only for operations that are information‑preserving (e.g., adding a column). Operations that may lose or alter data cannot be safely inverted without knowing how to convert existing values, so Ecto leaves the responsibility to the developer.
change/0, run mix ecto.migrate, insert sample data, then run mix ecto.rollback and confirm the column is removed and data remains.rename/3 in change/0, migrate, insert data, rollback, and observe that the column name does not revert (manual down required).:force, insert data exceeding the new type’s length, migrate, rollback, and check whether data is truncated; compare with a manual down that safely casts values.If you are using change/0 exclusively, you only need to worry about the constructs listed above; otherwise, ensure each migration includes a matching down/1 that handles data conversion or preservation.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.