Search code examples
postgresqlalembic

I would like drop a constraint if it exists. Is this possible with alembic?


If I try drop an non-existing constraint: In revision file

op.drop_constraint('exists_in_some_db_fkey', 'table', type='foreignkey')

I got:

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedObject)
constraint "exists_in_some_db_fkey" of relation "table" does not exist
[SQL: 'ALTER TABLE extensions DROP CONSTRAINT exists_in_some_db_fkey'] 
(Background on this error at: http://sqlalche.me/e/f405)

It's our fault, we have some corrupted database, but if we could drop constraint checking IF EXISTS, it could solve our problem.

We cannot change our models recently.


Solution

  • With Alembic you always have an option to execute an SQL statement manually like this:

    op.execute("ALTER TABLE new DROP CONSTRAINT IF EXISTS parent_id_f")
    

    See Alembic Operation Reference: execute