How to change column to nullable with modify in Ecto migration

Sooner or later you'll have to change the null constraint in one of your DB relations. How to do it easily in Ecto?

Table of contents

    Although I came across many different examples where a raw SQL has been used to perform this type of operation in Ecto, it's actually super easy to do it with modify/3 function.

    Let's assume that your migration looks like this:

    create table(:blog_posts) do
      add :title, :string, null: false
      add :intro, :text, null: false
      add :body, :text, null: false
      add :category_id, references(:blog_categories, on_delete: :delete_all)
    end

    ... and at some point, you realize that you don't want to force passing the intro column value.

    You can change it easily this way:

    alter table(:blog_posts) do
      modify :intro, :text, null: true, from: :text
    end

    It's also worth mentioning that it's possible to modify foreign keys with modify:

    alter table(:blog_posts) do
      modify :category_id,
        references(:blog_categories, on_delete: :delete_all),
        null: false,
        from: references(:blog_categories, on_delete: :delete_all)
    end
    Szymon Soppa Web Developer
    Szymon Soppa Curiosum Founder & CEO

    Read more
    on #curiosum blog