| 1 |
import os |
| 2 |
import sqlite3 |
| 3 |
from pathlib import Path |
| 4 |
from contextlib import suppress, closing |
| 5 |
from collections.abc import MutableMapping |
| 6 |
|
| 7 |
BUILD_TABLE = """ |
| 8 |
CREATE TABLE IF NOT EXISTS Dict ( |
| 9 |
key BLOB UNIQUE NOT NULL, |
| 10 |
value BLOB NOT NULL |
| 11 |
) |
| 12 |
""" |
| 13 |
GET_SIZE = "SELECT COUNT (key) FROM Dict" |
| 14 |
LOOKUP_KEY = "SELECT value FROM Dict WHERE key = CAST(? AS BLOB)" |
| 15 |
STORE_KV = "REPLACE INTO Dict (key, value) VALUES (CAST(? AS BLOB), CAST(? AS BLOB))" |
| 16 |
DELETE_KEY = "DELETE FROM Dict WHERE key = CAST(? AS BLOB)" |
| 17 |
ITER_KEYS = "SELECT key FROM Dict" |
| 18 |
|
| 19 |
|
| 20 |
class error(OSError): |
| 21 |
pass |
| 22 |
|
| 23 |
|
| 24 |
_ERR_CLOSED = "DBM object has already been closed" |
| 25 |
_ERR_REINIT = "DBM object does not support reinitialization" |
| 26 |
|
| 27 |
|
| 28 |
def _normalize_uri(path): |
| 29 |
path = Path(path) |
| 30 |
uri = path.absolute().as_uri() |
| 31 |
while "//" in uri: |
| 32 |
uri = uri.replace("//", "/") |
| 33 |
return uri |
| 34 |
|
| 35 |
|
| 36 |
class _Database(MutableMapping): |
| 37 |
|
| 38 |
def __init__(self, path, /, *, flag, mode): |
| 39 |
if hasattr(self, "_cx"): |
| 40 |
raise error(_ERR_REINIT) |
| 41 |
|
| 42 |
path = os.fsdecode(path) |
| 43 |
match flag: |
| 44 |
case "r": |
| 45 |
flag = "ro" |
| 46 |
case "w": |
| 47 |
flag = "rw" |
| 48 |
case "c": |
| 49 |
flag = "rwc" |
| 50 |
Path(path).touch(mode=mode, exist_ok=True) |
| 51 |
case "n": |
| 52 |
flag = "rwc" |
| 53 |
Path(path).unlink(missing_ok=True) |
| 54 |
Path(path).touch(mode=mode) |
| 55 |
case _: |
| 56 |
raise ValueError("Flag must be one of 'r', 'w', 'c', or 'n', " |
| 57 |
f"not {flag!r}") |
| 58 |
|
| 59 |
# We use the URI format when opening the database. |
| 60 |
uri = _normalize_uri(path) |
| 61 |
uri = f"{uri}?mode={flag}" |
| 62 |
if flag == "ro": |
| 63 |
# Add immutable=1 to allow read-only SQLite access even if wal/shm missing |
| 64 |
uri += "&immutable=1" |
| 65 |
|
| 66 |
try: |
| 67 |
self._cx = sqlite3.connect(uri, autocommit=True, uri=True) |
| 68 |
except sqlite3.Error as exc: |
| 69 |
raise error(str(exc)) |
| 70 |
|
| 71 |
if flag != "ro": |
| 72 |
# This is an optimization only; it's ok if it fails. |
| 73 |
with suppress(sqlite3.OperationalError): |
| 74 |
self._cx.execute("PRAGMA journal_mode = wal") |
| 75 |
|
| 76 |
if flag == "rwc": |
| 77 |
self._execute(BUILD_TABLE) |
| 78 |
|
| 79 |
def _execute(self, *args, **kwargs): |
| 80 |
if not self._cx: |
| 81 |
raise error(_ERR_CLOSED) |
| 82 |
try: |
| 83 |
return closing(self._cx.execute(*args, **kwargs)) |
| 84 |
except sqlite3.Error as exc: |
| 85 |
raise error(str(exc)) |
| 86 |
|
| 87 |
def __len__(self): |
| 88 |
with self._execute(GET_SIZE) as cu: |
| 89 |
row = cu.fetchone() |
| 90 |
return row[0] |
| 91 |
|
| 92 |
def __getitem__(self, key): |
| 93 |
with self._execute(LOOKUP_KEY, (key,)) as cu: |
| 94 |
row = cu.fetchone() |
| 95 |
if not row: |
| 96 |
raise KeyError(key) |
| 97 |
return row[0] |
| 98 |
|
| 99 |
def __setitem__(self, key, value): |
| 100 |
self._execute(STORE_KV, (key, value)) |
| 101 |
|
| 102 |
def __delitem__(self, key): |
| 103 |
with self._execute(DELETE_KEY, (key,)) as cu: |
| 104 |
if not cu.rowcount: |
| 105 |
raise KeyError(key) |
| 106 |
|
| 107 |
def __iter__(self): |
| 108 |
try: |
| 109 |
with self._execute(ITER_KEYS) as cu: |
| 110 |
for row in cu: |
| 111 |
yield row[0] |
| 112 |
except sqlite3.Error as exc: |
| 113 |
raise error(str(exc)) |
| 114 |
|
| 115 |
def close(self): |
| 116 |
if self._cx: |
| 117 |
self._cx.close() |
| 118 |
self._cx = None |
| 119 |
|
| 120 |
def keys(self): |
| 121 |
return list(super().keys()) |
| 122 |
|
| 123 |
def __enter__(self): |
| 124 |
return self |
| 125 |
|
| 126 |
def __exit__(self, *args): |
| 127 |
self.close() |
| 128 |
|
| 129 |
|
| 130 |
def open(filename, /, flag="r", mode=0o666): |
| 131 |
"""Open a dbm.sqlite3 database and return the dbm object. |
| 132 |
|
| 133 |
The 'filename' parameter is the name of the database file. |
| 134 |
|
| 135 |
The optional 'flag' parameter can be one of ...: |
| 136 |
'r' (default): open an existing database for read only access |
| 137 |
'w': open an existing database for read/write access |
| 138 |
'c': create a database if it does not exist; open for read/write access |
| 139 |
'n': always create a new, empty database; open for read/write access |
| 140 |
|
| 141 |
The optional 'mode' parameter is the Unix file access mode of the database; |
| 142 |
only used when creating a new database. Default: 0o666. |
| 143 |
""" |
| 144 |
return _Database(filename, flag=flag, mode=mode) |