-
Notifications
You must be signed in to change notification settings - Fork 2
/
pyxtdb.py
366 lines (307 loc) · 10.7 KB
/
pyxtdb.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
from enum import Enum
import json
import edn_format
import requests
class AlreadySent(Exception):
pass
class BadEDNString(Exception):
pass
class BadQuery(Exception):
pass
class MissingParameter(Exception):
pass
class UnknownParameter(Exception):
pass
class XtdbError(Exception):
def __init__(self, desc, code):
super().__init__(f'XtdbError({code}): {desc}')
self.description = desc
self.status_code = code
class Query:
def __init__(self, uri="http://localhost:3000", node=None):
if node:
self.node = node
else:
self.node = Node(uri)
self._find_clause = None
self._where_clauses = []
self._values = None
self.error = None
def find(self, clause):
if self._values:
raise AlreadySent()
self._find_clause = clause
return self
def where(self, clause):
if self._values:
raise AlreadySent()
self._where_clauses.append(clause)
return self
def values(self):
if not self._where_clauses:
raise BadQuery("No Where Clause")
_query = """
{
:find [%s]
:where [
[%s]
]
}
""" % (self._find_clause, ']\n['.join(self._where_clauses))
result = self.node.query(_query)
if type(result) is dict:
self.error = json.dumps(result, indent=4, sort_keys=True)
return []
return result
def __iter__(self):
self._values = self.values()
return self
def __next__(self):
if len(self._values):
return self._values.pop()
else:
raise StopIteration
class TxOps:
def __init__(self, uri="http://localhost:3000", node=None):
if node:
self.node = node
else:
self.node = Node(uri)
self._ops = []
self._result = None
def _put_single(self, rec, valid_time=None, end_valid_time=None):
op = ['put', rec]
if valid_time:
op.append(valid_time)
if valid_time and end_valid_time:
op.append(end_valid_time)
self._ops.append(op)
def put(self, rec, valid_time=None, end_valid_time=None):
if type(rec) is list:
for item in rec:
self._put_single(item, valid_time, end_valid_time)
else:
self._put_single(rec, valid_time, end_valid_time)
return self
def _delete_single(self, eid, valid_time=None, end_valid_time=None):
op = ['delete', eid]
if valid_time:
op.append(valid_time)
if valid_time and end_valid_time:
op.append(end_valid_time)
self._ops.append(op)
def delete(self, eid, valid_time=None, end_valid_time=None):
if type(eid) is list:
for item in eid:
self._delete_single(item, valid_time, end_valid_time)
else:
self._delete_single(eid, valid_time, end_valid_time)
return self
def evict(self, eid):
if type(eid) is list:
for item in eid:
self._ops.append(['evict', item])
else:
self._ops.append(['evict', eid])
return self
def match(self, eid, rec, valid_time=None):
op = ['match', eid, rec]
if valid_time:
op.append(valid_time)
self._ops.append(op)
return self
def submit(self):
if len(self._ops) == 0:
return None
if not self._result:
self._result = self.node.submitTx(self)
return self._result
@property
def ops(self):
return {'tx-ops': self._ops}
class Node:
def __init__(self, uri="http://localhost:3000"):
self.uri = uri
def find(self, find_clause):
return Query(node=self).find(find_clause)
@staticmethod
def _parse_kwargs(known_args, provided_args):
params = {}
for k,v in provided_args.items():
# convert from valid python keywords to url parameters,
# i.e. from 'with_opsQ' to 'with-ops?'
k = k.replace("_","-").replace('Q','?')
if k not in known_args:
raise UnknownParameter(f'Unknown parameter: {k}')
if v is not None:
# handle formatted values if they are edn or json,
# and for now we depend on the convention that
# the url parameters are named with the desired format.
if k.endswith('-edn'):
v = edn_format.dumps(v)
if k.endswith('-json'):
v = json.dumps(v)
params[k] = v
return params
@staticmethod
def _check_status(request):
if 400 <= request.status_code < 500:
raise XtdbError(
f"Client Error: {request.reason} for url: {request.url}",
request.status_code
)
elif 500 <= request.status_code < 600:
raise XtdbError(
f"Server Error: {request.reason} for url: {request.url}",
request.status_code
)
def _call_rest_api(self, action, params={}):
endpoint = "{}/_xtdb/{}".format(self.uri, action)
headers = {
"Content-Type": "application/json; charset=utf-8",
"Accept": "application/json",
}
rsp = requests.get(endpoint, headers=headers, params=params)
self._check_status(rsp)
return rsp.json()
def submitTx(self, txops):
action = "submit-tx"
endpoint = "{}/_xtdb/{}".format(self.uri, action)
headers = {
"Content-Type": "application/json; charset=utf-8",
"Accept": "application/json",
}
rsp = requests.post(endpoint, headers=headers, json=txops.ops)
self._check_status(rsp)
return rsp.json()
def put(self, rec, valid_time=None, end_valid_time=None):
return TxOps(node=self).put(rec, valid_time, end_valid_time)
def delete(self, eid, valid_time=None, end_valid_time=None):
return TxOps(node=self).delete(eid, valid_time, end_valid_time)
def evict(self, eid):
return TxOps(node=self).evict(eid)
def match(self, eid, rec, valid_time=None):
return TxOps(node=self).match(eid, rec, valid_time)
def query(self, query, in_args=None, **kwargs):
if type(query) is str:
try: # use edn_format to validate the string
query = query.strip()
_ = edn_format.loads(query)
except edn_format.exceptions.EDNDecodeError as e:
raise BadEDNString(str(e)) from e
else:
query = edn_format.dumps(query)
if in_args is not None:
if type(in_args) is str:
try: # use edn_format to validate the string
in_args = in_args.strip()
_ = edn_format.loads(in_args)
except edn_format.exceptions.EDNDecodeError as e:
raise BadEDNString(str(e)) from e
else:
in_args = edn_format.dumps(in_args)
if not in_args:
data = "{:query %s}" % query
else:
data = "{:query %s :in-args %s}" % (query, in_args)
# handle url parameters
known_args = [
"valid-time",
'tx-time',
'tx-id'
]
params = self._parse_kwargs(known_args, kwargs)
action = "query"
endpoint = "{}/_xtdb/{}".format(self.uri, action)
headers = {"Accept": "application/json", "Content-Type": "application/edn"}
rsp = requests.post(endpoint, headers=headers, data=data, params=params)
self._check_status(rsp)
return rsp.json()
def status(self):
action = "status"
return self._call_rest_api(action)
def entity(self, **kwargs):
action = "entity"
known_args = [
'eid',
'eid-json',
'eid-edn',
'valid-time',
'tx-time',
'tx-id'
]
params = self._parse_kwargs(known_args, kwargs)
return self._call_rest_api(action, params)
def entityHistory(self, **kwargs):
action = "entity?history=true"
known_args = [
'eid',
'eid-json',
'eid-edn',
'sort-order',
'with-corrections',
'with-docs',
'start-valid-time',
'start-tx-time',
'start-tx-id',
'end-valid-time',
'end-tx-time',
'end-tx-id'
]
params = self._parse_kwargs(known_args, kwargs)
return self._call_rest_api(action, params)
def entityTx(self, **kwargs):
action = "entity-tx"
known_args = [
'eid',
'eid-json',
'eid-edn',
'valid-time',
'tx-time',
'tx-id'
]
params = self._parse_kwargs(known_args, kwargs)
return self._call_rest_api(action, params)
def attributeStats(self):
action = "attribute-stats"
return self._call_rest_api(action)
def sync(self, **kwargs):
action = "sync"
known_args = ['timeout']
params = self._parse_kwargs(known_args, kwargs)
return self._call_rest_api(action, params)
def awaitTx(self, **kwargs):
action = "await-tx"
known_args = ['tx-id', 'timeout']
params = self._parse_kwargs(known_args, kwargs)
return self._call_rest_api(action, params)
def awaitTxTime(self, **kwargs):
action = "await-tx-time"
known_args = ['tx-time', 'timeout']
params = self._parse_kwargs(known_args, kwargs)
return self._call_rest_api(action, params)
def txLog(self, **kwargs):
action = "tx-log"
known_args = ['after-tx-id', 'with-ops?']
params = self._parse_kwargs(known_args, kwargs)
return self._call_rest_api(action, params)
def txCommitted(self, **kwargs):
action = "tx-committed"
known_args = ['tx-id']
params = self._parse_kwargs(known_args, kwargs)
return self._call_rest_api(action, params)
def latestCompletedTx(self):
action = "latest-completed-tx"
return self._call_rest_api(action)
def latestSubmittedTx(self):
action = "latest-submitted-tx"
return self._call_rest_api(action)
def activeQueries(self):
action = "active-queries"
return self._call_rest_api(action)
def recentQueries(self):
action = "recent-queries"
return self._call_rest_api(action)
def slowestQueries(self):
action = "slowest-queries"
return self._call_rest_api(action)