-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: use IS NOT NULL if word is a wildcard (#5)
- Loading branch information
Showing
3 changed files
with
49 additions
and
21 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,30 +1,39 @@ | ||
# Lucene: | ||
# - ?: a single character wildcard search | ||
# - *: multiple character wildcard search | ||
# SQL LIKE: | ||
# - _: Represents a single character | ||
# - %: Represents zero or more characters | ||
WILDCARD_TABLE = { | ||
"?": "_", | ||
"*": "%", | ||
} | ||
|
||
|
||
def replace_wildcards(s: str, *, table: dict[str, str] = WILDCARD_TABLE): | ||
for k, v in table.items(): | ||
from types import MappingProxyType | ||
|
||
|
||
def replace_wildcards(s: str, *, mapping: MappingProxyType[str, str]): | ||
for k, v in mapping.items(): | ||
s = s.replace(k, v) | ||
|
||
return s | ||
|
||
|
||
class LikeWord: | ||
def __init__(self, value: str, *, table: dict[str, str] = WILDCARD_TABLE): | ||
# Lucene: | ||
# - ?: a single character wildcard search | ||
# - *: multiple character wildcard search | ||
# SQL LIKE: | ||
# - _: Represents a single character | ||
# - %: Represents zero or more characters | ||
WILDCARD_MAPPING = MappingProxyType({"?": "_", "*": "%"}) | ||
|
||
def __init__(self, value: str): | ||
self.value = value | ||
self.table = table | ||
|
||
@property | ||
def is_wildcard(self) -> bool: | ||
return self.value == "*" | ||
|
||
@property | ||
def wildcards(self): | ||
return self.WILDCARD_MAPPING.keys() | ||
|
||
@property | ||
def has_wildcard(self) -> bool: | ||
return any(wildcard in self.value for wildcard in self.wildcards) | ||
|
||
def __str__(self): | ||
wildcards = self.table.keys() | ||
if any(wildcard in self.value for wildcard in wildcards): | ||
return replace_wildcards(self.value) | ||
if self.has_wildcard: | ||
return replace_wildcards(self.value, mapping=self.WILDCARD_MAPPING) | ||
|
||
return f"%{self.value}%" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters