Modify foreign key in Ecto
<p>I have this original migration that have already been run and sent upstream:</p>

<pre><code>create table(:videos) do
  add :url, :string
  add :title, :string
  add :description, :text
  add :user_id, references(:users, on_delete: :nothing)

  timestamps
end
create index(:videos, [:user_id])
</code></pre>

<p>Now i wish to change the foreign key on <code>user_id</code> to cascade deletions, so that when a user is deleted all of his associated videos will also be deleted.</p>

<p>I have tried the following migration:</p>

<pre><code>alter table(:videos) do
  modify :user_id, references(:users, on_delete: :delete_all)
end
</code></pre>

<p>But this raises an error:</p>

<pre><code>(Postgrex.Error) ERROR (duplicate_object): constraint "videos_user_id_fkey" for relation "videos" already exists
</code></pre>

<p>How can I formulate a migration script that will change this foreign key according to my requirement?</p>

<hr>

<p><strong>UPDATE</strong></p>

<p>I ended up with the following solution:</p>

<pre><code>def up do
  execute "ALTER TABLE videos DROP CONSTRAINT videos_user_id_fkey"
  alter table(:videos) do
    modify :user_id, references(:users, on_delete: :delete_all)
  end
end

def down do
  execute "ALTER TABLE videos DROP CONSTRAINT videos_user_id_fkey"
  alter table(:videos) do
    modify :user_id, references(:users, on_delete: :nothing)
  end
end
</code></pre>

<p>this drops the constraint before ecto tries to recreate it.</p>