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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
|
// 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)
{
self->ops->clear();
static char* kwargs[] = {0};
if (!PyArg_ParseTupleAndKeywords(args, kwds, (char*)"", kwargs))
return -1;
return 0;
}
static int PyLevelDBSnapshot_init(PyLevelDBSnapshot* self, PyObject* args, PyObject* kwds)
{
if (self->db && self->snapshot) {
self->db->n_snapshots -= 1;
self->db->_db->ReleaseSnapshot(self->snapshot);
Py_DECREF(self->db);
}
self->db = 0;
self->snapshot = 0;
PyLevelDB* db = 0;
const leveldb::Snapshot* snapshot;
const char* kwargs[] = {"db", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwds, (char*)"O!", (char**)kwargs, &PyLevelDB_Type, &db))
return -1;
snapshot = db->_db->GetSnapshot();
//! TBD: deal with GetSnapshot() failure
self->db = db;
self->snapshot = snapshot;
Py_INCREF(self->db);
self->db->n_snapshots += 1;
return 0;
}
static int PyLevelDBSnapshot_traverse(PyLevelDBSnapshot* iter, visitproc visit, void* arg)
{
Py_VISIT((PyObject*)iter->db);
return 0;
}
PyDoc_STRVAR(PyLevelDB_doc,
"LevelDB(filename, **kwargs) -> leveldb object\n"
"\n"
"Open a LevelDB database, from the given directory.\n"
"\n"
"Only the parameter filename is mandatory.\n"
"\n"
"filename the database directory\n"
"create_if_missing (default: True) if True, creates a new database if none exists\n"
"error_if_exists (default: False) if True, raises and error if the database already exists\n"
"paranoid_checks (default: False) if True, raises an error as soon as an internal corruption is detected\n"
"block_cache_size (default: 8 * (2 << 20)) maximum allowed size for the block cache in bytes\n"
"write_buffer_size (default 2 * (2 << 20)) \n"
"block_size (default: 4096) unit of transfer for the block cache in bytes\n""max_open_files: (default: 1000)\n"
"block_restart_interval \n"
"\n"
"Snappy compression is used, if available.\n"
"\n"
"Some methods support the following parameters, having these semantics:\n"
"\n"
" verify_checksum: iff True, the operation will check for checksum mismatches\n"
" fill_cache: iff True, the operation will fill the cache with the data read\n"
" sync: iff True, the operation will be guaranteed to sync the operation to disk\n"
"\n"
"Methods supported are:\n"
"\n"
" Get(key, verify_checksums = False, fill_cache = True): get value, raises KeyError if key not found\n"
"\n"
" key: the query key\n"
"\n"
" Put(key, value, sync = False): put key/value pair\n"
"\n"
" key: the key\n"
" value: the value\n"
"\n"
" Delete(key, sync = False): delete key/value pair, raises no error kf key not found\n"
"\n"
" key: the key\n"
"\n"
" Write(write_batch, sync = False): apply multiple put/delete operations atomatically\n"
"\n"
" write_batch: the WriteBatch object holding the operations\n"
"\n"
" RangeIter(key_from = None, key_to = None, include_value = True, verify_checksums = False, fill_cache = True): return iterator\n"
"\n"
" key_from: if not None: defines lower bound (inclusive) for iterator\n"
" key_to: if not None: defined upper bound (inclusive) for iterator\n"
" include_value: if True, iterator returns key/value 2-tuples, otherwise, just keys\n"
"\n"
" GetStats(): get a string of runtime information\n"
);
PyDoc_STRVAR(PyWriteBatch_doc,
"WriteBatch() -> write batch object\n"
"\n"
"Create an object, which can hold a list of database operations, which\n"
"can be applied atomically.\n"
"\n"
"Methods supported are:\n"
"\n"
" Put(key, value): add put operation to batch\n"
"\n"
" key: the key\n"
" value: the value\n"
"\n"
" Delete(key): add delete operation to batch\n"
"\n"
" key: the key\n"
);
PyDoc_STRVAR(PyLevelDBSnapshot_doc, "");
PyTypeObject PyLevelDB_Type = {
#if PY_MAJOR_VERSION >= 3
PyVarObject_HEAD_INIT(NULL, 0)
#else
PyObject_HEAD_INIT(NULL)
0,
#endif
(char*)"leveldb.LevelDB", /*tp_name*/
sizeof(PyLevelDB), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)PyLevelDB_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
(char*)PyLevelDB_doc, /*tp_doc */
0, /*tp_traverse */
0, /*tp_clear */
0, /*tp_richcompare */
0, /*tp_weaklistoffset */
0, /*tp_iter */
0, /*tp_iternext */
PyLevelDB_methods, /*tp_methods */
0, /*tp_members */
0, /*tp_getset */
0, /*tp_base */
0, /*tp_dict */
0, /*tp_descr_get */
0, /*tp_descr_set */
0, /*tp_dictoffset */
(initproc)PyLevelDB_init, /*tp_init */
0, /*tp_alloc */
PyLevelDB_new, /*tp_new */
};
PyTypeObject PyWriteBatch_Type = {
#if PY_MAJOR_VERSION >= 3
PyVarObject_HEAD_INIT(NULL, 0)
#else
PyObject_HEAD_INIT(NULL)
0,
#endif
(char*)"leveldb.WriteBatch", /*tp_name*/
sizeof(PyWriteBatch), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)PyWriteBatch_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
(char*)PyWriteBatch_doc, /*tp_doc */
0, /*tp_traverse */
0, /*tp_clear */
0, /*tp_richcompare */
0, /*tp_weaklistoffset */
0, /*tp_iter */
0, /*tp_iternext */
PyWriteBatch_methods, /*tp_methods */
0, /*tp_members */
0, /*tp_getset */
0, /*tp_base */
0, /*tp_dict */
0, /*tp_descr_get */
0, /*tp_descr_set */
0, /*tp_dictoffset */
(initproc)PyWriteBatch_init, /*tp_init */
0, /*tp_alloc */
PyWriteBatch_new, /*tp_new */
};
PyTypeObject PyLevelDBSnapshot_Type = {
#if PY_MAJOR_VERSION >= 3
PyVarObject_HEAD_INIT(NULL, 0)
#else
PyObject_HEAD_INIT(NULL)
0,
#endif
(char*)"leveldb.Snapshot", /*tp_name*/
sizeof(PyLevelDBSnapshot), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)PyLevelDBSnapshot_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
(char*)PyLevelDBSnapshot_doc, /*tp_doc */
(traverseproc)PyLevelDBSnapshot_traverse, /* tp_traverse */
0, /*tp_clear */
0, /*tp_richcompare */
0, /*tp_weaklistoffset */
0, /*tp_iter */
0, /*tp_iternext */
PyLevelDBSnapshot_methods, /*tp_methods */
0, /*tp_members */
0, /*tp_getset */
0, /*tp_base */
0, /*tp_dict */
0, /*tp_descr_get */
0, /*tp_descr_set */
0, /*tp_dictoffset */
(initproc)PyLevelDBSnapshot_init, /*tp_init */
0, /*tp_alloc */
PyLevelDBSnapshot_new, /*tp_new */
};
static void PyLevelDBIter_clean(PyLevelDBIter* iter)
{
if (iter->db)
iter->db->n_iterators -= 1;
Py_BEGIN_ALLOW_THREADS
delete iter->iterator;
delete iter->bound;
Py_END_ALLOW_THREADS
Py_XDECREF(iter->ref);
iter->ref = 0;
iter->db = 0;
iter->iterator = 0;
iter->bound = 0;
iter->include_value = 0;
}
static void PyLevelDBIter_dealloc(PyLevelDBIter* iter)
{
PyLevelDBIter_clean(iter);
PyObject_GC_Del(iter);
}
static int PyLevelDBIter_traverse(PyLevelDBIter* iter, visitproc visit, void* arg)
{
Py_VISIT((PyObject*)iter->ref);
return 0;
}
static PyObject* PyLevelDBIter_next(PyLevelDBIter* iter)
{
// empty, do cleanup (idempotent)
if (iter->ref == 0 || !iter->iterator->Valid()) {
PyLevelDBIter_clean(iter);
return 0;
}
// if we have an upper/lower bound, and we have run past it, clean up and return
if (iter->bound) {
leveldb::Slice a = leveldb::Slice(iter->bound->c_str(), iter->bound->size());
leveldb::Slice b = iter->iterator->key();
int c = iter->db->_options->comparator->Compare(a, b);
if (!iter->is_reverse && !(0 <= c)) {
PyLevelDBIter_clean(iter);
return 0;
} else if (iter->is_reverse && !(0 >= c)) {
PyLevelDBIter_clean(iter);
return 0;
}
}
// get key and (optional) value
PyObject* key = PY_LEVELDB_STRING_OR_BYTEARRAY(iter->iterator->key().data(), iter->iterator->key().size());
PyObject* value = 0;
PyObject* ret = key;
if (key == 0)
return 0;
if (iter->include_value) {
value = PY_LEVELDB_STRING_OR_BYTEARRAY(iter->iterator->value().data(), iter->iterator->value().size());
if (value == 0) {
Py_XDECREF(key);
return 0;
}
}
// key/value pairs are returned as 2-tuples
if (value) {
ret = PyTuple_New(2);
if (ret == 0) {
Py_DECREF(key);
Py_XDECREF(value);
return 0;
}
PyTuple_SET_ITEM(ret, 0, key);
PyTuple_SET_ITEM(ret, 1, value);
}
// get next/prev value
if (iter->is_reverse) {
iter->iterator->Prev();
} else {
iter->iterator->Next();
}
// return k/v pair or single key
return ret;
}
PyTypeObject PyLevelDBIter_Type = {
#if PY_MAJOR_VERSION >= 3
PyVarObject_HEAD_INIT(NULL, 0)
#else
PyObject_HEAD_INIT(NULL)
0,
#endif
(char*)"leveldb-iterator", /* tp_name */
sizeof(PyLevelDBIter), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)PyLevelDBIter_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
0, /* tp_doc */
(traverseproc)PyLevelDBIter_traverse, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
PyObject_SelfIter, /* tp_iter */
(iternextfunc)PyLevelDBIter_next, /* tp_iternext */
0, /* tp_methods */
0,
};
static PyObject* PyLevelDBIter_New(PyObject* ref, PyLevelDB* db, leveldb::Iterator* iterator, std::string* bound, int include_value, int is_reverse)
{
PyLevelDBIter* iter = PyObject_GC_New(PyLevelDBIter, &PyLevelDBIter_Type);
if (iter == 0) {
Py_BEGIN_ALLOW_THREADS
delete iterator;
Py_END_ALLOW_THREADS
return 0;
}
Py_XINCREF(ref);
iter->ref = ref;
iter->db = db;
iter->iterator = iterator;
iter->is_reverse = is_reverse;
iter->bound = bound;
iter->include_value = include_value;
if (iter->db)
iter->db->n_iterators += 1;
PyObject_GC_Track(iter);
return (PyObject*)iter;
}
static PyObject* PyLevelDBSnapshot_New(PyLevelDB* db, const leveldb::Snapshot* snapshot)
{
PyLevelDBSnapshot* s = PyObject_GC_New(PyLevelDBSnapshot, &PyLevelDBSnapshot_Type);
if (s == 0) {
db->_db->ReleaseSnapshot(snapshot);
return 0;
}
Py_INCREF(db);
s->db = db;
s->snapshot = snapshot;
s->db->n_snapshots += 1;
PyObject_GC_Track(s);
return (PyObject*)s;
}
|