'How to create an exclude constraint with a daterange using sqlalchemy
I know that just using raw sql, I can add an exclude constraint like so:
ADD CONSTRAINT unique_daterange_constraint
EXCLUDE USING gist
( foo WITH =,
daterange(start_date, end_date, '[]') WITH &&
);
However, I need to be able to do the same with sqlalchemy. What I currently have (which does not work) in my table args is:
__table_args__ = (
postgresql.ExcludeConstraint(
("foo", "="),
(DateRange("start_date", "end_date", bounds="[]"), "&&"),
name="unique_daterange_constraint",
using="gist",
),
)
DateRange is imported from psycopg2.extras, as it's my understanding that that is how to replicate the postgres daterange type as used in the sql above.
My stacktrace, when attempting to create an alembic migration file tells me that the daterange section is wrong with
sqlalchemy.exc.ArgumentError: SQL expression object expected, got object of type <class 'psycopg2._range.DateRange'> instead
I know that a potential way I could handle this (since it really wants a column where I'm putting the DateRange) is to create a daterange column and a trigger that upon insert or update populates my daterange column with the start and end dates, but it feels like I shouldn't have to do that. It seems that if I can simply define a daterange using existing columns in sql, I should be able to using sqlalchemy as well.
Is there any way to achieve this the way I want?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
