What is the correct way to make SQLalchemy store strings as lowercase? What is the correct way to make SQLalchemy store strings as lowercase? sqlite sqlite

What is the correct way to make SQLalchemy store strings as lowercase?


I haven't tried this personally, but perhaps you could use a custom comparator operator? I.e.

class CaseInsensitiveColumnComparator(ColumnProperty.Comparator):    def __eq__(self, other):        return func.lower(self.__clause_element__()) == func.lower(other)

This way, your ID can be stored in any case, but will compare as lowercase.


Another idea - augment sqlalchemy.types.Text, and use that for your ID.

import sqlalchemy.types as typesclass LowerCaseText(types.TypeDecorator):    '''Converts strings to lower case on the way in.'''    impl = types.Text    def process_bind_param(self, value, dialect):        return value.lower()class User(Base):    __tablename__ = 'user'    id = Column(LowerCaseText, primary_key=True)    ...