Skip to content

Commit

Permalink
Implement regex
Browse files Browse the repository at this point in the history
  • Loading branch information
mohamadkhalaj committed Nov 4, 2023
1 parent 2d6915c commit 1180f73
Showing 1 changed file with 35 additions and 23 deletions.
58 changes: 35 additions & 23 deletions aggify/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
class Operators:
QUERY_OPERATORS = {
"exact": "$eq",
"iexact": "$eq",
"iexact": "$regex",
"contains": "$regex",
"icontains": "$regex", # noqa
"startswith": "$regex",
Expand All @@ -34,6 +34,23 @@ class Operators:
**COMPARISON_OPERATORS,
}

REGEX_PATTERNS = {
"iexact": "^{value}$",
"contains": "{value}",
"icontains": "{value}",
"startswith": "^{value}",
"istartswith": "^{value}",
"endswith": "{value}$",
"iendswith": "{value}$",
}

REGEX_OPTIONS = {
"iexact": "i",
"icontains": "i",
"istartswith": "i",
"iendswith": "i",
}

def __init__(self, match_query: Dict[str, Any]):
self.match_query = match_query

Expand All @@ -42,35 +59,30 @@ def compile_match(self, operator: str, value, field: str):
# I think there should be easier way to inject comparison operators to be defined per each
# like map an existing template to each operator

if operator in ["exact", "iexact"]:
self.match_query[field] = {Operators.ALL_OPERATORS[operator]: value}

elif operator in [
"contains",
"startswith",
"endswith",
"icontains",
"istartswith",
"iendswith",
]: # noqa
self.match_query[field] = {
Operators.ALL_OPERATORS[operator]: f".*{value}.*",
"$options": "i",
}
if operator in Operators.REGEX_PATTERNS:
if isinstance(value, F):
raise ValueError("Not implemented yet")
pattern = Operators.REGEX_PATTERNS[operator].format(value=value)
# Create the base query with the pattern
query = {Operators.ALL_OPERATORS[operator]: pattern}

# If there's an option for the operator, add it to the query
if operator in Operators.REGEX_OPTIONS:
query["$options"] = Operators.REGEX_OPTIONS[operator]

elif operator in Operators.ALL_OPERATORS[operator]:
self.match_query[field] = query
elif operator in Operators.ALL_OPERATORS:
if isinstance(value, F):
self.match_query["$expr"] = {
Operators.ALL_OPERATORS[operator]: [
f"${field}",
value.to_dict(),
]
Operators.ALL_OPERATORS[operator]: [f"${field}", value.to_dict()]
}

else:
self.match_query[field] = {Operators.ALL_OPERATORS[operator]: value}
else:
self.match_query[field] = {Operators.ALL_OPERATORS[operator]: value}
# Default behavior
self.match_query[field] = {
Operators.ALL_OPERATORS.get(operator, operator): value
}

return self.match_query

Expand Down

0 comments on commit 1180f73

Please sign in to comment.