fadodb 0.9.0__py3-none-win_amd64.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.
- fadodb/__init__.py +30 -0
- fadodb/_database.py +194 -0
- fadodb/_library.py +199 -0
- fadodb/_server.py +79 -0
- fadodb/lib/duckdb.dll +4 -0
- fadodb/lib/fadodb.dll +0 -0
- fadodb-0.9.0.dist-info/METADATA +138 -0
- fadodb-0.9.0.dist-info/RECORD +12 -0
- fadodb-0.9.0.dist-info/WHEEL +4 -0
- fadodb-0.9.0.dist-info/licenses/LICENSE +201 -0
- fadodb-0.9.0.dist-info/licenses/LICENSE-duckdb +7 -0
- fadodb-0.9.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +2660 -0
fadodb/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""FadoDB for Python: a database over HTTP, or in the same process.
|
|
2
|
+
|
|
3
|
+
Two ways to the same database, and one way to use it (ADR-0101, step C):
|
|
4
|
+
|
|
5
|
+
import fadodb
|
|
6
|
+
|
|
7
|
+
# A server, as the user whose key it is:
|
|
8
|
+
db = fadodb.connect("https://fado.acme.example", key="fado_Q329CE63C9_…")
|
|
9
|
+
|
|
10
|
+
# Or the database file itself, in this process, through the library
|
|
11
|
+
# of C; the program says who is calling:
|
|
12
|
+
db = fadodb.open("books.fado", caller={"id": "ann", "groups": ["sales"]})
|
|
13
|
+
|
|
14
|
+
invoice = db.exec("create", {"class": "Invoice", "id": "FV/2026/11/0042",
|
|
15
|
+
"values": {"number": "FV/2026/11/0042"}})["document"]
|
|
16
|
+
try:
|
|
17
|
+
db.exec("transition", {"class": "Invoice", "id": "FV/2026/11/0042",
|
|
18
|
+
"transition": "book"})
|
|
19
|
+
except fadodb.Refused as refusal:
|
|
20
|
+
print(refusal.code, refusal.message) # guard_false …
|
|
21
|
+
|
|
22
|
+
A command is a name and one JSON object, and its answer is one JSON
|
|
23
|
+
object: the commands of the command set, the same as a server takes at
|
|
24
|
+
POST /v1/<command>. A refusal is raised as Refused, with the code a
|
|
25
|
+
program branches on. Nothing but the standard library is needed.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from ._database import Database, NoAnswer, Permanent, Refused, connect, open
|
|
29
|
+
|
|
30
|
+
__all__ = ["Database", "NoAnswer", "Permanent", "Refused", "connect", "open"]
|
fadodb/_database.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""The database a program uses, whichever way it reaches it."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
__all__ = ["Database", "NoAnswer", "Permanent", "Refused", "connect", "open"]
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Refused(Exception):
|
|
9
|
+
"""A command the database did not carry out.
|
|
10
|
+
|
|
11
|
+
code is what a program branches on, such as forbidden or guard_false;
|
|
12
|
+
message says why in words, hint how to send it so that it is carried
|
|
13
|
+
out, and path names the member of the object it is about. answer is
|
|
14
|
+
the whole answer: a refused definition has its findings there, under
|
|
15
|
+
diagnostics. status is the status of the reply over HTTP, and None in
|
|
16
|
+
the same process.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def __init__(self, answer, status=None):
|
|
20
|
+
error = answer.get("error") if isinstance(answer, dict) else None
|
|
21
|
+
if not isinstance(error, dict):
|
|
22
|
+
error = {"code": "internal", "message": "the answer is a refusal without an error"}
|
|
23
|
+
self.answer = answer
|
|
24
|
+
self.status = status
|
|
25
|
+
self.code = error.get("code")
|
|
26
|
+
self.message = error.get("message", "")
|
|
27
|
+
self.hint = error.get("hint")
|
|
28
|
+
self.path = error.get("path")
|
|
29
|
+
super().__init__(f"{self.code}: {self.message}")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class NoAnswer(Exception):
|
|
33
|
+
"""No answer came through: the server was not reached, what answered
|
|
34
|
+
is not a FadoDB server, or the answer was cut off. The command may
|
|
35
|
+
have been carried out; one that carries a "key" is safely sent
|
|
36
|
+
again."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Permanent(Exception):
|
|
40
|
+
"""Raised by the program's function for an action, a refusal: an
|
|
41
|
+
answer that asking again would not change. The action is dead at
|
|
42
|
+
once, with these words; any other exception is tried again."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def connect(url, key, *, timeout=60.0):
|
|
46
|
+
"""The database a server serves at url, as the user whose key it is.
|
|
47
|
+
|
|
48
|
+
Every command is judged by the rules of the database as that user's,
|
|
49
|
+
and written to its log under that user. timeout is how long one
|
|
50
|
+
command may take, in seconds, before NoAnswer.
|
|
51
|
+
"""
|
|
52
|
+
from ._server import Server
|
|
53
|
+
|
|
54
|
+
return Database(Server(url, key, timeout), None)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def open(path, *, caller=None, options=None, library=None, actions=None):
|
|
58
|
+
"""The database file at path, held in this process through the
|
|
59
|
+
library of C, and made when it does not exist.
|
|
60
|
+
|
|
61
|
+
caller is who the program says is calling, with the members a user
|
|
62
|
+
has: {"id": "ann", "kind": "person", "groups": ["sales"],
|
|
63
|
+
"system_groups": ["designers"], "today": "2026-11-27"}; None is
|
|
64
|
+
nobody. The engine trusts it: the program has said who it is.
|
|
65
|
+
Database.as_caller gives the same database to another caller.
|
|
66
|
+
|
|
67
|
+
options are the options of fado_open, such as {"timezone":
|
|
68
|
+
"Europe/Warsaw"}. library is the path of the library; when it is
|
|
69
|
+
None, the variable FADODB_LIBRARY of the environment names it, or
|
|
70
|
+
the one beside this package, or the one the system finds.
|
|
71
|
+
|
|
72
|
+
actions are the actions the program carries out itself, a function
|
|
73
|
+
by the name of each (ADR-0102): {"mail.send": send}. The function is
|
|
74
|
+
called with the call, a dict as a webhook gets it, from a thread of
|
|
75
|
+
the worker, and returns the action's result as a dict, or None for
|
|
76
|
+
nothing; raising Permanent refuses the call, and any other exception
|
|
77
|
+
fails it, to be tried again.
|
|
78
|
+
"""
|
|
79
|
+
from ._library import Opened
|
|
80
|
+
|
|
81
|
+
return Database(Opened(path, options, library, actions), caller)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
# A command whose answer is a stream, which one call cannot answer.
|
|
85
|
+
_STREAMS = {"subscribe"}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class Database:
|
|
89
|
+
"""A database, over HTTP or in this process: the same commands, the
|
|
90
|
+
same answers."""
|
|
91
|
+
|
|
92
|
+
def __init__(self, door, caller):
|
|
93
|
+
self._door = door
|
|
94
|
+
self._caller = _caller_text(caller)
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def in_process(self):
|
|
98
|
+
"""Whether the database is held in this process."""
|
|
99
|
+
return self._door.in_process
|
|
100
|
+
|
|
101
|
+
def as_caller(self, caller):
|
|
102
|
+
"""The same database, for another caller. Only a database held
|
|
103
|
+
in this process has a caller of the program's choosing: over
|
|
104
|
+
HTTP, the key says who calls."""
|
|
105
|
+
if not self._door.in_process:
|
|
106
|
+
raise TypeError("over HTTP the key says who is calling: connect with that user's key")
|
|
107
|
+
return Database(self._door, caller)
|
|
108
|
+
|
|
109
|
+
def exec(self, command, object=None):
|
|
110
|
+
"""Runs one command and answers its answer, a dict. A refusal is
|
|
111
|
+
raised as Refused."""
|
|
112
|
+
if command in _STREAMS:
|
|
113
|
+
raise Refused({"error": {
|
|
114
|
+
"code": "not_supported",
|
|
115
|
+
"message": command + " answers a stream of events, and exec answers one object",
|
|
116
|
+
"hint": "wait_for_changes answers the same events, one call at a time"}})
|
|
117
|
+
text = json.dumps({} if object is None else object, ensure_ascii=False)
|
|
118
|
+
status, answer = self._door.exec(self._caller, command, text)
|
|
119
|
+
return _answered(status, answer)
|
|
120
|
+
|
|
121
|
+
def put_file(self, data, *, name=None, media_type=None):
|
|
122
|
+
"""Keeps the bytes of a file and answers its facts, {"hash": …,
|
|
123
|
+
"name": …, "media_type": …, "size": …}, for a command to commit in
|
|
124
|
+
a variable of the schema File."""
|
|
125
|
+
if not isinstance(data, (bytes, bytearray, memoryview)):
|
|
126
|
+
raise TypeError("the file is bytes")
|
|
127
|
+
status, answer = self._door.put_file(self._caller, name, media_type, bytes(data))
|
|
128
|
+
return _answered(status, answer)["file"]
|
|
129
|
+
|
|
130
|
+
def get_file(self, class_, id, hash, *, version=None, for_=None, reason=None):
|
|
131
|
+
"""Reads a file a document holds, under the rules of the document:
|
|
132
|
+
its facts and its bytes. version reads it as an earlier version of
|
|
133
|
+
the document held it, for_ says for whom the caller acts, and
|
|
134
|
+
reason is a content administrator's for reading past a rule."""
|
|
135
|
+
asked = {"class": class_, "id": id, "hash": hash}
|
|
136
|
+
if version is not None:
|
|
137
|
+
asked["version"] = version
|
|
138
|
+
if for_ is not None:
|
|
139
|
+
asked["for"] = for_
|
|
140
|
+
if reason is not None:
|
|
141
|
+
asked["reason"] = reason
|
|
142
|
+
status, answer, data = self._door.get_file(self._caller, asked)
|
|
143
|
+
return _file(_answered(status, answer)["file"]), data
|
|
144
|
+
|
|
145
|
+
def get_blob(self, hash, *, reason):
|
|
146
|
+
"""Reads bytes by their hash alone, which the engine does for a
|
|
147
|
+
content administrator and nobody else, with a reason the log of
|
|
148
|
+
reads keeps: their facts and their bytes."""
|
|
149
|
+
status, answer, data = self._door.get_blob(self._caller, {"hash": hash, "reason": reason})
|
|
150
|
+
return _file(_answered(status, answer)["file"]), data
|
|
151
|
+
|
|
152
|
+
def close(self):
|
|
153
|
+
"""Closes the database: in this process the file, for every caller
|
|
154
|
+
it was given to; over HTTP the connections. Closing again does
|
|
155
|
+
nothing."""
|
|
156
|
+
self._door.close()
|
|
157
|
+
|
|
158
|
+
def __enter__(self):
|
|
159
|
+
return self
|
|
160
|
+
|
|
161
|
+
def __exit__(self, *exc):
|
|
162
|
+
self.close()
|
|
163
|
+
return False
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _caller_text(caller):
|
|
167
|
+
if caller is None:
|
|
168
|
+
return ""
|
|
169
|
+
if isinstance(caller, str):
|
|
170
|
+
return caller
|
|
171
|
+
if not isinstance(caller, dict):
|
|
172
|
+
raise TypeError("the caller is a dict, such as {\"id\": \"ann\", \"groups\": [\"sales\"]}")
|
|
173
|
+
return json.dumps(caller, ensure_ascii=False)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _answered(status, text):
|
|
177
|
+
try:
|
|
178
|
+
answer = json.loads(text)
|
|
179
|
+
except ValueError:
|
|
180
|
+
raise NoAnswer("what answered is no JSON: " + text[:200]) from None
|
|
181
|
+
if not isinstance(answer, dict):
|
|
182
|
+
raise NoAnswer("what answered is no JSON object: " + text[:200])
|
|
183
|
+
if "error" in answer:
|
|
184
|
+
raise Refused(answer, status)
|
|
185
|
+
return answer
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _file(facts):
|
|
189
|
+
# A file of no known type is application/octet-stream, as a server
|
|
190
|
+
# serves it.
|
|
191
|
+
facts = dict(facts)
|
|
192
|
+
if not facts.get("media_type"):
|
|
193
|
+
facts["media_type"] = "application/octet-stream"
|
|
194
|
+
return facts
|
fadodb/_library.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""A database held in this process, through the library of C (ADR-0101)."""
|
|
2
|
+
|
|
3
|
+
import ctypes
|
|
4
|
+
import ctypes.util
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
import threading
|
|
9
|
+
import weakref
|
|
10
|
+
|
|
11
|
+
# The files of the two libraries on each system (ADR-0102): libfadodb,
|
|
12
|
+
# with DuckDB, which a wheel carries, and libfadodb-core.
|
|
13
|
+
if sys.platform == "win32":
|
|
14
|
+
_NAMES = ("fadodb.dll", "fadodb-core.dll")
|
|
15
|
+
elif sys.platform == "darwin":
|
|
16
|
+
_NAMES = ("libfadodb.dylib", "libfadodb-core.dylib")
|
|
17
|
+
else:
|
|
18
|
+
_NAMES = ("libfadodb.so", "libfadodb-core.so")
|
|
19
|
+
|
|
20
|
+
# A process holds one library: a second Go library beside it would not
|
|
21
|
+
# work (ADR-0101, item 11). It is loaded the first time it is asked for.
|
|
22
|
+
_loaded = None
|
|
23
|
+
_loading = threading.Lock()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _load(path):
|
|
27
|
+
global _loaded
|
|
28
|
+
with _loading:
|
|
29
|
+
if _loaded is not None:
|
|
30
|
+
if path is not None and os.path.abspath(path) != _loaded[0]:
|
|
31
|
+
raise RuntimeError("this process already holds the library " + _loaded[0]
|
|
32
|
+
+ ", and a process holds one library")
|
|
33
|
+
return _loaded[1]
|
|
34
|
+
here = os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")
|
|
35
|
+
candidates = [path] if path is not None else [
|
|
36
|
+
os.environ.get("FADODB_LIBRARY"),
|
|
37
|
+
*(os.path.join(here, name) for name in _NAMES),
|
|
38
|
+
ctypes.util.find_library("fadodb"),
|
|
39
|
+
ctypes.util.find_library("fadodb-core"),
|
|
40
|
+
]
|
|
41
|
+
tried = []
|
|
42
|
+
for candidate in candidates:
|
|
43
|
+
if not candidate:
|
|
44
|
+
continue
|
|
45
|
+
if os.sep in candidate or "/" in candidate:
|
|
46
|
+
if not os.path.exists(candidate):
|
|
47
|
+
tried.append(candidate)
|
|
48
|
+
continue
|
|
49
|
+
candidate = os.path.abspath(candidate)
|
|
50
|
+
lib = ctypes.CDLL(candidate)
|
|
51
|
+
_declare(lib)
|
|
52
|
+
_loaded = (candidate, lib)
|
|
53
|
+
return lib
|
|
54
|
+
raise FileNotFoundError(
|
|
55
|
+
"no library of FadoDB was found (" + ", ".join(tried or ["none was named"]) + "): "
|
|
56
|
+
"give its path as library, or in the variable FADODB_LIBRARY; scripts/library.sh build builds both as bin/library/"
|
|
57
|
+
+ _NAMES[0] + " and " + _NAMES[1])
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
# The program's function for its actions, as fadodb.h declares it.
|
|
61
|
+
_ACTION = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_uint64, ctypes.c_char_p, ctypes.c_char_p)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _declare(lib):
|
|
65
|
+
u64, text, void = ctypes.c_uint64, ctypes.c_char_p, ctypes.c_void_p
|
|
66
|
+
out, size = ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_size_t)
|
|
67
|
+
lib.fado_open.argtypes = [text, text, out]
|
|
68
|
+
lib.fado_open.restype = u64
|
|
69
|
+
lib.fado_open_with.argtypes = [text, text, _ACTION, void, out]
|
|
70
|
+
lib.fado_open_with.restype = u64
|
|
71
|
+
lib.fado_answer.argtypes = [u64, text]
|
|
72
|
+
lib.fado_answer.restype = ctypes.c_int
|
|
73
|
+
# The answers are kept as pointers, so that they are given back.
|
|
74
|
+
lib.fado_exec.argtypes = [u64, text, text, text]
|
|
75
|
+
lib.fado_exec.restype = void
|
|
76
|
+
lib.fado_close.argtypes = [u64, out]
|
|
77
|
+
lib.fado_close.restype = ctypes.c_int
|
|
78
|
+
lib.fado_free.argtypes = [void]
|
|
79
|
+
lib.fado_free.restype = None
|
|
80
|
+
lib.fado_version.argtypes = []
|
|
81
|
+
lib.fado_version.restype = text
|
|
82
|
+
lib.fado_put_file.argtypes = [u64, text, text, text, ctypes.c_size_t]
|
|
83
|
+
lib.fado_put_file.restype = void
|
|
84
|
+
lib.fado_get_file.argtypes = [u64, text, text, out, size]
|
|
85
|
+
lib.fado_get_file.restype = void
|
|
86
|
+
lib.fado_get_blob.argtypes = [u64, text, text, out, size]
|
|
87
|
+
lib.fado_get_blob.restype = void
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _take(lib, pointer):
|
|
91
|
+
"""The text of an answer of the library, which is then given back."""
|
|
92
|
+
if not pointer:
|
|
93
|
+
return ""
|
|
94
|
+
try:
|
|
95
|
+
return ctypes.string_at(pointer).decode("utf-8")
|
|
96
|
+
finally:
|
|
97
|
+
lib.fado_free(pointer)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def version(library=None):
|
|
101
|
+
"""The version of the library, such as v0.9.0, or dev."""
|
|
102
|
+
return _load(library).fado_version().decode("utf-8")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class Opened:
|
|
106
|
+
"""One database the library opened, shared by every caller it is
|
|
107
|
+
given to."""
|
|
108
|
+
|
|
109
|
+
in_process = True
|
|
110
|
+
|
|
111
|
+
def __init__(self, path, options, library, actions=None):
|
|
112
|
+
from ._database import Refused
|
|
113
|
+
|
|
114
|
+
self._lib = _load(library)
|
|
115
|
+
options = dict(options or {})
|
|
116
|
+
carry_out = _ACTION()
|
|
117
|
+
if actions:
|
|
118
|
+
if "actions" in options:
|
|
119
|
+
raise TypeError("the actions are given once: as functions in actions, not as names in options")
|
|
120
|
+
for name, function in actions.items():
|
|
121
|
+
if not callable(function):
|
|
122
|
+
raise TypeError("the action " + name + " is given no function")
|
|
123
|
+
options["actions"] = sorted(actions)
|
|
124
|
+
carry_out = _ACTION(_carrier(self._lib, dict(actions)))
|
|
125
|
+
refusal = ctypes.c_void_p()
|
|
126
|
+
options_text = json.dumps(options, ensure_ascii=False).encode("utf-8")
|
|
127
|
+
self._n = self._lib.fado_open_with(os.fspath(path).encode("utf-8"), options_text, carry_out, None, ctypes.byref(refusal))
|
|
128
|
+
if self._n == 0:
|
|
129
|
+
raise Refused(json.loads(_take(self._lib, refusal.value)))
|
|
130
|
+
# A database nobody holds any more is closed, as a file is; the
|
|
131
|
+
# function for its actions lives as long as it.
|
|
132
|
+
self._finalizer = weakref.finalize(self, _close, self._lib, self._n, carry_out)
|
|
133
|
+
|
|
134
|
+
def exec(self, caller, command, object_text):
|
|
135
|
+
answer = self._lib.fado_exec(self._n, caller.encode("utf-8"), command.encode("utf-8"), object_text.encode("utf-8"))
|
|
136
|
+
return None, _take(self._lib, answer)
|
|
137
|
+
|
|
138
|
+
def put_file(self, caller, name, media_type, data):
|
|
139
|
+
asked = {}
|
|
140
|
+
if name is not None:
|
|
141
|
+
asked["name"] = name
|
|
142
|
+
if media_type is not None:
|
|
143
|
+
asked["media_type"] = media_type
|
|
144
|
+
object_text = json.dumps(asked, ensure_ascii=False).encode("utf-8")
|
|
145
|
+
answer = self._lib.fado_put_file(self._n, caller.encode("utf-8"), object_text, data, len(data))
|
|
146
|
+
return None, _take(self._lib, answer)
|
|
147
|
+
|
|
148
|
+
def get_file(self, caller, asked):
|
|
149
|
+
return self._get(self._lib.fado_get_file, caller, asked)
|
|
150
|
+
|
|
151
|
+
def get_blob(self, caller, asked):
|
|
152
|
+
return self._get(self._lib.fado_get_blob, caller, asked)
|
|
153
|
+
|
|
154
|
+
def _get(self, function, caller, asked):
|
|
155
|
+
data, length = ctypes.c_void_p(), ctypes.c_size_t()
|
|
156
|
+
object_text = json.dumps(asked, ensure_ascii=False).encode("utf-8")
|
|
157
|
+
answer = function(self._n, caller.encode("utf-8"), object_text, ctypes.byref(data), ctypes.byref(length))
|
|
158
|
+
got = None
|
|
159
|
+
if data.value:
|
|
160
|
+
try:
|
|
161
|
+
got = ctypes.string_at(data.value, length.value)
|
|
162
|
+
finally:
|
|
163
|
+
self._lib.fado_free(data.value)
|
|
164
|
+
return None, _take(self._lib, answer), got
|
|
165
|
+
|
|
166
|
+
def close(self):
|
|
167
|
+
self._finalizer()
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _close(lib, n, carry_out=None):
|
|
171
|
+
lib.fado_close(n, None)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _carrier(lib, actions):
|
|
175
|
+
"""The function the library calls for an action the program carries
|
|
176
|
+
out: it runs the program's function and answers with fado_answer."""
|
|
177
|
+
from ._database import Permanent
|
|
178
|
+
|
|
179
|
+
def carry_out(_context, call, action, object_text):
|
|
180
|
+
name = action.decode("utf-8")
|
|
181
|
+
try:
|
|
182
|
+
result = actions[name](json.loads(object_text.decode("utf-8")))
|
|
183
|
+
if result is None:
|
|
184
|
+
result = {}
|
|
185
|
+
if not isinstance(result, dict):
|
|
186
|
+
raise TypeError("the function for " + name + " returned " + type(result).__name__
|
|
187
|
+
+ ", and the result of an action is a dict of what it returns")
|
|
188
|
+
answer = {"result": result}
|
|
189
|
+
except Permanent as refusal:
|
|
190
|
+
answer = {"error": {"message": str(refusal) or name + " was refused", "permanent": True}}
|
|
191
|
+
except Exception as failure: # noqa: BLE001 - a failure of the program's function is tried again
|
|
192
|
+
answer = {"error": {"message": type(failure).__name__ + ": " + str(failure)}}
|
|
193
|
+
try:
|
|
194
|
+
text = json.dumps(answer, ensure_ascii=False)
|
|
195
|
+
except (TypeError, ValueError) as failure:
|
|
196
|
+
text = json.dumps({"error": {"message": "the result of " + name + " is no JSON: " + str(failure)}})
|
|
197
|
+
lib.fado_answer(call, text.encode("utf-8"))
|
|
198
|
+
|
|
199
|
+
return carry_out
|
fadodb/_server.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""A database a server serves, over HTTP (ADR-0055)."""
|
|
2
|
+
|
|
3
|
+
import email.message
|
|
4
|
+
import json
|
|
5
|
+
import urllib.error
|
|
6
|
+
import urllib.parse
|
|
7
|
+
import urllib.request
|
|
8
|
+
|
|
9
|
+
from ._database import NoAnswer
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Server:
|
|
13
|
+
"""The commands of one database, sent to its server as one user."""
|
|
14
|
+
|
|
15
|
+
in_process = False
|
|
16
|
+
|
|
17
|
+
def __init__(self, url, key, timeout):
|
|
18
|
+
if not url.startswith(("http://", "https://")):
|
|
19
|
+
raise ValueError("the address of a server begins with https:// or http://")
|
|
20
|
+
self._base = url.rstrip("/") + "/v1/"
|
|
21
|
+
self._key = key
|
|
22
|
+
self._timeout = timeout
|
|
23
|
+
|
|
24
|
+
def _send(self, method, address, body=None, content_type=None):
|
|
25
|
+
headers = {"Authorization": "Bearer " + self._key, "Accept": "application/json"}
|
|
26
|
+
if body is not None:
|
|
27
|
+
# A body is sent with its own type, or none: never as a form,
|
|
28
|
+
# which is what urllib would say it is.
|
|
29
|
+
headers["Content-Type"] = content_type or ""
|
|
30
|
+
request = urllib.request.Request(self._base + address, data=body, method=method, headers=headers)
|
|
31
|
+
try:
|
|
32
|
+
with urllib.request.urlopen(request, timeout=self._timeout) as reply:
|
|
33
|
+
return reply.status, reply.headers, reply.read()
|
|
34
|
+
except urllib.error.HTTPError as reply:
|
|
35
|
+
try:
|
|
36
|
+
return reply.code, reply.headers, reply.read()
|
|
37
|
+
finally:
|
|
38
|
+
reply.close()
|
|
39
|
+
except (urllib.error.URLError, OSError) as failure:
|
|
40
|
+
raise NoAnswer("the server at " + self._base + " was not reached: " + str(failure)) from failure
|
|
41
|
+
|
|
42
|
+
def exec(self, caller, command, object_text):
|
|
43
|
+
status, _, body = self._send("POST", urllib.parse.quote(command, safe=""), object_text.encode("utf-8"), "application/json")
|
|
44
|
+
return status, body.decode("utf-8", "replace")
|
|
45
|
+
|
|
46
|
+
def put_file(self, caller, name, media_type, data):
|
|
47
|
+
address = "blobs"
|
|
48
|
+
if name is not None:
|
|
49
|
+
address += "?" + urllib.parse.urlencode({"name": name})
|
|
50
|
+
status, _, body = self._send("POST", address, data, media_type)
|
|
51
|
+
return status, body.decode("utf-8", "replace")
|
|
52
|
+
|
|
53
|
+
def get_file(self, caller, asked):
|
|
54
|
+
return self._get("file", asked)
|
|
55
|
+
|
|
56
|
+
def get_blob(self, caller, asked):
|
|
57
|
+
return self._get("blob", asked)
|
|
58
|
+
|
|
59
|
+
def _get(self, address, asked):
|
|
60
|
+
status, headers, body = self._send("GET", address + "?" + urllib.parse.urlencode(asked))
|
|
61
|
+
if status != 200:
|
|
62
|
+
return status, body.decode("utf-8", "replace"), None
|
|
63
|
+
# The facts of the file are in the headers of the reply, as the
|
|
64
|
+
# library answers them in JSON.
|
|
65
|
+
facts = {"hash": (headers.get("ETag") or "").strip('"'), "size": len(body)}
|
|
66
|
+
disposition = email.message.Message()
|
|
67
|
+
disposition["Content-Disposition"] = headers.get("Content-Disposition", "")
|
|
68
|
+
name = disposition.get_param("filename", header="Content-Disposition")
|
|
69
|
+
if name:
|
|
70
|
+
facts["name"] = name
|
|
71
|
+
media_type = (headers.get("Content-Type") or "").split(";")[0].strip()
|
|
72
|
+
if media_type:
|
|
73
|
+
facts["media_type"] = media_type
|
|
74
|
+
return status, json.dumps({"file": facts}), body
|
|
75
|
+
|
|
76
|
+
def close(self):
|
|
77
|
+
# Each request has its own connection, closed when it is
|
|
78
|
+
# answered.
|
|
79
|
+
pass
|
fadodb/lib/duckdb.dll
ADDED
fadodb/lib/fadodb.dll
ADDED
|
Binary file
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fadodb
|
|
3
|
+
Version: 0.9.0
|
|
4
|
+
Summary: FadoDB for Python: a database over HTTP, or in the same process
|
|
5
|
+
Requires-Python: >=3.9
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
License-File: THIRD_PARTY_NOTICES.md
|
|
9
|
+
License-File: LICENSE-duckdb
|
|
10
|
+
Project-URL: Homepage, https://fadodb.org
|
|
11
|
+
Project-URL: Source, https://github.com/MojoHand70/fadodb
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# FadoDB for Python
|
|
15
|
+
|
|
16
|
+
One package, two ways to the same database, and one way to use it
|
|
17
|
+
([ADR-0101](../../docs/adr/0101-the-library-of-c.md)). Nothing but
|
|
18
|
+
Python's own library is needed.
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
import fadodb
|
|
22
|
+
|
|
23
|
+
# A server, as the user whose key it is:
|
|
24
|
+
db = fadodb.connect("https://fado.acme.example", key="fado_Q329CE63C9_…")
|
|
25
|
+
|
|
26
|
+
# Or the database file itself, in this process, through the library of
|
|
27
|
+
# C; the program says who is calling:
|
|
28
|
+
db = fadodb.open("books.fado", caller={"id": "ann", "kind": "person", "groups": ["sales"]})
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
A command is a name and one JSON object, and its answer is one JSON
|
|
32
|
+
object, a `dict`: the [commands](../../docs/manual/commands.md) a server
|
|
33
|
+
takes at `POST /v1/<command>`, answered the same. Ann of sales makes an
|
|
34
|
+
invoice, and Bob of accounting books it:
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
ann = db # opened as Ann above
|
|
38
|
+
bob = db.as_caller({"id": "bob", "kind": "person", "groups": ["accounting"]})
|
|
39
|
+
|
|
40
|
+
ann.exec("create", {"class": "Invoice", "id": "FV/2026/11/0042",
|
|
41
|
+
"values": {"number": "FV/2026/11/0042"}})
|
|
42
|
+
try:
|
|
43
|
+
bob.exec("transition", {"class": "Invoice", "id": "FV/2026/11/0042", "transition": "book"})
|
|
44
|
+
except fadodb.Refused as refusal:
|
|
45
|
+
print(refusal.code, refusal.hint) # guard_false the guard: NOT ISBLANK(account)
|
|
46
|
+
|
|
47
|
+
bob.exec("set", {"class": "Invoice", "id": "FV/2026/11/0042", "values": {"account": "400-01"}})
|
|
48
|
+
bob.exec("transition", {"class": "Invoice", "id": "FV/2026/11/0042", "transition": "book"})
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
A refusal is raised as `fadodb.Refused`: `code` is what a program
|
|
52
|
+
branches on, `message` and `hint` say why and what to send instead,
|
|
53
|
+
`path` names the member it is about, and `answer` is the whole answer,
|
|
54
|
+
with the findings of a refused definition under `diagnostics`.
|
|
55
|
+
`fadodb.NoAnswer` is raised when no answer came through; a command that
|
|
56
|
+
carries a `key` is then safely sent again.
|
|
57
|
+
|
|
58
|
+
`as_caller` is for a database in this process. Over HTTP the key says
|
|
59
|
+
who calls, so each user connects with their own key.
|
|
60
|
+
|
|
61
|
+
## Files
|
|
62
|
+
|
|
63
|
+
The bytes of a file travel beside the commands, and its facts in them:
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
facts = ann.put_file(scan, name="taxi.pdf", media_type="application/pdf")
|
|
67
|
+
ann.exec("set", {"class": "Claim", "id": "C-7", "values": {"scan": facts}})
|
|
68
|
+
facts, data = bob.get_file("Claim", "C-7", facts["hash"])
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## The program's own actions
|
|
72
|
+
|
|
73
|
+
An action whose definition has no request is carried out by the
|
|
74
|
+
program, in the same process: a function by the name of the action.
|
|
75
|
+
It is called with the call, as a webhook gets it, from a thread of the
|
|
76
|
+
worker, and returns what the action returns:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
def post(call):
|
|
80
|
+
entry = books.post(amount=call["args"]["amount"], key=call["key"])
|
|
81
|
+
return {"entry": entry}
|
|
82
|
+
|
|
83
|
+
shop = fadodb.open("shop.fado", actions={"books.post": post})
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
`raise fadodb.Permanent("the period 2026-11 is closed")` refuses the
|
|
87
|
+
call, and the action is dead at once; any other exception is a failure,
|
|
88
|
+
tried again later. The call's `key` is the same at every attempt, so
|
|
89
|
+
the function makes twice once by it. Over HTTP the server carries out
|
|
90
|
+
the actions, and `fadodb.connect` takes none.
|
|
91
|
+
|
|
92
|
+
## Waiting for a change
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
after = bob.exec("wait_for_changes", {"classes": ["Invoice"]})["after"]
|
|
96
|
+
while True:
|
|
97
|
+
heard = bob.exec("wait_for_changes", {"classes": ["Invoice"], "after": after, "seconds": 60})
|
|
98
|
+
for event in heard["events"]:
|
|
99
|
+
...
|
|
100
|
+
after = heard["after"]
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
`subscribe`, whose answer is a stream, is refused with `not_supported`:
|
|
104
|
+
`wait_for_changes` answers the same events one call at a time.
|
|
105
|
+
|
|
106
|
+
## The library
|
|
107
|
+
|
|
108
|
+
`fadodb.open` loads the library of C: the path given as `library`, or
|
|
109
|
+
the one the variable `FADODB_LIBRARY` names, or the one beside the
|
|
110
|
+
package in `fadodb/lib`, or the one the system finds: `libfadodb`, with
|
|
111
|
+
DuckDB, before `libfadodb-core`. A database opened through `libfadodb`
|
|
112
|
+
keeps a copy of its documents in DuckDB beside its file, and the
|
|
113
|
+
questions that read everything, such as `flow`, are answered from it;
|
|
114
|
+
`fadodb.open(path, options={"analytics": {"memory": "2GB"}})` tells it
|
|
115
|
+
how much it may take. `scripts/library.sh build` builds both into
|
|
116
|
+
`bin/library/`. A process holds one library, and opens
|
|
117
|
+
as many databases through it as it needs. Every call may be made from
|
|
118
|
+
any thread: the library lets go of Python's lock while it works.
|
|
119
|
+
|
|
120
|
+
From v0.9.0 on, every release carries the package as wheels: one for each system with
|
|
121
|
+
`libfadodb` and DuckDB's library inside, which `fadodb.open` finds with
|
|
122
|
+
nothing named, about 35 MB, and
|
|
123
|
+
`fadodb-<version>-py3-none-any.whl` for every system without it, for a
|
|
124
|
+
program that talks to a server. `pip install` takes the file of the
|
|
125
|
+
release. A release also publishes them on PyPI, so from v0.9.0 on
|
|
126
|
+
`pip install fadodb` takes the right one for the machine.
|
|
127
|
+
|
|
128
|
+
## Its tests
|
|
129
|
+
|
|
130
|
+
The same tests run both ways: over HTTP against a `fadodb-core serve`
|
|
131
|
+
they start, with a user and a key for each caller, and in the same
|
|
132
|
+
process with the same callers.
|
|
133
|
+
|
|
134
|
+
```sh
|
|
135
|
+
make build library
|
|
136
|
+
FADODB_PROGRAM=bin/fadodb-core FADODB_LIBRARY=bin/libfadodb-core.so \
|
|
137
|
+
python3 -m unittest discover -s clients/py/tests
|
|
138
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
fadodb/__init__.py,sha256=zMuIvqJb8xSGLbgOYHLNCzGGz8IWzJCAEBelrjJC8xA,1356
|
|
2
|
+
fadodb/_database.py,sha256=uevUAS5Wk0Rk9mpoOG2fSrGTInWfR-b28tgsmkU_UbU,7961
|
|
3
|
+
fadodb/_library.py,sha256=qovJ6QONyCQfZoiW7ZtD73Wv0r0gP07aWdA0tq_SHdA,8352
|
|
4
|
+
fadodb/_server.py,sha256=xriJFlCk02BUzbxB3iheMWbHAS6euDtt2piZfE7XeBE,3359
|
|
5
|
+
fadodb/lib/fadodb.dll,sha256=P2cBQ5Y8VaEb2eTbboOZUqRQQXjqlLa1LVN8mRKKYRg,16629248
|
|
6
|
+
fadodb/lib/duckdb.dll,sha256=h4W8uw9FcMlmLEyJD5-lx8-zI5ziXlicKWk84hOfmJc,61311784
|
|
7
|
+
fadodb-0.9.0.dist-info/METADATA,sha256=aEDRD6vXsSiQcwJSO1hN_U1ouvrsyE_UtCWsNGnEXcg,5485
|
|
8
|
+
fadodb-0.9.0.dist-info/WHEEL,sha256=nCEJJ8OG1fLljF6cRWpVOAgBxP2bM7dKASrl6EQP5MA,104
|
|
9
|
+
fadodb-0.9.0.dist-info/licenses/LICENSE,sha256=HrhfyXIkWY2tGFK11kg7vPCqhgh5DcxleloqdhrpyMY,11558
|
|
10
|
+
fadodb-0.9.0.dist-info/licenses/THIRD_PARTY_NOTICES.md,sha256=kbxaJRMkGQfR5xr418aK9p8qfTa7WukUTqcIPLbxpt0,121504
|
|
11
|
+
fadodb-0.9.0.dist-info/licenses/LICENSE-duckdb,sha256=B1wzQA_8sMWG3RBqAp0-cz6do2k_j8uc6_xlHIovFOM,1072
|
|
12
|
+
fadodb-0.9.0.dist-info/RECORD,,
|