ferrousdb 0.1.0rc4__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.
- ferrousdb-0.1.0rc4/PKG-INFO +18 -0
- ferrousdb-0.1.0rc4/README.md +8 -0
- ferrousdb-0.1.0rc4/ferrousdb/__init__.py +363 -0
- ferrousdb-0.1.0rc4/ferrousdb/dbapi.py +400 -0
- ferrousdb-0.1.0rc4/ferrousdb/langgraph.py +249 -0
- ferrousdb-0.1.0rc4/ferrousdb.egg-info/PKG-INFO +18 -0
- ferrousdb-0.1.0rc4/ferrousdb.egg-info/SOURCES.txt +11 -0
- ferrousdb-0.1.0rc4/ferrousdb.egg-info/dependency_links.txt +1 -0
- ferrousdb-0.1.0rc4/ferrousdb.egg-info/top_level.txt +1 -0
- ferrousdb-0.1.0rc4/pyproject.toml +19 -0
- ferrousdb-0.1.0rc4/setup.cfg +4 -0
- ferrousdb-0.1.0rc4/tests/test_dbapi_and_langgraph.py +94 -0
- ferrousdb-0.1.0rc4/tests/test_smoke.py +63 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ferrousdb
|
|
3
|
+
Version: 0.1.0rc4
|
|
4
|
+
Summary: Python bindings (ctypes) over FerrousDB's stable C-ABI (ferrous_ffi).
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Repository, https://github.com/cleissonbarbosa/FerrousDB
|
|
7
|
+
Keywords: database,sql,embedded,ferrousdb,ai-agents
|
|
8
|
+
Requires-Python: >=3.9
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
|
|
11
|
+
# `ferrousdb` (Python)
|
|
12
|
+
|
|
13
|
+
Python `ctypes` bindings over FerrousDB's stable C-ABI (`crates/ferrous-ffi`).
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
cargo build --locked --release -p ferrous_ffi
|
|
17
|
+
PYTHONPATH=packaging/python python3 -m unittest discover -s packaging/python/tests -v
|
|
18
|
+
```
|
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
"""Python ctypes bindings for FerrousDB (over crates/ferrous-ffi)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ctypes
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, List, Optional, Tuple
|
|
12
|
+
|
|
13
|
+
FERROUS_OK = 0
|
|
14
|
+
FERROUS_ERR = 1
|
|
15
|
+
FERROUS_ERR_SYNTAX = 2
|
|
16
|
+
FERROUS_ERR_CONSTRAINT = 3
|
|
17
|
+
FERROUS_ERR_TYPE = 4
|
|
18
|
+
FERROUS_ERR_NOT_FOUND = 5
|
|
19
|
+
FERROUS_ERR_BUSY = 6
|
|
20
|
+
FERROUS_ERR_READONLY = 7
|
|
21
|
+
FERROUS_ERR_CONFLICT = 8
|
|
22
|
+
FERROUS_ERR_IO = 9
|
|
23
|
+
FERROUS_ERR_LIMIT = 10
|
|
24
|
+
|
|
25
|
+
FERROUS_TYPE_NULL = 0
|
|
26
|
+
FERROUS_TYPE_INTEGER = 1
|
|
27
|
+
FERROUS_TYPE_REAL = 2
|
|
28
|
+
FERROUS_TYPE_TEXT = 3
|
|
29
|
+
FERROUS_TYPE_BOOLEAN = 4
|
|
30
|
+
FERROUS_TYPE_BLOB = 5
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class FerrousError(Exception):
|
|
34
|
+
"""Error raised by FerrousDB, carrying the structured Diagnostic dict when available."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, code: int, message: str, diagnostic: Optional[dict] = None) -> None:
|
|
37
|
+
super().__init__(message)
|
|
38
|
+
self.code = code
|
|
39
|
+
self.diagnostic = diagnostic
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class ExecutionLimits:
|
|
44
|
+
allow_read: bool = True
|
|
45
|
+
allow_write: bool = True
|
|
46
|
+
allow_schema: bool = True
|
|
47
|
+
allow_unfiltered_write: bool = True
|
|
48
|
+
allow_drop: bool = True
|
|
49
|
+
max_rows_affected: Optional[int] = None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _default_lib_name() -> str:
|
|
53
|
+
if sys.platform == "darwin":
|
|
54
|
+
return "libferrous_ffi.dylib"
|
|
55
|
+
if sys.platform == "win32":
|
|
56
|
+
return "ferrous_ffi.dll"
|
|
57
|
+
return "libferrous_ffi.so"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _load_library(lib_path: Optional[str] = None) -> ctypes.CDLL:
|
|
61
|
+
candidates: List[Path] = []
|
|
62
|
+
if lib_path:
|
|
63
|
+
candidates.append(Path(lib_path))
|
|
64
|
+
env_path = os.environ.get("FERROUS_FFI_LIB")
|
|
65
|
+
if env_path:
|
|
66
|
+
candidates.append(Path(env_path))
|
|
67
|
+
here = Path(__file__).resolve().parent
|
|
68
|
+
lib_name = _default_lib_name()
|
|
69
|
+
candidates.extend(
|
|
70
|
+
[
|
|
71
|
+
here / lib_name,
|
|
72
|
+
here.parent.parent.parent / "target" / "release" / lib_name,
|
|
73
|
+
here.parent.parent.parent / "target" / "debug" / lib_name,
|
|
74
|
+
]
|
|
75
|
+
)
|
|
76
|
+
for cand in candidates:
|
|
77
|
+
if cand.is_file():
|
|
78
|
+
lib = ctypes.CDLL(str(cand))
|
|
79
|
+
_configure_signatures(lib)
|
|
80
|
+
return lib
|
|
81
|
+
# Fall back to system linker search path
|
|
82
|
+
lib = ctypes.CDLL(lib_name)
|
|
83
|
+
_configure_signatures(lib)
|
|
84
|
+
return lib
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _configure_signatures(lib: ctypes.CDLL) -> None:
|
|
88
|
+
c_void_p = ctypes.c_void_p
|
|
89
|
+
c_char_p = ctypes.c_char_p
|
|
90
|
+
c_int32 = ctypes.c_int32
|
|
91
|
+
c_int64 = ctypes.c_int64
|
|
92
|
+
c_size_t = ctypes.c_size_t
|
|
93
|
+
c_double = ctypes.c_double
|
|
94
|
+
|
|
95
|
+
lib.ferrous_version.restype = c_char_p
|
|
96
|
+
lib.ferrous_last_error.restype = c_void_p
|
|
97
|
+
lib.ferrous_last_error_code.restype = c_int32
|
|
98
|
+
lib.ferrous_last_diagnostic_json.restype = c_void_p
|
|
99
|
+
lib.ferrous_string_free.argtypes = [c_void_p]
|
|
100
|
+
|
|
101
|
+
lib.ferrous_open.argtypes = [c_char_p]
|
|
102
|
+
lib.ferrous_open.restype = c_void_p
|
|
103
|
+
lib.ferrous_open_read_only.argtypes = [c_char_p]
|
|
104
|
+
lib.ferrous_open_read_only.restype = c_void_p
|
|
105
|
+
lib.ferrous_open_in_memory.restype = c_void_p
|
|
106
|
+
lib.ferrous_close.argtypes = [c_void_p]
|
|
107
|
+
|
|
108
|
+
lib.ferrous_connect.argtypes = [c_void_p]
|
|
109
|
+
lib.ferrous_connect.restype = c_void_p
|
|
110
|
+
lib.ferrous_conn_close.argtypes = [c_void_p]
|
|
111
|
+
lib.ferrous_conn_set_limits.argtypes = [
|
|
112
|
+
c_void_p,
|
|
113
|
+
c_int32,
|
|
114
|
+
c_int32,
|
|
115
|
+
c_int32,
|
|
116
|
+
c_int32,
|
|
117
|
+
c_int32,
|
|
118
|
+
c_int64,
|
|
119
|
+
]
|
|
120
|
+
lib.ferrous_conn_set_limits.restype = c_int32
|
|
121
|
+
|
|
122
|
+
lib.ferrous_execute.argtypes = [c_void_p, c_char_p, ctypes.POINTER(c_int64)]
|
|
123
|
+
lib.ferrous_execute.restype = c_int32
|
|
124
|
+
lib.ferrous_query.argtypes = [c_void_p, c_char_p]
|
|
125
|
+
lib.ferrous_query.restype = c_void_p
|
|
126
|
+
lib.ferrous_preview_json.argtypes = [c_void_p, c_char_p]
|
|
127
|
+
lib.ferrous_preview_json.restype = c_void_p
|
|
128
|
+
lib.ferrous_restore_point_create.argtypes = [c_void_p, c_char_p]
|
|
129
|
+
lib.ferrous_restore_point_create.restype = c_int32
|
|
130
|
+
lib.ferrous_restore_point_undo.argtypes = [c_void_p, c_char_p]
|
|
131
|
+
lib.ferrous_restore_point_undo.restype = c_int32
|
|
132
|
+
|
|
133
|
+
lib.ferrous_result_row_count.argtypes = [c_void_p]
|
|
134
|
+
lib.ferrous_result_row_count.restype = c_size_t
|
|
135
|
+
lib.ferrous_result_col_count.argtypes = [c_void_p]
|
|
136
|
+
lib.ferrous_result_col_count.restype = c_size_t
|
|
137
|
+
lib.ferrous_result_col_name.argtypes = [c_void_p, c_size_t]
|
|
138
|
+
lib.ferrous_result_col_name.restype = c_void_p
|
|
139
|
+
lib.ferrous_result_cell_type.argtypes = [c_void_p, c_size_t, c_size_t]
|
|
140
|
+
lib.ferrous_result_cell_type.restype = c_int32
|
|
141
|
+
lib.ferrous_result_cell_int.argtypes = [c_void_p, c_size_t, c_size_t]
|
|
142
|
+
lib.ferrous_result_cell_int.restype = c_int64
|
|
143
|
+
lib.ferrous_result_cell_real.argtypes = [c_void_p, c_size_t, c_size_t]
|
|
144
|
+
lib.ferrous_result_cell_real.restype = c_double
|
|
145
|
+
lib.ferrous_result_cell_bool.argtypes = [c_void_p, c_size_t, c_size_t]
|
|
146
|
+
lib.ferrous_result_cell_bool.restype = c_int32
|
|
147
|
+
lib.ferrous_result_cell_text.argtypes = [c_void_p, c_size_t, c_size_t]
|
|
148
|
+
lib.ferrous_result_cell_text.restype = c_void_p
|
|
149
|
+
lib.ferrous_result_cell_blob.argtypes = [
|
|
150
|
+
c_void_p,
|
|
151
|
+
c_size_t,
|
|
152
|
+
c_size_t,
|
|
153
|
+
ctypes.POINTER(c_size_t),
|
|
154
|
+
]
|
|
155
|
+
lib.ferrous_result_cell_blob.restype = ctypes.POINTER(ctypes.c_uint8)
|
|
156
|
+
lib.ferrous_result_free.argtypes = [c_void_p]
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _take_cstr(lib: ctypes.CDLL, ptr: Any) -> Optional[str]:
|
|
160
|
+
if not ptr:
|
|
161
|
+
return None
|
|
162
|
+
try:
|
|
163
|
+
raw = ctypes.cast(ptr, ctypes.c_char_p).value
|
|
164
|
+
return raw.decode("utf-8") if raw is not None else None
|
|
165
|
+
finally:
|
|
166
|
+
lib.ferrous_string_free(ptr)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _raise_last_error(lib: ctypes.CDLL) -> None:
|
|
170
|
+
code = int(lib.ferrous_last_error_code())
|
|
171
|
+
msg = _take_cstr(lib, lib.ferrous_last_error()) or "FerrousDB error"
|
|
172
|
+
diag_raw = _take_cstr(lib, lib.ferrous_last_diagnostic_json())
|
|
173
|
+
diag = json.loads(diag_raw) if diag_raw else None
|
|
174
|
+
raise FerrousError(code, msg, diag)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class Connection:
|
|
178
|
+
def __init__(self, lib: ctypes.CDLL, handle: Any) -> None:
|
|
179
|
+
self._lib = lib
|
|
180
|
+
self._handle = handle
|
|
181
|
+
|
|
182
|
+
def close(self) -> None:
|
|
183
|
+
if self._handle:
|
|
184
|
+
self._lib.ferrous_conn_close(self._handle)
|
|
185
|
+
self._handle = None
|
|
186
|
+
|
|
187
|
+
def __enter__(self) -> "Connection":
|
|
188
|
+
return self
|
|
189
|
+
|
|
190
|
+
def __exit__(self, *args: Any) -> None:
|
|
191
|
+
self.close()
|
|
192
|
+
|
|
193
|
+
def set_limits(self, limits: ExecutionLimits) -> None:
|
|
194
|
+
cap = -1 if limits.max_rows_affected is None else int(limits.max_rows_affected)
|
|
195
|
+
rc = self._lib.ferrous_conn_set_limits(
|
|
196
|
+
self._handle,
|
|
197
|
+
int(limits.allow_read),
|
|
198
|
+
int(limits.allow_write),
|
|
199
|
+
int(limits.allow_schema),
|
|
200
|
+
int(limits.allow_unfiltered_write),
|
|
201
|
+
int(limits.allow_drop),
|
|
202
|
+
cap,
|
|
203
|
+
)
|
|
204
|
+
if rc != FERROUS_OK:
|
|
205
|
+
_raise_last_error(self._lib)
|
|
206
|
+
|
|
207
|
+
def execute(self, sql: str) -> int:
|
|
208
|
+
affected = ctypes.c_int64(0)
|
|
209
|
+
rc = self._lib.ferrous_execute(
|
|
210
|
+
self._handle, sql.encode("utf-8"), ctypes.byref(affected)
|
|
211
|
+
)
|
|
212
|
+
if rc != FERROUS_OK:
|
|
213
|
+
_raise_last_error(self._lib)
|
|
214
|
+
return int(affected.value)
|
|
215
|
+
|
|
216
|
+
def query(self, sql: str) -> Tuple[List[str], List[List[Any]]]:
|
|
217
|
+
res = self._lib.ferrous_query(self._handle, sql.encode("utf-8"))
|
|
218
|
+
if not res:
|
|
219
|
+
_raise_last_error(self._lib)
|
|
220
|
+
try:
|
|
221
|
+
nrows = int(self._lib.ferrous_result_row_count(res))
|
|
222
|
+
ncols = int(self._lib.ferrous_result_col_count(res))
|
|
223
|
+
columns = [
|
|
224
|
+
_take_cstr(self._lib, self._lib.ferrous_result_col_name(res, c)) or ""
|
|
225
|
+
for c in range(ncols)
|
|
226
|
+
]
|
|
227
|
+
rows: List[List[Any]] = []
|
|
228
|
+
for r in range(nrows):
|
|
229
|
+
row: List[Any] = []
|
|
230
|
+
for c in range(ncols):
|
|
231
|
+
ty = int(self._lib.ferrous_result_cell_type(res, r, c))
|
|
232
|
+
if ty == FERROUS_TYPE_NULL:
|
|
233
|
+
row.append(None)
|
|
234
|
+
elif ty == FERROUS_TYPE_INTEGER:
|
|
235
|
+
row.append(int(self._lib.ferrous_result_cell_int(res, r, c)))
|
|
236
|
+
elif ty == FERROUS_TYPE_REAL:
|
|
237
|
+
row.append(float(self._lib.ferrous_result_cell_real(res, r, c)))
|
|
238
|
+
elif ty == FERROUS_TYPE_BOOLEAN:
|
|
239
|
+
row.append(bool(self._lib.ferrous_result_cell_bool(res, r, c)))
|
|
240
|
+
elif ty == FERROUS_TYPE_TEXT:
|
|
241
|
+
row.append(
|
|
242
|
+
_take_cstr(
|
|
243
|
+
self._lib, self._lib.ferrous_result_cell_text(res, r, c)
|
|
244
|
+
)
|
|
245
|
+
)
|
|
246
|
+
elif ty == FERROUS_TYPE_BLOB:
|
|
247
|
+
blen = ctypes.c_size_t(0)
|
|
248
|
+
bptr = self._lib.ferrous_result_cell_blob(
|
|
249
|
+
res, r, c, ctypes.byref(blen)
|
|
250
|
+
)
|
|
251
|
+
row.append(bytes(bptr[: blen.value]) if bptr else b"")
|
|
252
|
+
else:
|
|
253
|
+
row.append(None)
|
|
254
|
+
rows.append(row)
|
|
255
|
+
return columns, rows
|
|
256
|
+
finally:
|
|
257
|
+
self._lib.ferrous_result_free(res)
|
|
258
|
+
|
|
259
|
+
def preview(self, sql: str) -> dict:
|
|
260
|
+
ptr = self._lib.ferrous_preview_json(self._handle, sql.encode("utf-8"))
|
|
261
|
+
if not ptr:
|
|
262
|
+
_raise_last_error(self._lib)
|
|
263
|
+
raw = _take_cstr(self._lib, ptr) or "{}"
|
|
264
|
+
return json.loads(raw)
|
|
265
|
+
|
|
266
|
+
def create_restore_point(self, name: str) -> None:
|
|
267
|
+
rc = self._lib.ferrous_restore_point_create(self._handle, name.encode("utf-8"))
|
|
268
|
+
if rc != FERROUS_OK:
|
|
269
|
+
_raise_last_error(self._lib)
|
|
270
|
+
|
|
271
|
+
def restore_to(self, name: str) -> None:
|
|
272
|
+
rc = self._lib.ferrous_restore_point_undo(self._handle, name.encode("utf-8"))
|
|
273
|
+
if rc != FERROUS_OK:
|
|
274
|
+
_raise_last_error(self._lib)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
class Database:
|
|
278
|
+
def __init__(self, lib: ctypes.CDLL, handle: Any) -> None:
|
|
279
|
+
self._lib = lib
|
|
280
|
+
self._handle = handle
|
|
281
|
+
|
|
282
|
+
@classmethod
|
|
283
|
+
def open(
|
|
284
|
+
cls, path: str, *, read_only: bool = False, lib_path: Optional[str] = None
|
|
285
|
+
) -> "Database":
|
|
286
|
+
lib = _load_library(lib_path)
|
|
287
|
+
fn = lib.ferrous_open_read_only if read_only else lib.ferrous_open
|
|
288
|
+
handle = fn(str(path).encode("utf-8"))
|
|
289
|
+
if not handle:
|
|
290
|
+
_raise_last_error(lib)
|
|
291
|
+
return cls(lib, handle)
|
|
292
|
+
|
|
293
|
+
@classmethod
|
|
294
|
+
def in_memory(cls, *, lib_path: Optional[str] = None) -> "Database":
|
|
295
|
+
lib = _load_library(lib_path)
|
|
296
|
+
handle = lib.ferrous_open_in_memory()
|
|
297
|
+
if not handle:
|
|
298
|
+
_raise_last_error(lib)
|
|
299
|
+
return cls(lib, handle)
|
|
300
|
+
|
|
301
|
+
def connect(self) -> Connection:
|
|
302
|
+
handle = self._lib.ferrous_connect(self._handle)
|
|
303
|
+
if not handle:
|
|
304
|
+
_raise_last_error(self._lib)
|
|
305
|
+
return Connection(self._lib, handle)
|
|
306
|
+
|
|
307
|
+
def close(self) -> None:
|
|
308
|
+
if self._handle:
|
|
309
|
+
self._lib.ferrous_close(self._handle)
|
|
310
|
+
self._handle = None
|
|
311
|
+
|
|
312
|
+
def __enter__(self) -> "Database":
|
|
313
|
+
return self
|
|
314
|
+
|
|
315
|
+
def __exit__(self, *args: Any) -> None:
|
|
316
|
+
self.close()
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
# PEP 249 (DB-API 2.0) and LangGraph exports.
|
|
320
|
+
from .dbapi import ( # noqa: E402
|
|
321
|
+
DBAPIConnection,
|
|
322
|
+
DBAPICursor,
|
|
323
|
+
DatabaseError,
|
|
324
|
+
DataError,
|
|
325
|
+
Error,
|
|
326
|
+
IntegrityError,
|
|
327
|
+
InterfaceError,
|
|
328
|
+
InternalError,
|
|
329
|
+
NotSupportedError,
|
|
330
|
+
OperationalError,
|
|
331
|
+
ProgrammingError,
|
|
332
|
+
Warning,
|
|
333
|
+
apilevel,
|
|
334
|
+
connect,
|
|
335
|
+
paramstyle,
|
|
336
|
+
threadsafety,
|
|
337
|
+
)
|
|
338
|
+
from .langgraph import CheckpointTuple, FerrousSaver # noqa: E402
|
|
339
|
+
|
|
340
|
+
__all__ = [
|
|
341
|
+
"Connection",
|
|
342
|
+
"Database",
|
|
343
|
+
"ExecutionLimits",
|
|
344
|
+
"FerrousError",
|
|
345
|
+
"apilevel",
|
|
346
|
+
"threadsafety",
|
|
347
|
+
"paramstyle",
|
|
348
|
+
"connect",
|
|
349
|
+
"DBAPIConnection",
|
|
350
|
+
"DBAPICursor",
|
|
351
|
+
"Warning",
|
|
352
|
+
"Error",
|
|
353
|
+
"InterfaceError",
|
|
354
|
+
"DatabaseError",
|
|
355
|
+
"DataError",
|
|
356
|
+
"OperationalError",
|
|
357
|
+
"IntegrityError",
|
|
358
|
+
"InternalError",
|
|
359
|
+
"ProgrammingError",
|
|
360
|
+
"NotSupportedError",
|
|
361
|
+
"FerrousSaver",
|
|
362
|
+
"CheckpointTuple",
|
|
363
|
+
]
|
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
"""PEP 249 (DB-API 2.0) interface for FerrousDB."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Iterable, List, Optional, Sequence, Tuple
|
|
6
|
+
|
|
7
|
+
from . import (
|
|
8
|
+
FERROUS_ERR_BUSY,
|
|
9
|
+
FERROUS_ERR_CONFLICT,
|
|
10
|
+
FERROUS_ERR_CONSTRAINT,
|
|
11
|
+
FERROUS_ERR_IO,
|
|
12
|
+
FERROUS_ERR_LIMIT,
|
|
13
|
+
FERROUS_ERR_NOT_FOUND,
|
|
14
|
+
FERROUS_ERR_READONLY,
|
|
15
|
+
FERROUS_ERR_SYNTAX,
|
|
16
|
+
FERROUS_ERR_TYPE,
|
|
17
|
+
Connection as RawConnection,
|
|
18
|
+
Database as RawDatabase,
|
|
19
|
+
ExecutionLimits,
|
|
20
|
+
FerrousError,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
apilevel = "2.0"
|
|
24
|
+
threadsafety = 1
|
|
25
|
+
paramstyle = "qmark"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Warning(Exception):
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Error(Exception):
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
message: str,
|
|
36
|
+
*,
|
|
37
|
+
code: Optional[int] = None,
|
|
38
|
+
diagnostic: Optional[dict] = None,
|
|
39
|
+
) -> None:
|
|
40
|
+
super().__init__(message)
|
|
41
|
+
self.code = code
|
|
42
|
+
self.diagnostic = diagnostic
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class InterfaceError(Error):
|
|
46
|
+
pass
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class DatabaseError(Error):
|
|
50
|
+
pass
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class DataError(DatabaseError):
|
|
54
|
+
pass
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class OperationalError(DatabaseError):
|
|
58
|
+
pass
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class IntegrityError(DatabaseError):
|
|
62
|
+
pass
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class InternalError(DatabaseError):
|
|
66
|
+
pass
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class ProgrammingError(DatabaseError):
|
|
70
|
+
pass
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class NotSupportedError(DatabaseError):
|
|
74
|
+
pass
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _translate_error(err: FerrousError) -> Error:
|
|
78
|
+
cls = {
|
|
79
|
+
FERROUS_ERR_SYNTAX: ProgrammingError,
|
|
80
|
+
FERROUS_ERR_NOT_FOUND: ProgrammingError,
|
|
81
|
+
FERROUS_ERR_CONSTRAINT: IntegrityError,
|
|
82
|
+
FERROUS_ERR_TYPE: DataError,
|
|
83
|
+
FERROUS_ERR_BUSY: OperationalError,
|
|
84
|
+
FERROUS_ERR_READONLY: OperationalError,
|
|
85
|
+
FERROUS_ERR_CONFLICT: OperationalError,
|
|
86
|
+
FERROUS_ERR_IO: OperationalError,
|
|
87
|
+
FERROUS_ERR_LIMIT: OperationalError,
|
|
88
|
+
}.get(err.code, DatabaseError)
|
|
89
|
+
return cls(str(err), code=err.code, diagnostic=err.diagnostic)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _sql_literal(value: Any) -> str:
|
|
93
|
+
if value is None:
|
|
94
|
+
return "NULL"
|
|
95
|
+
if isinstance(value, bool):
|
|
96
|
+
return "TRUE" if value else "FALSE"
|
|
97
|
+
if isinstance(value, int):
|
|
98
|
+
return str(value)
|
|
99
|
+
if isinstance(value, float):
|
|
100
|
+
return repr(value)
|
|
101
|
+
if isinstance(value, (bytes, bytearray, memoryview)):
|
|
102
|
+
return f"X'{bytes(value).hex()}'"
|
|
103
|
+
if isinstance(value, str):
|
|
104
|
+
escaped = value.replace("'", "''")
|
|
105
|
+
return f"'{escaped}'"
|
|
106
|
+
raise DataError(f"Unsupported parameter type: {type(value).__name__}")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _bind_qmark(sql: str, parameters: Sequence[Any]) -> str:
|
|
110
|
+
if not parameters:
|
|
111
|
+
return sql
|
|
112
|
+
out: List[str] = []
|
|
113
|
+
idx = 0
|
|
114
|
+
in_single = False
|
|
115
|
+
in_double = False
|
|
116
|
+
i = 0
|
|
117
|
+
n = len(sql)
|
|
118
|
+
while i < n:
|
|
119
|
+
ch = sql[i]
|
|
120
|
+
if in_single:
|
|
121
|
+
out.append(ch)
|
|
122
|
+
if ch == "'":
|
|
123
|
+
if i + 1 < n and sql[i + 1] == "'":
|
|
124
|
+
out.append("'")
|
|
125
|
+
i += 2
|
|
126
|
+
continue
|
|
127
|
+
in_single = False
|
|
128
|
+
i += 1
|
|
129
|
+
continue
|
|
130
|
+
if in_double:
|
|
131
|
+
out.append(ch)
|
|
132
|
+
if ch == '"':
|
|
133
|
+
in_double = False
|
|
134
|
+
i += 1
|
|
135
|
+
continue
|
|
136
|
+
if ch == "'":
|
|
137
|
+
in_single = True
|
|
138
|
+
out.append(ch)
|
|
139
|
+
i += 1
|
|
140
|
+
continue
|
|
141
|
+
if ch == '"':
|
|
142
|
+
in_double = True
|
|
143
|
+
out.append(ch)
|
|
144
|
+
i += 1
|
|
145
|
+
continue
|
|
146
|
+
if ch == "?":
|
|
147
|
+
# Support positional `?` and 1-based `?N`.
|
|
148
|
+
j = i + 1
|
|
149
|
+
while j < n and sql[j].isdigit():
|
|
150
|
+
j += 1
|
|
151
|
+
if j > i + 1:
|
|
152
|
+
pos = int(sql[i + 1 : j]) - 1
|
|
153
|
+
if pos < 0 or pos >= len(parameters):
|
|
154
|
+
raise ProgrammingError(f"Parameter index ?{pos + 1} out of range")
|
|
155
|
+
out.append(_sql_literal(parameters[pos]))
|
|
156
|
+
i = j
|
|
157
|
+
else:
|
|
158
|
+
if idx >= len(parameters):
|
|
159
|
+
raise ProgrammingError("Not enough parameters supplied for '?' placeholders")
|
|
160
|
+
out.append(_sql_literal(parameters[idx]))
|
|
161
|
+
idx += 1
|
|
162
|
+
i += 1
|
|
163
|
+
continue
|
|
164
|
+
out.append(ch)
|
|
165
|
+
i += 1
|
|
166
|
+
return "".join(out)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _is_query_statement(sql: str) -> bool:
|
|
170
|
+
head = sql.lstrip()
|
|
171
|
+
upper = head.upper()
|
|
172
|
+
return (
|
|
173
|
+
upper.startswith("SELECT ")
|
|
174
|
+
or upper.startswith("SELECT\n")
|
|
175
|
+
or upper.startswith("SELECT\t")
|
|
176
|
+
or upper.startswith("WITH ")
|
|
177
|
+
or upper.startswith("EXPLAIN ")
|
|
178
|
+
or upper.startswith("PRAGMA ")
|
|
179
|
+
or " RETURNING " in upper
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
class DBAPICursor:
|
|
184
|
+
"""PEP 249 compliant database cursor."""
|
|
185
|
+
|
|
186
|
+
def __init__(self, conn: "DBAPIConnection") -> None:
|
|
187
|
+
self._conn = conn
|
|
188
|
+
self.description: Optional[Tuple[Tuple[Any, ...], ...]] = None
|
|
189
|
+
self.rowcount: int = -1
|
|
190
|
+
self.arraysize: int = 1
|
|
191
|
+
self._rows: List[Tuple[Any, ...]] = []
|
|
192
|
+
self._pos: int = 0
|
|
193
|
+
self._closed: bool = False
|
|
194
|
+
|
|
195
|
+
def _check_open(self) -> None:
|
|
196
|
+
if self._closed:
|
|
197
|
+
raise InterfaceError("Cursor is closed")
|
|
198
|
+
self._conn._check_open()
|
|
199
|
+
|
|
200
|
+
def execute(self, operation: str, parameters: Sequence[Any] = ()) -> "DBAPICursor":
|
|
201
|
+
self._check_open()
|
|
202
|
+
bound = _bind_qmark(operation, list(parameters))
|
|
203
|
+
self._rows = []
|
|
204
|
+
self._pos = 0
|
|
205
|
+
self.description = None
|
|
206
|
+
self.rowcount = -1
|
|
207
|
+
try:
|
|
208
|
+
if _is_query_statement(bound):
|
|
209
|
+
cols, rows = self._conn._raw_conn.query(bound)
|
|
210
|
+
self.description = tuple((c, None, None, None, None, None, None) for c in cols)
|
|
211
|
+
self._rows = [tuple(r) for r in rows]
|
|
212
|
+
self.rowcount = len(self._rows)
|
|
213
|
+
else:
|
|
214
|
+
affected = self._conn._raw_conn.execute(bound)
|
|
215
|
+
self.rowcount = affected
|
|
216
|
+
except FerrousError as err:
|
|
217
|
+
raise _translate_error(err) from err
|
|
218
|
+
return self
|
|
219
|
+
|
|
220
|
+
def executemany(
|
|
221
|
+
self, operation: str, seq_of_parameters: Iterable[Sequence[Any]]
|
|
222
|
+
) -> "DBAPICursor":
|
|
223
|
+
self._check_open()
|
|
224
|
+
total = 0
|
|
225
|
+
for params in seq_of_parameters:
|
|
226
|
+
self.execute(operation, params)
|
|
227
|
+
if self.rowcount >= 0:
|
|
228
|
+
total += self.rowcount
|
|
229
|
+
self.rowcount = total
|
|
230
|
+
return self
|
|
231
|
+
|
|
232
|
+
def fetchone(self) -> Optional[Tuple[Any, ...]]:
|
|
233
|
+
self._check_open()
|
|
234
|
+
if self._pos >= len(self._rows):
|
|
235
|
+
return None
|
|
236
|
+
row = self._rows[self._pos]
|
|
237
|
+
self._pos += 1
|
|
238
|
+
return row
|
|
239
|
+
|
|
240
|
+
def fetchmany(self, size: Optional[int] = None) -> List[Tuple[Any, ...]]:
|
|
241
|
+
self._check_open()
|
|
242
|
+
n = self.arraysize if size is None else int(size)
|
|
243
|
+
if n <= 0:
|
|
244
|
+
return []
|
|
245
|
+
chunk = self._rows[self._pos : self._pos + n]
|
|
246
|
+
self._pos += len(chunk)
|
|
247
|
+
return chunk
|
|
248
|
+
|
|
249
|
+
def fetchall(self) -> List[Tuple[Any, ...]]:
|
|
250
|
+
self._check_open()
|
|
251
|
+
rest = self._rows[self._pos :]
|
|
252
|
+
self._pos = len(self._rows)
|
|
253
|
+
return rest
|
|
254
|
+
|
|
255
|
+
def setinputsizes(self, sizes: Any) -> None:
|
|
256
|
+
self._check_open()
|
|
257
|
+
|
|
258
|
+
def setoutputsize(self, size: Any, column: Any = None) -> None:
|
|
259
|
+
self._check_open()
|
|
260
|
+
|
|
261
|
+
def close(self) -> None:
|
|
262
|
+
self._closed = True
|
|
263
|
+
self._rows = []
|
|
264
|
+
|
|
265
|
+
def __iter__(self) -> "DBAPICursor":
|
|
266
|
+
return self
|
|
267
|
+
|
|
268
|
+
def __next__(self) -> Tuple[Any, ...]:
|
|
269
|
+
row = self.fetchone()
|
|
270
|
+
if row is None:
|
|
271
|
+
raise StopIteration
|
|
272
|
+
return row
|
|
273
|
+
|
|
274
|
+
def __enter__(self) -> "DBAPICursor":
|
|
275
|
+
return self
|
|
276
|
+
|
|
277
|
+
def __exit__(self, *args: Any) -> None:
|
|
278
|
+
self.close()
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
class DBAPIConnection:
|
|
282
|
+
"""PEP 249 compliant connection with FerrousDB safety extensions."""
|
|
283
|
+
|
|
284
|
+
def __init__(
|
|
285
|
+
self,
|
|
286
|
+
raw_db: RawDatabase,
|
|
287
|
+
raw_conn: RawConnection,
|
|
288
|
+
*,
|
|
289
|
+
limits: Optional[ExecutionLimits] = None,
|
|
290
|
+
) -> None:
|
|
291
|
+
self._raw_db = raw_db
|
|
292
|
+
self._raw_conn = raw_conn
|
|
293
|
+
self._closed = False
|
|
294
|
+
self._in_tx = False
|
|
295
|
+
if limits is not None:
|
|
296
|
+
self.set_limits(limits)
|
|
297
|
+
|
|
298
|
+
def _check_open(self) -> None:
|
|
299
|
+
if self._closed:
|
|
300
|
+
raise InterfaceError("Connection is closed")
|
|
301
|
+
|
|
302
|
+
def cursor(self) -> DBAPICursor:
|
|
303
|
+
self._check_open()
|
|
304
|
+
return DBAPICursor(self)
|
|
305
|
+
|
|
306
|
+
def execute(self, sql: str, parameters: Sequence[Any] = ()) -> DBAPICursor:
|
|
307
|
+
cur = self.cursor()
|
|
308
|
+
return cur.execute(sql, parameters)
|
|
309
|
+
|
|
310
|
+
def begin(self) -> None:
|
|
311
|
+
self._check_open()
|
|
312
|
+
try:
|
|
313
|
+
self._raw_conn.execute("BEGIN")
|
|
314
|
+
self._in_tx = True
|
|
315
|
+
except FerrousError as err:
|
|
316
|
+
raise _translate_error(err) from err
|
|
317
|
+
|
|
318
|
+
def commit(self) -> None:
|
|
319
|
+
self._check_open()
|
|
320
|
+
if self._in_tx:
|
|
321
|
+
try:
|
|
322
|
+
self._raw_conn.execute("COMMIT")
|
|
323
|
+
except FerrousError as err:
|
|
324
|
+
raise _translate_error(err) from err
|
|
325
|
+
finally:
|
|
326
|
+
self._in_tx = False
|
|
327
|
+
|
|
328
|
+
def rollback(self) -> None:
|
|
329
|
+
self._check_open()
|
|
330
|
+
if self._in_tx:
|
|
331
|
+
try:
|
|
332
|
+
self._raw_conn.execute("ROLLBACK")
|
|
333
|
+
except FerrousError as err:
|
|
334
|
+
raise _translate_error(err) from err
|
|
335
|
+
finally:
|
|
336
|
+
self._in_tx = False
|
|
337
|
+
|
|
338
|
+
def set_limits(self, limits: ExecutionLimits) -> None:
|
|
339
|
+
self._check_open()
|
|
340
|
+
try:
|
|
341
|
+
self._raw_conn.set_limits(limits)
|
|
342
|
+
except FerrousError as err:
|
|
343
|
+
raise _translate_error(err) from err
|
|
344
|
+
|
|
345
|
+
def preview(self, sql: str, parameters: Sequence[Any] = ()) -> dict:
|
|
346
|
+
self._check_open()
|
|
347
|
+
bound = _bind_qmark(sql, list(parameters))
|
|
348
|
+
try:
|
|
349
|
+
return self._raw_conn.preview(bound)
|
|
350
|
+
except FerrousError as err:
|
|
351
|
+
raise _translate_error(err) from err
|
|
352
|
+
|
|
353
|
+
def create_restore_point(self, name: str) -> None:
|
|
354
|
+
self._check_open()
|
|
355
|
+
try:
|
|
356
|
+
self._raw_conn.create_restore_point(name)
|
|
357
|
+
except FerrousError as err:
|
|
358
|
+
raise _translate_error(err) from err
|
|
359
|
+
|
|
360
|
+
def restore_to(self, name: str) -> None:
|
|
361
|
+
self._check_open()
|
|
362
|
+
try:
|
|
363
|
+
self._raw_conn.restore_to(name)
|
|
364
|
+
except FerrousError as err:
|
|
365
|
+
raise _translate_error(err) from err
|
|
366
|
+
|
|
367
|
+
def close(self) -> None:
|
|
368
|
+
if not self._closed:
|
|
369
|
+
self._closed = True
|
|
370
|
+
self._raw_conn.close()
|
|
371
|
+
self._raw_db.close()
|
|
372
|
+
|
|
373
|
+
def __enter__(self) -> "DBAPIConnection":
|
|
374
|
+
return self
|
|
375
|
+
|
|
376
|
+
def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
|
|
377
|
+
if exc_type is not None:
|
|
378
|
+
self.rollback()
|
|
379
|
+
else:
|
|
380
|
+
self.commit()
|
|
381
|
+
self.close()
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def connect(
|
|
385
|
+
database: str = ":memory:",
|
|
386
|
+
*,
|
|
387
|
+
read_only: bool = False,
|
|
388
|
+
limits: Optional[ExecutionLimits] = None,
|
|
389
|
+
lib_path: Optional[str] = None,
|
|
390
|
+
) -> DBAPIConnection:
|
|
391
|
+
"""Open a PEP 249 DB-API 2.0 connection to a FerrousDB database."""
|
|
392
|
+
try:
|
|
393
|
+
if database == ":memory:":
|
|
394
|
+
raw_db = RawDatabase.in_memory(lib_path=lib_path)
|
|
395
|
+
else:
|
|
396
|
+
raw_db = RawDatabase.open(database, read_only=read_only, lib_path=lib_path)
|
|
397
|
+
raw_conn = raw_db.connect()
|
|
398
|
+
return DBAPIConnection(raw_db, raw_conn, limits=limits)
|
|
399
|
+
except FerrousError as err:
|
|
400
|
+
raise _translate_error(err) from err
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
"""LangGraph-compatible checkpointer backed by FerrousDB.
|
|
2
|
+
|
|
3
|
+
Subclasses ``langgraph.checkpoint.base.BaseCheckpointSaver`` automatically when
|
|
4
|
+
LangGraph is installed, and works standalone with the identical checkpoint tuple
|
|
5
|
+
contract when LangGraph is not installed.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple
|
|
13
|
+
|
|
14
|
+
from .dbapi import DBAPIConnection, connect
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
from langgraph.checkpoint.base import BaseCheckpointSaver, CheckpointTuple # type: ignore
|
|
18
|
+
except ImportError:
|
|
19
|
+
|
|
20
|
+
class BaseCheckpointSaver: # type: ignore[no-redef]
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class CheckpointTuple: # type: ignore[no-redef]
|
|
25
|
+
config: Dict[str, Any]
|
|
26
|
+
checkpoint: Dict[str, Any]
|
|
27
|
+
metadata: Dict[str, Any]
|
|
28
|
+
parent_config: Optional[Dict[str, Any]] = None
|
|
29
|
+
pending_writes: Optional[List[Tuple[str, str, Any]]] = None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class FerrousSaver(BaseCheckpointSaver):
|
|
33
|
+
"""Durable LangGraph checkpoint saver using FerrousDB strict tables and restore points."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, conn: DBAPIConnection) -> None:
|
|
36
|
+
super().__init__()
|
|
37
|
+
self.conn = conn
|
|
38
|
+
self.setup()
|
|
39
|
+
|
|
40
|
+
@classmethod
|
|
41
|
+
def from_conn_string(cls, path: str = ":memory:", **kwargs: Any) -> "FerrousSaver":
|
|
42
|
+
return cls(connect(path, **kwargs))
|
|
43
|
+
|
|
44
|
+
def setup(self) -> None:
|
|
45
|
+
self.conn.execute(
|
|
46
|
+
"""
|
|
47
|
+
CREATE TABLE IF NOT EXISTS langgraph_checkpoints (
|
|
48
|
+
thread_id TEXT NOT NULL,
|
|
49
|
+
checkpoint_ns TEXT NOT NULL,
|
|
50
|
+
checkpoint_id TEXT NOT NULL,
|
|
51
|
+
parent_checkpoint_id TEXT,
|
|
52
|
+
checkpoint_json TEXT NOT NULL,
|
|
53
|
+
metadata_json TEXT NOT NULL,
|
|
54
|
+
PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id)
|
|
55
|
+
)
|
|
56
|
+
"""
|
|
57
|
+
)
|
|
58
|
+
self.conn.execute(
|
|
59
|
+
"""
|
|
60
|
+
CREATE TABLE IF NOT EXISTS langgraph_writes (
|
|
61
|
+
thread_id TEXT NOT NULL,
|
|
62
|
+
checkpoint_ns TEXT NOT NULL,
|
|
63
|
+
checkpoint_id TEXT NOT NULL,
|
|
64
|
+
task_id TEXT NOT NULL,
|
|
65
|
+
idx INTEGER NOT NULL,
|
|
66
|
+
channel TEXT NOT NULL,
|
|
67
|
+
value_json TEXT NOT NULL,
|
|
68
|
+
PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id, task_id, idx)
|
|
69
|
+
)
|
|
70
|
+
"""
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
def put(
|
|
74
|
+
self,
|
|
75
|
+
config: Dict[str, Any],
|
|
76
|
+
checkpoint: Dict[str, Any],
|
|
77
|
+
metadata: Dict[str, Any],
|
|
78
|
+
new_versions: Optional[Dict[str, Any]] = None,
|
|
79
|
+
) -> Dict[str, Any]:
|
|
80
|
+
del new_versions
|
|
81
|
+
cfg = config.get("configurable", {})
|
|
82
|
+
thread_id = str(cfg["thread_id"])
|
|
83
|
+
checkpoint_ns = str(cfg.get("checkpoint_ns", ""))
|
|
84
|
+
checkpoint_id = str(checkpoint["id"])
|
|
85
|
+
parent_id = cfg.get("checkpoint_id")
|
|
86
|
+
|
|
87
|
+
self.conn.execute(
|
|
88
|
+
"""
|
|
89
|
+
INSERT OR REPLACE INTO langgraph_checkpoints
|
|
90
|
+
(thread_id, checkpoint_ns, checkpoint_id, parent_checkpoint_id, checkpoint_json, metadata_json)
|
|
91
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
92
|
+
""",
|
|
93
|
+
(
|
|
94
|
+
thread_id,
|
|
95
|
+
checkpoint_ns,
|
|
96
|
+
checkpoint_id,
|
|
97
|
+
str(parent_id) if parent_id is not None else None,
|
|
98
|
+
json.dumps(checkpoint, sort_keys=True),
|
|
99
|
+
json.dumps(metadata, sort_keys=True),
|
|
100
|
+
),
|
|
101
|
+
)
|
|
102
|
+
return {
|
|
103
|
+
"configurable": {
|
|
104
|
+
"thread_id": thread_id,
|
|
105
|
+
"checkpoint_ns": checkpoint_ns,
|
|
106
|
+
"checkpoint_id": checkpoint_id,
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
def put_writes(
|
|
111
|
+
self,
|
|
112
|
+
config: Dict[str, Any],
|
|
113
|
+
writes: Sequence[Tuple[str, Any]],
|
|
114
|
+
task_id: str,
|
|
115
|
+
) -> None:
|
|
116
|
+
cfg = config.get("configurable", {})
|
|
117
|
+
thread_id = str(cfg["thread_id"])
|
|
118
|
+
checkpoint_ns = str(cfg.get("checkpoint_ns", ""))
|
|
119
|
+
checkpoint_id = str(cfg["checkpoint_id"])
|
|
120
|
+
for idx, (channel, value) in enumerate(writes):
|
|
121
|
+
self.conn.execute(
|
|
122
|
+
"""
|
|
123
|
+
INSERT OR REPLACE INTO langgraph_writes
|
|
124
|
+
(thread_id, checkpoint_ns, checkpoint_id, task_id, idx, channel, value_json)
|
|
125
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
126
|
+
""",
|
|
127
|
+
(
|
|
128
|
+
thread_id,
|
|
129
|
+
checkpoint_ns,
|
|
130
|
+
checkpoint_id,
|
|
131
|
+
str(task_id),
|
|
132
|
+
idx,
|
|
133
|
+
str(channel),
|
|
134
|
+
json.dumps(value),
|
|
135
|
+
),
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
def get_tuple(self, config: Dict[str, Any]) -> Optional[CheckpointTuple]:
|
|
139
|
+
cfg = config.get("configurable", {})
|
|
140
|
+
thread_id = str(cfg["thread_id"])
|
|
141
|
+
checkpoint_ns = str(cfg.get("checkpoint_ns", ""))
|
|
142
|
+
checkpoint_id = cfg.get("checkpoint_id")
|
|
143
|
+
|
|
144
|
+
if checkpoint_id is not None:
|
|
145
|
+
cur = self.conn.execute(
|
|
146
|
+
"""
|
|
147
|
+
SELECT checkpoint_id, parent_checkpoint_id, checkpoint_json, metadata_json
|
|
148
|
+
FROM langgraph_checkpoints
|
|
149
|
+
WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ?
|
|
150
|
+
""",
|
|
151
|
+
(thread_id, checkpoint_ns, str(checkpoint_id)),
|
|
152
|
+
)
|
|
153
|
+
else:
|
|
154
|
+
cur = self.conn.execute(
|
|
155
|
+
"""
|
|
156
|
+
SELECT checkpoint_id, parent_checkpoint_id, checkpoint_json, metadata_json
|
|
157
|
+
FROM langgraph_checkpoints
|
|
158
|
+
WHERE thread_id = ? AND checkpoint_ns = ?
|
|
159
|
+
ORDER BY checkpoint_id DESC
|
|
160
|
+
LIMIT 1
|
|
161
|
+
""",
|
|
162
|
+
(thread_id, checkpoint_ns),
|
|
163
|
+
)
|
|
164
|
+
row = cur.fetchone()
|
|
165
|
+
if row is None:
|
|
166
|
+
return None
|
|
167
|
+
|
|
168
|
+
cid, parent_id, cp_json, meta_json = row
|
|
169
|
+
wcur = self.conn.execute(
|
|
170
|
+
"""
|
|
171
|
+
SELECT task_id, channel, value_json
|
|
172
|
+
FROM langgraph_writes
|
|
173
|
+
WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ?
|
|
174
|
+
ORDER BY idx ASC
|
|
175
|
+
""",
|
|
176
|
+
(thread_id, checkpoint_ns, cid),
|
|
177
|
+
)
|
|
178
|
+
pending_writes = [(t, ch, json.loads(vj)) for (t, ch, vj) in wcur.fetchall()]
|
|
179
|
+
parent_cfg = (
|
|
180
|
+
{
|
|
181
|
+
"configurable": {
|
|
182
|
+
"thread_id": thread_id,
|
|
183
|
+
"checkpoint_ns": checkpoint_ns,
|
|
184
|
+
"checkpoint_id": parent_id,
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
if parent_id is not None
|
|
188
|
+
else None
|
|
189
|
+
)
|
|
190
|
+
return CheckpointTuple(
|
|
191
|
+
config={
|
|
192
|
+
"configurable": {
|
|
193
|
+
"thread_id": thread_id,
|
|
194
|
+
"checkpoint_ns": checkpoint_ns,
|
|
195
|
+
"checkpoint_id": cid,
|
|
196
|
+
}
|
|
197
|
+
},
|
|
198
|
+
checkpoint=json.loads(cp_json),
|
|
199
|
+
metadata=json.loads(meta_json),
|
|
200
|
+
parent_config=parent_cfg,
|
|
201
|
+
pending_writes=pending_writes,
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
def list(
|
|
205
|
+
self,
|
|
206
|
+
config: Optional[Dict[str, Any]],
|
|
207
|
+
*,
|
|
208
|
+
limit: Optional[int] = None,
|
|
209
|
+
) -> Iterator[CheckpointTuple]:
|
|
210
|
+
cfg = (config or {}).get("configurable", {})
|
|
211
|
+
thread_id = cfg.get("thread_id")
|
|
212
|
+
checkpoint_ns = cfg.get("checkpoint_ns")
|
|
213
|
+
clauses: List[str] = []
|
|
214
|
+
params: List[Any] = []
|
|
215
|
+
if thread_id is not None:
|
|
216
|
+
clauses.append("thread_id = ?")
|
|
217
|
+
params.append(str(thread_id))
|
|
218
|
+
if checkpoint_ns is not None:
|
|
219
|
+
clauses.append("checkpoint_ns = ?")
|
|
220
|
+
params.append(str(checkpoint_ns))
|
|
221
|
+
where = f"WHERE {' AND '.join(clauses)}" if clauses else ""
|
|
222
|
+
lim = f" LIMIT {int(limit)}" if limit is not None else ""
|
|
223
|
+
cur = self.conn.execute(
|
|
224
|
+
f"""
|
|
225
|
+
SELECT thread_id, checkpoint_ns, checkpoint_id
|
|
226
|
+
FROM langgraph_checkpoints
|
|
227
|
+
{where}
|
|
228
|
+
ORDER BY checkpoint_id DESC{lim}
|
|
229
|
+
""",
|
|
230
|
+
params,
|
|
231
|
+
)
|
|
232
|
+
for tid, ns, cid in cur.fetchall():
|
|
233
|
+
tup = self.get_tuple(
|
|
234
|
+
{"configurable": {"thread_id": tid, "checkpoint_ns": ns, "checkpoint_id": cid}}
|
|
235
|
+
)
|
|
236
|
+
if tup is not None:
|
|
237
|
+
yield tup
|
|
238
|
+
|
|
239
|
+
def delete_thread(self, thread_id: str) -> None:
|
|
240
|
+
self.conn.execute("DELETE FROM langgraph_writes WHERE thread_id = ?", (thread_id,))
|
|
241
|
+
self.conn.execute("DELETE FROM langgraph_checkpoints WHERE thread_id = ?", (thread_id,))
|
|
242
|
+
|
|
243
|
+
def save_restore_point(self, name: str) -> None:
|
|
244
|
+
"""Create a whole-database FerrousDB restore point for instant agent rollback."""
|
|
245
|
+
self.conn.create_restore_point(name)
|
|
246
|
+
|
|
247
|
+
def undo_to_restore_point(self, name: str) -> None:
|
|
248
|
+
"""Roll back the entire agent checkpoint store to a saved restore point."""
|
|
249
|
+
self.conn.restore_to(name)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ferrousdb
|
|
3
|
+
Version: 0.1.0rc4
|
|
4
|
+
Summary: Python bindings (ctypes) over FerrousDB's stable C-ABI (ferrous_ffi).
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Repository, https://github.com/cleissonbarbosa/FerrousDB
|
|
7
|
+
Keywords: database,sql,embedded,ferrousdb,ai-agents
|
|
8
|
+
Requires-Python: >=3.9
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
|
|
11
|
+
# `ferrousdb` (Python)
|
|
12
|
+
|
|
13
|
+
Python `ctypes` bindings over FerrousDB's stable C-ABI (`crates/ferrous-ffi`).
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
cargo build --locked --release -p ferrous_ffi
|
|
17
|
+
PYTHONPATH=packaging/python python3 -m unittest discover -s packaging/python/tests -v
|
|
18
|
+
```
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
ferrousdb/__init__.py
|
|
4
|
+
ferrousdb/dbapi.py
|
|
5
|
+
ferrousdb/langgraph.py
|
|
6
|
+
ferrousdb.egg-info/PKG-INFO
|
|
7
|
+
ferrousdb.egg-info/SOURCES.txt
|
|
8
|
+
ferrousdb.egg-info/dependency_links.txt
|
|
9
|
+
ferrousdb.egg-info/top_level.txt
|
|
10
|
+
tests/test_dbapi_and_langgraph.py
|
|
11
|
+
tests/test_smoke.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ferrousdb
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ferrousdb"
|
|
7
|
+
version = "0.1.0rc4"
|
|
8
|
+
description = "Python bindings (ctypes) over FerrousDB's stable C-ABI (ferrous_ffi)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
keywords = ["database", "sql", "embedded", "ferrousdb", "ai-agents"]
|
|
13
|
+
|
|
14
|
+
[project.urls]
|
|
15
|
+
Repository = "https://github.com/cleissonbarbosa/FerrousDB"
|
|
16
|
+
|
|
17
|
+
[tool.setuptools.packages.find]
|
|
18
|
+
where = ["."]
|
|
19
|
+
include = ["ferrousdb*"]
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import tempfile
|
|
2
|
+
import unittest
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import ferrousdb
|
|
6
|
+
from ferrousdb import (
|
|
7
|
+
ExecutionLimits,
|
|
8
|
+
FerrousSaver,
|
|
9
|
+
IntegrityError,
|
|
10
|
+
OperationalError,
|
|
11
|
+
ProgrammingError,
|
|
12
|
+
connect,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class DbApiAndLangGraphTests(unittest.TestCase):
|
|
17
|
+
def test_pep249_dbapi_crud_params_transactions_and_errors(self) -> None:
|
|
18
|
+
self.assertEqual(ferrousdb.apilevel, "2.0")
|
|
19
|
+
self.assertEqual(ferrousdb.paramstyle, "qmark")
|
|
20
|
+
|
|
21
|
+
with connect(":memory:") as conn:
|
|
22
|
+
cur = conn.cursor()
|
|
23
|
+
cur.execute(
|
|
24
|
+
"CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL UNIQUE, score REAL)"
|
|
25
|
+
)
|
|
26
|
+
cur.executemany(
|
|
27
|
+
"INSERT INTO users (name, score) VALUES (?, ?)",
|
|
28
|
+
[("Ada", 9.5), ("Bob", 8.0), ("O'Brien", 7.25)],
|
|
29
|
+
)
|
|
30
|
+
self.assertEqual(cur.rowcount, 3)
|
|
31
|
+
|
|
32
|
+
cur.execute("SELECT id, name, score FROM users WHERE score >= ? ORDER BY id", (8.0,))
|
|
33
|
+
self.assertEqual([d[0] for d in cur.description], ["id", "name", "score"])
|
|
34
|
+
self.assertEqual(cur.fetchone(), (1, "Ada", 9.5))
|
|
35
|
+
self.assertEqual(cur.fetchall(), [(2, "Bob", 8.0)])
|
|
36
|
+
|
|
37
|
+
# IntegrityError on duplicate UNIQUE
|
|
38
|
+
with self.assertRaises(IntegrityError) as ctx:
|
|
39
|
+
cur.execute("INSERT INTO users (name, score) VALUES (?, ?)", ("Ada", 1.0))
|
|
40
|
+
self.assertIsNotNone(ctx.exception.diagnostic)
|
|
41
|
+
|
|
42
|
+
# ProgrammingError on syntax / unknown table
|
|
43
|
+
with self.assertRaises(ProgrammingError):
|
|
44
|
+
cur.execute("SELECT * FROM nonexistent_table")
|
|
45
|
+
|
|
46
|
+
# Engine-enforced limits surface as OperationalError
|
|
47
|
+
conn.set_limits(ExecutionLimits(allow_unfiltered_write=False))
|
|
48
|
+
with self.assertRaises(OperationalError):
|
|
49
|
+
cur.execute("DELETE FROM users")
|
|
50
|
+
|
|
51
|
+
# Preview dry-run works via DB-API connection
|
|
52
|
+
prev = conn.preview("UPDATE users SET score = 10.0 WHERE id = ?", (1,))
|
|
53
|
+
self.assertEqual(len(prev["changes"]), 1)
|
|
54
|
+
|
|
55
|
+
def test_langgraph_ferrous_saver_checkpoint_and_restore(self) -> None:
|
|
56
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
57
|
+
db_path = str(Path(tmp) / "agent.ferrous")
|
|
58
|
+
saver = FerrousSaver.from_conn_string(db_path)
|
|
59
|
+
cfg1 = {"configurable": {"thread_id": "t1", "checkpoint_ns": ""}}
|
|
60
|
+
saved1 = saver.put(
|
|
61
|
+
cfg1,
|
|
62
|
+
{"id": "cp-001", "channel_values": {"messages": ["hello"]}},
|
|
63
|
+
{"step": 1},
|
|
64
|
+
)
|
|
65
|
+
saver.put_writes(saved1, [("messages", "thinking...")], task_id="task-1")
|
|
66
|
+
saver.save_restore_point("before_step2")
|
|
67
|
+
|
|
68
|
+
saved2 = saver.put(
|
|
69
|
+
saved1,
|
|
70
|
+
{"id": "cp-002", "channel_values": {"messages": ["hello", "world"]}},
|
|
71
|
+
{"step": 2},
|
|
72
|
+
)
|
|
73
|
+
latest = saver.get_tuple(cfg1)
|
|
74
|
+
self.assertIsNotNone(latest)
|
|
75
|
+
self.assertEqual(latest.checkpoint["id"], "cp-002")
|
|
76
|
+
self.assertEqual(latest.parent_config["configurable"]["checkpoint_id"], "cp-001")
|
|
77
|
+
|
|
78
|
+
all_cps = list(saver.list(cfg1))
|
|
79
|
+
self.assertEqual([c.checkpoint["id"] for c in all_cps], ["cp-002", "cp-001"])
|
|
80
|
+
|
|
81
|
+
# Instant database-level rollback back to before step 2!
|
|
82
|
+
saver.undo_to_restore_point("before_step2")
|
|
83
|
+
rolled = saver.get_tuple(cfg1)
|
|
84
|
+
self.assertIsNotNone(rolled)
|
|
85
|
+
self.assertEqual(rolled.checkpoint["id"], "cp-001")
|
|
86
|
+
self.assertEqual(rolled.pending_writes, [("task-1", "messages", "thinking...")])
|
|
87
|
+
|
|
88
|
+
saver.delete_thread("t1")
|
|
89
|
+
self.assertIsNone(saver.get_tuple(cfg1))
|
|
90
|
+
saver.conn.close()
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
if __name__ == "__main__":
|
|
94
|
+
unittest.main()
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import tempfile
|
|
3
|
+
import unittest
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from ferrousdb import (
|
|
7
|
+
Database,
|
|
8
|
+
ExecutionLimits,
|
|
9
|
+
FERROUS_ERR_LIMIT,
|
|
10
|
+
FERROUS_ERR_READONLY,
|
|
11
|
+
FerrousError,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class SmokeTest(unittest.TestCase):
|
|
16
|
+
def test_in_memory_query_preview_limits_and_undo(self) -> None:
|
|
17
|
+
with Database.in_memory() as db, db.connect() as conn:
|
|
18
|
+
conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL)")
|
|
19
|
+
conn.execute("INSERT INTO users VALUES (1, 'Ada'), (2, 'Bob')")
|
|
20
|
+
conn.create_restore_point("init")
|
|
21
|
+
|
|
22
|
+
prev = conn.preview("UPDATE users SET name = 'Grace' WHERE id = 1")
|
|
23
|
+
self.assertEqual(prev["rows_affected"], 1)
|
|
24
|
+
|
|
25
|
+
cols, rows = conn.query("SELECT id, name FROM users ORDER BY id")
|
|
26
|
+
self.assertEqual(cols, ["id", "name"])
|
|
27
|
+
self.assertEqual(rows, [[1, "Ada"], [2, "Bob"]])
|
|
28
|
+
|
|
29
|
+
conn.set_limits(
|
|
30
|
+
ExecutionLimits(
|
|
31
|
+
allow_unfiltered_write=False,
|
|
32
|
+
allow_drop=False,
|
|
33
|
+
max_rows_affected=1,
|
|
34
|
+
)
|
|
35
|
+
)
|
|
36
|
+
with self.assertRaises(FerrousError) as ctx:
|
|
37
|
+
conn.execute("DELETE FROM users")
|
|
38
|
+
self.assertEqual(ctx.exception.code, FERROUS_ERR_LIMIT)
|
|
39
|
+
self.assertEqual(ctx.exception.diagnostic["code"], "FERROUS_ERR_LIMIT")
|
|
40
|
+
|
|
41
|
+
conn.execute("UPDATE users SET name = 'Grace' WHERE id = 1")
|
|
42
|
+
conn.restore_to("init")
|
|
43
|
+
_, rows_after = conn.query("SELECT name FROM users WHERE id = 1")
|
|
44
|
+
self.assertEqual(rows_after, [["Ada"]])
|
|
45
|
+
|
|
46
|
+
def test_read_only_on_disk(self) -> None:
|
|
47
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
48
|
+
db_path = Path(tmp) / "ro.ferrous"
|
|
49
|
+
with Database.open(str(db_path)) as db, db.connect() as conn:
|
|
50
|
+
conn.execute("CREATE TABLE kv (k TEXT PRIMARY KEY, v INTEGER)")
|
|
51
|
+
conn.execute("INSERT INTO kv VALUES ('a', 1)")
|
|
52
|
+
|
|
53
|
+
with Database.open(str(db_path), read_only=True) as ro, ro.connect() as conn:
|
|
54
|
+
_, rows = conn.query("SELECT k, v FROM kv")
|
|
55
|
+
self.assertEqual(rows, [["a", 1]])
|
|
56
|
+
with self.assertRaises(FerrousError) as ctx:
|
|
57
|
+
conn.execute("INSERT INTO kv VALUES ('b', 2)")
|
|
58
|
+
self.assertEqual(ctx.exception.code, FERROUS_ERR_READONLY)
|
|
59
|
+
self.assertEqual(ctx.exception.diagnostic["code"], "FERROUS_ERR_READONLY")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
if __name__ == "__main__":
|
|
63
|
+
unittest.main()
|