Skip to content

sqlite3.Connection.iterdump() can lose AUTOINCREMENT counters after a temporary table is dropped #162646

Backlog

Description

@limadog9

Bug report

Restoring a database from Connection.iterdump() can cause an AUTOINCREMENT table to reuse a previously issued ID. This happens even when the temporary table that triggered the problem had a different name and was dropped before the dump.

import sqlite3

source = sqlite3.connect(":memory:")
source.executescript("""
    CREATE TABLE invoices(id INTEGER PRIMARY KEY AUTOINCREMENT);
    INSERT INTO invoices DEFAULT VALUES;
    INSERT INTO invoices DEFAULT VALUES;
    DELETE FROM invoices WHERE id = 2;

    CREATE TEMP TABLE staging(id INTEGER PRIMARY KEY AUTOINCREMENT);
    DROP TABLE temp.staging;
""")

restored = sqlite3.connect(":memory:")
restored.executescript("\n".join(source.iterdump()))

for db in (source, restored):
    print(db.execute("INSERT INTO invoices DEFAULT VALUES").lastrowid)

Expected: both inserts allocate ID 3.
Actual: the source allocates ID 3 and the restored database reuses ID 2.

Before the insert, both databases contain only invoice 1 and both pass PRAGMA integrity_check. A copy made with Connection.backup() correctly allocates ID 3. Removing the two staging-table statements also makes the SQL restore allocate ID 3.

Creating the temporary table leaves an empty temp.sqlite_sequence behind after the table is dropped. In Lib/sqlite3/dump.py, SELECT * FROM "sqlite_sequence" resolves to that temporary table. The dump consequently emits DELETE FROM "sqlite_sequence" without the INSERT that would restore the ('invoices', 2) counter. Qualifying the source query as main.sqlite_sequence fixes this reproducer.

CPython versions tested on:

3.12, 3.13, 3.14, 3.15, 3.16, CPython main branch

Operating systems tested on:

Linux

Activity

  1. added
    type-bug
    on Nov 25, 2026
  2. added
    stdlib
    on Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibtopic-sqlite3type-bug

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions