From bf348a22fc04fc7fc17674b6c3533b7d62b01ad0 Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Tue, 8 Sep 2026 21:12:23 -0700 Subject: [PATCH] Escape LIKE metacharacters in FTS detection --- datasette/utils/__init__.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/datasette/utils/__init__.py b/datasette/utils/__init__.py index 47e3be27..14f40f7e 100644 --- a/datasette/utils/__init__.py +++ b/datasette/utils/__init__.py @@ -829,13 +829,14 @@ def detect_fts(conn, table): def detect_fts_sql(table): + escaped_table = table.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") return ( r""" select name from sqlite_master where rootpage = 0 and ( - sql like :fts_double_quoted - or sql like :fts_bracket_quoted + sql like :fts_double_quoted escape char(92) + or sql like :fts_bracket_quoted escape char(92) or ( tbl_name = :table and sql like '%VIRTUAL TABLE%USING FTS%' @@ -843,8 +844,8 @@ def detect_fts_sql(table): ) """, { - "fts_double_quoted": f'%VIRTUAL TABLE%USING FTS%content="{table}"%', - "fts_bracket_quoted": f"%VIRTUAL TABLE%USING FTS%content=[{table}]%", + "fts_double_quoted": f'%VIRTUAL TABLE%USING FTS%content="{escaped_table}"%', + "fts_bracket_quoted": f"%VIRTUAL TABLE%USING FTS%content=[{escaped_table}]%", "table": table, }, )