如何删除没有名称的约束?

时间:2015-01-28 14:25:45

标签: mysql postgresql sqlalchemy alembic

我有Alembic迁移,它声明了外键约束:

op.create_table(
    'that',
    ...
    Column('this_id', String),
    ForeignKeyConstraint(['this_id'], ['this.id'])
    ...
)

我的项目要求支持两个数据库 - PostgreSQL和MySQL。并且由于未定义约束的名称,因此每个数据库都会自动生成它。在MySQL中,它看起来像this_ibfk_1,在Postgres中看起来像that_this_id_key

现在我需要编写一个将删除约束的迁移。但考虑到我不知道它的名字,我怎么能参考呢?

2 个答案:

答案 0 :(得分:0)

您可以使用sqlalchemy中的inspect方法获取表格详细信息,详细信息请参见here

inspect方法中,您可以使用get_foreign_keys方法获取指定表名的现有外键。从该列表中,您可以通过选中referred_table的值来找到外键的名称。

希望这有帮助。

答案 1 :(得分:0)

This answer may be about 4 years late, but I just had that problem myself: Alembic would throw upon dropping a constraint whose name is not known.
Here follows a bunch of solutions to find it:

  • get an SQLAlchemy Table object to manipulate:
from alembic import op
from sqlalchemy import Table, MetaData

meta = MetaData(bind=op.get_bind())
my_table = Table('my_table_name', meta)

my_table_constraints = list(my_table.constraints)

All of the constraints on your table are now listed in my_table_constraints. To get their names:

my_constraint_names = list(map(lambda x: x.name, my_table_constraints))
  • "guess" the name of your constraint. For a Postgres database it will most likely be something along the lines of '<table>_<column>_fkey, or 'fk_<table>_<column>'.

  • For a Postgres database, check the contents of catalog tables. The table you're interested in is pg_constraints. If you use pgAdmin, this table is located under Servers > [Your server] > Databases > [Your db] > Catalogs > PostgreSQL Catalog (pg_catalog) > Tables > pg_constraints.
    If you cannot use a GUI tool or want to query it more precisely, this answer explains how to do it.