Compilation extension in SQLAlchemy: functions used in indexes

后端 未结 1 485
青春惊慌失措
青春惊慌失措 2021-01-15 02:40

I want to make a case-insensitive unique constraint in SQLAlchemy, which would work with both Postgres and SQLite.

In Postgres it is achieved:

  • SQL:
相关标签:
1条回答
  • 2021-01-15 03:06

    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)
    
    0 讨论(0)
提交回复
热议问题