Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for like and ilike operators for the PhoneNumberType type #737

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion sqlalchemy_utils/types/phone_number.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
.. _phonenumbers: https://github.com/daviddrysdale/python-phonenumbers
"""

from sqlalchemy import exc, types
from sqlalchemy import exc, String, types
from sqlalchemy.sql.operators import ilike_op, like_op, notilike_op, notlike_op

from ..exceptions import ImproperlyConfigured
from ..utils import str_coercible
Expand Down Expand Up @@ -180,6 +181,12 @@ def __init__(self, region="US", max_length=20, *args, **kwargs):
self.region = region
self.impl = types.Unicode(max_length)

def coerce_compared_value(self, op, value):
if op in (like_op, notlike_op, ilike_op, notilike_op):
return String()
else:
return self

def process_bind_param(self, value, dialect):
if value:
if not isinstance(value, PhoneNumber):
Expand Down
22 changes: 22 additions & 0 deletions tests/types/test_phonenumber.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,28 @@ def test_compilation(self, User, session):
# the type should be cacheable and not throw exception
session.execute(query)

def test_op_like_notlike_and_ilike_notilike(self, session, User):
user1 = User(phone_number="040 1234567")
user2 = User(phone_number="040 1234568")
user3 = User(phone_number="041 1234568")

session.add_all([user1, user2, user3])
session.commit()

result = session.query(User).filter(User.phone_number.like("%568"))
assert len(result.all()) == 2

result = session.query(User).filter(User.phone_number.notlike("+1040%"))
assert len(result.all()) == 1
assert result[0] == user3

result = session.query(User).filter(User.phone_number.ilike("%568"))
assert len(result.all()) == 2

result = session.query(User).filter(User.phone_number.notilike("+1040%"))
assert len(result.all()) == 1
assert result[0] == user3


@pytest.mark.skipif("types.phone_number.phonenumbers is None")
class TestPhoneNumberComposite:
Expand Down
Loading