/
impl.py
1698 lines (1295 loc) · 55.3 KB
/
impl.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# impl.py
#
# This source file is part of the FoundationDB open source project
#
# Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# FoundationDB Python API
import ctypes
import ctypes.util
import functools
import threading
import traceback
import inspect
import datetime
import platform
import os
import sys
import multiprocessing
from fdb import six
_network_thread = None
_network_thread_reentrant_lock = threading.RLock()
_open_file = open
_thread_local_storage = threading.local()
import weakref
class _NetworkOptions(object):
def __init__(self, parent):
self._parent = parent
class _ErrorPredicates(object):
def __init__(self, parent):
self._parent = parent
class _DatabaseOptions(object):
def __init__(self, db):
self._parent = weakref.proxy(db)
class _TransactionOptions(object):
def __init__(self, tr):
self._parent = weakref.proxy(tr)
from fdb import fdboptions as _opts
import types
import struct
def option_wrap(code):
def setfunc(self):
self._parent._set_option(code, None, 0)
return setfunc
def option_wrap_string(code):
def setfunc(self, param=None):
param, length = optionalParamToBytes(param)
self._parent._set_option(code, param, length)
return setfunc
def option_wrap_bytes(code):
def setfunc(self, param=None):
if param is None:
self._parent._set_option(code, None, 0)
elif isinstance(param, bytes):
self._parent._set_option(code, param, len(param))
else:
raise TypeError('Value must be of type ' + bytes.__name__)
return setfunc
def option_wrap_int(code):
def setfunc(self, param):
self._parent._set_option(code, struct.pack("<q", param), 8)
return setfunc
def pred_wrap(code):
def predfunc(self, error):
return self._parent._error_predicate(code, error.code)
return predfunc
def operation_wrap(code):
def opfunc(self, key, param):
self._atomic_operation(code, key, param)
return opfunc
def fill_options(scope, predicates=False):
_dict = getattr(_opts, scope)
for k, v in _dict.items():
fname = (predicates and 'is_' or 'set_') + k.lower()
code, desc, paramType, paramDesc = v
if predicates:
f = pred_wrap(code)
else:
if paramType == type(None):
f = option_wrap(code)
elif paramType == type(''):
f = option_wrap_string(code)
elif paramType == type(b''): # This won't happen in Python 2 because type('') == type(b''), but it will happen in Python 3
f = option_wrap_bytes(code)
elif paramType == type(0):
f = option_wrap_int(code)
else:
raise TypeError("Don't know how to set options of type %s" % paramType.__name__)
f.__name__ = fname
f.__doc__ = desc
if paramDesc is not None:
f.__doc__ += '\n\nArgument is ' + paramDesc
klass = globals()['_' + scope + 's']
setattr(klass, fname, f)
def add_operation(fname, v):
code, desc, paramType, paramDesc = v
f = operation_wrap(code)
f.__name__ = fname
f.__doc__ = desc + '\n\nArguments are the key to which the operation is applied and the ' + paramDesc
setattr(globals()['Database'], fname, f)
setattr(globals()['Transaction'], fname, f)
def fill_operations():
_dict = getattr(_opts, 'MutationType')
for k, v in _dict.items():
fname = k.lower()
add_operation(fname, v)
add_operation("bit_" + fname, v)
for scope in ['DatabaseOption', 'TransactionOption', 'NetworkOption']:
fill_options(scope)
fill_options('ErrorPredicate', True)
options = _NetworkOptions(sys.modules[__name__])
predicates = _ErrorPredicates(sys.modules[__name__])
def _set_option(option, param, length):
_capi.fdb_network_set_option(option, param, length)
def _error_predicate(predicate, error_code):
return bool(_capi.fdb_error_predicate(predicate, error_code))
def make_enum(scope):
_dict = getattr(_opts, scope)
x = type(scope, (), {})
def makeprop(value, doc):
return property(fget=lambda o: value, doc=doc)
for k, v in _dict.items():
setattr(x, k.lower(), makeprop(v[0], v[1]))
globals()[scope] = x()
make_enum("StreamingMode")
make_enum("ConflictRangeType")
def transactional(*tr_args, **tr_kwargs):
"""Decorate a funcation as transactional.
The decorator looks for a named argument (default 'tr') and takes
one of two actions, depending on the type of the parameter passed
to the function at call time.
If given a Database, a Transaction will be created and passed into
the wrapped code in place of the Database. After the function is
complete, the newly created transaction will be committed.
It is important to note that the wrapped method may be called
multiple times in the event of a commit failure, until the commit
succeeds.
If given a Transaction, the Transaction will be passed into the
wrapped code, and WILL NOT be committed at completion of the
function. This allows new transactional functions to be composed
of other transactional methods.
The transactional decorator may be used with or without
arguments. The keyword argument 'parameter' is recognized and
specifies the name of the parameter to the wrapped function that
will contain either a Database or Transaction.
"""
def decorate(func):
try:
parameter = tr_kwargs['parameter']
except:
parameter = 'tr'
wfunc = func
while getattr(wfunc, '__wrapped__', None):
wfunc = wfunc.__wrapped__
if hasattr(inspect, 'getfullargspec'):
index = inspect.getfullargspec(wfunc).args.index(parameter)
else:
index = inspect.getargspec(wfunc).args.index(parameter)
if getattr(func, '_is_coroutine', False):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if isinstance(args[index], TransactionRead):
raise asyncio.Return((yield asyncio.From(func(*args, **kwargs))))
largs = list(args)
tr = largs[index] = args[index].create_transaction()
while True:
try:
ret = yield asyncio.From(func(*largs, **kwargs))
yield asyncio.From(tr.commit())
raise asyncio.Return(ret)
except FDBError as e:
yield asyncio.From(tr.on_error(e.code))
else:
@functools.wraps(func)
def wrapper(*args, **kwargs):
if isinstance(args[index], TransactionRead):
return func(*args, **kwargs)
largs = list(args)
tr = largs[index] = args[index].create_transaction()
committed = False
# retries = 0
# start = datetime.datetime.now()
# last = start
while not committed:
try:
ret = func(*largs, **kwargs)
tr.commit().wait()
committed = True
except FDBError as e:
tr.on_error(e.code).wait()
# now = datetime.datetime.now()
# td = now - last
# elapsed = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / float(10**6)
# if elapsed >= 1:
# td = now - start
# print ('fdb WARNING: long transaction (%gs elapsed in transactional function \'%s\' (%d retries, %s))'
# % (elapsed, func.__name__, retries, committed and 'committed' or 'not yet committed'))
# last = now
# retries += 1
return ret
return wrapper
if not tr_args:
# Being called with parameters (possibly none); return a
# decorator
return decorate
elif len(tr_args) == 1 and not tr_kwargs:
# Being called as a decorator
return decorate(tr_args[0])
else:
raise Exception('Invalid use of transactional decorator.')
class FDBError(Exception):
"""This exception is raised when an FDB API call returns an
error. The error code will be stored in the code attribute, and a
textual description of the error will be stored in the description
attribute.
"""
def __init__(self, code):
self.code = code
self._description = None
@property
def description(self):
if not self._description:
self._description = _capi.fdb_get_error(self.code)
return self._description
def __str__(self):
return '%s (%d)' % (self.description, self.code)
def __repr__(self):
return 'FDBError(%d)' % self.code
class _FDBBase(object):
# By inheriting from _FDBBase, every class gets access to self.capi
# (set below when we open libfdb_capi)
pass
class FDBRange(object):
"""Iterates over the results of an FDB range query. Returns
KeyValue objects.
"""
def __init__(self, tr, begin, end, limit, reverse, streaming_mode):
self._tr = tr
self._bsel = begin
self._esel = end
self._limit = limit
self._reverse = reverse
self._mode = streaming_mode
self._future = self._tr._get_range(begin, end, limit, streaming_mode, 1, reverse)
def to_list(self):
if self._mode == StreamingMode.iterator:
if self._limit > 0:
mode = StreamingMode.exact
else:
mode = StreamingMode.want_all
else:
mode = self._mode
return list(self.__iter__(mode=mode))
def __iter__(self, mode=None):
if mode is None:
mode = self._mode
bsel = self._bsel
esel = self._esel
limit = self._limit
iteration = 1 # the first read was fired off when the FDBRange was initialized
future = self._future
done = False
while not done:
if future:
(kvs, count, more) = future.wait()
index = 0
future = None
if not count:
return
result = kvs[index]
index += 1
if index == count:
if not more or limit == count:
done = True
else:
iteration += 1
if limit > 0:
limit = limit - count
if self._reverse:
esel = KeySelector.first_greater_or_equal(kvs[-1].key)
else:
bsel = KeySelector.first_greater_than(kvs[-1].key)
future = self._tr._get_range(bsel, esel, limit, mode, iteration, self._reverse)
yield result
class TransactionRead(_FDBBase):
def __init__(self, tpointer, db, snapshot):
self.tpointer = tpointer
self.db = db
self._snapshot = snapshot
def __del__(self):
# print('Destroying transactionread 0x%x' % self.tpointer)
self.capi.fdb_transaction_destroy(self.tpointer)
def get_read_version(self):
"""Get the read version of the transaction."""
return FutureVersion(self.capi.fdb_transaction_get_read_version(self.tpointer))
def get(self, key):
key = keyToBytes(key)
return Value(self.capi.fdb_transaction_get(self.tpointer, key, len(key), self._snapshot))
def get_key(self, key_selector):
key = keyToBytes(key_selector.key)
return Key(self.capi.fdb_transaction_get_key(
self.tpointer, key, len(key), key_selector.or_equal, key_selector.offset, self._snapshot))
def _get_range(self, begin, end, limit, streaming_mode, iteration, reverse):
beginKey = keyToBytes(begin.key)
endKey = keyToBytes(end.key)
return FutureKeyValueArray(
self.capi.fdb_transaction_get_range(
self.tpointer, beginKey, len(beginKey), begin.or_equal, begin.offset,
endKey, len(endKey), end.or_equal, end.offset,
limit, 0, streaming_mode, iteration, self._snapshot, reverse))
def _to_selector(self, key_or_selector):
if not isinstance(key_or_selector, KeySelector):
key_or_selector = KeySelector.first_greater_or_equal(key_or_selector)
return key_or_selector
def get_range(self, begin, end, limit=0, reverse=False, streaming_mode=StreamingMode.iterator):
if begin is None:
begin = b''
if end is None:
end = b'\xff'
begin = self._to_selector(begin)
end = self._to_selector(end)
return FDBRange(self, begin, end, limit, reverse, streaming_mode)
def get_range_startswith(self, prefix, *args, **kwargs):
prefix = keyToBytes(prefix)
return self.get_range(prefix, strinc(prefix), *args, **kwargs)
def __getitem__(self, key):
if isinstance(key, slice):
return self.get_range(key.start, key.stop, reverse=(key.step == -1))
return self.get(key)
class Transaction(TransactionRead):
"""A modifiable snapshot of a Database.
"""
def __init__(self, tpointer, db):
super(Transaction, self).__init__(tpointer, db, False)
self.options = _TransactionOptions(self)
self.__snapshot = self.snapshot = TransactionRead(tpointer, db, True)
def __del__(self):
pass
def set_read_version(self, version):
"""Set the read version of the transaction."""
self.capi.fdb_transaction_set_read_version(self.tpointer, version)
def _set_option(self, option, param, length):
self.capi.fdb_transaction_set_option(self.tpointer, option, param, length)
def _atomic_operation(self, opcode, key, param):
paramBytes = valueToBytes(param)
paramLength = len(paramBytes)
keyBytes = keyToBytes(key)
keyLength = len(keyBytes)
self.capi.fdb_transaction_atomic_op(self.tpointer, keyBytes, keyLength, paramBytes, paramLength, opcode)
def set(self, key, value):
key = keyToBytes(key)
value = valueToBytes(value)
self.capi.fdb_transaction_set(self.tpointer, key, len(key), value, len(value))
def clear(self, key):
if isinstance(key, KeySelector):
key = self.get_key(key)
key = keyToBytes(key)
self.capi.fdb_transaction_clear(self.tpointer, key, len(key))
def clear_range(self, begin, end):
if begin is None:
begin = b''
if end is None:
end = b'\xff'
if isinstance(begin, KeySelector):
begin = self.get_key(begin)
if isinstance(end, KeySelector):
end = self.get_key(end)
begin = keyToBytes(begin)
end = keyToBytes(end)
self.capi.fdb_transaction_clear_range(self.tpointer, begin, len(begin),
end, len(end))
def clear_range_startswith(self, prefix):
prefix = keyToBytes(prefix)
return self.clear_range(prefix, strinc(prefix))
def watch(self, key):
key = keyToBytes(key)
return FutureVoid(self.capi.fdb_transaction_watch(self.tpointer, key, len(key)))
def add_read_conflict_range(self, begin, end):
begin = keyToBytes(begin)
end = keyToBytes(end)
self.capi.fdb_transaction_add_conflict_range(self.tpointer, begin, len(begin), end, len(end), ConflictRangeType.read)
def add_read_conflict_key(self, key):
key = keyToBytes(key)
self.add_read_conflict_range(key, key + b'\x00')
def add_write_conflict_range(self, begin, end):
begin = keyToBytes(begin)
end = keyToBytes(end)
self.capi.fdb_transaction_add_conflict_range(self.tpointer, begin, len(begin), end, len(end), ConflictRangeType.write)
def add_write_conflict_key(self, key):
key = keyToBytes(key)
self.add_write_conflict_range(key, key + b'\x00')
def commit(self):
return FutureVoid(self.capi.fdb_transaction_commit(self.tpointer))
def get_committed_version(self):
version = ctypes.c_int64()
self.capi.fdb_transaction_get_committed_version(self.tpointer, ctypes.byref(version))
return version.value
def get_versionstamp(self):
return Key(self.capi.fdb_transaction_get_versionstamp(self.tpointer))
def on_error(self, error):
if isinstance(error, FDBError):
code = error.code
elif isinstance(error, int):
code = error
else:
raise error
return FutureVoid(self.capi.fdb_transaction_on_error(self.tpointer, code))
def reset(self):
self.capi.fdb_transaction_reset(self.tpointer)
def cancel(self):
self.capi.fdb_transaction_cancel(self.tpointer)
def __setitem__(self, key, value):
self.set(key, value)
def __delitem__(self, key):
if isinstance(key, slice):
self.clear_range(key.start, key.stop)
else:
self.clear(key)
class Future(_FDBBase):
Event = threading.Event
_state = None # < Hack for trollius
def __init__(self, fpointer):
# print('Creating future 0x%x' % fpointer)
self.fpointer = fpointer
def __del__(self):
if self.fpointer:
# print('Destroying future 0x%x' % self.fpointer)
self.capi.fdb_future_destroy(self.fpointer)
self.fpointer = None
def cancel(self):
self.capi.fdb_future_cancel(self.fpointer)
def _release_memory(self):
self.capi.fdb_future_release_memory(self.fpointer)
def wait(self):
raise NotImplementedError
def is_ready(self):
return bool(self.capi.fdb_future_is_ready(self.fpointer))
def block_until_ready(self):
# Checking readiness is faster than using the callback, so it saves us time if we are already
# ready. It also doesn't add much to the cost of this function
if not self.is_ready():
# Blocking in the native client from the main thread prevents Python from handling signals.
# To avoid that behavior, we implement the blocking in Python using semaphores and on_ready.
# Using a Semaphore is faster than an Event, and we create only one per thread to avoid the
# cost of creating one every time.
semaphore = getattr(_thread_local_storage, 'future_block_semaphore', None)
if semaphore is None:
semaphore = multiprocessing.Semaphore(0)
_thread_local_storage.future_block_semaphore = semaphore
self.on_ready(lambda self: semaphore.release())
try:
semaphore.acquire()
except:
# If this semaphore didn't actually get released, then we need to replace our thread-local
# copy so that later callers still function correctly
_thread_local_storage.future_block_semaphore = multiprocessing.Semaphore(0)
raise
def on_ready(self, callback):
def cb_and_delref(ignore):
_unpin_callback(cbfunc[0])
del cbfunc[:]
try:
callback(self)
except:
try:
sys.stderr.write("Discarding uncaught exception from user FDB callback:\n")
traceback.print_exception(*sys.exc_info(), file=sys.stderr)
except:
pass
cbfunc = [_CBFUNC(cb_and_delref)]
del cb_and_delref
_pin_callback(cbfunc[0])
self.capi.fdb_future_set_callback(self.fpointer, cbfunc[0], None)
@staticmethod
def wait_for_any(*futures):
"""Does not return until at least one of the given futures is ready.
Returns the index in the parameter list of a ready future."""
if not futures:
raise ValueError("wait_for_any requires at least one future")
d = {}
ev = futures[0].Event()
for i, f in enumerate(futures):
def cb(ignore, i=i):
if d.setdefault('i', i) == i:
ev.set()
f.on_ready(cb)
ev.wait()
return d['i']
# asyncio future protocol
def cancelled(self):
if not self.done():
return False
e = self.exception()
return getattr(e, 'code', 0) == 1101
done = is_ready
def result(self):
if not self.done():
raise Exception("Future result not available")
return self.wait()
def exception(self):
if not self.done():
raise Exception("Future result not available")
try:
self.wait()
return None
except BaseException as e:
return e
def add_done_callback(self, fn):
self.on_ready(lambda f: self.call_soon_threadsafe(fn, f))
def remove_done_callback(self, fn):
raise NotImplementedError()
class FutureVoid(Future):
def wait(self):
self.block_until_ready()
self.capi.fdb_future_get_error(self.fpointer)
return None
class FutureVersion(Future):
def wait(self):
self.block_until_ready()
version = ctypes.c_int64()
self.capi.fdb_future_get_version(self.fpointer, ctypes.byref(version))
return version.value
class FutureKeyValueArray(Future):
def wait(self):
self.block_until_ready()
kvs = ctypes.pointer(KeyValueStruct())
count = ctypes.c_int()
more = ctypes.c_int()
self.capi.fdb_future_get_keyvalue_array(self.fpointer, ctypes.byref(kvs), ctypes.byref(count), ctypes.byref(more))
return ([KeyValue(ctypes.string_at(x.key, x.key_length), ctypes.string_at(x.value, x.value_length))
for x in kvs[0:count.value]], count.value, more.value)
# Logically, we should self._release_memory() after extracting the
# KVs but before returning, but then we would have to store
# the KVs on the python side and in most cases we are about to
# destroy the future anyway
class FutureStringArray(Future):
def wait(self):
self.block_until_ready()
strings = ctypes.pointer(ctypes.c_char_p())
count = ctypes.c_int()
self.capi.fdb_future_get_string_array(self.fpointer, ctypes.byref(strings), ctypes.byref(count))
return list(strings[0:count.value])
class replaceable_property(object):
def __get__(self, obj, cls=None):
return self.method(obj)
def __init__(self, method):
self.method = method
class LazyFuture(Future):
def __init__(self, *args, **kwargs):
super(LazyFuture, self).__init__(*args, **kwargs)
def wait(self):
self.value
return self
def _getter(self):
raise NotImplementedError
@replaceable_property
def value(self):
self.block_until_ready()
try:
self._getter()
self._release_memory()
except:
e = sys.exc_info()
if not (isinstance(e[1], FDBError) and e[1].code == 1102): # future_released
raise
return self.value
# This is a workaround to avoid a compiler issue as described here:
# http://bugs.python.org/issue12370
_super = super
class FutureString(LazyFuture):
def __init__(self, *args):
self._error = None
_super(FutureString, self).__init__(*args)
def getclass(self):
return bytes
__class__ = property(getclass)
def as_foundationdb_key(self):
return self.value
def as_foundationdb_value(self):
return self.value
def __str__(self):
return self.value.__str__()
def __bytes__(self):
return self.value
def __repr__(self):
return self.value.__repr__()
def __add__(self, rhs):
if isinstance(rhs, FutureString):
rhs = rhs.value
return self.value + rhs
def __radd__(self, lhs):
if isinstance(lhs, FutureString):
lhs = lhs.value
return lhs + self.value
def __mul__(self, rhs):
return self.value * rhs
def __rmul__(self, lhs):
return lhs * self.value
def __lt__(self, rhs):
if isinstance(rhs, FutureString):
rhs = rhs.value
return self.value < rhs
def __le__(self, rhs):
if isinstance(rhs, FutureString):
rhs = rhs.value
return self.value <= rhs
def __gt__(self, rhs):
if isinstance(rhs, FutureString):
rhs = rhs.value
return self.value > rhs
def __ge__(self, rhs):
if isinstance(rhs, FutureString):
rhs = rhs.value
return self.value >= rhs
def __eq__(self, rhs):
if isinstance(rhs, FutureString):
rhs = rhs.value
return self.value == rhs
def __ne__(self, rhs):
return not self == rhs
def __nonzero__(self):
return bool(self.value)
def __int__(self):
return int(self.value)
def makewrapper(func):
def tmpfunc(self, *args):
return func(self.value, *args)
return tmpfunc
for i in dir(bytes):
if not i.startswith('_') or i in ('__getitem__', '__getslice__', '__hash__', '__len__'):
setattr(FutureString, i, makewrapper(getattr(bytes, i)))
class Value(FutureString):
def _getter(self):
present = ctypes.c_int()
value = ctypes.pointer(ctypes.c_byte())
value_length = ctypes.c_int()
self.capi.fdb_future_get_value(self.fpointer, ctypes.byref(present),
ctypes.byref(value), ctypes.byref(value_length))
if present.value:
self.value = ctypes.string_at(value, value_length.value)
else:
self.value = None
def present(self):
return self.value is not None
class Key(FutureString):
def _getter(self):
key = ctypes.pointer(ctypes.c_byte())
key_length = ctypes.c_int()
self.capi.fdb_future_get_key(self.fpointer, ctypes.byref(key), ctypes.byref(key_length))
self.value = ctypes.string_at(key, key_length.value)
class FormerFuture(_FDBBase):
def wait(self):
return self
def is_ready(self):
return True
def block_until_ready(self):
pass
def on_ready(self, callback):
try:
callback(self)
except:
try:
sys.stderr.write("Discarding uncaught exception from user FDB callback:\n")
traceback.print_exception(*sys.exc_info(), file=sys.stderr)
except:
pass
class Database(_FDBBase):
def __init__(self, dpointer):
self.dpointer = dpointer
self.options = _DatabaseOptions(self)
def __del__(self):
# print('Destroying database 0x%x' % self.dpointer)
self.capi.fdb_database_destroy(self.dpointer)
def get(self, key):
return Database.__database_getitem(self, key)
def __getitem__(self, key):
if isinstance(key, slice):
return self.get_range(key.start, key.stop, reverse=(key.step == -1))
return Database.__database_getitem(self, key)
def get_key(self, key_selector):
return Database.__database_get_key(self, key_selector)
def get_range(self, begin, end, limit=0, reverse=False, streaming_mode=StreamingMode.want_all):
return Database.__database_get_range(self, begin, end, limit, reverse, streaming_mode)
def get_range_startswith(self, prefix, *args, **kwargs):
return Database.__database_get_range_startswith(self, prefix, *args, **kwargs)
def set(self, key, value):
Database.__database_setitem(self, key, value)
def __setitem__(self, key, value):
Database.__database_setitem(self, key, value)
def clear(self, key):
Database.__database_delitem(self, key)
def clear_range(self, begin, end):
Database.__database_delitem(self, slice(begin, end))
def __delitem__(self, key_or_slice):
Database.__database_delitem(self, key_or_slice)
def clear_range_startswith(self, prefix):
Database.__database_clear_range_startswith(self, prefix)
def get_and_watch(self, key):
return Database.__database_get_and_watch(self, key)
def set_and_watch(self, key, value):
return Database.__database_set_and_watch(self, key, value)
def clear_and_watch(self, key):
return Database.__database_clear_and_watch(self, key)
def create_transaction(self):
pointer = ctypes.c_void_p()
self.capi.fdb_database_create_transaction(self.dpointer, ctypes.byref(pointer))
return Transaction(pointer.value, self)
def _set_option(self, option, param, length):
self.capi.fdb_database_set_option(self.dpointer, option, param, length)
def _atomic_operation(self, opcode, key, param):
Database.__database_atomic_operation(self, opcode, key, param)
#### Transaction implementations ####
@staticmethod
@transactional
def __database_getitem(tr, key):
return tr[key].value
@staticmethod
@transactional
def __database_get_key(tr, key_selector):
return tr.get_key(key_selector).value
@staticmethod
@transactional
def __database_get_range(tr, begin, end, limit, reverse, streaming_mode):
return tr.get_range(begin, end, limit, reverse, streaming_mode).to_list()
@staticmethod
@transactional
def __database_get_range_startswith(tr, prefix, *args, **kwargs):
return tr.get_range_startswith(prefix, *args, **kwargs).to_list()
@staticmethod
@transactional
def __database_setitem(tr, key, value):
tr[key] = value
@staticmethod
@transactional
def __database_clear_range_startswith(tr, prefix):
tr.clear_range_startswith(prefix)
@staticmethod
@transactional
def __database_get_and_watch(tr, key):
v = tr.get(key)
return v, tr.watch(key)
@staticmethod
@transactional
def __database_set_and_watch(tr, key, value):
tr.set(key, value)
return tr.watch(key)