From 9e125eee6af7b9d84f7fc32f640c2df7e4c44fa7 Mon Sep 17 00:00:00 2001 From: Vikash Date: Thu, 26 Nov 2026 03:36:27 +0000 Subject: [PATCH] fix(sqlite3): preserve AUTOINCREMENT counters in iterdump() (gh-162646) --- Lib/sqlite3/dump.py | 2 +- Lib/test/test_sqlite3/test_dump.py | 20 +++++++++++++++++++ ...-11-26-09-05-00.gh-issue-162646.Vk7Qp2.rst | 4 ++++ 3 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2026-11-26-09-05-00.gh-issue-162646.Vk7Qp2.rst diff --git a/Lib/sqlite3/dump.py b/Lib/sqlite3/dump.py index 95e14a6655ef172..f55b79a4d371a3b 100644 --- a/Lib/sqlite3/dump.py +++ b/Lib/sqlite3/dump.py @@ -57,7 +57,7 @@ def _iterdump(connection, *, filter=None): sqlite_sequence = [] for table_name, type, sql in schema_res.fetchall(): if table_name == 'sqlite_sequence': - rows = cu.execute('SELECT * FROM "sqlite_sequence";') + rows = cu.execute('SELECT * FROM main."sqlite_sequence";') sqlite_sequence = ['DELETE FROM "sqlite_sequence"'] sqlite_sequence += [ f'INSERT INTO "sqlite_sequence" VALUES({_quote_value(table_name)},{seq_value})' diff --git a/Lib/test/test_sqlite3/test_dump.py b/Lib/test/test_sqlite3/test_dump.py index 7841b610cd222a7..dfb127986e65a97 100644 --- a/Lib/test/test_sqlite3/test_dump.py +++ b/Lib/test/test_sqlite3/test_dump.py @@ -189,6 +189,26 @@ def test_dump_autoincrement_create_new_db(self): rows = res.fetchall() self.assertEqual(rows[0][0], seq) + def test_dump_autoincrement_with_temp_table(self): + # gh-162646: a dropped temporary AUTOINCREMENT table leaves an empty + # temp.sqlite_sequence behind, which must not shadow the main one. + self.cu.executescript("\n".join([ + "CREATE TABLE t1 (id INTEGER PRIMARY KEY AUTOINCREMENT);", + "INSERT INTO t1 DEFAULT VALUES;", + "INSERT INTO t1 DEFAULT VALUES;", + "DELETE FROM t1 WHERE id = 2;", + "CREATE TEMP TABLE staging (id INTEGER PRIMARY KEY AUTOINCREMENT);", + "DROP TABLE temp.staging;", + ])) + + dump = "\n".join(self.cx.iterdump()) + self.assertEqual( + self.cu.execute("INSERT INTO t1 DEFAULT VALUES").lastrowid, 3) + with memory_database() as cx2: + cx2.executescript(dump) + self.assertEqual( + cx2.execute("INSERT INTO t1 DEFAULT VALUES").lastrowid, 3) + def test_unorderable_row(self): # iterdump() should be able to cope with unorderable row types (issue #15545) class UnorderableRow: diff --git a/Misc/NEWS.d/next/Library/2026-11-26-09-05-00.gh-issue-162646.Vk7Qp2.rst b/Misc/NEWS.d/next/Library/2026-11-26-09-05-00.gh-issue-162646.Vk7Qp2.rst new file mode 100644 index 000000000000000..bd0c39aedde6109 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-26-09-05-00.gh-issue-162646.Vk7Qp2.rst @@ -0,0 +1,4 @@ +Fix :meth:`sqlite3.Connection.iterdump` to preserve ``AUTOINCREMENT`` +counters when a temporary table with an ``AUTOINCREMENT`` column was created +and dropped: the ``sqlite_sequence`` query now explicitly reads the ``main`` +database instead of a leftover empty ``temp.sqlite_sequence`` table.