Skip to content

Commit 3869719

Browse files
committed
[IMP] util.create_fk: drop existing constraint if exists
closes #28 Signed-off-by: Nicolas Seinlet (nse) <[email protected]>
1 parent 56567a9 commit 3869719

File tree

1 file changed

+15
-9
lines changed

1 file changed

+15
-9
lines changed

src/util/pg.py

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -348,17 +348,23 @@ def create_column(cr, table, column, definition, **kwargs):
348348
return True
349349

350350

351-
def create_fk(cr, table, column, fk_table, on_delete_action=""):
352-
assert on_delete_action in ON_DELETE_ACTIONS | {""}
353-
on_delete = "" if not on_delete_action else "ON DELETE {}".format(on_delete_action)
354-
cr.execute(
355-
"""
356-
ALTER TABLE "{table}"
357-
ADD FOREIGN KEY ("{column}") REFERENCES "{fk_table}"(id) {on_delete}
358-
""".format(
359-
**locals()
351+
def create_fk(cr, table, column, fk_table, on_delete_action="NO ACTION"):
352+
assert on_delete_action in ON_DELETE_ACTIONS
353+
current_target = target_of(cr, table, column)
354+
if current_target:
355+
if current_target[:2] == (fk_table, "id"):
356+
# assume the `on_delete_action` is correct
357+
return
358+
cr.execute(
359+
sql.SQL("ALTER TABLE {} DROP CONSTRAINT {}").format(
360+
sql.Identifier(table), sql.Identifier(current_target[2])
361+
)
360362
)
363+
364+
query = sql.SQL("ALTER TABLE {} ADD FOREIGN KEY ({}) REFERENCES {}(id) ON DELETE {}").format(
365+
sql.Identifier(table), sql.Identifier(column), sql.Identifier(fk_table), sql.SQL(on_delete_action)
361366
)
367+
cr.execute(query)
362368

363369

364370
def remove_column(cr, table, column, cascade=False):

0 commit comments

Comments
 (0)