1import sqlalchemy as sa
2
3from ..operators import CaseInsensitiveComparator
4
5
6class EmailType(sa.types.TypeDecorator):
7 """
8 Provides a way for storing emails in a lower case.
9
10 Example::
11
12
13 from sqlalchemy_utils import EmailType
14
15
16 class User(Base):
17 __tablename__ = 'user'
18 id = sa.Column(sa.Integer, primary_key=True)
19 name = sa.Column(sa.Unicode(255))
20 email = sa.Column(EmailType)
21
22
23 user = User()
24 user.email = 'John.Smith@foo.com'
25 user.name = 'John Smith'
26 session.add(user)
27 session.commit()
28 # Notice - email in filter() is lowercase.
29 user = (session.query(User)
30 .filter(User.email == 'john.smith@foo.com')
31 .one())
32 assert user.name == 'John Smith'
33 """
34
35 impl = sa.Unicode
36 comparator_factory = CaseInsensitiveComparator
37 cache_ok = True
38
39 def __init__(self, length=255, *args, **kwargs):
40 super().__init__(length=length, *args, **kwargs)
41
42 def process_bind_param(self, value, dialect):
43 if value is not None:
44 return value.lower()
45 return value
46
47 @property
48 def python_type(self):
49 return self.impl.type.python_type