-
Notifications
You must be signed in to change notification settings - Fork 30
/
leveldb_object.cc
1433 lines (1155 loc) · 38.7 KB
/
leveldb_object.cc
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
// Copyright (c) Arni Mar Jonsson.
// See LICENSE for details.
#include "leveldb_ext.h"
#include <leveldb/comparator.h>
static PyObject* PyLevelDBIter_New(PyObject* ref, PyLevelDB* db, leveldb::Iterator* iterator, std::string* bound, int include_value, int is_reverse);
static PyObject* PyLevelDBSnapshot_New(PyLevelDB* db, const leveldb::Snapshot* snapshot);
static void PyLevelDB_set_error(leveldb::Status& status)
{
PyErr_SetString(leveldb_exception, status.ToString().c_str());
}
const char pyleveldb_destroy_db_doc[] =
"leveldb.DestroyDB(db_dir)\n\nAttempts to recover as much data as possible from a corrupt database."
;
PyObject* pyleveldb_destroy_db(PyObject* self, PyObject* args)
{
const char* db_dir = 0;
if (!PyArg_ParseTuple(args, (char*)"s", &db_dir))
return 0;
std::string _db_dir(db_dir);
leveldb::Status status;
leveldb::Options options;
Py_BEGIN_ALLOW_THREADS
status = leveldb::DestroyDB(_db_dir.c_str(), options);
Py_END_ALLOW_THREADS
if (!status.ok()) {
PyLevelDB_set_error(status);
return 0;
}
Py_INCREF(Py_None);
return Py_None;
}
static void PyLevelDB_dealloc(PyLevelDB* self)
{
Py_BEGIN_ALLOW_THREADS
delete self->_db;
delete self->_options;
delete self->_cache;
if (self->_comparator != leveldb::BytewiseComparator())
delete self->_comparator;
Py_END_ALLOW_THREADS
self->_db = 0;
self->_options = 0;
self->_cache = 0;
self->_comparator = 0;
self->n_iterators = 0;
self->n_snapshots = 0;
#if PY_MAJOR_VERSION >= 3
Py_TYPE(self)->tp_free((PyObject*)self);
#else
((PyObject*)self)->ob_type->tp_free((PyObject*)self);
#endif
}
static void PyLevelDBSnapshot_dealloc(PyLevelDBSnapshot* self)
{
if (self->db && self->snapshot) {
Py_BEGIN_ALLOW_THREADS
self->db->_db->ReleaseSnapshot(self->snapshot);
Py_END_ALLOW_THREADS
}
if (self->db)
self->db->n_snapshots -= 1;
Py_DECREF(self->db);
self->db = 0;
self->snapshot = 0;
#if PY_MAJOR_VERSION >= 3
Py_TYPE(self)->tp_free((PyObject*)self);
#else
((PyObject*)self)->ob_type->tp_free((PyObject*)self);
#endif
}
static void PyWriteBatch_dealloc(PyWriteBatch* self)
{
delete self->ops;
#if PY_MAJOR_VERSION >= 3
Py_TYPE(self)->tp_free((PyObject*)self);
#else
((PyObject*)self)->ob_type->tp_free((PyObject*)self);
#endif
}
static PyObject* PyLevelDB_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
PyLevelDB* self = (PyLevelDB*)type->tp_alloc(type, 0);
if (self) {
self->_db = 0;
self->_options = 0;
self->_cache = 0;
self->_comparator = 0;
self->n_iterators = 0;
self->n_snapshots = 0;
}
return (PyObject*)self;
}
static PyObject* PyWriteBatch_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
PyWriteBatch* self = (PyWriteBatch*)type->tp_alloc(type, 0);
if (self) {
self->ops = new std::vector<PyWriteBatchEntry>;
if (self->ops == 0) {
#if PY_MAJOR_VERSION >= 3
Py_TYPE(self)->tp_free((PyObject*)self);
#else
((PyObject*)self)->ob_type->tp_free((PyObject*)self);
#endif
return PyErr_NoMemory();
}
}
return (PyObject*)self;
}
static PyObject* PyLevelDBSnapshot_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
PyLevelDBSnapshot* self = (PyLevelDBSnapshot*)type->tp_alloc(type, 0);
if (self) {
self->db = 0;
self->snapshot = 0;
}
return (PyObject*)self;
}
// Python 2.6+
#if PY_MAJOR_VERSION >= 3 || (PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 6)
#define PY_LEVELDB_DEFINE_BUFFER(n) Py_buffer n; (n).buf = 0; (n).len = 0; (n).obj = 0
#define PY_LEVELDB_RELEASE_BUFFER(n) if (n.obj) {PyBuffer_Release(&n);}
#define PARAM_V(n) &(n)
#define PY_LEVELDB_BEGIN_ALLOW_THREADS Py_BEGIN_ALLOW_THREADS
#define PY_LEVELDB_END_ALLOW_THREADS Py_END_ALLOW_THREADS
#define PY_LEVELDB_SLICE_VALUE(n) leveldb::Slice((const char*)(n).buf, (size_t)(n).len)
#define PY_LEVELDB_STRING(n) std::string((const char*)(n).buf, (size_t)(n).len)
#if PY_MAJOR_VERSION >= 3
#define PARAM_S "y*"
#define PY_LEVELDB_STRING_OR_BYTEARRAY PyByteArray_FromStringAndSize
#else
#define PARAM_S "s*"
#define PY_LEVELDB_STRING_OR_BYTEARRAY PyString_FromStringAndSize
#endif
// Python 2.4/2.5
#else
#define PY_LEVELDB_DEFINE_BUFFER(n) const char* s_##n = 0; int n_##n
#define PY_LEVELDB_RELEASE_BUFFER(n)
#define PARAM_V(n) &s_##n, &n_##n
#define PY_LEVELDB_BEGIN_ALLOW_THREADS
#define PY_LEVELDB_END_ALLOW_THREADS
#define PY_LEVELDB_SLICE_VALUE(n) leveldb::Slice((const char*)s_##n, (size_t)n_##n)
#define PY_LEVELDB_STRING(n) std::string((const char*)s_##n, (size_t)n_##n);
#define PARAM_S "t#"
#define PY_LEVELDB_STRING_OR_BYTEARRAY PyString_FromStringAndSize
#endif
class PythonComparatorWrapper : public leveldb::Comparator {
public:
PythonComparatorWrapper(const char* name, PyObject* comparator) :
name(name),
comparator(comparator),
last_exception_type(0),
last_exception_value(0),
last_exception_traceback(0)
{
Py_INCREF(comparator);
#if PY_MAJOR_VERSION >= 3
zero = PyLong_FromLong(0);
#else
zero = PyInt_FromLong(0);
#endif
}
~PythonComparatorWrapper()
{
Py_DECREF(comparator);
Py_XDECREF(last_exception_type);
Py_XDECREF(last_exception_value);
Py_XDECREF(last_exception_traceback);
Py_XDECREF(zero);
}
private:
int GetSign(PyObject* i, int* c) const
{
#if PY_MAJOR_VERSION >= 3
if (PyLong_Check(i)) {
#else
if (PyInt_Check(i) || PyLong_Check(i)) {
#endif
#if PY_MAJOR_VERSION >= 3
if (PyObject_RichCompareBool(i, zero, Py_LT))
*c = -1;
else if (PyObject_RichCompareBool(i, zero, Py_GT))
*c = 1;
else
*c = 0;
#else
*c = PyObject_Compare(i, zero);
#endif
if (PyErr_Occurred())
return 0;
return 1;
}
PyErr_SetString(PyExc_TypeError, "comparison value is not an integer");
return 0;
}
void SetError() const
{
// we don't do too much
fprintf(stderr, "py-leveldb: Python comparison failure. Unable to reliably continue. Goodbye cruel world.\n\n");
PyErr_Print();
fflush(stderr);
abort();
// assert(PyErr_Occurred());
// Py_XDECREF(last_exception_type);
// Py_XDECREF(last_exception_value);
// Py_XDECREF(last_exception_traceback);
// PyErr_Fetch(&last_exception_type, &last_exception_value, &last_exception_value);
}
public:
// bool CheckAndSetError()
// {
// if (last_exception_type) {
// PyErr_Restore(last_exception_type, last_exception_value, last_exception_traceback);
// last_exception_type = 0;
// last_exception_value = 0;
// last_exception_traceback = 0;
// return true;
// }
//
// return false;
// }
// this can be called from pretty much any leveldb threads
int Compare(const leveldb::Slice& a, const leveldb::Slice& b) const
{
// http://docs.python.org/dev/c-api/init.html#non-python-created-threads
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
// acquire python thread
PyObject* a_ = PY_LEVELDB_STRING_OR_BYTEARRAY(a.data(), a.size());
PyObject* b_ = PY_LEVELDB_STRING_OR_BYTEARRAY(b.data(), b.size());
if (a_ == 0 || b_ == 0) {
Py_XDECREF(a_);
Py_XDECREF(b_);
SetError();
PyGILState_Release(gstate);
return 0;
}
PyObject* c = PyObject_CallFunctionObjArgs(comparator, a_, b_, 0);
int cmp = 0;
Py_XDECREF(a_);
Py_XDECREF(b_);
if (c == 0 || !GetSign(c, &cmp))
SetError();
PyGILState_Release(gstate);
return cmp;
}
const char* Name() const
{
return name.c_str();
}
void FindShortestSeparator(std::string*, const leveldb::Slice&) const { }
void FindShortSuccessor(std::string*) const { }
private:
std::string name;
PyObject* comparator;
PyObject* last_exception_type;
PyObject* last_exception_value;
PyObject* last_exception_traceback;
PyObject* zero;
};
static PyObject* PyLevelDB_Put(PyLevelDB* self, PyObject* args, PyObject* kwds)
{
const char* kwargs[] = {"key", "value", "sync", 0};
PyObject* sync = Py_False;
PY_LEVELDB_DEFINE_BUFFER(key);
PY_LEVELDB_DEFINE_BUFFER(value);
leveldb::WriteOptions options;
leveldb::Status status;
if (!PyArg_ParseTupleAndKeywords(args, kwds, (char*)PARAM_S PARAM_S "|O!", (char**)kwargs, PARAM_V(key), PARAM_V(value), &PyBool_Type, &sync))
return 0;
PY_LEVELDB_BEGIN_ALLOW_THREADS
leveldb::Slice key_slice = PY_LEVELDB_SLICE_VALUE(key);
leveldb::Slice value_slice = PY_LEVELDB_SLICE_VALUE(value);
options.sync = (sync == Py_True) ? true : false;
status = self->_db->Put(options, key_slice, value_slice);
PY_LEVELDB_END_ALLOW_THREADS
PY_LEVELDB_RELEASE_BUFFER(key);
PY_LEVELDB_RELEASE_BUFFER(value);
if (!status.ok()) {
PyLevelDB_set_error(status);
return 0;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject* PyLevelDB_Get_(PyLevelDB* self, leveldb::DB* db, const leveldb::Snapshot* snapshot, PyObject* args, PyObject* kwds)
{
PyObject* verify_checksums = Py_False;
PyObject* fill_cache = Py_True;
PyObject* failobj = 0;
const char* kwargs[] = {"key", "verify_checksums", "fill_cache", "default", 0};
leveldb::Status status;
std::string value;
PY_LEVELDB_DEFINE_BUFFER(key);
if (!PyArg_ParseTupleAndKeywords(args, kwds, (char*)PARAM_S "|O!O!O", (char**)kwargs, PARAM_V(key), &PyBool_Type, &verify_checksums, &PyBool_Type, &fill_cache, &failobj))
return 0;
PY_LEVELDB_BEGIN_ALLOW_THREADS
leveldb::Slice key_slice = PY_LEVELDB_SLICE_VALUE(key);
leveldb::ReadOptions options;
options.verify_checksums = (verify_checksums == Py_True) ? true : false;
options.fill_cache = (fill_cache == Py_True) ? true : false;
options.snapshot = snapshot;
status = db->Get(options, key_slice, &value);
PY_LEVELDB_END_ALLOW_THREADS
PY_LEVELDB_RELEASE_BUFFER(key);
if (status.IsNotFound()) {
if (failobj) {
Py_INCREF(failobj);
return failobj;
}
PyErr_SetNone(PyExc_KeyError);
return 0;
}
if (!status.ok()) {
PyLevelDB_set_error(status);
return 0;
}
return PY_LEVELDB_STRING_OR_BYTEARRAY(value.c_str(), value.length());
}
static PyObject* PyLevelDB_Get(PyLevelDB* self, PyObject* args, PyObject* kwds)
{
return PyLevelDB_Get_(self, self->_db, 0, args, kwds);
}
static PyObject* PyLevelDBSnaphot_Get(PyLevelDBSnapshot* self, PyObject* args, PyObject* kwds)
{
return PyLevelDB_Get_(self->db, self->db->_db, self->snapshot, args, kwds);
}
static PyObject* PyLevelDB_Delete(PyLevelDB* self, PyObject* args, PyObject* kwds)
{
PyObject* sync = Py_False;
const char* kwargs[] = {"key", "sync", 0};
PY_LEVELDB_DEFINE_BUFFER(key);
leveldb::Status status;
if (!PyArg_ParseTupleAndKeywords(args, kwds, (char*)PARAM_S "|O!", (char**)kwargs, PARAM_V(key), &PyBool_Type, &sync))
return 0;
PY_LEVELDB_BEGIN_ALLOW_THREADS
leveldb::Slice key_slice = PY_LEVELDB_SLICE_VALUE(key);
leveldb::WriteOptions options;
options.sync = (sync == Py_True) ? true : false;
status = self->_db->Delete(options, key_slice);
PY_LEVELDB_END_ALLOW_THREADS
PY_LEVELDB_RELEASE_BUFFER(key);
if (!status.ok()) {
PyLevelDB_set_error(status);
return 0;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject* PyWriteBatch_Put(PyWriteBatch* self, PyObject* args)
{
// NOTE: we copy all buffers
PY_LEVELDB_DEFINE_BUFFER(key);
PY_LEVELDB_DEFINE_BUFFER(value);
if (!PyArg_ParseTuple(args, (char*)PARAM_S PARAM_S, PARAM_V(key), PARAM_V(value)))
return 0;
PyWriteBatchEntry op;
op.is_put = true;
PY_LEVELDB_BEGIN_ALLOW_THREADS
op.key = PY_LEVELDB_STRING(key);
op.value = PY_LEVELDB_STRING(value);
PY_LEVELDB_END_ALLOW_THREADS
PY_LEVELDB_RELEASE_BUFFER(key);
PY_LEVELDB_RELEASE_BUFFER(value);
self->ops->push_back(op);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject* PyWriteBatch_Delete(PyWriteBatch* self, PyObject* args)
{
// NOTE: we copy all buffers
PY_LEVELDB_DEFINE_BUFFER(key);
if (!PyArg_ParseTuple(args, (char*)PARAM_S, PARAM_V(key)))
return 0;
PyWriteBatchEntry op;
op.is_put = false;
PY_LEVELDB_BEGIN_ALLOW_THREADS
op.key = PY_LEVELDB_STRING(key);
PY_LEVELDB_END_ALLOW_THREADS
PY_LEVELDB_RELEASE_BUFFER(key);
self->ops->push_back(op);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject* PyLevelDB_Write(PyLevelDB* self, PyObject* args, PyObject* kwds)
{
PyWriteBatch* write_batch = 0;
PyObject* sync = Py_False;
const char* kwargs[] = {"write_batch", "sync", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwds, (char*)"O!|O!", (char**)kwargs, &PyWriteBatch_Type, &write_batch, &PyBool_Type, &sync))
return 0;
leveldb::WriteOptions options;
options.sync = (sync == Py_True) ? true : false;
leveldb::WriteBatch batch;
leveldb::Status status;
for (size_t i = 0; i < write_batch->ops->size(); i++) {
PyWriteBatchEntry& op = (*write_batch->ops)[i];
leveldb::Slice key(op.key.c_str(), op.key.size());
leveldb::Slice value(op.value.c_str(), op.value.size());
if (op.is_put) {
batch.Put(key, value);
} else {
batch.Delete(key);
}
}
Py_BEGIN_ALLOW_THREADS
status = self->_db->Write(options, &batch);
Py_END_ALLOW_THREADS
if (!status.ok()) {
PyLevelDB_set_error(status);
return 0;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject* PyLevelDB_RangeIter_(PyLevelDB* self, const leveldb::Snapshot* snapshot, PyObject* args, PyObject* kwds)
{
int is_from = 0;
int is_to = 0;
PY_LEVELDB_DEFINE_BUFFER(a);
PY_LEVELDB_DEFINE_BUFFER(b);
PyObject* _a = Py_None;
PyObject* _b = Py_None;
PyObject* verify_checksums = Py_False;
PyObject* fill_cache = Py_True;
PyObject* include_value = Py_True;
PyObject* is_reverse = Py_False;
const char* kwargs[] = {"key_from", "key_to", "verify_checksums", "fill_cache", "include_value", "reverse", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwds, (char*)"|OOO!O!O!O!", (char**)kwargs, &_a, &_b, &PyBool_Type, &verify_checksums, &PyBool_Type, &fill_cache, &PyBool_Type, &include_value, &PyBool_Type, &is_reverse))
return 0;
std::string from;
std::string to;
leveldb::ReadOptions read_options;
read_options.verify_checksums = (verify_checksums == Py_True) ? true : false;
read_options.fill_cache = (fill_cache == Py_True) ? true : false;
read_options.snapshot = snapshot;
if (_a != Py_None) {
is_from = 1;
if (!PyArg_Parse(_a, (char*)PARAM_S, PARAM_V(a)))
return 0;
}
if (_b != Py_None) {
is_to = 1;
if (!PyArg_Parse(_b, (char*)PARAM_S, PARAM_V(b)))
return 0;
}
if (is_from)
from = PY_LEVELDB_STRING(a);
if (is_to)
to = PY_LEVELDB_STRING(b);
leveldb::Slice key(is_reverse == Py_True ? to.c_str() : from.c_str(), is_reverse == Py_True ? to.size() : from.size());
if (is_from)
PY_LEVELDB_RELEASE_BUFFER(a);
if (is_to)
PY_LEVELDB_RELEASE_BUFFER(b);
// create iterator
leveldb::Iterator* iter = 0;
Py_BEGIN_ALLOW_THREADS
iter = self->_db->NewIterator(read_options);
// if we have an iterator
if (iter) {
// forward iteration
if (is_reverse == Py_False) {
if (!is_from)
iter->SeekToFirst();
else
iter->Seek(key);
} else {
if (!is_to) {
iter->SeekToLast();
} else {
iter->Seek(key);
if (!iter->Valid()) {
iter->SeekToLast();
} else {
leveldb::Slice a = key;
leveldb::Slice b = iter->key();
int c = self->_options->comparator->Compare(a, b);
if (c) {
iter->Prev();
}
}
}
}
}
Py_END_ALLOW_THREADS
if (iter == 0)
return PyErr_NoMemory();
// if iterator is empty, return an empty iterator object
if (!iter->Valid()) {
Py_BEGIN_ALLOW_THREADS
delete iter;
Py_END_ALLOW_THREADS
return PyLevelDBIter_New(0, 0, 0, 0, 0, 0);
}
// otherwise, we're good
std::string* s = 0;
if (is_reverse == Py_False && is_to) {
s = new std::string(to);
if (s == 0) {
Py_BEGIN_ALLOW_THREADS
delete iter;
Py_END_ALLOW_THREADS
return PyErr_NoMemory();
}
} else if (is_reverse == Py_True && is_from) {
s = new std::string(from);
if (s == 0) {
Py_BEGIN_ALLOW_THREADS
delete iter;
Py_END_ALLOW_THREADS
return PyErr_NoMemory();
}
}
return PyLevelDBIter_New((PyObject*)self, self, iter, s, (include_value == Py_True) ? 1 : 0, (is_reverse == Py_True) ? 1 : 0);
}
static PyObject* PyLevelDB_RangeIter(PyLevelDB* self, PyObject* args, PyObject* kwds)
{
return PyLevelDB_RangeIter_(self, 0, args, kwds);
}
static PyObject* PyLevelDBSnapshot_RangeIter(PyLevelDBSnapshot* self, PyObject* args, PyObject* kwds)
{
return PyLevelDB_RangeIter_(self->db, self->snapshot, args, kwds);
}
static PyObject* PyLevelDB_GetStatus(PyLevelDB* self)
{
std::string value;
if (!self->_db->GetProperty(leveldb::Slice("leveldb.stats"), &value)) {
PyErr_SetString(PyExc_ValueError, "unknown property");
return 0;
}
#if PY_MAJOR_VERSION >= 3
return PyUnicode_DecodeLatin1(value.c_str(), value.size(), 0);
#else
return PyString_FromString(value.c_str());
#endif
}
static PyObject* PyLevelDB_CreateSnapshot(PyLevelDB* self)
{
const leveldb::Snapshot* snapshot = self->_db->GetSnapshot();
//! TBD: check for GetSnapshot() failures
return PyLevelDBSnapshot_New(self, snapshot);
}
static PyObject* PyLevelDB_CompactRange(PyLevelDB* self, PyObject* args, PyObject* kwds)
{
PyObject* _start = Py_None;
PyObject* _end = Py_None;
int is_start = 0;
int is_end = 0;
PY_LEVELDB_DEFINE_BUFFER(a);
PY_LEVELDB_DEFINE_BUFFER(b);
const char* kwargs[] = {"start", "end", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwds, (char*)"|OO", (char**)kwargs, &_start, &_end))
return 0;
if (_start != Py_None) {
is_start = 1;
if (!PyArg_Parse(_start, (char*)PARAM_S, PARAM_V(a)))
return 0;
}
if (_end != Py_None) {
is_end = 1;
if (!PyArg_Parse(_end, (char*)PARAM_S, PARAM_V(b)))
return 0;
}
Py_BEGIN_ALLOW_THREADS
leveldb::Slice start_slice("");
leveldb::Slice end_slice("");
if (is_start)
start_slice = PY_LEVELDB_SLICE_VALUE(a);
if (is_end)
end_slice = PY_LEVELDB_SLICE_VALUE(b);
self->_db->CompactRange(is_start ? &start_slice : 0, is_end ? &end_slice : 0);
Py_END_ALLOW_THREADS
if (is_start)
PY_LEVELDB_RELEASE_BUFFER(a);
if (is_end)
PY_LEVELDB_RELEASE_BUFFER(b);
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef PyLevelDB_methods[] = {
{(char*)"Put", (PyCFunction)PyLevelDB_Put, METH_VARARGS | METH_KEYWORDS, (char*)"add a key/value pair to database, with an optional synchronous disk write" },
{(char*)"Get", (PyCFunction)PyLevelDB_Get, METH_VARARGS | METH_KEYWORDS, (char*)"get a value from the database" },
{(char*)"Delete", (PyCFunction)PyLevelDB_Delete, METH_VARARGS | METH_KEYWORDS, (char*)"delete a value in the database" },
{(char*)"Write", (PyCFunction)PyLevelDB_Write, METH_VARARGS | METH_KEYWORDS, (char*)"apply a write-batch"},
{(char*)"RangeIter", (PyCFunction)PyLevelDB_RangeIter, METH_VARARGS | METH_KEYWORDS, (char*)"key/value range scan"},
{(char*)"GetStats", (PyCFunction)PyLevelDB_GetStatus, METH_VARARGS | METH_NOARGS, (char*)"get a mapping of all DB statistics"},
{(char*)"CreateSnapshot", (PyCFunction)PyLevelDB_CreateSnapshot, METH_NOARGS, (char*)"create a new snapshot from current DB state"},
{(char*)"CompactRange", (PyCFunction)PyLevelDB_CompactRange, METH_VARARGS | METH_KEYWORDS, (char*)"Compact keys in the range"},
{NULL}
};
static PyMethodDef PyWriteBatch_methods[] = {
{(char*)"Put", (PyCFunction)PyWriteBatch_Put, METH_VARARGS, (char*)"add a put op to batch" },
{(char*)"Delete", (PyCFunction)PyWriteBatch_Delete, METH_VARARGS, (char*)"add a delete op to batch" },
{NULL}
};
static PyMethodDef PyLevelDBSnapshot_methods[] = {
{(char*)"Get", (PyCFunction)PyLevelDBSnaphot_Get, METH_VARARGS | METH_KEYWORDS, (char*)"get a value from the snapshot" },
{(char*)"RangeIter", (PyCFunction)PyLevelDBSnapshot_RangeIter, METH_VARARGS | METH_KEYWORDS, (char*)"key/value range scan"},
{NULL}
};
static int pyleveldb_str_eq(PyObject* p, const char* s)
{
// 8-bit string
#if PY_MAJOR_VERSION < 3
if (PyString_Check(p) && strcmp(PyString_AS_STRING(p), "bytewise") == 0)
return 1;
#endif
// unicode string
if (PyUnicode_Check(p)) {
size_t i = 0;
Py_UNICODE* c = PyUnicode_AS_UNICODE(p);
while (s[i] && c[i] && (int)s[i] == (int)c[i])
i++;
return ((int)s[i] == (int)c[i]);
}
return 0;
}
static const leveldb::Comparator* pyleveldb_get_comparator(PyObject* comparator)
{
// default comparator
if (comparator == 0 || pyleveldb_str_eq(comparator, "bytewise"))
return leveldb::BytewiseComparator();
// (name-ascii, python-callable)
const char* cmp_name = 0;
PyObject* cmp = 0;
if (!PyArg_Parse(comparator, (char*)"(sO)", &cmp_name, &cmp) || !PyCallable_Check(cmp)) {
PyErr_SetString(PyExc_TypeError, "comparator must be a string, or a 2-tuple (name, func)");
return 0;
}
const leveldb::Comparator* c = new PythonComparatorWrapper(cmp_name, cmp);
if (c == 0) {
PyErr_NoMemory();
return 0;
}
return c;
}
const char pyleveldb_repair_db_doc[] =
"leveldb.RepairDB(db_dir)\n\nAttempts to recover as much data as possible from a corrupt database."
;
PyObject* pyleveldb_repair_db(PyLevelDB* self, PyObject* args, PyObject* kwds)
{
const char* db_dir = 0;
const char* kwargs[] = {"filename", "comparator", 0};
PyObject* comparator = 0;
if (!PyArg_ParseTupleAndKeywords(args, kwds, (char*)"s|O", (char**)kwargs,
&db_dir,
&comparator))
return 0;
// get comparator
const leveldb::Comparator* c = pyleveldb_get_comparator(comparator);
if (c == 0) {
PyErr_SetString(leveldb_exception, "error loading comparator");
return NULL;
}
std::string _db_dir(db_dir);
leveldb::Status status;
leveldb::Options options;
options.comparator = c;
Py_BEGIN_ALLOW_THREADS
status = leveldb::RepairDB(_db_dir.c_str(), options);
Py_END_ALLOW_THREADS
if (!status.ok()) {
PyLevelDB_set_error(status);
return 0;
}
Py_INCREF(Py_None);
return Py_None;
}
static int PyLevelDB_init(PyLevelDB* self, PyObject* args, PyObject* kwds)
{
// cleanup
if (self->_db || self->_cache || self->_comparator || self->_options) {
Py_BEGIN_ALLOW_THREADS
delete self->_db;
delete self->_options;
delete self->_cache;
if (self->_comparator != leveldb::BytewiseComparator())
delete self->_comparator;
Py_END_ALLOW_THREADS
self->_db = 0;
self->_options = 0;
self->_cache = 0;
self->_comparator = 0;
}
// get params
const char* db_dir = 0;
PyObject* create_if_missing = Py_True;
PyObject* error_if_exists = Py_False;
PyObject* paranoid_checks = Py_False;
int block_cache_size = 8 * (2 << 20);
int write_buffer_size = 4<<20;
int block_size = 4096;
int max_open_files = 1000;
int block_restart_interval = 16;
const char* kwargs[] = {"filename", "create_if_missing", "error_if_exists", "paranoid_checks", "write_buffer_size", "block_size", "max_open_files", "block_restart_interval", "block_cache_size", "comparator", 0};
PyObject* comparator = 0;
if (!PyArg_ParseTupleAndKeywords(args, kwds, (char*)"s|O!O!O!iiiiiO", (char**)kwargs,
&db_dir,
&PyBool_Type, &create_if_missing,
&PyBool_Type, &error_if_exists,
&PyBool_Type, ¶noid_checks,
&write_buffer_size,
&block_size,
&max_open_files,
&block_restart_interval,
&block_cache_size,
&comparator))
return -1;
if (write_buffer_size < 0 || block_size < 0 || max_open_files < 0 || block_restart_interval < 0 || block_cache_size < 0) {
PyErr_SetString(PyExc_ValueError, "negative write_buffer_size/block_size/max_open_files/block_restart_interval/cache_size");
return -1;
}
// get comparator
const leveldb::Comparator* c = pyleveldb_get_comparator(comparator);
if (c == 0)
return -1;
// open database
self->_options = new leveldb::Options();
self->_cache = leveldb::NewLRUCache(block_cache_size);
self->_comparator = c;
if (self->_options == 0 || self->_cache == 0 || self->_comparator == 0) {
Py_BEGIN_ALLOW_THREADS
delete self->_options;
delete self->_cache;
if (self->_comparator != leveldb::BytewiseComparator())
delete self->_comparator;
Py_END_ALLOW_THREADS
self->_options = 0;
self->_cache = 0;
self->_comparator = 0;
PyErr_NoMemory();
return -1;
}
self->_options->create_if_missing = (create_if_missing == Py_True) ? true : false;
self->_options->error_if_exists = (error_if_exists == Py_True) ? true : false;
self->_options->paranoid_checks = (paranoid_checks == Py_True) ? true : false;
self->_options->write_buffer_size = write_buffer_size;
self->_options->block_size = block_size;
self->_options->max_open_files = max_open_files;
self->_options->block_restart_interval = block_restart_interval;
self->_options->compression = leveldb::kSnappyCompression;
self->_options->block_cache = self->_cache;
self->_options->comparator = self->_comparator;
leveldb::Status status;
// note: copy string parameter, since we might lose it when we release the GIL
std::string _db_dir(db_dir);
int i = 0;
Py_BEGIN_ALLOW_THREADS
status = leveldb::DB::Open(*self->_options, _db_dir, &self->_db);
if (!status.ok()) {
delete self->_db;
delete self->_options;
delete self->_cache;
//! move out of thread block
if (self->_comparator != leveldb::BytewiseComparator())
delete self->_comparator;
self->_db = 0;
self->_options = 0;
self->_cache = 0;
self->_comparator = 0;
i = -1;
}
Py_END_ALLOW_THREADS
if (i == -1)
PyLevelDB_set_error(status);
return i;
}
static int PyWriteBatch_init(PyWriteBatch* self, PyObject* args, PyObject* kwds)
{