diff --git a/Lib/sqlite3/_completer.py b/Lib/sqlite3/_completer.py index ba580f968bf92dc..a5339b0c999fddd 100644 --- a/Lib/sqlite3/_completer.py +++ b/Lib/sqlite3/_completer.py @@ -11,6 +11,11 @@ _completion_matches = [] +def _quote_schema(schema): + # Quote an SQLite identifier, doubling embedded double quotes. + return '"' + schema.replace('"', '""') + '"' + + def _complete(con, text, state): global _completion_matches @@ -32,7 +37,7 @@ def _complete(con, text, state): # escape '_' which can appear in attached database names select_clauses = ( f"""\ - SELECT name || ' ' FROM \"{schema}\".sqlite_master + SELECT name || ' ' FROM {_quote_schema(schema)}.sqlite_master WHERE name LIKE REPLACE(:text, '_', '^_') || '%' ESCAPE '^'""" for schema in schemata ) @@ -46,8 +51,8 @@ def _complete(con, text, state): try: select_clauses = ( f"""\ - SELECT pti.name || ' ' FROM "{schema}".sqlite_master AS sm - JOIN pragma_table_xinfo(sm.name,'{schema}') AS pti + SELECT pti.name || ' ' FROM {_quote_schema(schema)}.sqlite_master AS sm + JOIN pragma_table_xinfo(sm.name,{_quote_schema(schema)}) AS pti WHERE sm.type='table' AND pti.name LIKE REPLACE(:text, '_', '^_') || '%' ESCAPE '^'""" for schema in schemata diff --git a/Lib/test/test_sqlite3/test_completer.py b/Lib/test/test_sqlite3/test_completer.py new file mode 100644 index 000000000000000..578c835ab8f119f --- /dev/null +++ b/Lib/test/test_sqlite3/test_completer.py @@ -0,0 +1,19 @@ +import sqlite3 +import unittest +from sqlite3 import _completer + + +class CompleterTests(unittest.TestCase): + def test_schema_with_double_quote(self): + con = sqlite3.connect(':memory:') + self.addCleanup(con.close) + con.execute('ATTACH DATABASE \':memory:\' AS \'weird"name\'') + matches = [] + state = 0 + while True: + match = _completer._complete(con, 'a', state) + if match is None: + break + matches.append(match) + state += 1 + self.assertTrue(matches) diff --git a/Misc/NEWS.d/next/Library/2026-09-26-12-34-38.gh-issue-158215.AbCdEf.rst b/Misc/NEWS.d/next/Library/2026-09-26-12-34-38.gh-issue-158215.AbCdEf.rst new file mode 100644 index 000000000000000..16bd3c4e8c8d94d --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-09-26-12-34-38.gh-issue-158215.AbCdEf.rst @@ -0,0 +1,2 @@ +Fix :mod:`sqlite3` completer to handle attached database names +containing a double quote. Patch by Tony Leung.