python / python/cpython

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

未關閉
#135,117 6 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

docs OS-windows topic-sqlite3 type-bug
主要語言
Python
星號
77.2k
分支
35.9k
PR 合併指標
PR 指標待擷取

描述

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

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

未指定任何儲存庫檔案或測試。首先執行 Windows 重現程式,並比較有無 c.close() 時的行為,然後追蹤 sqlite3 游標和連線的生命週期。完成的標準是確立關閉後檔案控制代碼的預期行為,並新增或更新涵蓋範圍,使回報的刪除案例獲得解決或記錄。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
python, sqlite
領域
databases
Issue 類型
缺陷
難度
4/5
預估耗時
3-5 天
活躍度
停滯
描述清晰度
基本清楚
新手友好度
38/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。