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 12 commits into
base: main
Choose a base branch
from

Conversation

GeneralK1ng
Copy link

@GeneralK1ng GeneralK1ng commented Jun 16, 2025

What

This PR adds the SQLite URI parameter immutable=1 when opening a database in read-only mode in Lib/dbm/sqlite3.py. This explicitly informs SQLite that the database is read-only and avoids attempts to create or write to auxiliary WAL/SHM files.

Why

Without this flag, opening a read-only SQLite database may fail with errors such as "unable to open database file" when the WAL or SHM files cannot be created due to filesystem permissions or other restrictions. This is especially common when the database file is read-only and the environment prevents creation of additional files.

Adding immutable=1 allows SQLite to operate correctly without needing to create WAL/SHM files, thus preventing these errors.

Where

The change is made in the _Database.__init__ constructor in Lib/dbm/sqlite3.py. The URI used to open the database connection is appended with &immutable=1 only if the flag is "ro" (read-only).

Related issue

#135386


This is my first contribution to CPython. I appreciate the opportunity and look forward to feedback from the community. Thank you!

@python-cla-bot
Copy link

python-cla-bot bot commented Jun 16, 2025

All commit authors signed the Contributor License Agreement.

CLA signed

@bedevere-app
Copy link

bedevere-app bot commented Jun 16, 2025

Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply the skip news label instead.

Copy link
Member

@ZeroIntensity ZeroIntensity left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a test case. You can refer to the devguide for how to do that.

@GeneralK1ng GeneralK1ng force-pushed the fix-issue-135386 branch 2 times, most recently from 707f4a3 to 779faf2 Compare June 17, 2025 04:53
@ZeroIntensity
Copy link
Member

No need to force-push, we squash at the end.

@GeneralK1ng
Copy link
Author

No need to force-push, we squash at the end.

Got it, thanks for the reminder!

@ZeroIntensity
Copy link
Member

FYI, tests are failing on Windows.

@GeneralK1ng
Copy link
Author

FYI, tests are failing on Windows.

Thanks for the suggestion. I've skipped the test on Windows using @unittest.skipIf(sys.platform.startswith("win"), ...) because of platform differences in file permissions and locking behavior that caused the test to fail in CI. Should be good now!

Copy link
Member

@tomasr8 tomasr8 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR!

I've skipped the test on Windows

I think we should be testing this on all platforms if possible. Maybe we can figure out why the test is failing on Windows and adapt it?

GeneralK1ng and others added 2 commits June 23, 2025 21:38
Co-authored-by: Tomas R. <tomas.roun8@gmail.com>
Co-authored-by: Tomas R. <tomas.roun8@gmail.com>
@GeneralK1ng
Copy link
Author

I think we should be testing this on all platforms if possible. Maybe we can figure out why the test is failing on Windows and adapt it?

Sure, that makes sense — I'd be happy to look into making the test work on Windows as well.
For now, I'm developing on macOS and don't have a Windows environment set up yet.
Once I'm back home and can test on my Windows machine, I'd be glad to revisit this.

Also, thanks for the suggestions — I've adopted the URI change and simplified the flag check as suggested. : )

@GeneralK1ng
Copy link
Author

I think we should be testing this on all platforms if possible. Maybe we can figure out why the test is failing on Windows and adapt it?

I've updated the test so it no longer skips on Windows — instead, it now explicitly closes the database before setting read-only permissions, and restores the original permissions after the test.
This should work more reliably across platforms, including Windows.
Let me know if you'd suggest any further adjustments!

@tomasr8 tomasr8 self-requested a review June 23, 2025 17:45
Comment on lines 94 to 115
def test_readonly_open_without_wal_shm(self):
wal_path = self.filename + "-wal"
shm_path = self.filename + "-shm"

for suffix in wal_path, shm_path:
os_helper.unlink(suffix)

try:
self.db.close()
except Exception:
pass

os.chmod(self.filename, stat.S_IREAD)

db = dbm_sqlite3.open(self.filename, "r")
try:
self.assertEqual(db[b"key1"], b"value1")
self.assertEqual(db[b"key2"], b"value2")
finally:
db.close()

os.chmod(self.filename, stat.S_IWRITE)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIUC correctly, this change makes it so that the WAL/SHM files are no longer created in read-only mode? In that case, we could simplify the test to simply open the database in read-only mode and check that the auxiliary files are not written. I'm thinking something like this:

class Immutable(unittest.TestCase):
    def setUp(self):
        self.filename = os_helper.TESTFN
        self.db = dbm_sqlite3.open(self.filename, "r")

    def tearDown(self):
        self.db.close()

    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))

Or does this also affect the database file itself? i.e. does passing immutable=1 allow opening read-only files whereas otherwise it would be impossible?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I’ve replaced the original test with your suggested version in a new Immutable test class. It’s much cleaner and focused.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or does this also affect the database file itself? i.e. does passing immutable=1 allow opening read-only files whereas otherwise it would be impossible?

Yes, exactly — without immutable=1, even in mode=ro, SQLite may still attempt operations that require write access (like writing lock files or checking for journal/WAL state), and will fail if the database file is read-only or in a read-only directory.

Passing immutable=1 tells SQLite to treat the database as entirely static and read-only, which avoids those operations and allows the file to be opened successfully even with 0444 permissions or from a read-only mount.

@toslunar
Copy link

