Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add escape like helper #81

Open
gaborbernat opened this issue Nov 6, 2024 · 2 comments
Open

Add escape like helper #81

gaborbernat opened this issue Nov 6, 2024 · 2 comments

Comments

@gaborbernat
Copy link
Contributor

gaborbernat commented Nov 6, 2024

This helper method should be part of the lib:

def escape_like(text: str) -> str:
    """Escape text for like.

    :param text: the raw text
    :return: escaped text
    """
    return text.replace("%", "\\%").replace("_", "\\_")

Example of other frameworks having this https://sqlalchemy-utils.readthedocs.io/en/stable/orm_helpers.html#escape-like

Or at least documented somewhere...

@godlygeek
Copy link
Contributor

godlygeek commented Feb 18, 2025

I'm reluctant to add this as a function to the library because it's fairly trivial, and more importantly because it won't work out of the box (you need to not only call this escape_like function on your input, but also use the 3 argument form of LIKE where you pass an ESCAPE \ as well).

I'm comfortable adding this to the docs, though. I'll add a bullet to the tips page, and I'll link to that from the .execute method of comdb2.dbapi2.Cursor and comdb2.cdb2.Handle.

@godlygeek
Copy link
Contributor

godlygeek commented Feb 18, 2025

This also needs to escape any \ in the input text. I think it ought to be either:

return text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")

or

return re.sub(r"(?=[\\_%])", r"\\", text)

or

return re.sub(r"([\\_%])", r"\\\1", text)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants