glyff-sqlite 0.12.0__py3-none-any.whl

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.
@@ -0,0 +1,7 @@
1
+ from ._sqlite_client import SQLiteClient
2
+ from ._sqlite_store import SQLiteSessionStore
3
+
4
+ __all__ = [
5
+ "SQLiteClient",
6
+ "SQLiteSessionStore",
7
+ ]
@@ -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()
@@ -0,0 +1,218 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import logging
5
+ from collections.abc import Iterable
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from glyff import (
10
+ Execution,
11
+ ExecutionId,
12
+ ExecutionRecord,
13
+ ExecutionStatus,
14
+ SessionStore,
15
+ Transaction,
16
+ )
17
+ from glyff.serialization import JsonSerializer
18
+ from glyff.serialization.constants import DEFAULT_ENCODING
19
+ from glyff.store.utils import execution_id_to_path, path_to_execution_id
20
+
21
+ from ._sqlite_client import SQLiteClient
22
+ from ._transaction import _ClientTransaction
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ _EXECUTIONS_NAMESPACE = "executions"
27
+
28
+ _STATUS_NAMES = {
29
+ ExecutionStatus.STARTED: "started",
30
+ ExecutionStatus.COMPLETED: "completed",
31
+ ExecutionStatus.FAILED: "failed",
32
+ }
33
+ _NAME_TO_STATUS = {v: k for k, v in _STATUS_NAMES.items()}
34
+
35
+
36
+ def _to_stored_bytes(record: dict[str, Any]) -> bytes:
37
+ return json.dumps(record, ensure_ascii=False, sort_keys=True).encode(
38
+ DEFAULT_ENCODING
39
+ )
40
+
41
+
42
+ def _from_stored_bytes(data: bytes | None) -> dict[str, Any] | None:
43
+ if data is None:
44
+ return None
45
+ return json.loads(data.decode(DEFAULT_ENCODING))
46
+
47
+
48
+ def _make_stored(
49
+ status: ExecutionStatus,
50
+ result_json: str | None = None,
51
+ error: str | None = None,
52
+ ) -> bytes:
53
+ return _to_stored_bytes(
54
+ {
55
+ "status": _STATUS_NAMES[status],
56
+ "result_json": result_json,
57
+ "error": error,
58
+ }
59
+ )
60
+
61
+
62
+ async def _to_record(
63
+ data: bytes,
64
+ return_type: type,
65
+ serializer: JsonSerializer,
66
+ ) -> ExecutionRecord:
67
+ stored = json.loads(data.decode(DEFAULT_ENCODING))
68
+ status = _NAME_TO_STATUS[stored["status"]]
69
+ result: Any | None = None
70
+ error: str | None = None
71
+ if status == ExecutionStatus.COMPLETED:
72
+ result_json = stored.get("result_json")
73
+ if result_json is not None:
74
+ result = await serializer.deserialize(
75
+ result_json.encode(DEFAULT_ENCODING), return_type
76
+ )
77
+ elif status == ExecutionStatus.FAILED:
78
+ error = stored.get("error") or ""
79
+ return ExecutionRecord(status=status, result=result, error=error)
80
+
81
+
82
+ class _SQLiteExecution(Execution):
83
+ def __init__(
84
+ self,
85
+ client: SQLiteClient,
86
+ execution_id: ExecutionId,
87
+ serializer: JsonSerializer,
88
+ ) -> None:
89
+ self._client = client
90
+ self._key = execution_id_to_path(execution_id)
91
+ self._serializer = serializer
92
+
93
+ async def complete(self, value: object, return_type: type) -> None:
94
+ serialized_bytes = await self._serializer.serialize(value, return_type)
95
+ result_json = serialized_bytes.decode(DEFAULT_ENCODING)
96
+
97
+ def fn(data: bytes | None) -> bytes | None:
98
+ if data is None:
99
+ raise LookupError(f"Execution at {self._key} not found")
100
+ stored = json.loads(data.decode(DEFAULT_ENCODING))
101
+ if stored["status"] in (
102
+ _STATUS_NAMES[ExecutionStatus.COMPLETED],
103
+ _STATUS_NAMES[ExecutionStatus.FAILED],
104
+ ):
105
+ raise ValueError(
106
+ f"Cannot complete execution at {self._key}: "
107
+ f"already {stored['status']}"
108
+ )
109
+ stored["status"] = _STATUS_NAMES[ExecutionStatus.COMPLETED]
110
+ stored["result_json"] = result_json
111
+ return _to_stored_bytes(stored)
112
+
113
+ self._client.stage_update(_EXECUTIONS_NAMESPACE, self._key, fn)
114
+
115
+ async def fail(self, error: str) -> None:
116
+ def fn(data: bytes | None) -> bytes | None:
117
+ if data is None:
118
+ raise LookupError(f"Execution at {self._key} not found")
119
+ stored = json.loads(data.decode(DEFAULT_ENCODING))
120
+ if stored["status"] in (
121
+ _STATUS_NAMES[ExecutionStatus.COMPLETED],
122
+ _STATUS_NAMES[ExecutionStatus.FAILED],
123
+ ):
124
+ raise ValueError(
125
+ f"Cannot fail execution at {self._key}: already {stored['status']}"
126
+ )
127
+ stored["status"] = _STATUS_NAMES[ExecutionStatus.FAILED]
128
+ stored["error"] = error
129
+ return _to_stored_bytes(stored)
130
+
131
+ self._client.stage_update(_EXECUTIONS_NAMESPACE, self._key, fn)
132
+
133
+
134
+ class SQLiteSessionStore(SessionStore):
135
+ """A SQLite-backed SessionStore for durable local persistence.
136
+
137
+ All execution data is stored in the ``records`` table of ``SQLiteClient``
138
+ under the ``"executions"`` namespace. Mutations are staged via
139
+ ``stage_write`` / ``stage_update`` and committed atomically on commit.
140
+ """
141
+
142
+ def __init__(
143
+ self,
144
+ database_path: str | Path | None = None,
145
+ serializer: JsonSerializer | None = None,
146
+ *,
147
+ client: SQLiteClient | None = None,
148
+ busy_timeout_ms: int = 30_000,
149
+ synchronous: str = "FULL",
150
+ ):
151
+ if serializer is None:
152
+ raise TypeError("serializer is required.")
153
+
154
+ if client is None:
155
+ if database_path is None:
156
+ raise TypeError("database_path or client is required.")
157
+ client = SQLiteClient(
158
+ database_path,
159
+ busy_timeout_ms=busy_timeout_ms,
160
+ synchronous=synchronous,
161
+ )
162
+ elif database_path is not None:
163
+ raise TypeError("Pass either database_path or client, not both.")
164
+
165
+ self._client = client
166
+ self._serializer = serializer
167
+
168
+ self._client._initialize_schema_sync()
169
+
170
+ @property
171
+ def client(self) -> SQLiteClient:
172
+ return self._client
173
+
174
+ # -- SessionStore API ------------------------------------------------------
175
+
176
+ async def begin_transaction(self) -> Transaction:
177
+ return await _ClientTransaction(self._client).begin()
178
+
179
+ async def start_execution(self, execution_id: ExecutionId) -> Execution:
180
+ key = execution_id_to_path(execution_id)
181
+ existing = await self.get_execution_record(execution_id, type(None))
182
+ if existing is None:
183
+
184
+ def fn(data: bytes | None) -> bytes | None:
185
+ if data is not None:
186
+ stored = json.loads(data.decode(DEFAULT_ENCODING))
187
+ if stored["status"] in (
188
+ _STATUS_NAMES[ExecutionStatus.COMPLETED],
189
+ _STATUS_NAMES[ExecutionStatus.FAILED],
190
+ ):
191
+ raise ValueError(
192
+ f"Cannot start execution {execution_id}: "
193
+ f"already {stored['status']}"
194
+ )
195
+ return _make_stored(ExecutionStatus.STARTED)
196
+
197
+ self._client.stage_update(_EXECUTIONS_NAMESPACE, key, fn)
198
+
199
+ return _SQLiteExecution(self._client, execution_id, self._serializer)
200
+
201
+ async def get_execution_record(
202
+ self, execution_id: ExecutionId, return_type: type
203
+ ) -> ExecutionRecord | None:
204
+ key = execution_id_to_path(execution_id)
205
+ data = await self._client.read(_EXECUTIONS_NAMESPACE, key, staged=True)
206
+ if data is None:
207
+ return None
208
+ return await _to_record(data, return_type, self._serializer)
209
+
210
+ async def get_descendants(self, execution_id: ExecutionId) -> list[ExecutionId]:
211
+ prefix = execution_id_to_path(execution_id) + "/"
212
+ keys = await self._client.list_keys(_EXECUTIONS_NAMESPACE, prefix, staged=True)
213
+ return [path_to_execution_id(k) for k in keys]
214
+
215
+ async def delete_executions(self, execution_ids: Iterable[ExecutionId]) -> None:
216
+ for execution_id in execution_ids:
217
+ key = execution_id_to_path(execution_id)
218
+ self._client.stage_delete(_EXECUTIONS_NAMESPACE, key)
@@ -0,0 +1,54 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import contextvars
5
+ from typing import Any
6
+
7
+ from glyff import Transaction
8
+
9
+
10
+ class _ClientTransaction(Transaction):
11
+ def __init__(self, client: Any) -> None:
12
+ self._client = client
13
+ self._closed = False
14
+ self._lock = asyncio.Lock()
15
+ self._token: contextvars.Token | None = None
16
+ self._staging = None
17
+
18
+ async def begin(self) -> _ClientTransaction:
19
+ self._token, self._staging = self._client.begin_staging()
20
+ return self
21
+
22
+ async def commit(self) -> None:
23
+ async with self._lock:
24
+ if self._closed:
25
+ return
26
+
27
+ if self._staging is None:
28
+ raise RuntimeError("transaction not started")
29
+ self._client._require_current_staging(self._staging)
30
+ self._closed = True
31
+
32
+ try:
33
+ await self._client.commit_staged()
34
+ finally:
35
+ if self._token is None:
36
+ raise RuntimeError("transaction not started")
37
+ self._client.end_staging(self._token)
38
+
39
+ async def rollback(self) -> None:
40
+ async with self._lock:
41
+ if self._closed:
42
+ return
43
+
44
+ if self._staging is None:
45
+ raise RuntimeError("transaction not started")
46
+ self._client._require_current_staging(self._staging)
47
+ self._closed = True
48
+
49
+ try:
50
+ await self._client.clear_staged()
51
+ finally:
52
+ if self._token is None:
53
+ raise RuntimeError("transaction not started")
54
+ self._client.end_staging(self._token)
@@ -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,8 @@
1
+ glyff_sqlite/__init__.py,sha256=xq2sTlXxFZu_kY_QUx7d-Lc1bTf-SdwPzLEt1yjMMfM,148
2
+ glyff_sqlite/_sqlite_client.py,sha256=P1SYcCN2AfqERFG3tDLBuJ4J5GQiCdVpF91nuyrNUu4,11173
3
+ glyff_sqlite/_sqlite_store.py,sha256=c2wyqupDMZqCMUc_XNO7AAxXyxLjGlF40gbZUsw_l9A,7672
4
+ glyff_sqlite/_transaction.py,sha256=4iW6FT_UMipQSge7stfZlMkTBtlWLI2QL0aIWWKPB18,1660
5
+ glyff_sqlite-0.12.0.dist-info/METADATA,sha256=VqFYs9EGExxT8a0C9tfDZg_KqEP_rATYuMGuCaQmQ9c,3899
6
+ glyff_sqlite-0.12.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
7
+ glyff_sqlite-0.12.0.dist-info/licenses/LICENSE,sha256=bNtLcBZk03HGyB7qD0gK37uO4E0sre_G01X1vCFBPG8,1064
8
+ glyff_sqlite-0.12.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.