Postgres → DuckDB/SQLite: LIKE patterns with backslash escapes match different rows
What's wrong?
Postgres uses backslash as the default escape character in LIKE patterns. For example, 'stg\_%' matches strings starting with stg_.
DuckDB and SQLite don't have a default escape character, so they treat the backslash literally. Right now, sqlglot keeps the pattern unchanged when translating between these dialects, which can silently give different results without any error.
How to reproduce
import duckdb, sqlglot
sql = r"SELECT name, name LIKE 'stg\_%' AS m FROM (VALUES ('stg_orders'), ('stgxorders')) AS t(name) ORDER BY name"
out = sqlglot.transpile(sql, read="postgres", write="duckdb")[0]
print(out)
print(duckdb.sql(out).fetchall())
# [('stg_orders', False), ('stgxorders', False)]
# Postgres: [('stg_orders', True), ('stgxorders', False)]
sql = r"SELECT path LIKE 'C:\%' FROM (VALUES ('C:\temp')) AS t(path)"
print(duckdb.sql(sql).fetchall()) # [(True,)]
print(sqlglot.transpile(sql, read="duckdb", write="postgres")[0])
# unchanged, and Postgres returns false
Tested with sqlglot main, DuckDB 2.0.0, and Postgres 16.
Expected behavior
When translating from Postgres to DuckDB or SQLite, sqlglot should add ESCAPE '\' if the pattern contains a backslash. I tested this and it gives the same results as Postgres.
For DuckDB → Postgres, it should add ESCAPE '' to keep the original behavior.
Other notes
I also noticed the same problem with Postgres → SQLite and with NOT LIKE, where the results are reversed.
I saw the recent BigQuery LIKE ... ESCAPE fix (#9095), but this seems a bit different since it's about the default escape behavior rather than an explicit escape.
Happy to contribute
I'm happy to work on a PR for this. Would it make sense to track each dialect's default LIKE escape character, or would you prefer a different approach?
AI usage
I used an AI assistant to help identify and investigate the issue, and I verified the behavior with the tests above.