Search code examples
elixirphoenix-frameworkecto

Elixir, Ecto rollback only timestamp


In one of the tables created I had to add timestamps after the table was created. My current migration script looks like

defmodule Database.Repo.Migrations.UpdateSubscriptionTableInsertedAt do
  use Ecto.Migration
   def up do
    alter table(:subscriptions) do
      timestamps()
    end
  end
  def down do
    alter table(:subscriptions) do
      timestamps()
    end
  end
end

this works fine for the migration but while trying to rollback throws an error

[info] == Running Database.Repo.Migrations.UpdateSubscriptionTableInsertedAt.down/0 forward
[info] alter table subscriptions
** (Postgrex.Error) ERROR 42701 (duplicate_column): column "inserted_at" of relation "subscriptions" already exists

Any ideas how can I resolve this?


Solution

  • You are telling it to do the same thing for both the up and down. In this case you can actually just specify a single callback as follows.

    def change do
      alter table(:subscriptions) do
        timestamps()
      end
    end
    

    This will do the right thing when migrating, but it will also remove the fields when doing a rollback. If you really want to keep the up/0 and down/0 callbacks, you will need to manually remove the fields.

    def down do
      alter table(:subscriptions) do
        remove :inserted_at
        remove :updated_at
      end
    end