Forge
pythonf8555a15
1"""Public database API."""
2
3from __future__ import annotations
4
5from collections.abc import Iterator
6from contextlib import contextmanager
7from typing import Literal
8
9from pywitdb.exceptions import BridgeNotAvailableError, WitDbStoreError
10
11Backend = Literal["bridge", "auto", "native"]
12
13
14class Database:
15 """Handle to an open `.witdb` store."""
16
17 def get(self, key: bytes) -> bytes | None:
18 raise NotImplementedError
19
20 def put(self, key: bytes, value: bytes) -> None:
21 raise NotImplementedError
22
23 def delete(self, key: bytes) -> bool:
24 raise NotImplementedError
25
26 @contextmanager
27 def transaction(self) -> Iterator[None]:
28 raise NotImplementedError
29
30 def close(self) -> None:
31 return None
32
33 def __enter__(self) -> Database:
34 return self
35
36 def __exit__(self, *exc: object) -> None:
37 self.close()
38
39
40def open(
41 path: str,
42 *,
43 password: str | None = None,
44 backend: Backend = "auto",
45 create: bool = True,
46) -> Database:
47 """Open a WitDatabase store at `path`."""
48 if backend in ("native", "auto"):
49 try:
50 from pywitdb._native.db import native_available, open_native
51
52 if native_available():
53 return open_native(path, password=password, create=create)
54 except WitDbStoreError:
55 if backend == "native":
56 raise
57 except OSError as exc:
58 if backend == "native":
59 raise WitDbStoreError(str(exc)) from exc
60
61 if backend == "native":
62 raise WitDbStoreError(
63 "native backend unavailable; build witdb.dll or set WITDB_NATIVE_PATH"
64 )
65
66 try:
67 from pywitdb._bridge.client import bridge_available
68 from pywitdb._bridge.db import open_bridge
69
70 if bridge_available():
71 return open_bridge(path, password=password, create=create)
72 except WitDbStoreError:
73 raise
74 except OSError as exc:
75 raise BridgeNotAvailableError(str(exc)) from exc
76
77 if backend == "bridge":
78 raise BridgeNotAvailableError(
79 "witdb-bridge not found; build bridge/WitDbBridge or set WITDB_BRIDGE_PATH"
80 )
81
82 raise BridgeNotAvailableError(
83 "no backend available: native lib missing and witdb-bridge not found"
84 )
85
View only · write via MCP/CIDE