def sql_esc(pattern):
    """ Apply SQLite escaping, if needed. Returns pattern and esc. """
    esc = ''
    if "_" in pattern or "%" in pattern:
        esc = ' ESCAPE "!"'
        pattern = pattern.replace("!", "!!")
        pattern = pattern.replace("%", "!%")
        pattern = pattern.replace("_", "!_")
    return (pattern, esc)