SQLAlchemy CheckConstraint with multiple conditions raises warning

Viewed 451

I'm using SQLAlchemy 1.3.18, Python 3.8.5 and PostgreSQL 12.

I have the following table declaration with a Check Constraint with multiple columns and conditions:

Table(
    'my_table',
    MetaData(),
    Column('id', Integer, primary_key=True),
    Column('start', DateTime(), nullable=False),
    Column('end', DateTime(), nullable=False),
    CheckConstraint(
        and_(
            or_(
                func.date_trunc('month', column('start')) == func.date_trunc('month', column('end')),
                func.extract('day', column('end')) == 1
            ),
            (column('end') - (column('start') + func.make_interval(0, 1)) <= func.make_interval())
        )
    )
)

Although the application DOES create the check constraint in the database correctly, I'm getting the following warning:

C:\Python38\lib\site-packages\sqlalchemy\sql\base.py:559: SAWarning: Column 'end' on table None being replaced by <sqlalchemy.sql.elements.ColumnClause at 0x26522ab0e50; end>, which has the same key. Consider use_labels for select() statements.

C:\Python38\lib\site-packages\sqlalchemy\sql\base.py:559: SAWarning: Column 'start' on table None being replaced by <sqlalchemy.sql.elements.ColumnClause at 0x26522ab0b80; start>, which has the same key. Consider use_labels for select() statements.

C:\Python38\lib\site-packages\sqlalchemy\sql\base.py:559: SAWarning: Column 'end' on table None being replaced by <sqlalchemy.sql.elements.ColumnClause at 0x26522ab0c70; end>, which has the same key. Consider use_labels for select() statements.

What I am doing wrong?

1 Answers

Thanks to Ilja Everilä for the comment that solved the problem.

This is the solution, put the columns in variables so they are the same object in memory.

my_table_start = column('start')
my_table_end = column('end')

Table(
    'my_table',
    MetaData(),
    Column('id', Integer, primary_key=True),
    Column('start', DateTime(), nullable=False),
    Column('end', DateTime(), nullable=False),
    CheckConstraint(
        and_(
            or_(
                func.date_trunc('month', my_table_start) == func.date_trunc('month', my_table_end),
                func.extract('day', my_table_end) == 1
            ),
            (my_table_end - (my_table_start + func.make_interval(0, 1)) <= func.make_interval())
        )
    )
)
Related