I want to enforce a unique constraint on a column but only if it is not null. This is the default behavior in SQLite, but not in MS SQL Server.
It seems the way to accomplish this in SQL Server is to use an index with a where clause, as described in this post. My question is how do I do that in SQLAlchemy and have it still work with SQLite.
I think this is approximately what I want:
class MyClass(Base):
__tablename__ = 'myclass'
__table_args__ = (Index('unique_index', <where clause?>, unique=True)
my_column = Column(Integer) # The column I want unique if not null
where <where clause?>
is some expression that puts the index on my_column
where it is not NULL
. It seems this is possible by reading the documentation for index, but I do not know what expression I would need. Help with this or a different approach would be much appreciated.