Skip to content

Add opt-in autogenerate support for check constraints #1761

@jrmalin

Description

@jrmalin

Describe the use case

Currently, Alembic's autogenerate does not detect check constraints. When a CheckConstraint is added to or removed from a SQLAlchemy model, running alembic revision --autogenerate does not produce any migration operations for these constraints. This forces developers to manually write migrations for check constraints, which is error-prone and inconsistent with how other constraints (unique, foreign key) are handled.

This feature request is for an opt-in configuration option compare_check_constraints:

  • Check constraints present in models but missing from the database; generates CreateCheckConstraintOp
  • Check constraints present in the database but missing from models; generates DropConstraintOp

The comparison is done by name only to avoid false positives from SQL text normalization differences between databases and SQLAlchemy - this should be reasonably safe, as changing the text should mean that the constraint will be different in purpose and thus deserves a different name.

Databases / Backends / Drivers targeted

Any database that supports Inspector.get_check_constraints().

Example Use

# configuration in env.py
context.configure(
    connection=connection,
    target_metadata=target_metadata,
    compare_check_constraints=True,
)

# model code
CheckConstraint("amount >= 0", name="ck_order_amount_non_negative")

# generated migration
def upgrade():
    op.create_check_constraint(
        'ck_order_amount_non_negative',
        'order',
        'amount >= 0'
    )

Additional context

  • opt-in: will not change existing functionality
  • throws if constraint is unnamed: otherwise no reliable way to match
  • name-based comparison: avoiding false positives for SQL normalization would be difficult, especially for each dialect.
  • filtered out auto-generated psql enum constraints

Have a nice day!

Metadata

Metadata

Assignees

No one assigned

    Labels

    autogenerate - detectionuse casenot quite a feature and not quite a bug, something we just didn't think of

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions