Add __like and __ilike filters (#421) #954
Open
+129
−0
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Adds support for __like and __ilike filters (#421)
Description
Adds support for filtering by arbitrary LIKE patterns. For example:
await User.filter(name__like='J_hn%')
I made three potentially contentious implementation decisions:
%
and_
with backslashes in the pattern string if they desire to match those characters literally. If they are not escaped, they are treated as SQL wildcards. The caller does not need to escape\
to match it literally. As far as I can see, this is consistent with how__contains
works, for example. It also escapes\
on behalf of the caller.__ilike
using UPPER + LIKE. Therefore, it works with flavors of SQL that do not support the ILIKE operator, such as MySQL.__like
, at least in the current implementation, is case-sensitive or case-insensitive depending on the flavor of SQL that is used. If desired, this might be changed, so that__like
is guaranteed to be case-sensitive independently of the underlying database. I did not try to enforce case-sensitivity because LIKE queries on the database and__like
filters in Tortoise would yield different results, which might be confusing.Motivation and Context
Fixes #421
(The issue is assigned to someone else but has not been worked on for over a year. I hope it's fine that I opened a PR addressing it.)
How Has This Been Tested?
I added tests in
test_filters.py
. Someone with a good understanding of SQL injections should take a look at the tests and let me know if there are further tests I should add.Checklist:
The two tests
tests/test_default.py::TestDefault::test_default
andtests/fields/test_time.py::TestDatetimeFields::test_update
fail when runningmake test_postgres
locally on my machine. However, that is the case on thedevelop
branch as well and seems unrelated to the changes I made.This is my first contribution to Tortoise ORM. Please let me know if there are more elegant ways to implement LIKE filters using existing functionality in the code base that I might not be familiar with.