postgresql - 如何使用 SQLAlchemy 和 alembic 声明 NOT VALID PostgreSQL 约束?

标签 postgresql sqlalchemy alembic

我想创建一个标记为 NOT VALID 的 PostgreSQL CHECK 约束,但我没有找到在 alembic 中创建此类约束或声明的方法它使用 SQLAlchemy。

看起来 SQLAlchemy 添加了对 NOT VALID 约束内省(introspection)的支持,但反之则不然:https://github.com/sqlalchemy/sqlalchemy/commit/3980a9a455d08c5073cabc3c2b77de46fa36d7b4 .

有办法做到这一点吗?或者只是缺少该功能,我需要用 alembic 手动编写 SQL 语句?

最佳答案

SQLAlchemy 1.4.32 中添加了对在 PostgreSQL 方言中声明 NOT VALID 约束的支持。可以通过将 postgresql_not_valid 方言选项设置为 True 来声明此类约束:

import sqlalchemy as sa


sa.CheckConstraint(
    "lastname IS NOT NULL",
    postgresql_not_valid=True,  # ⬅
)
sa.ForeignKeyConstraint(
    ["head_teacher_id"],
    ["teachers.id"],
    postgresql_not_valid=True,  # ⬅
)

Alembic 的 create_check_constraintcreate_foreign_key函数会将任何方言选项转发给 SQLAlchemy,因此创建具有此类约束的迁移非常简单:

from alembic import op


def upgrade():
    op.create_check_constraint(
        "ck_lastname_not_null",
        "students",
        "lastname IS NOT NULL",
        postgresql_not_valid=True,  # ⬅
    )
    op.create_foreign_key(
        "fk_head_teacher",
        "students",
        "teachers",
        ["head_teacher_id"],
        ["id"],
        postgresql_not_valid=True,  # ⬅
    )


def downgrade():
    op.drop_constraint("ck_lastname_not_null", "students")
    op.drop_constraint("fk_head_teacher", "students")

另请参阅PostgreSQL constraint options文档。

关于postgresql - 如何使用 SQLAlchemy 和 alembic 声明 NOT VALID PostgreSQL 约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70803156/

相关文章:

python - 为什么 key 会是:value pair not be added to a Dictionary?

python - Sqlalchemy:从 sqlalchemy.schema.MetaData 获取 python 类

python - Alembic 可以自动生成列更改吗?

postgresql - 词素在 tsvector 中的位置

postgresql - 查找postgres中特定时间范围内的id计数

sql - Postgres max 在几列上

python - 如何从geoalchemy2的查询结果中获取lng lat值

python - 如何使用 sqlalchemy 按列表对结果进行排序?

python - Alembic SqlAlchemy Postgres "NameError: name ' 字符串'未定义“试图添加数组(字符串)字段

python-3.x - psycopg2 在 "$body$"处或附近抛出未终止的美元引用字符串错误