forked from twmht/python-rocksdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_rocksdb.pyx
2426 lines (1953 loc) · 77.9 KB
/
_rocksdb.pyx
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
import cython
from libcpp.string cimport string
from libcpp.deque cimport deque
from libcpp.vector cimport vector
from cpython cimport bool as py_bool
from libcpp cimport bool as cpp_bool
from libc.stdint cimport uint32_t
from cython.operator cimport dereference as deref
from cpython.bytes cimport PyBytes_AsString
from cpython.bytes cimport PyBytes_Size
from cpython.bytes cimport PyBytes_FromString
from cpython.bytes cimport PyBytes_FromStringAndSize
from cpython.unicode cimport PyUnicode_Decode
from std_memory cimport shared_ptr
cimport options
cimport merge_operator
cimport filter_policy
cimport comparator
cimport slice_transform
cimport cache
cimport logger
cimport snapshot
cimport db
cimport iterator
cimport backup
cimport env
cimport table_factory
cimport memtablerep
cimport universal_compaction
# Enums are the only exception for direct imports
# Their name als already unique enough
from universal_compaction cimport kCompactionStopStyleSimilarSize
from universal_compaction cimport kCompactionStopStyleTotalSize
from options cimport kCompactionStyleLevel
from options cimport kCompactionStyleUniversal
from options cimport kCompactionStyleFIFO
from options cimport kCompactionStyleNone
from slice_ cimport Slice
from status cimport Status
import sys
from interfaces import MergeOperator as IMergeOperator
from interfaces import AssociativeMergeOperator as IAssociativeMergeOperator
from interfaces import FilterPolicy as IFilterPolicy
from interfaces import Comparator as IComparator
from interfaces import SliceTransform as ISliceTransform
import traceback
import errors
import weakref
ctypedef const filter_policy.FilterPolicy ConstFilterPolicy
cdef extern from "cpp/utils.hpp" namespace "py_rocks":
cdef const Slice* vector_data(vector[Slice]&)
# Prepare python for threaded usage.
# Python callbacks (merge, comparator)
# could be executed in a rocksdb background thread (eg. compaction).
cdef extern from "Python.h":
void PyEval_InitThreads()
PyEval_InitThreads()
## Here comes the stuff to wrap the status to exception
cdef check_status(const Status& st):
if st.ok():
return
if st.IsNotFound():
raise errors.NotFound(st.ToString())
if st.IsCorruption():
raise errors.Corruption(st.ToString())
if st.IsNotSupported():
raise errors.NotSupported(st.ToString())
if st.IsInvalidArgument():
raise errors.InvalidArgument(st.ToString())
if st.IsIOError():
raise errors.RocksIOError(st.ToString())
if st.IsMergeInProgress():
raise errors.MergeInProgress(st.ToString())
if st.IsIncomplete():
raise errors.Incomplete(st.ToString())
raise Exception("Unknown error: %s" % st.ToString())
######################################################
cdef string bytes_to_string(path) except *:
return string(PyBytes_AsString(path), PyBytes_Size(path))
cdef string_to_bytes(string ob):
return PyBytes_FromStringAndSize(ob.c_str(), ob.size())
cdef Slice bytes_to_slice(ob) except *:
return Slice(PyBytes_AsString(ob), PyBytes_Size(ob))
cdef slice_to_bytes(Slice sl):
return PyBytes_FromStringAndSize(sl.data(), sl.size())
## only for filsystem paths
cdef string path_to_string(object path) except *:
if isinstance(path, bytes):
return bytes_to_string(path)
if isinstance(path, unicode):
path = path.encode(sys.getfilesystemencoding())
return bytes_to_string(path)
else:
raise TypeError("Wrong type for path: %s" % path)
cdef object string_to_path(string path):
fs_encoding = sys.getfilesystemencoding().encode('ascii')
return PyUnicode_Decode(path.c_str(), path.size(), fs_encoding, "replace")
## Here comes the stuff for the comparator
@cython.internal
cdef class PyComparator(object):
cdef object get_ob(self):
return None
cdef const comparator.Comparator* get_comparator(self):
return NULL
cdef set_info_log(self, shared_ptr[logger.Logger] info_log):
pass
@cython.internal
cdef class PyGenericComparator(PyComparator):
cdef comparator.ComparatorWrapper* comparator_ptr
cdef object ob
def __cinit__(self, object ob):
self.comparator_ptr = NULL
if not isinstance(ob, IComparator):
raise TypeError("%s is not of type %s" % (ob, IComparator))
self.ob = ob
self.comparator_ptr = new comparator.ComparatorWrapper(
bytes_to_string(ob.name()),
<void*>ob,
compare_callback)
def __dealloc__(self):
if not self.comparator_ptr == NULL:
del self.comparator_ptr
cdef object get_ob(self):
return self.ob
cdef const comparator.Comparator* get_comparator(self):
return <comparator.Comparator*> self.comparator_ptr
cdef set_info_log(self, shared_ptr[logger.Logger] info_log):
self.comparator_ptr.set_info_log(info_log)
@cython.internal
cdef class PyBytewiseComparator(PyComparator):
cdef const comparator.Comparator* comparator_ptr
def __cinit__(self):
self.comparator_ptr = comparator.BytewiseComparator()
def name(self):
return PyBytes_FromString(self.comparator_ptr.Name())
def compare(self, a, b):
return self.comparator_ptr.Compare(
bytes_to_slice(a),
bytes_to_slice(b))
cdef object get_ob(self):
return self
cdef const comparator.Comparator* get_comparator(self):
return self.comparator_ptr
cdef int compare_callback(
void* ctx,
logger.Logger* log,
string& error_msg,
const Slice& a,
const Slice& b) with gil:
try:
return (<object>ctx).compare(slice_to_bytes(a), slice_to_bytes(b))
except BaseException as error:
tb = traceback.format_exc()
logger.Log(log, "Error in compare callback: %s", <bytes>tb)
error_msg.assign(<bytes>str(error))
BytewiseComparator = PyBytewiseComparator
#########################################
## Here comes the stuff for the filter policy
@cython.internal
cdef class PyFilterPolicy(object):
cdef object get_ob(self):
return None
cdef shared_ptr[ConstFilterPolicy] get_policy(self):
return shared_ptr[ConstFilterPolicy]()
cdef set_info_log(self, shared_ptr[logger.Logger] info_log):
pass
@cython.internal
cdef class PyGenericFilterPolicy(PyFilterPolicy):
cdef shared_ptr[filter_policy.FilterPolicyWrapper] policy
cdef object ob
def __cinit__(self, object ob):
if not isinstance(ob, IFilterPolicy):
raise TypeError("%s is not of type %s" % (ob, IFilterPolicy))
self.ob = ob
self.policy.reset(new filter_policy.FilterPolicyWrapper(
bytes_to_string(ob.name()),
<void*>ob,
create_filter_callback,
key_may_match_callback))
cdef object get_ob(self):
return self.ob
cdef shared_ptr[ConstFilterPolicy] get_policy(self):
return <shared_ptr[ConstFilterPolicy]>(self.policy)
cdef set_info_log(self, shared_ptr[logger.Logger] info_log):
self.policy.get().set_info_log(info_log)
cdef void create_filter_callback(
void* ctx,
logger.Logger* log,
string& error_msg,
const Slice* keys,
int n,
string* dst) with gil:
try:
ret = (<object>ctx).create_filter(
[slice_to_bytes(keys[i]) for i in range(n)])
dst.append(bytes_to_string(ret))
except BaseException as error:
tb = traceback.format_exc()
logger.Log(log, "Error in create filter callback: %s", <bytes>tb)
error_msg.assign(<bytes>str(error))
cdef cpp_bool key_may_match_callback(
void* ctx,
logger.Logger* log,
string& error_msg,
const Slice& key,
const Slice& filt) with gil:
try:
return (<object>ctx).key_may_match(
slice_to_bytes(key),
slice_to_bytes(filt))
except BaseException as error:
tb = traceback.format_exc()
logger.Log(log, "Error in key_mach_match callback: %s", <bytes>tb)
error_msg.assign(<bytes>str(error))
@cython.internal
cdef class PyBloomFilterPolicy(PyFilterPolicy):
cdef shared_ptr[ConstFilterPolicy] policy
def __cinit__(self, int bits_per_key):
self.policy.reset(filter_policy.NewBloomFilterPolicy(bits_per_key))
def name(self):
return PyBytes_FromString(self.policy.get().Name())
def create_filter(self, keys):
cdef string dst
cdef vector[Slice] c_keys
for key in keys:
c_keys.push_back(bytes_to_slice(key))
self.policy.get().CreateFilter(
vector_data(c_keys),
<int>c_keys.size(),
cython.address(dst))
return string_to_bytes(dst)
def key_may_match(self, key, filter_):
return self.policy.get().KeyMayMatch(
bytes_to_slice(key),
bytes_to_slice(filter_))
cdef object get_ob(self):
return self
cdef shared_ptr[ConstFilterPolicy] get_policy(self):
return self.policy
BloomFilterPolicy = PyBloomFilterPolicy
#############################################
## Here comes the stuff for the merge operator
@cython.internal
cdef class PyMergeOperator(object):
cdef shared_ptr[merge_operator.MergeOperator] merge_op
cdef object ob
def __cinit__(self, object ob):
self.ob = ob
if isinstance(ob, IAssociativeMergeOperator):
self.merge_op.reset(
<merge_operator.MergeOperator*>
new merge_operator.AssociativeMergeOperatorWrapper(
bytes_to_string(ob.name()),
<void*>(ob),
merge_callback))
elif isinstance(ob, IMergeOperator):
self.merge_op.reset(
<merge_operator.MergeOperator*>
new merge_operator.MergeOperatorWrapper(
bytes_to_string(ob.name()),
<void*>ob,
<void*>ob,
full_merge_callback,
partial_merge_callback))
# elif isinstance(ob, str):
# if ob == "put":
# self.merge_op = merge_operator.MergeOperators.CreatePutOperator()
# elif ob == "put_v1":
# self.merge_op = merge_operator.MergeOperators.CreateDeprecatedPutOperator()
# elif ob == "uint64add":
# self.merge_op = merge_operator.MergeOperators.CreateUInt64AddOperator()
# elif ob == "stringappend":
# self.merge_op = merge_operator.MergeOperators.CreateStringAppendOperator()
# #TODO: necessary?
# # elif ob == "stringappendtest":
# # self.merge_op = merge_operator.MergeOperators.CreateStringAppendTESTOperator()
# elif ob == "max":
# self.merge_op = merge_operator.MergeOperators.CreateMaxOperator()
# else:
# msg = "{0} is not the default type".format(ob)
# raise TypeError(msg)
else:
msg = "%s is not of this types %s"
msg %= (ob, (IAssociativeMergeOperator, IMergeOperator))
raise TypeError(msg)
cdef object get_ob(self):
return self.ob
cdef shared_ptr[merge_operator.MergeOperator] get_operator(self):
return self.merge_op
cdef cpp_bool merge_callback(
void* ctx,
const Slice& key,
const Slice* existing_value,
const Slice& value,
string* new_value,
logger.Logger* log) with gil:
if existing_value == NULL:
py_existing_value = None
else:
py_existing_value = slice_to_bytes(deref(existing_value))
try:
ret = (<object>ctx).merge(
slice_to_bytes(key),
py_existing_value,
slice_to_bytes(value))
if ret[0]:
new_value.assign(bytes_to_string(ret[1]))
return True
return False
except:
tb = traceback.format_exc()
logger.Log(log, "Error in merge_callback: %s", <bytes>tb)
return False
cdef cpp_bool full_merge_callback(
void* ctx,
const Slice& key,
const Slice* existing_value,
const deque[string]& op_list,
string* new_value,
logger.Logger* log) with gil:
if existing_value == NULL:
py_existing_value = None
else:
py_existing_value = slice_to_bytes(deref(existing_value))
try:
ret = (<object>ctx).full_merge(
slice_to_bytes(key),
py_existing_value,
[string_to_bytes(op_list[i]) for i in range(op_list.size())])
if ret[0]:
new_value.assign(bytes_to_string(ret[1]))
return True
return False
except:
tb = traceback.format_exc()
logger.Log(log, "Error in full_merge_callback: %s", <bytes>tb)
return False
cdef cpp_bool partial_merge_callback(
void* ctx,
const Slice& key,
const Slice& left_op,
const Slice& right_op,
string* new_value,
logger.Logger* log) with gil:
try:
ret = (<object>ctx).partial_merge(
slice_to_bytes(key),
slice_to_bytes(left_op),
slice_to_bytes(right_op))
if ret[0]:
new_value.assign(bytes_to_string(ret[1]))
return True
return False
except:
tb = traceback.format_exc()
logger.Log(log, "Error in partial_merge_callback: %s", <bytes>tb)
return False
##############################################
#### Here comes the Cache stuff
@cython.internal
cdef class PyCache(object):
cdef shared_ptr[cache.Cache] get_cache(self):
return shared_ptr[cache.Cache]()
@cython.internal
cdef class PyLRUCache(PyCache):
cdef shared_ptr[cache.Cache] cache_ob
def __cinit__(self, capacity, shard_bits=None):
if shard_bits is not None:
self.cache_ob = cache.NewLRUCache(capacity, shard_bits)
else:
self.cache_ob = cache.NewLRUCache(capacity)
cdef shared_ptr[cache.Cache] get_cache(self):
return self.cache_ob
LRUCache = PyLRUCache
###############################
### Here comes the stuff for SliceTransform
@cython.internal
cdef class PySliceTransform(object):
cdef shared_ptr[slice_transform.SliceTransform] transfomer
cdef object ob
def __cinit__(self, object ob):
if not isinstance(ob, ISliceTransform):
raise TypeError("%s is not of type %s" % (ob, ISliceTransform))
self.ob = ob
self.transfomer.reset(
<slice_transform.SliceTransform*>
new slice_transform.SliceTransformWrapper(
bytes_to_string(ob.name()),
<void*>ob,
slice_transform_callback,
slice_in_domain_callback,
slice_in_range_callback))
cdef object get_ob(self):
return self.ob
cdef shared_ptr[slice_transform.SliceTransform] get_transformer(self):
return self.transfomer
cdef set_info_log(self, shared_ptr[logger.Logger] info_log):
cdef slice_transform.SliceTransformWrapper* ptr
ptr = <slice_transform.SliceTransformWrapper*> self.transfomer.get()
ptr.set_info_log(info_log)
cdef Slice slice_transform_callback(
void* ctx,
logger.Logger* log,
string& error_msg,
const Slice& src) with gil:
cdef size_t offset
cdef size_t size
try:
ret = (<object>ctx).transform(slice_to_bytes(src))
offset = ret[0]
size = ret[1]
if (offset + size) > src.size():
msg = "offset(%i) + size(%i) is bigger than slice(%i)"
raise Exception(msg % (offset, size, src.size()))
return Slice(src.data() + offset, size)
except BaseException as error:
tb = traceback.format_exc()
logger.Log(log, "Error in slice transfrom callback: %s", <bytes>tb)
error_msg.assign(<bytes>str(error))
cdef cpp_bool slice_in_domain_callback(
void* ctx,
logger.Logger* log,
string& error_msg,
const Slice& src) with gil:
try:
return (<object>ctx).in_domain(slice_to_bytes(src))
except BaseException as error:
tb = traceback.format_exc()
logger.Log(log, "Error in slice transfrom callback: %s", <bytes>tb)
error_msg.assign(<bytes>str(error))
cdef cpp_bool slice_in_range_callback(
void* ctx,
logger.Logger* log,
string& error_msg,
const Slice& src) with gil:
try:
return (<object>ctx).in_range(slice_to_bytes(src))
except BaseException as error:
tb = traceback.format_exc()
logger.Log(log, "Error in slice transfrom callback: %s", <bytes>tb)
error_msg.assign(<bytes>str(error))
###########################################
## Here are the TableFactories
@cython.internal
cdef class PyTableFactory(object):
cdef shared_ptr[table_factory.TableFactory] factory
cdef shared_ptr[table_factory.TableFactory] get_table_factory(self):
return self.factory
cdef set_info_log(self, shared_ptr[logger.Logger] info_log):
pass
cdef class BlockBasedTableFactory(PyTableFactory):
cdef PyFilterPolicy py_filter_policy
def __init__(self,
index_type='binary_search',
py_bool hash_index_allow_collision=True,
checksum='crc32',
PyCache block_cache=None,
PyCache block_cache_compressed=None,
filter_policy=None,
no_block_cache=False,
block_size=None,
block_size_deviation=None,
block_restart_interval=None,
whole_key_filtering=None):
cdef table_factory.BlockBasedTableOptions table_options
if index_type == 'binary_search':
table_options.index_type = table_factory.kBinarySearch
elif index_type == 'hash_search':
table_options.index_type = table_factory.kHashSearch
else:
raise ValueError("Unknown index_type: %s" % index_type)
if hash_index_allow_collision:
table_options.hash_index_allow_collision = True
else:
table_options.hash_index_allow_collision = False
if checksum == 'crc32':
table_options.checksum = table_factory.kCRC32c
elif checksum == 'xxhash':
table_options.checksum = table_factory.kxxHash
else:
raise ValueError("Unknown checksum: %s" % checksum)
if no_block_cache:
table_options.no_block_cache = True
else:
table_options.no_block_cache = False
# If the following options are None use the rocksdb default.
if block_size is not None:
table_options.block_size = block_size
if block_size_deviation is not None:
table_options.block_size_deviation = block_size_deviation
if block_restart_interval is not None:
table_options.block_restart_interval = block_restart_interval
if whole_key_filtering is not None:
if whole_key_filtering:
table_options.whole_key_filtering = True
else:
table_options.whole_key_filtering = False
if block_cache is not None:
table_options.block_cache = block_cache.get_cache()
if block_cache_compressed is not None:
table_options.block_cache_compressed = block_cache_compressed.get_cache()
# Set the filter_policy
self.py_filter_policy = None
if filter_policy is not None:
if isinstance(filter_policy, PyFilterPolicy):
if (<PyFilterPolicy?>filter_policy).get_policy().get() == NULL:
raise Exception("Cannot set filter policy: %s" % filter_policy)
self.py_filter_policy = filter_policy
else:
self.py_filter_policy = PyGenericFilterPolicy(filter_policy)
table_options.filter_policy = self.py_filter_policy.get_policy()
self.factory.reset(table_factory.NewBlockBasedTableFactory(table_options))
cdef set_info_log(self, shared_ptr[logger.Logger] info_log):
if self.py_filter_policy is not None:
self.py_filter_policy.set_info_log(info_log)
cdef class PlainTableFactory(PyTableFactory):
def __init__(
self,
user_key_len=0,
bloom_bits_per_key=10,
hash_table_ratio=0.75,
index_sparseness=10,
huge_page_tlb_size=0,
encoding_type='plain',
py_bool full_scan_mode=False):
cdef table_factory.PlainTableOptions table_options
table_options.user_key_len = user_key_len
table_options.bloom_bits_per_key = bloom_bits_per_key
table_options.hash_table_ratio = hash_table_ratio
table_options.index_sparseness = index_sparseness
table_options.huge_page_tlb_size = huge_page_tlb_size
if encoding_type == 'plain':
table_options.encoding_type = table_factory.kPlain
elif encoding_type == 'prefix':
table_options.encoding_type = table_factory.kPrefix
else:
raise ValueError("Unknown encoding_type: %s" % encoding_type)
table_options.full_scan_mode = full_scan_mode
self.factory.reset( table_factory.NewPlainTableFactory(table_options))
#############################################
### Here are the MemtableFactories
@cython.internal
cdef class PyMemtableFactory(object):
cdef shared_ptr[memtablerep.MemTableRepFactory] factory
cdef shared_ptr[memtablerep.MemTableRepFactory] get_memtable_factory(self):
return self.factory
cdef class SkipListMemtableFactory(PyMemtableFactory):
def __init__(self):
self.factory.reset(memtablerep.NewSkipListFactory())
cdef class VectorMemtableFactory(PyMemtableFactory):
def __init__(self, count=0):
self.factory.reset(memtablerep.NewVectorRepFactory(count))
cdef class HashSkipListMemtableFactory(PyMemtableFactory):
def __init__(
self,
bucket_count=1000000,
skiplist_height=4,
skiplist_branching_factor=4):
self.factory.reset(
memtablerep.NewHashSkipListRepFactory(
bucket_count,
skiplist_height,
skiplist_branching_factor))
cdef class HashLinkListMemtableFactory(PyMemtableFactory):
def __init__(self, bucket_count=50000):
self.factory.reset(memtablerep.NewHashLinkListRepFactory(bucket_count))
##################################
cdef class CompressionType(object):
no_compression = u'no_compression'
snappy_compression = u'snappy_compression'
zlib_compression = u'zlib_compression'
bzip2_compression = u'bzip2_compression'
lz4_compression = u'lz4_compression'
lz4hc_compression = u'lz4hc_compression'
xpress_compression = u'xpress_compression'
zstd_compression = u'zstd_compression'
zstdnotfinal_compression = u'zstdnotfinal_compression'
disable_compression = u'disable_compression'
cdef class CompactionPri(object):
by_compensated_size = u'by_compensated_size'
oldest_largest_seq_first = u'oldest_largest_seq_first'
oldest_smallest_seq_first = u'oldest_smallest_seq_first'
min_overlapping_ratio = u'min_overlapping_ratio'
@cython.internal
cdef class _ColumnFamilyHandle:
""" This is an internal class that we will weakref for safety """
cdef db.ColumnFamilyHandle* handle
cdef object __weakref__
cdef object weak_handle
def __cinit__(self):
self.handle = NULL
def __dealloc__(self):
if not self.handle == NULL:
del self.handle
@staticmethod
cdef from_handle_ptr(db.ColumnFamilyHandle* handle):
inst = <_ColumnFamilyHandle>_ColumnFamilyHandle.__new__(_ColumnFamilyHandle)
inst.handle = handle
return inst
@property
def name(self):
return self.handle.GetName()
@property
def id(self):
return self.handle.GetID()
@property
def weakref(self):
if self.weak_handle is None:
self.weak_handle = ColumnFamilyHandle.from_wrapper(self)
return self.weak_handle
cdef class ColumnFamilyHandle:
""" This represents a ColumnFamilyHandle """
cdef object _ref
cdef readonly bytes name
cdef readonly int id
def __cinit__(self, weakhandle):
self._ref = weakhandle
self.name = self._ref().name
self.id = self._ref().id
def __init__(self, *):
raise TypeError("These can not be constructed from Python")
@staticmethod
cdef object from_wrapper(_ColumnFamilyHandle real_handle):
return ColumnFamilyHandle.__new__(ColumnFamilyHandle, weakref.ref(real_handle))
@property
def is_valid(self):
return self._ref() is not None
def __repr__(self):
valid = "valid" if self.is_valid else "invalid"
return f"<ColumnFamilyHandle name: {self.name}, id: {self.id}, state: {valid}>"
cdef db.ColumnFamilyHandle* get_handle(self) except NULL:
cdef _ColumnFamilyHandle real_handle = self._ref()
if real_handle is None:
raise ValueError(f"{self} is no longer a valid ColumnFamilyHandle!")
return real_handle.handle
def __eq__(self, other):
cdef ColumnFamilyHandle fast_other
if isinstance(other, ColumnFamilyHandle):
fast_other = other
return (
self.name == fast_other.name
and self.id == fast_other.id
and self._ref == fast_other._ref
)
return False
def __lt__(self, other):
cdef ColumnFamilyHandle fast_other
if isinstance(other, ColumnFamilyHandle):
return self.id < other.id
return NotImplemented
# Since @total_ordering isn't a thing for cython
def __ne__(self, other):
return not self == other
def __gt__(self, other):
return other < self
def __le__(self, other):
return not other < self
def __ge__(self, other):
return not self < other
def __hash__(self):
# hash of a weakref matches that of its original ref'ed object
# so we use the id of our weakref object here to prevent
# a situation where we are invalid, but match a valid handle's hash
return hash((self.id, self.name, id(self._ref)))
cdef class ColumnFamilyOptions(object):
cdef options.ColumnFamilyOptions* copts
cdef PyComparator py_comparator
cdef PyMergeOperator py_merge_operator
cdef PySliceTransform py_prefix_extractor
cdef PyTableFactory py_table_factory
cdef PyMemtableFactory py_memtable_factory
# Used to protect sharing of Options with many DB-objects
cdef cpp_bool in_use
def __cinit__(self):
self.copts = NULL
self.copts = new options.ColumnFamilyOptions()
self.in_use = False
def __dealloc__(self):
if not self.copts == NULL:
del self.copts
def __init__(self, **kwargs):
self.py_comparator = BytewiseComparator()
self.py_merge_operator = None
self.py_prefix_extractor = None
self.py_table_factory = None
self.py_memtable_factory = None
for key, value in kwargs.items():
setattr(self, key, value)
property write_buffer_size:
def __get__(self):
return self.copts.write_buffer_size
def __set__(self, value):
self.copts.write_buffer_size = value
property max_write_buffer_number:
def __get__(self):
return self.copts.max_write_buffer_number
def __set__(self, value):
self.copts.max_write_buffer_number = value
property min_write_buffer_number_to_merge:
def __get__(self):
return self.copts.min_write_buffer_number_to_merge
def __set__(self, value):
self.copts.min_write_buffer_number_to_merge = value
property compression_opts:
def __get__(self):
cdef dict ret_ob = {}
ret_ob['window_bits'] = self.copts.compression_opts.window_bits
ret_ob['level'] = self.copts.compression_opts.level
ret_ob['strategy'] = self.copts.compression_opts.strategy
ret_ob['max_dict_bytes'] = self.copts.compression_opts.max_dict_bytes
return ret_ob
def __set__(self, dict value):
cdef options.CompressionOptions* copts
copts = cython.address(self.copts.compression_opts)
# CompressionOptions(int wbits, int _lev, int _strategy, int _max_dict_bytes)
if 'window_bits' in value:
copts.window_bits = value['window_bits']
if 'level' in value:
copts.level = value['level']
if 'strategy' in value:
copts.strategy = value['strategy']
if 'max_dict_bytes' in value:
copts.max_dict_bytes = value['max_dict_bytes']
property compaction_pri:
def __get__(self):
if self.copts.compaction_pri == options.kByCompensatedSize:
return CompactionPri.by_compensated_size
if self.copts.compaction_pri == options.kOldestLargestSeqFirst:
return CompactionPri.oldest_largest_seq_first
if self.copts.compaction_pri == options.kOldestSmallestSeqFirst:
return CompactionPri.oldest_smallest_seq_first
if self.copts.compaction_pri == options.kMinOverlappingRatio:
return CompactionPri.min_overlapping_ratio
def __set__(self, value):
if value == CompactionPri.by_compensated_size:
self.copts.compaction_pri = options.kByCompensatedSize
elif value == CompactionPri.oldest_largest_seq_first:
self.copts.compaction_pri = options.kOldestLargestSeqFirst
elif value == CompactionPri.oldest_smallest_seq_first:
self.copts.compaction_pri = options.kOldestSmallestSeqFirst
elif value == CompactionPri.min_overlapping_ratio:
self.copts.compaction_pri = options.kMinOverlappingRatio
else:
raise TypeError("Unknown compaction pri: %s" % value)
property compression:
def __get__(self):
if self.copts.compression == options.kNoCompression:
return CompressionType.no_compression
elif self.copts.compression == options.kSnappyCompression:
return CompressionType.snappy_compression
elif self.copts.compression == options.kZlibCompression:
return CompressionType.zlib_compression
elif self.copts.compression == options.kBZip2Compression:
return CompressionType.bzip2_compression
elif self.copts.compression == options.kLZ4Compression:
return CompressionType.lz4_compression
elif self.copts.compression == options.kLZ4HCCompression:
return CompressionType.lz4hc_compression
elif self.copts.compression == options.kXpressCompression:
return CompressionType.xpress_compression
elif self.copts.compression == options.kZSTD:
return CompressionType.zstd_compression
elif self.copts.compression == options.kZSTDNotFinalCompression:
return CompressionType.zstdnotfinal_compression
elif self.copts.compression == options.kDisableCompressionOption:
return CompressionType.disable_compression
else:
raise Exception("Unknonw type: %s" % self.opts.compression)
def __set__(self, value):
if value == CompressionType.no_compression:
self.copts.compression = options.kNoCompression
elif value == CompressionType.snappy_compression:
self.copts.compression = options.kSnappyCompression
elif value == CompressionType.zlib_compression:
self.copts.compression = options.kZlibCompression
elif value == CompressionType.bzip2_compression:
self.copts.compression = options.kBZip2Compression
elif value == CompressionType.lz4_compression:
self.copts.compression = options.kLZ4Compression
elif value == CompressionType.lz4hc_compression:
self.copts.compression = options.kLZ4HCCompression
elif value == CompressionType.zstd_compression:
self.copts.compression = options.kZSTD
elif value == CompressionType.zstdnotfinal_compression:
self.copts.compression = options.kZSTDNotFinalCompression
elif value == CompressionType.disable_compression:
self.copts.compression = options.kDisableCompressionOption
else:
raise TypeError("Unknown compression: %s" % value)
property max_compaction_bytes:
def __get__(self):
return self.copts.max_compaction_bytes
def __set__(self, value):
self.copts.max_compaction_bytes = value
property num_levels:
def __get__(self):
return self.copts.num_levels
def __set__(self, value):
self.copts.num_levels = value
property level0_file_num_compaction_trigger:
def __get__(self):
return self.copts.level0_file_num_compaction_trigger
def __set__(self, value):
self.copts.level0_file_num_compaction_trigger = value
property level0_slowdown_writes_trigger:
def __get__(self):
return self.copts.level0_slowdown_writes_trigger
def __set__(self, value):