In order to use immutable=1, we must assert the DB will not be overwritten (by other jobs). Maybe dbm.open needs a new flag beyond 'r' to indicate the immutability.

https://www.sqlite.org/uri.html#recognized_query_parameters says

immutable=1
The immutable query parameter is a boolean that signals to SQLite that the underlying database file is held on read-only media and cannot be modified, even by another process with elevated privileges. SQLite always opens immutable database files read-only and it skips all file locking and change detection on immutable database files. If this query parameter (or the SQLITE_IOCAP_IMMUTABLE bit in xDeviceCharacteristics) asserts that a database file is immutable and that file changes anyhow, then SQLite might return incorrect query results and/or SQLITE_CORRUPT errors.

@GeneralK1ng
Copy link
Author

In order to use immutable=1, we must assert the DB will not be overwritten (by other jobs). Maybe dbm.open needs a new flag beyond 'r' to indicate the immutability.

That's a good point — I agree immutable=1 should only be used when it's safe to assume the file won’t be modified by other processes.

That said, in the context of dbm.open(..., 'r'), the user's intent is already explicitly read-only, and the module is not designed for concurrent writes across processes.

The use of immutable=1 here makes the 'r' mode work reliably in environments where the DB file is marked read-only or resides in a read-only filesystem — where the connection would otherwise fail due to WAL/journal setup.

If needed, we could consider adding a separate flag like 'ri' in the future for stricter use cases, but I think using immutable=1 under 'r' is a reasonable default for now.

@GeneralK1ng GeneralK1ng requested a review from tomasr8 July 2, 2025 12:26
Copy link
Member

@serhiy-storchaka serhiy-storchaka left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for your PR @GeneralK1ng. I have some notes about the test.

It does not actually test the database file is in a read-only directory. I suggest to create a directory, then create a database in that directory, then make both the directory readonly, then try to open and use it. You can also add a test that tries to open it in read-write mode to check how this fails. You can also add tests that make the database file itself readonly instead of the directory. Use os_helper.rmtree() for cleanup.

@GeneralK1ng
Copy link
Author

You can also add a test that tries to open it in read-write mode to check how this fails. You can also add tests that make the database file itself readonly instead of the directory. Use os_helper.rmtree() for cleanup.

Thanks a lot for the detailed and thoughtful feedback, your suggestions make perfect sense and I really appreciate the guidance on improving the test coverage.

I'm currently a bit tied up and might not be able to get to it in the next couple of days, but I’ll follow up soon and revise the tests as suggested.

@GeneralK1ng
Copy link
Author

You can also add tests that make the database file itself readonly instead of the directory. Use os_helper.rmtree() for cleanup.

Thanks for the detailed suggestions! I’ve replaced the previous test with new ones that explicitly test:

  • Opening a db file inside a read-only directory (success with 'r', fail with 'w')
  • Opening a db file marked as read-only

Let me know if there’s anything else I can adjust.

Copy link
Member

@serhiy-storchaka serhiy-storchaka left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for your update @GeneralK1ng. Here is a new batch of comments.

@toslunar
Copy link

toslunar commented Jul 9, 2025

That said, in the context of dbm.open(..., 'r'), the user's intent is already explicitly read-only, and the module is not designed for concurrent writes across processes.

Isn't it a restriction of shelve? I couldn't find a doc that says the dbm module does not support concurrent accesses.
https://docs.python.org/3/library/shelve.html#restrictions

@GeneralK1ng
Copy link
Author

Isn't it a restriction of shelve? I couldn't find a doc that says the dbm module does not support concurrent accesses.

You're right — the restriction on concurrent access is explicitly stated in shelve, not dbm.

My use of immutable=1 is mainly to ensure that shelve.open(..., 'r') can work reliably on a read-only file or in a read-only directory, since otherwise SQLite may still attempt to create WAL/SHM files or acquire locks and fail.

The patch doesn’t try to enforce concurrency restrictions at the dbm level, but just ensures compatibility with shelve's expected read-only semantics.

@GeneralK1ng
Copy link
Author

I skip the tests that check for 'w' mode failure in read-only directories without WAL/SHM. On Windows and Linux, SQLite appears to fall back gracefully and allows writing to the database even without those files. @serhiy-storchaka

@serhiy-storchaka
Copy link
Member

One thing puzzles me -- why these changes affect the result of the last two tests? They only affect the reading mode, right? But on Linux, attempt to change the DB in a read-only directory raises "dbm.sqlite3.error: attempt to write a readonly database" in main, and don't raise any exception on this PR code. I don't understand this.

cc @erlend-aasland

@toslunar
Copy link

toslunar commented Jul 10, 2025

https://www.sqlite.org/wal.html#persistence_of_wal_mode

Unlike the other journaling modes, PRAGMA journal_mode=WAL is persistent.

https://www.sqlite.org/wal.html#readonly

On newer versions of SQLite, a WAL-mode database on read-only media, or a WAL-mode database that lacks write permission, can still be read as long as one or more of the following conditions are met:

  1. The -shm and -wal files already exist and are readable.
  2. There is write permission on the directory containing the database so that the -shm and -wal files can be created.
  3. The database connection is opened using the immutable query parameter.

@serhiy-storchaka
Copy link
Member

It seems that I missed something, but is not the SQLite database only opened in read-write mode in these tests? And is not this PR only affects opening in read-only mode?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy