This commit is contained in:
Timothy Jaeryang Baek
2026-08-30 21:36:17 -04:00
parent d8133c905a
commit 49aab7451c

View File

@@ -323,25 +323,41 @@ elif 'sqlite' in SQLALCHEMY_DATABASE_URL:
def _apply_sqlite_pragmas(dbapi_connection):
"""Apply all configured SQLite PRAGMAs to a raw DBAPI connection."""
# SQLite LIKE folds ASCII only; SQLAlchemy SQLite ILIKE compiles to lower(x) LIKE lower(?).
compiled_patterns = {}
def like(pattern, value, escape=None):
if pattern is None or value is None:
return None
regex = []
escaped = False
pattern = str(pattern).lower()
escape = str(escape).lower() if escape is not None else None
for char in str(pattern).lower():
if escape and not escaped and char == escape:
escaped = True
continue
regex.append(
'.*' if not escaped and char == '%' else '.' if not escaped and char == '_' else re.escape(char)
)
escaped = False
if escaped:
key = (pattern, escape)
compiled = compiled_patterns.get(key)
if compiled is False:
return False
if compiled is None:
regex = []
escaped = False
for char in pattern:
if escape and not escaped and char == escape:
escaped = True
continue
regex.append(
'.*' if not escaped and char == '%' else '.' if not escaped and char == '_' else re.escape(char)
)
escaped = False
if escaped:
compiled = False
if len(compiled_patterns) >= 512:
compiled_patterns.clear()
compiled_patterns[key] = compiled
return False
compiled = re.compile(''.join(regex), re.DOTALL)
if len(compiled_patterns) >= 512:
compiled_patterns.clear()
compiled_patterns[key] = compiled
return re.fullmatch(''.join(regex), str(value).lower(), re.DOTALL) is not None
return compiled.fullmatch(str(value).lower()) is not None
dbapi_connection.create_function('like', 2, like, deterministic=True)
dbapi_connection.create_function('like', 3, like, deterministic=True)