Skip to content

gh-135386: Fix "unable to open database file" errors on readonly DB #135566

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
12 changes: 8 additions & 4 deletions Lib/dbm/sqlite3.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,18 +60,22 @@ def __init__(self, path, /, *, flag, mode):
# We use the URI format when opening the database.
uri = _normalize_uri(path)
uri = f"{uri}?mode={flag}"
if flag == "ro":
# Add immutable=1 to allow read-only SQLite access even if wal/shm missing
uri += "&immutable=1"

try:
self._cx = sqlite3.connect(uri, autocommit=True, uri=True)
except sqlite3.Error as exc:
raise error(str(exc))

# This is an optimization only; it's ok if it fails.
with suppress(sqlite3.OperationalError):
self._cx.execute("PRAGMA journal_mode = wal")
if flag != "ro":
with suppress(sqlite3.OperationalError):
self._cx.execute("PRAGMA journal_mode = OFF")

if flag == "rwc":
self._execute(BUILD_TABLE)
if flag == "rwc":
self._execute(BUILD_TABLE)

def _execute(self, *args, **kwargs):
if not self._cx:
Expand Down
25 changes: 25 additions & 0 deletions Lib/test/test_dbm_sqlite3.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
import sys
import unittest
from contextlib import closing
Expand Down Expand Up @@ -89,6 +90,30 @@ def test_readonly_keys(self):
def test_readonly_iter(self):
self.assertEqual([k for k in self.db], [b"key1", b"key2"])

class Immutable(unittest.TestCase):
def setUp(self):
self.filename = os_helper.TESTFN

db = dbm_sqlite3.open(self.filename, "c")
db[b"key"] = b"value"
db.close()

self.db = dbm_sqlite3.open(self.filename, "r")

def tearDown(self):
self.db.close()
for suffix in "", "-wal", "-shm":
os_helper.unlink(self.filename + suffix)

def test_readonly_open_without_wal_shm(self):
wal_path = self.filename + "-wal"
shm_path = self.filename + "-shm"

self.assertFalse(os.path.exists(wal_path))
self.assertFalse(os.path.exists(shm_path))

self.assertEqual(self.db[b"key"], b"value")


class ReadWrite(_SQLiteDbmTests):

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix :exc:`sqlite3.OperationalError` error when using :func:`dbm.open` with a read-only file object.
Loading