Hi all!
I have this setup:
defmodule Koko.Repo.Migrations.AddToDocs do
use Ecto.Migration
def change do
alter table(:documents) do
add :author_id, references(:authentication_users, on_delete: :nothing)
add :identifier, :string
add :parent_id, :string
add :children, {:array, :string}
add :tags, {:array, :string}
add :attributes, :map
add :resources, {:array, :map}
add :viewed_at, :utc_datetime
add :edited_at, :utc_datetime
end
end
end
and would like to do something like this in a migration.
def change do
alter table(:documents) do
modify :author_id, references(:authentication_users, on_delete: :delete_all)
end
end
In other words, I want to change a constraint — but not mess with my data!
Maybe just drop down to SQL and alter the constraint with execute?
Ah – how would I do that?
Thanks all! I ended up using a combination of SQL and the Ecto migration dsl:
defmodule Koko.Repo.Migrations.ChangeConstraint do
use Ecto.Migration
def change do
execute "ALTER TABLE documents DROP CONSTRAINT documents_author_id_fkey"
alter table(:documents) do
modify :author_id, references(:authentication_users, on_delete: :delete_all)
end
end
end
10 Likes
this migration is not reversible, a little improvement would be to define up and down.
def up do
execute(
"ALTER TABLE factsheet_trading_account DROP CONSTRAINT factsheet_trading_account_trading_account_id_fkey"
)
alter table(:factsheet_trading_account) do
modify(
:trading_account_id,
references(:trading_accounts, on_delete: :delete_all),
null: false
)
end
end
def down do
execute(
"ALTER TABLE factsheet_trading_account DROP CONSTRAINT factsheet_trading_account_trading_account_id_fkey"
)
alter table(:factsheet_trading_account) do
modify(
:trading_account_id,
references(:trading_accounts, on_delete: :nothing),
null: false
)
end
end
4 Likes