"""Database query utilities.""" def escape_like(s: str) -> str: """Escape SQL LIKE metacharacters in a user-supplied string. Use this before embedding user input as a *literal substring* inside a LIKE / ILIKE pattern. Always pair with ``escape="\\\\"`` on the ORM call:: column.ilike(f"%{escape_like(q)}%", escape="\\\\") column.contains(escape_like(q), escape="\\\\") Without escaping, a user can supply ``%`` (matches everything) or ``_`` (matches any single character), turning a substring search into a wildcard query. Escaping makes those characters literal. The backslash is escaped first to avoid double-escaping. """ return s.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")