Skip to content

Commit 372c5c4

Browse files
authored
Allow CASCADE when dropping a constraint on postgres (#496)
1 parent 2462c64 commit 372c5c4

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

lib/ecto/adapters/postgres/connection.ex

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1022,12 +1022,13 @@ if Code.ensure_loaded?(Postgrex) do
10221022
queries ++ comments_on("CONSTRAINT", constraint.name, constraint.comment, table_name)
10231023
end
10241024

1025-
def execute_ddl({command, %Constraint{}, :cascade}) when command in @drops,
1026-
do: error!(nil, "PostgreSQL does not support `CASCADE` in DROP CONSTRAINT commands")
1027-
1028-
def execute_ddl({command, %Constraint{} = constraint, :restrict}) when command in @drops do
1029-
[["ALTER TABLE ", quote_table(constraint.prefix, constraint.table),
1030-
" DROP CONSTRAINT ", if_do(command == :drop_if_exists, "IF EXISTS "), quote_name(constraint.name)]]
1025+
def execute_ddl({command, %Constraint{} = constraint, mode}) when command in @drops do
1026+
[["ALTER TABLE ",
1027+
quote_table(constraint.prefix, constraint.table),
1028+
" DROP CONSTRAINT ",
1029+
if_do(command == :drop_if_exists, "IF EXISTS "),
1030+
quote_name(constraint.name),
1031+
drop_mode(mode)]]
10311032
end
10321033

10331034
def execute_ddl(string) when is_binary(string), do: [string]

test/ecto/adapters/postgres_test.exs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2003,6 +2003,10 @@ defmodule Ecto.Adapters.PostgresTest do
20032003
assert execute_ddl(drop) ==
20042004
[~s|ALTER TABLE "products" DROP CONSTRAINT "price_must_be_positive"|]
20052005

2006+
drop = {:drop, constraint(:products, "price_must_be_positive"), :cascade}
2007+
assert execute_ddl(drop) ==
2008+
[~s|ALTER TABLE "products" DROP CONSTRAINT "price_must_be_positive" CASCADE|]
2009+
20062010
drop = {:drop, constraint(:products, "price_must_be_positive", prefix: "foo"), :restrict}
20072011
assert execute_ddl(drop) ==
20082012
[~s|ALTER TABLE "foo"."products" DROP CONSTRAINT "price_must_be_positive"|]
@@ -2013,6 +2017,10 @@ defmodule Ecto.Adapters.PostgresTest do
20132017
assert execute_ddl(drop) ==
20142018
[~s|ALTER TABLE "products" DROP CONSTRAINT IF EXISTS "price_must_be_positive"|]
20152019

2020+
drop = {:drop_if_exists, constraint(:products, "price_must_be_positive"), :cascade}
2021+
assert execute_ddl(drop) ==
2022+
[~s|ALTER TABLE "products" DROP CONSTRAINT IF EXISTS "price_must_be_positive" CASCADE|]
2023+
20162024
drop = {:drop_if_exists, constraint(:products, "price_must_be_positive", prefix: "foo"), :restrict}
20172025
assert execute_ddl(drop) ==
20182026
[~s|ALTER TABLE "foo"."products" DROP CONSTRAINT IF EXISTS "price_must_be_positive"|]

0 commit comments

Comments
 (0)