glyff-sqlite 0.12.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- glyff_sqlite-0.12.0/.gitignore +12 -0
- glyff_sqlite-0.12.0/LICENSE +21 -0
- glyff_sqlite-0.12.0/PKG-INFO +106 -0
- glyff_sqlite-0.12.0/README.md +67 -0
- glyff_sqlite-0.12.0/pyproject.toml +43 -0
- glyff_sqlite-0.12.0/src/glyff_sqlite/__init__.py +7 -0
- glyff_sqlite-0.12.0/src/glyff_sqlite/_sqlite_client.py +333 -0
- glyff_sqlite-0.12.0/src/glyff_sqlite/_sqlite_store.py +218 -0
- glyff_sqlite-0.12.0/src/glyff_sqlite/_transaction.py +54 -0
- glyff_sqlite-0.12.0/src/glyff_sqlite/tests/conftest.py +31 -0
- glyff_sqlite-0.12.0/src/glyff_sqlite/tests/test_sqlite_parallel_durability.py +78 -0
- glyff_sqlite-0.12.0/src/glyff_sqlite/tests/test_sqlite_session_store.py +456 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 nueruyu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: glyff-sqlite
|
|
3
|
+
Version: 0.12.0
|
|
4
|
+
Summary: SQLite-backed durable SessionStore for glyff.
|
|
5
|
+
License: MIT License
|
|
6
|
+
|
|
7
|
+
Copyright (c) 2026 nueruyu
|
|
8
|
+
|
|
9
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
10
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
11
|
+
in the Software without restriction, including without limitation the rights
|
|
12
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
13
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
14
|
+
furnished to do so, subject to the following conditions:
|
|
15
|
+
|
|
16
|
+
The above copyright notice and this permission notice shall be included in all
|
|
17
|
+
copies or substantial portions of the Software.
|
|
18
|
+
|
|
19
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
20
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
21
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
22
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
23
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
24
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
25
|
+
SOFTWARE.
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Classifier: Development Status :: 3 - Alpha
|
|
28
|
+
Classifier: Framework :: AsyncIO
|
|
29
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
30
|
+
Classifier: Operating System :: OS Independent
|
|
31
|
+
Classifier: Programming Language :: Python :: 3
|
|
32
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
33
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
34
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
35
|
+
Classifier: Typing :: Typed
|
|
36
|
+
Requires-Python: >=3.11
|
|
37
|
+
Requires-Dist: glyff>=0.1.0
|
|
38
|
+
Description-Content-Type: text/markdown
|
|
39
|
+
|
|
40
|
+
# glyff-sqlite
|
|
41
|
+
|
|
42
|
+
SQLite-backed durable `SessionStore` implementation for
|
|
43
|
+
[glyff](https://pypi.org/project/glyff/).
|
|
44
|
+
|
|
45
|
+
This is the **production** backend: one row per execution in a SQLite database,
|
|
46
|
+
WAL mode, indexed lookups, and native transaction atomicity.
|
|
47
|
+
|
|
48
|
+
## Install
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
pip install glyff-sqlite
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
This package depends on `glyff>=0.1.0` (no additional runtime dependencies —
|
|
55
|
+
`sqlite3` is part of the standard library).
|
|
56
|
+
|
|
57
|
+
## Usage
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
from glyff.serialization import JsonSerializer
|
|
61
|
+
from glyff_sqlite import SQLiteSessionStore
|
|
62
|
+
|
|
63
|
+
store = SQLiteSessionStore("executions.sqlite3", JsonSerializer())
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Public API
|
|
67
|
+
|
|
68
|
+
| Name | Description |
|
|
69
|
+
| -------------------- | ------------------------------------------------------------- |
|
|
70
|
+
| `SQLiteSessionStore` | Durable `SessionStore` backed by a local SQLite database. |
|
|
71
|
+
| `SQLiteClient` | Low-level SQLite key/value store (generic, reusable). |
|
|
72
|
+
|
|
73
|
+
## External metadata
|
|
74
|
+
|
|
75
|
+
The underlying ``SQLiteClient`` exposes ``stage_write`` / ``stage_delete`` /
|
|
76
|
+
``stage_update`` so application code can persist its own rows alongside execution
|
|
77
|
+
records and commit or roll back atomically together:
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
client = SQLiteClient("session.sqlite3")
|
|
81
|
+
store = SQLiteSessionStore(client=client, serializer=JsonSerializer())
|
|
82
|
+
|
|
83
|
+
tx = await store.begin_transaction()
|
|
84
|
+
execution = await store.start_execution(some_id)
|
|
85
|
+
await execution.complete("ok", str)
|
|
86
|
+
|
|
87
|
+
client.stage_write("metadata", "my_key", b"my_value")
|
|
88
|
+
client.stage_delete("metadata", "old_key")
|
|
89
|
+
|
|
90
|
+
await tx.commit() # execution record + metadata commit atomically
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Transaction model
|
|
94
|
+
|
|
95
|
+
- Writes are staged in-memory per transaction and flushed on commit.
|
|
96
|
+
- Nested transactions (child scopes) commit independently of their parent.
|
|
97
|
+
- `BEGIN IMMEDIATE` prevents writer contention; WAL mode keeps reads fast.
|
|
98
|
+
- A per-database asyncio write lock serialises concurrent write transactions.
|
|
99
|
+
|
|
100
|
+
## Status
|
|
101
|
+
|
|
102
|
+
Early development. APIs may change before v1.0.
|
|
103
|
+
|
|
104
|
+
## License
|
|
105
|
+
|
|
106
|
+
MIT
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# glyff-sqlite
|
|
2
|
+
|
|
3
|
+
SQLite-backed durable `SessionStore` implementation for
|
|
4
|
+
[glyff](https://pypi.org/project/glyff/).
|
|
5
|
+
|
|
6
|
+
This is the **production** backend: one row per execution in a SQLite database,
|
|
7
|
+
WAL mode, indexed lookups, and native transaction atomicity.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install glyff-sqlite
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
This package depends on `glyff>=0.1.0` (no additional runtime dependencies —
|
|
16
|
+
`sqlite3` is part of the standard library).
|
|
17
|
+
|
|
18
|
+
## Usage
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
from glyff.serialization import JsonSerializer
|
|
22
|
+
from glyff_sqlite import SQLiteSessionStore
|
|
23
|
+
|
|
24
|
+
store = SQLiteSessionStore("executions.sqlite3", JsonSerializer())
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Public API
|
|
28
|
+
|
|
29
|
+
| Name | Description |
|
|
30
|
+
| -------------------- | ------------------------------------------------------------- |
|
|
31
|
+
| `SQLiteSessionStore` | Durable `SessionStore` backed by a local SQLite database. |
|
|
32
|
+
| `SQLiteClient` | Low-level SQLite key/value store (generic, reusable). |
|
|
33
|
+
|
|
34
|
+
## External metadata
|
|
35
|
+
|
|
36
|
+
The underlying ``SQLiteClient`` exposes ``stage_write`` / ``stage_delete`` /
|
|
37
|
+
``stage_update`` so application code can persist its own rows alongside execution
|
|
38
|
+
records and commit or roll back atomically together:
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
client = SQLiteClient("session.sqlite3")
|
|
42
|
+
store = SQLiteSessionStore(client=client, serializer=JsonSerializer())
|
|
43
|
+
|
|
44
|
+
tx = await store.begin_transaction()
|
|
45
|
+
execution = await store.start_execution(some_id)
|
|
46
|
+
await execution.complete("ok", str)
|
|
47
|
+
|
|
48
|
+
client.stage_write("metadata", "my_key", b"my_value")
|
|
49
|
+
client.stage_delete("metadata", "old_key")
|
|
50
|
+
|
|
51
|
+
await tx.commit() # execution record + metadata commit atomically
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Transaction model
|
|
55
|
+
|
|
56
|
+
- Writes are staged in-memory per transaction and flushed on commit.
|
|
57
|
+
- Nested transactions (child scopes) commit independently of their parent.
|
|
58
|
+
- `BEGIN IMMEDIATE` prevents writer contention; WAL mode keeps reads fast.
|
|
59
|
+
- A per-database asyncio write lock serialises concurrent write transactions.
|
|
60
|
+
|
|
61
|
+
## Status
|
|
62
|
+
|
|
63
|
+
Early development. APIs may change before v1.0.
|
|
64
|
+
|
|
65
|
+
## License
|
|
66
|
+
|
|
67
|
+
MIT
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "glyff-sqlite"
|
|
3
|
+
description = "SQLite-backed durable SessionStore for glyff."
|
|
4
|
+
readme = "README.md"
|
|
5
|
+
license = { file = "LICENSE" }
|
|
6
|
+
requires-python = ">=3.11"
|
|
7
|
+
dependencies = [
|
|
8
|
+
"glyff>=0.1.0",
|
|
9
|
+
]
|
|
10
|
+
dynamic = ["version"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Programming Language :: Python :: 3",
|
|
13
|
+
"Programming Language :: Python :: 3.11",
|
|
14
|
+
"Programming Language :: Python :: 3.12",
|
|
15
|
+
"Programming Language :: Python :: 3.13",
|
|
16
|
+
"License :: OSI Approved :: MIT License",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
"Development Status :: 3 - Alpha",
|
|
19
|
+
"Framework :: AsyncIO",
|
|
20
|
+
"Typing :: Typed",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
[tool.uv.sources]
|
|
24
|
+
glyff = { workspace = true }
|
|
25
|
+
|
|
26
|
+
[build-system]
|
|
27
|
+
requires = ["hatchling", "hatch-vcs"]
|
|
28
|
+
build-backend = "hatchling.build"
|
|
29
|
+
|
|
30
|
+
[tool.hatch.build.targets.wheel]
|
|
31
|
+
packages = ["src/glyff_sqlite"]
|
|
32
|
+
exclude = ["src/glyff_sqlite/tests"]
|
|
33
|
+
|
|
34
|
+
[tool.hatch.version]
|
|
35
|
+
source = "vcs"
|
|
36
|
+
raw-options = { root = "../.." }
|
|
37
|
+
|
|
38
|
+
[tool.pytest.ini_options]
|
|
39
|
+
asyncio_mode = "auto"
|
|
40
|
+
testpaths = ["src/glyff_sqlite/tests"]
|
|
41
|
+
|
|
42
|
+
[dependency-groups]
|
|
43
|
+
dev = ["pytest>=8.0", "pytest-asyncio>=0.23"]
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import contextvars
|
|
5
|
+
import sqlite3
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
SQLiteUpdate = Callable[[bytes | None], bytes | None]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class _Write:
|
|
16
|
+
value: bytes
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class _Delete:
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class _Update:
|
|
26
|
+
fn: SQLiteUpdate
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
_StagedOp = _Write | _Delete | _Update
|
|
30
|
+
|
|
31
|
+
_VALID_SYNCHRONOUS_VALUES = {"OFF", "NORMAL", "FULL", "EXTRA"}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class _SQLiteStagingBuffer:
|
|
35
|
+
__slots__ = ("ops",)
|
|
36
|
+
|
|
37
|
+
def __init__(self) -> None:
|
|
38
|
+
self.ops: dict[tuple[str, str], list[_StagedOp]] = {}
|
|
39
|
+
|
|
40
|
+
def clear(self) -> None:
|
|
41
|
+
self.ops.clear()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class SQLiteClient:
|
|
45
|
+
"""A generic SQLite-backed transactional key/value store.
|
|
46
|
+
|
|
47
|
+
Each record is identified by ``(namespace, key)`` and stored as a blob
|
|
48
|
+
in the ``records`` table. Operations are staged per-transaction and
|
|
49
|
+
committed atomically.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
def __init__(
|
|
53
|
+
self,
|
|
54
|
+
database_path: str | Path,
|
|
55
|
+
*,
|
|
56
|
+
busy_timeout_ms: int = 30_000,
|
|
57
|
+
synchronous: str = "FULL",
|
|
58
|
+
) -> None:
|
|
59
|
+
synchronous = synchronous.upper()
|
|
60
|
+
if synchronous not in _VALID_SYNCHRONOUS_VALUES:
|
|
61
|
+
valid = ", ".join(sorted(_VALID_SYNCHRONOUS_VALUES))
|
|
62
|
+
raise ValueError(f"synchronous must be one of: {valid}")
|
|
63
|
+
|
|
64
|
+
if str(database_path) == ":memory:":
|
|
65
|
+
raise ValueError(
|
|
66
|
+
"SQLiteClient does not support ':memory:' because it opens "
|
|
67
|
+
"a new connection per operation."
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
self._database_path = Path(database_path)
|
|
71
|
+
self._busy_timeout_ms = busy_timeout_ms
|
|
72
|
+
self._synchronous = synchronous
|
|
73
|
+
self._write_lock = asyncio.Lock()
|
|
74
|
+
self._current: contextvars.ContextVar[_SQLiteStagingBuffer | None] = (
|
|
75
|
+
contextvars.ContextVar("sqlite_client_staging", default=None)
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
self._database_path.parent.mkdir(parents=True, exist_ok=True)
|
|
79
|
+
|
|
80
|
+
# -- Connection helpers ----------------------------------------------------
|
|
81
|
+
|
|
82
|
+
def _connect(self) -> sqlite3.Connection:
|
|
83
|
+
connection = sqlite3.connect(
|
|
84
|
+
self._database_path,
|
|
85
|
+
isolation_level=None,
|
|
86
|
+
timeout=self._busy_timeout_ms / 1000,
|
|
87
|
+
check_same_thread=False,
|
|
88
|
+
)
|
|
89
|
+
connection.execute(f"PRAGMA busy_timeout={self._busy_timeout_ms}")
|
|
90
|
+
connection.execute("PRAGMA journal_mode=WAL")
|
|
91
|
+
connection.execute(f"PRAGMA synchronous={self._synchronous}")
|
|
92
|
+
return connection
|
|
93
|
+
|
|
94
|
+
# -- Schema initialization -------------------------------------------------
|
|
95
|
+
|
|
96
|
+
def _initialize_schema_sync(self) -> None:
|
|
97
|
+
connection = self._connect()
|
|
98
|
+
in_transaction = False
|
|
99
|
+
try:
|
|
100
|
+
connection.execute("BEGIN IMMEDIATE")
|
|
101
|
+
in_transaction = True
|
|
102
|
+
connection.execute(
|
|
103
|
+
"""
|
|
104
|
+
CREATE TABLE IF NOT EXISTS records (
|
|
105
|
+
namespace TEXT NOT NULL,
|
|
106
|
+
key TEXT NOT NULL,
|
|
107
|
+
value BLOB NOT NULL,
|
|
108
|
+
PRIMARY KEY (namespace, key)
|
|
109
|
+
)
|
|
110
|
+
"""
|
|
111
|
+
)
|
|
112
|
+
connection.execute("COMMIT")
|
|
113
|
+
in_transaction = False
|
|
114
|
+
except BaseException:
|
|
115
|
+
if in_transaction:
|
|
116
|
+
try:
|
|
117
|
+
connection.execute("ROLLBACK")
|
|
118
|
+
except sqlite3.Error:
|
|
119
|
+
pass
|
|
120
|
+
raise
|
|
121
|
+
finally:
|
|
122
|
+
connection.close()
|
|
123
|
+
|
|
124
|
+
# -- Staging lifecycle -----------------------------------------------------
|
|
125
|
+
|
|
126
|
+
def begin_staging(self) -> tuple[contextvars.Token, _SQLiteStagingBuffer]:
|
|
127
|
+
staging = _SQLiteStagingBuffer()
|
|
128
|
+
token = self._current.set(staging)
|
|
129
|
+
return token, staging
|
|
130
|
+
|
|
131
|
+
def end_staging(self, token: contextvars.Token) -> None:
|
|
132
|
+
self._current.reset(token)
|
|
133
|
+
|
|
134
|
+
def _require_staging(self) -> _SQLiteStagingBuffer:
|
|
135
|
+
staging = self._current.get()
|
|
136
|
+
if staging is None:
|
|
137
|
+
raise RuntimeError("SQLiteClient write attempted outside a transaction.")
|
|
138
|
+
return staging
|
|
139
|
+
|
|
140
|
+
def _require_current_staging(self, expected: _SQLiteStagingBuffer) -> None:
|
|
141
|
+
if self._current.get() is not expected:
|
|
142
|
+
raise RuntimeError("Transaction closed out of order.")
|
|
143
|
+
|
|
144
|
+
# -- Staging API -----------------------------------------------------------
|
|
145
|
+
|
|
146
|
+
def stage_write(self, namespace: str, key: str, value: bytes) -> None:
|
|
147
|
+
staging = self._require_staging()
|
|
148
|
+
staging.ops.setdefault((namespace, key), []).append(_Write(value))
|
|
149
|
+
|
|
150
|
+
def stage_delete(self, namespace: str, key: str) -> None:
|
|
151
|
+
staging = self._require_staging()
|
|
152
|
+
staging.ops.setdefault((namespace, key), []).append(_Delete())
|
|
153
|
+
|
|
154
|
+
def stage_update(self, namespace: str, key: str, fn: SQLiteUpdate) -> None:
|
|
155
|
+
staging = self._require_staging()
|
|
156
|
+
staging.ops.setdefault((namespace, key), []).append(_Update(fn))
|
|
157
|
+
|
|
158
|
+
async def clear_staged(self) -> None:
|
|
159
|
+
self._require_staging().clear()
|
|
160
|
+
|
|
161
|
+
# -- Commit ----------------------------------------------------------------
|
|
162
|
+
|
|
163
|
+
async def commit_staged(self) -> None:
|
|
164
|
+
staging = self._require_staging()
|
|
165
|
+
|
|
166
|
+
if not staging.ops:
|
|
167
|
+
return
|
|
168
|
+
|
|
169
|
+
async with self._write_lock:
|
|
170
|
+
await asyncio.to_thread(self._commit_staged_sync, staging)
|
|
171
|
+
|
|
172
|
+
staging.clear()
|
|
173
|
+
|
|
174
|
+
def _commit_staged_sync(self, staging: _SQLiteStagingBuffer) -> None:
|
|
175
|
+
connection = self._connect()
|
|
176
|
+
in_transaction = False
|
|
177
|
+
try:
|
|
178
|
+
connection.execute("BEGIN IMMEDIATE")
|
|
179
|
+
in_transaction = True
|
|
180
|
+
|
|
181
|
+
for (namespace, key), ops in staging.ops.items():
|
|
182
|
+
current = self._read_value_sync(connection, namespace, key)
|
|
183
|
+
result = self._apply_ops(current, ops)
|
|
184
|
+
|
|
185
|
+
if result is None:
|
|
186
|
+
connection.execute(
|
|
187
|
+
"DELETE FROM records WHERE namespace = ? AND key = ?",
|
|
188
|
+
(namespace, key),
|
|
189
|
+
)
|
|
190
|
+
else:
|
|
191
|
+
connection.execute(
|
|
192
|
+
"""INSERT INTO records (namespace, key, value)
|
|
193
|
+
VALUES (?, ?, ?)
|
|
194
|
+
ON CONFLICT(namespace, key) DO UPDATE SET value = excluded.value""",
|
|
195
|
+
(namespace, key, result),
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
connection.execute("COMMIT")
|
|
199
|
+
in_transaction = False
|
|
200
|
+
except BaseException:
|
|
201
|
+
if in_transaction:
|
|
202
|
+
try:
|
|
203
|
+
connection.execute("ROLLBACK")
|
|
204
|
+
except sqlite3.Error:
|
|
205
|
+
pass
|
|
206
|
+
raise
|
|
207
|
+
finally:
|
|
208
|
+
connection.close()
|
|
209
|
+
|
|
210
|
+
@staticmethod
|
|
211
|
+
def _apply_ops(data: bytes | None, ops: list[_StagedOp]) -> bytes | None:
|
|
212
|
+
current = data
|
|
213
|
+
for op in ops:
|
|
214
|
+
if isinstance(op, _Write):
|
|
215
|
+
current = op.value
|
|
216
|
+
elif isinstance(op, _Delete):
|
|
217
|
+
current = None
|
|
218
|
+
elif isinstance(op, _Update):
|
|
219
|
+
current = op.fn(current)
|
|
220
|
+
else:
|
|
221
|
+
raise TypeError(f"Unknown SQLite op: {op!r}")
|
|
222
|
+
return current
|
|
223
|
+
|
|
224
|
+
# -- Read / list_keys ------------------------------------------------------
|
|
225
|
+
|
|
226
|
+
async def read(
|
|
227
|
+
self, namespace: str, key: str, *, staged: bool = True
|
|
228
|
+
) -> bytes | None:
|
|
229
|
+
committed = await asyncio.to_thread(self._read_committed_sync, namespace, key)
|
|
230
|
+
|
|
231
|
+
if staged:
|
|
232
|
+
staging = self._current.get()
|
|
233
|
+
if staging is not None:
|
|
234
|
+
ops = staging.ops.get((namespace, key))
|
|
235
|
+
if ops:
|
|
236
|
+
committed = self._apply_ops(committed, ops)
|
|
237
|
+
|
|
238
|
+
return committed
|
|
239
|
+
|
|
240
|
+
def _read_committed_sync(self, namespace: str, key: str) -> bytes | None:
|
|
241
|
+
connection = self._connect()
|
|
242
|
+
try:
|
|
243
|
+
return self._read_value_sync(connection, namespace, key)
|
|
244
|
+
finally:
|
|
245
|
+
connection.close()
|
|
246
|
+
|
|
247
|
+
@staticmethod
|
|
248
|
+
def _read_value_sync(
|
|
249
|
+
connection: sqlite3.Connection, namespace: str, key: str
|
|
250
|
+
) -> bytes | None:
|
|
251
|
+
row = connection.execute(
|
|
252
|
+
"SELECT value FROM records WHERE namespace = ? AND key = ?",
|
|
253
|
+
(namespace, key),
|
|
254
|
+
).fetchone()
|
|
255
|
+
return row[0] if row else None
|
|
256
|
+
|
|
257
|
+
async def list_keys(
|
|
258
|
+
self, namespace: str, prefix: str = "", *, staged: bool = True
|
|
259
|
+
) -> set[str]:
|
|
260
|
+
committed = await asyncio.to_thread(
|
|
261
|
+
self._list_committed_keys_sync, namespace, prefix
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
if staged:
|
|
265
|
+
staging = self._current.get()
|
|
266
|
+
if staging is not None:
|
|
267
|
+
for (ns, key), ops in staging.ops.items():
|
|
268
|
+
if ns != namespace:
|
|
269
|
+
continue
|
|
270
|
+
if not key.startswith(prefix):
|
|
271
|
+
continue
|
|
272
|
+
final = self._apply_ops(
|
|
273
|
+
self._read_committed_sync(namespace, key),
|
|
274
|
+
ops,
|
|
275
|
+
)
|
|
276
|
+
if final is None:
|
|
277
|
+
committed.discard(key)
|
|
278
|
+
else:
|
|
279
|
+
committed.add(key)
|
|
280
|
+
|
|
281
|
+
return committed
|
|
282
|
+
|
|
283
|
+
def _list_committed_keys_sync(self, namespace: str, prefix: str = "") -> set[str]:
|
|
284
|
+
connection = self._connect()
|
|
285
|
+
try:
|
|
286
|
+
if prefix:
|
|
287
|
+
rows = connection.execute(
|
|
288
|
+
"SELECT key FROM records WHERE namespace = ? AND substr(key, 1, ?) = ?",
|
|
289
|
+
(namespace, len(prefix), prefix),
|
|
290
|
+
).fetchall()
|
|
291
|
+
else:
|
|
292
|
+
rows = connection.execute(
|
|
293
|
+
"SELECT key FROM records WHERE namespace = ?",
|
|
294
|
+
(namespace,),
|
|
295
|
+
).fetchall()
|
|
296
|
+
return {row[0] for row in rows}
|
|
297
|
+
finally:
|
|
298
|
+
connection.close()
|
|
299
|
+
|
|
300
|
+
# -- Direct SQL access (for initialization / inspection) -------------------
|
|
301
|
+
|
|
302
|
+
async def read_sql(self, sql: str, *params: Any) -> list[tuple]:
|
|
303
|
+
return await asyncio.to_thread(self._read_sql_sync, sql, params)
|
|
304
|
+
|
|
305
|
+
def _read_sql_sync(self, sql: str, params: tuple[Any, ...]) -> list[tuple]:
|
|
306
|
+
connection = self._connect()
|
|
307
|
+
try:
|
|
308
|
+
return list(connection.execute(sql, params))
|
|
309
|
+
finally:
|
|
310
|
+
connection.close()
|
|
311
|
+
|
|
312
|
+
async def execute(self, sql: str, *params: Any) -> None:
|
|
313
|
+
async with self._write_lock:
|
|
314
|
+
await asyncio.to_thread(self._execute_sync, sql, params)
|
|
315
|
+
|
|
316
|
+
def _execute_sync(self, sql: str, params: tuple[Any, ...]) -> None:
|
|
317
|
+
connection = self._connect()
|
|
318
|
+
in_transaction = False
|
|
319
|
+
try:
|
|
320
|
+
connection.execute("BEGIN IMMEDIATE")
|
|
321
|
+
in_transaction = True
|
|
322
|
+
connection.execute(sql, params)
|
|
323
|
+
connection.execute("COMMIT")
|
|
324
|
+
in_transaction = False
|
|
325
|
+
except BaseException:
|
|
326
|
+
if in_transaction:
|
|
327
|
+
try:
|
|
328
|
+
connection.execute("ROLLBACK")
|
|
329
|
+
except sqlite3.Error:
|
|
330
|
+
pass
|
|
331
|
+
raise
|
|
332
|
+
finally:
|
|
333
|
+
connection.close()
|