def convert_to_sql_wildcards(pattern, sql_escape='|'):
    """Converts wildcards '*' and '?' to SQL versions '%' and '_'.
       A state machine is used to allow for using the backslash to
       escape this characters:
            t\\e\\s\\t -> test
            test -> test
            test* -> test%
            test\\* -> test*
            test\\\\* -> test\\%
            test\\\\\\* -> test\\*
            test\\\\\\\\* -> test\\\\%
            test\\\\\\\\\\* -> test\\\\*
            % -> \\%
            _ -> \\_
            test_test% -> test\\_test\\%
            test__test% -> test\\_\\_test\\%
            test\\_test\\% -> test\\_test\\%
            test\\\\_test\\\\% -> test\\\\_test\\\\%
            test\\\\\\_test\\\\\\% -> test\\\\_test\\\\%
            test\\\\\\\\_test\\\\\\% -> test\\\\\\_test\\\\%
    """
    pat = ''
    esc = False
    for p in pattern:
        if p not in '*?\\':
            esc = False
            if p in '%_':
                pat += sql_escape
            pat += p
        elif esc:
            esc = False
            pat += p
        elif p == '\\':
            esc = True
        elif p == '*':
            pat += '%'
        elif p == '?':
            pat += '_'
    return pat
