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