Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何删除定义的没有名称的约束?_Mysql_Postgresql_Sqlalchemy_Alembic - Fatal编程技术网

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

Mysql 如何删除定义的没有名称的约束?,mysql,postgresql,sqlalchemy,alembic,Mysql,Postgresql,Sqlalchemy,Alembic,我使用Alembic迁移声明外键约束,如下所示: op.create_table( 'that', ... Column('this_id', String), ForeignKeyConstraint(['this_id'], ['this.id']) ... ) 我的项目需要支持两个数据库——PostgreSQL和MySQL。由于并没有定义约束的名称,所以每个数据库都会自动生成约束。在MySQL中,它看起来像是this\u ibfk\u 1,而在Po

我使用Alembic迁移声明外键约束,如下所示:

op.create_table(
    'that',
    ...
    Column('this_id', String),
    ForeignKeyConstraint(['this_id'], ['this.id'])
    ...
)
我的项目需要支持两个数据库——PostgreSQL和MySQL。由于并没有定义约束的名称,所以每个数据库都会自动生成约束。在MySQL中,它看起来像是
this\u ibfk\u 1
,而在Postgres中,它像
this\u id\u key


现在,我需要编写一个迁移来删除约束。但是,考虑到我不知道它的名称,我如何引用它呢?

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

inspect
方法中,可以使用
get\u foreign\u keys
方法获取指定表名的现有外键。从该列表中,您可以通过检查
referenced\u table
的值来查找外键的名称


希望这能有所帮助。

这个答案可能晚了4年,但我自己也遇到了这个问题:Alembic会放弃一个名称未知的约束。
以下是一系列解决方案:

  • 获取要操作的SQLAlchemy
    对象:
来自alembic导入操作
从sqlalchemy导入表,元数据
meta=元数据(bind=op.get\u bind())
my_table=table('my_table_name',meta)
my_table_constraints=列表(my_table.constraints)
表上的所有约束现在都列在
my\u table\u constraints
中。要知道他们的名字:

my_constraint_names=list(映射(lambda x:x.name,my_table_constraints))
  • “猜测”约束的名称。对于Postgres数据库来说,它很可能是类似于
    “fkey
    “fk”
    的东西

  • 对于Postgres数据库,请检查目录表的内容。您感兴趣的表是
    pg\u约束
    。如果使用pgAdmin,此表位于
    Servers>[Your server]>Databases>[Your db]>Catalogs>PostgreSQL目录(pg_目录)>表>pg_约束下

    如果您不能使用GUI工具或希望更精确地查询它,请说明如何执行此操作


对于PostgreSQL,请检查视图pg_约束,并找到您要查找的约束的名称。信息\u架构视图应适用于两者。