python / python/cpython

sqlite3 - file stays opened even after connection is closed (still opened by the cursor?)

Offen
#135,117 6 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

docs OS-windows topic-sqlite3 type-bug
Vorherrschende Sprache
Python
Sterne
77.2k
Forks
35.9k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug report

Bug description:

Python 3.11.9

Consider the snippet below.
It creates a new sqlite database, then closing the connection to it and trying to delete the file. On Windows it fails since sqlite file is still used by Python.

It seems the created cursor is still using the file, though all connections to it are closed.
Which is kind of unexpected, since when you close the connection to the database, connection object and all cursors are effectively become dead and they cannot be reopened, so nothing should be still using the file after connection is closed.

What helps is to close cursor explicitly (c.close() or just delete it del c).

Another detail - if we create a table, but don't insert anything to it, issue doesn't occur.

from pathlib import Path
import sqlite3

db_path = Path("new_db.sqlite")
if db_path.exists():
    db_path.unlink()

db = sqlite3.connect(db_path)
c = db.cursor()
c.execute("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)")

# Commenting out resolves the issue.
c.executemany("INSERT INTO test (value) VALUES (?)", [(f"value_{i}",) for i in range(1000)])

db.commit()
# c.close() # Required to avoid the error.
db.close()

# PermissionError:
# [WinError 32] The process cannot access the file because it is being used by another process: 'new_db.sqlite'
db_path.unlink()
CPython versions tested on:

3.11

Operating systems tested on:

Windows

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Es ist weder eine Repository-Datei noch ein Test angegeben. Beginne damit, den Windows-Reproducer auszuführen und das Verhalten mit und ohne c.close() zu vergleichen; verfolge anschließend den Lebenszyklus von sqlite3-Cursor und -Verbindung. Als abgeschlossen gilt die Ermittlung des vorgesehenen Verhaltens des Datei-Handles nach dem Schließen sowie das Hinzufügen oder Aktualisieren der Abdeckung, sodass der gemeldete Fall der Löschung behoben oder dokumentiert ist.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python, sqlite
Bereich
databases
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
38/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.