I want to make a case-insensitive unique constraint in SQLAlchemy, which would work with both Postgres and SQLite.
In Postgres it is achieved:
the @compiles method has to return a string. Also, there's some glitch in how Index is traversing the functionelement here so we need one little workaround:
class CaseInsensitive(FunctionElement):
__visit_name__ = 'notacolumn'
name = 'CaseInsensitive'
type = VARCHAR()
@compiles(CaseInsensitive, 'sqlite')
def case_insensitive_sqlite(element, compiler, **kw):
arg1, = list(element.clauses)
return compiler.process(collate(arg1, 'nocase'), **kw)
@compiles(CaseInsensitive, 'postgresql')
def case_insensitive_postgresql(element, compiler, **kw):
arg1, = list(element.clauses)
return compiler.process(func.lower(arg1), **kw)