-
-
Notifications
You must be signed in to change notification settings - Fork 177
/
binding.cc
1761 lines (1466 loc) · 44.7 KB
/
binding.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
#define NAPI_VERSION 3
#include <napi-macros.h>
#include <node_api.h>
#include <assert.h>
#include <leveldb/db.h>
#include <leveldb/write_batch.h>
#include <leveldb/cache.h>
#include <leveldb/filter_policy.h>
#include <map>
#include <vector>
/**
* Forward declarations.
*/
struct Database;
struct Iterator;
struct EndWorker;
static void iterator_end_do (napi_env env, Iterator* iterator, napi_value cb);
/**
* Macros.
*/
#define NAPI_DB_CONTEXT() \
Database* database = NULL; \
NAPI_STATUS_THROWS(napi_get_value_external(env, argv[0], (void**)&database));
#define NAPI_ITERATOR_CONTEXT() \
Iterator* iterator = NULL; \
NAPI_STATUS_THROWS(napi_get_value_external(env, argv[0], (void**)&iterator));
#define NAPI_BATCH_CONTEXT() \
Batch* batch = NULL; \
NAPI_STATUS_THROWS(napi_get_value_external(env, argv[0], (void**)&batch));
#define NAPI_RETURN_UNDEFINED() \
return 0;
#define NAPI_UTF8_NEW(name, val) \
size_t name##_size = 0; \
NAPI_STATUS_THROWS(napi_get_value_string_utf8(env, val, NULL, 0, &name##_size)) \
char* name = new char[name##_size + 1]; \
NAPI_STATUS_THROWS(napi_get_value_string_utf8(env, val, name, name##_size + 1, &name##_size)) \
name[name##_size] = '\0';
#define NAPI_ARGV_UTF8_NEW(name, i) \
NAPI_UTF8_NEW(name, argv[i])
#define LD_STRING_OR_BUFFER_TO_COPY(env, from, to) \
char* to##Ch_ = 0; \
size_t to##Sz_ = 0; \
if (IsString(env, from)) { \
napi_get_value_string_utf8(env, from, NULL, 0, &to##Sz_); \
to##Ch_ = new char[to##Sz_ + 1]; \
napi_get_value_string_utf8(env, from, to##Ch_, to##Sz_ + 1, &to##Sz_); \
to##Ch_[to##Sz_] = '\0'; \
} else if (IsBuffer(env, from)) { \
char* buf = 0; \
napi_get_buffer_info(env, from, (void **)&buf, &to##Sz_); \
to##Ch_ = new char[to##Sz_]; \
memcpy(to##Ch_, buf, to##Sz_); \
}
/*********************************************************************
* Helpers.
********************************************************************/
/**
* Returns true if 'value' is a string.
*/
static bool IsString (napi_env env, napi_value value) {
napi_valuetype type;
napi_typeof(env, value, &type);
return type == napi_string;
}
/**
* Returns true if 'value' is a buffer.
*/
static bool IsBuffer (napi_env env, napi_value value) {
bool isBuffer;
napi_is_buffer(env, value, &isBuffer);
return isBuffer;
}
/**
* Returns true if 'value' is an object.
*/
static bool IsObject (napi_env env, napi_value value) {
napi_valuetype type;
napi_typeof(env, value, &type);
return type == napi_object;
}
/**
* Create an error object.
*/
static napi_value CreateError (napi_env env, const char* str) {
napi_value msg;
napi_create_string_utf8(env, str, strlen(str), &msg);
napi_value error;
napi_create_error(env, NULL, msg, &error);
return error;
}
/**
* Returns true if 'obj' has a property 'key'.
*/
static bool HasProperty (napi_env env, napi_value obj, const char* key) {
bool has = false;
napi_has_named_property(env, obj, key, &has);
return has;
}
/**
* Returns a property in napi_value form.
*/
static napi_value GetProperty (napi_env env, napi_value obj, const char* key) {
napi_value value;
napi_get_named_property(env, obj, key, &value);
return value;
}
/**
* Returns a boolean property 'key' from 'obj'.
* Returns 'DEFAULT' if the property doesn't exist.
*/
static bool BooleanProperty (napi_env env, napi_value obj, const char* key,
bool DEFAULT) {
if (HasProperty(env, obj, key)) {
napi_value value = GetProperty(env, obj, key);
bool result;
napi_get_value_bool(env, value, &result);
return result;
}
return DEFAULT;
}
/**
* Returns a uint32 property 'key' from 'obj'.
* Returns 'DEFAULT' if the property doesn't exist.
*/
static uint32_t Uint32Property (napi_env env, napi_value obj, const char* key,
uint32_t DEFAULT) {
if (HasProperty(env, obj, key)) {
napi_value value = GetProperty(env, obj, key);
uint32_t result;
napi_get_value_uint32(env, value, &result);
return result;
}
return DEFAULT;
}
/**
* Returns a uint32 property 'key' from 'obj'.
* Returns 'DEFAULT' if the property doesn't exist.
*/
static int Int32Property (napi_env env, napi_value obj, const char* key,
int DEFAULT) {
if (HasProperty(env, obj, key)) {
napi_value value = GetProperty(env, obj, key);
int result;
napi_get_value_int32(env, value, &result);
return result;
}
return DEFAULT;
}
/**
* Returns a string property 'key' from 'obj'.
* Returns empty string if the property doesn't exist.
*/
static std::string StringProperty (napi_env env, napi_value obj, const char* key) {
if (HasProperty(env, obj, key)) {
napi_value value = GetProperty(env, obj, key);
if (IsString(env, value)) {
size_t size = 0;
napi_get_value_string_utf8(env, value, NULL, 0, &size);
char* buf = new char[size + 1];
napi_get_value_string_utf8(env, value, buf, size + 1, &size);
buf[size] = '\0';
std::string result = buf;
delete [] buf;
return result;
}
}
return "";
}
static void DisposeSliceBuffer (leveldb::Slice slice) {
if (!slice.empty()) delete [] slice.data();
}
/**
* Convert a napi_value to a leveldb::Slice.
*/
static leveldb::Slice ToSlice (napi_env env, napi_value from) {
LD_STRING_OR_BUFFER_TO_COPY(env, from, to);
return leveldb::Slice(toCh_, toSz_);
}
/**
* Returns length of string or buffer
*/
static size_t StringOrBufferLength (napi_env env, napi_value value) {
size_t size = 0;
if (IsString(env, value)) {
napi_get_value_string_utf8(env, value, NULL, 0, &size);
} else if (IsBuffer(env, value)) {
char* buf;
napi_get_buffer_info(env, value, (void **)&buf, &size);
}
return size;
}
/**
* Takes a Buffer or string property 'name' from 'opts'.
* Returns null if the property does not exist or is zero-length.
*/
static std::string* RangeOption (napi_env env, napi_value opts, const char* name) {
if (HasProperty(env, opts, name)) {
napi_value value = GetProperty(env, opts, name);
if (StringOrBufferLength(env, value) > 0) {
LD_STRING_OR_BUFFER_TO_COPY(env, value, to);
std::string* result = new std::string(toCh_, toSz_);
delete [] toCh_;
return result;
}
}
return NULL;
}
/**
* Calls a function.
*/
static napi_status CallFunction (napi_env env,
napi_value callback,
const int argc,
napi_value* argv) {
napi_value global;
napi_get_global(env, &global);
return napi_call_function(env, global, callback, argc, argv, NULL);
}
/**
* Base worker class. Handles the async work. Derived classes can override the
* following virtual methods (listed in the order in which they're called):
*
* - DoExecute (abstract, worker pool thread): main work
* - HandleOKCallback (main thread): call JS callback on success
* - DoFinally (main thread): do cleanup regardless of success
*/
struct BaseWorker {
BaseWorker (napi_env env,
Database* database,
napi_value callback,
const char* resourceName)
: env_(env), database_(database), errMsg_(NULL) {
NAPI_STATUS_THROWS_VOID(napi_create_reference(env_, callback, 1, &callbackRef_));
napi_value asyncResourceName;
NAPI_STATUS_THROWS_VOID(napi_create_string_utf8(env_, resourceName,
NAPI_AUTO_LENGTH,
&asyncResourceName));
NAPI_STATUS_THROWS_VOID(napi_create_async_work(env_, callback,
asyncResourceName,
BaseWorker::Execute,
BaseWorker::Complete,
this, &asyncWork_));
}
virtual ~BaseWorker () {
delete [] errMsg_;
napi_delete_reference(env_, callbackRef_);
napi_delete_async_work(env_, asyncWork_);
}
static void Execute (napi_env env, void* data) {
BaseWorker* self = (BaseWorker*)data;
self->DoExecute();
}
void SetStatus (leveldb::Status status) {
status_ = status;
if (!status.ok()) {
SetErrorMessage(status.ToString().c_str());
}
}
void SetErrorMessage(const char *msg) {
delete [] errMsg_;
size_t size = strlen(msg) + 1;
errMsg_ = new char[size];
memcpy(errMsg_, msg, size);
}
virtual void DoExecute () = 0;
virtual void DoFinally () {};
static void Complete (napi_env env, napi_status status, void* data) {
BaseWorker* self = (BaseWorker*)data;
self->DoComplete();
self->DoFinally();
delete self;
}
void DoComplete () {
if (status_.ok()) {
return HandleOKCallback();
}
napi_value argv = CreateError(env_, errMsg_);
napi_value callback;
napi_get_reference_value(env_, callbackRef_, &callback);
CallFunction(env_, callback, 1, &argv);
}
virtual void HandleOKCallback () {
napi_value argv;
napi_get_null(env_, &argv);
napi_value callback;
napi_get_reference_value(env_, callbackRef_, &callback);
CallFunction(env_, callback, 1, &argv);
}
void Queue () {
napi_queue_async_work(env_, asyncWork_);
}
napi_env env_;
napi_ref callbackRef_;
napi_async_work asyncWork_;
Database* database_;
private:
leveldb::Status status_;
char *errMsg_;
};
/**
* Owns the LevelDB storage, cache, filter policy and iterators.
*/
struct Database {
Database (napi_env env)
: env_(env),
db_(NULL),
blockCache_(NULL),
filterPolicy_(leveldb::NewBloomFilterPolicy(10)),
currentIteratorId_(0),
pendingCloseWorker_(NULL),
priorityWork_(0) {}
~Database () {
if (db_ != NULL) {
delete db_;
db_ = NULL;
}
}
leveldb::Status Open (const leveldb::Options& options,
const char* location) {
return leveldb::DB::Open(options, location, &db_);
}
void CloseDatabase () {
delete db_;
db_ = NULL;
if (blockCache_) {
delete blockCache_;
blockCache_ = NULL;
}
}
leveldb::Status Put (const leveldb::WriteOptions& options,
leveldb::Slice key,
leveldb::Slice value) {
return db_->Put(options, key, value);
}
leveldb::Status Get (const leveldb::ReadOptions& options,
leveldb::Slice key,
std::string& value) {
return db_->Get(options, key, &value);
}
leveldb::Status Del (const leveldb::WriteOptions& options,
leveldb::Slice key) {
return db_->Delete(options, key);
}
leveldb::Status WriteBatch (const leveldb::WriteOptions& options,
leveldb::WriteBatch* batch) {
return db_->Write(options, batch);
}
uint64_t ApproximateSize (const leveldb::Range* range) {
uint64_t size = 0;
db_->GetApproximateSizes(range, 1, &size);
return size;
}
void CompactRange (const leveldb::Slice* start,
const leveldb::Slice* end) {
db_->CompactRange(start, end);
}
void GetProperty (const leveldb::Slice& property, std::string* value) {
db_->GetProperty(property, value);
}
const leveldb::Snapshot* NewSnapshot () {
return db_->GetSnapshot();
}
leveldb::Iterator* NewIterator (leveldb::ReadOptions* options) {
return db_->NewIterator(*options);
}
void ReleaseSnapshot (const leveldb::Snapshot* snapshot) {
return db_->ReleaseSnapshot(snapshot);
}
void AttachIterator (uint32_t id, Iterator* iterator) {
iterators_[id] = iterator;
IncrementPriorityWork();
}
void DetachIterator (uint32_t id) {
iterators_.erase(id);
DecrementPriorityWork();
}
void IncrementPriorityWork () {
++priorityWork_;
}
void DecrementPriorityWork () {
if (--priorityWork_ == 0 && pendingCloseWorker_ != NULL) {
pendingCloseWorker_->Queue();
pendingCloseWorker_ = NULL;
}
}
bool HasPriorityWork () {
return priorityWork_ > 0;
}
napi_env env_;
leveldb::DB* db_;
leveldb::Cache* blockCache_;
const leveldb::FilterPolicy* filterPolicy_;
uint32_t currentIteratorId_;
BaseWorker *pendingCloseWorker_;
std::map< uint32_t, Iterator * > iterators_;
private:
uint32_t priorityWork_;
};
/**
* Runs when a Database is garbage collected.
*/
static void FinalizeDatabase (napi_env env, void* data, void* hint) {
if (data) {
delete (Database*)data;
}
}
/**
* Base worker class for doing async work that defers closing the database.
*/
struct PriorityWorker : public BaseWorker {
PriorityWorker (napi_env env, Database* database, napi_value callback, const char* resourceName)
: BaseWorker(env, database, callback, resourceName) {
database_->IncrementPriorityWork();
}
~PriorityWorker () {}
void DoFinally () override {
database_->DecrementPriorityWork();
}
};
/**
* Owns a leveldb iterator.
*/
struct Iterator {
Iterator (Database* database,
uint32_t id,
std::string* start,
std::string* end,
bool reverse,
bool keys,
bool values,
int limit,
std::string* lt,
std::string* lte,
std::string* gt,
std::string* gte,
bool fillCache,
bool keyAsBuffer,
bool valueAsBuffer,
uint32_t highWaterMark)
: database_(database),
id_(id),
start_(start),
end_(end),
reverse_(reverse),
keys_(keys),
values_(values),
limit_(limit),
lt_(lt),
lte_(lte),
gt_(gt),
gte_(gte),
keyAsBuffer_(keyAsBuffer),
valueAsBuffer_(valueAsBuffer),
highWaterMark_(highWaterMark),
dbIterator_(NULL),
count_(0),
seeking_(false),
landed_(false),
nexting_(false),
ended_(false),
endWorker_(NULL),
ref_(NULL) {
options_ = new leveldb::ReadOptions();
options_->fill_cache = fillCache;
options_->snapshot = database->NewSnapshot();
}
~Iterator () {
assert(ended_);
if (start_ != NULL) delete start_;
if (end_ != NULL) delete end_;
if (lt_ != NULL) delete lt_;
if (gt_ != NULL) delete gt_;
if (lte_ != NULL) delete lte_;
if (gte_ != NULL) delete gte_;
delete options_;
}
void Attach (napi_ref ref) {
ref_ = ref;
database_->AttachIterator(id_, this);
}
napi_ref Detach () {
database_->DetachIterator(id_);
return ref_;
}
leveldb::Status IteratorStatus () {
return dbIterator_->status();
}
void IteratorEnd () {
delete dbIterator_;
dbIterator_ = NULL;
database_->ReleaseSnapshot(options_->snapshot);
}
bool GetIterator () {
if (dbIterator_ != NULL) return false;
dbIterator_ = database_->NewIterator(options_);
if (start_ != NULL) {
dbIterator_->Seek(*start_);
if (reverse_) {
if (!dbIterator_->Valid()) {
dbIterator_->SeekToLast();
} else {
leveldb::Slice key = dbIterator_->key();
if ((lt_ != NULL && key.compare(*lt_) >= 0) ||
(lte_ != NULL && key.compare(*lte_) > 0) ||
(start_ != NULL && key.compare(*start_) > 0)) {
dbIterator_->Prev();
}
}
if (dbIterator_->Valid() && lt_ != NULL) {
if (dbIterator_->key().compare(*lt_) >= 0)
assert(false);
}
} else {
if (dbIterator_->Valid() && gt_ != NULL
&& dbIterator_->key().compare(*gt_) == 0)
dbIterator_->Next();
}
} else if (reverse_) {
dbIterator_->SeekToLast();
} else {
dbIterator_->SeekToFirst();
}
return true;
}
bool Read (std::string& key, std::string& value) {
if (!GetIterator() && !seeking_) {
if (reverse_) {
dbIterator_->Prev();
}
else {
dbIterator_->Next();
}
}
seeking_ = false;
if (dbIterator_->Valid()) {
std::string keyStr = dbIterator_->key().ToString();
const int isEnd = end_ == NULL ? 1 : end_->compare(keyStr);
if ((limit_ < 0 || ++count_ <= limit_)
&& (end_ == NULL
|| (reverse_ && (isEnd <= 0))
|| (!reverse_ && (isEnd >= 0)))
&& ( lt_ != NULL ? (lt_->compare(keyStr) > 0)
: lte_ != NULL ? (lte_->compare(keyStr) >= 0)
: true )
&& ( gt_ != NULL ? (gt_->compare(keyStr) < 0)
: gte_ != NULL ? (gte_->compare(keyStr) <= 0)
: true )
) {
if (keys_) {
key.assign(dbIterator_->key().data(), dbIterator_->key().size());
}
if (values_) {
value.assign(dbIterator_->value().data(), dbIterator_->value().size());
}
return true;
}
}
return false;
}
bool OutOfRange (leveldb::Slice& target) {
if ((lt_ != NULL && target.compare(*lt_) >= 0) ||
(lte_ != NULL && target.compare(*lte_) > 0) ||
(start_ != NULL && reverse_ && target.compare(*start_) > 0)) {
return true;
}
if (end_ != NULL) {
int d = target.compare(*end_);
if (reverse_ ? d < 0 : d > 0) return true;
}
return ((gt_ != NULL && target.compare(*gt_) <= 0) ||
(gte_ != NULL && target.compare(*gte_) < 0) ||
(start_ != NULL && !reverse_ && target.compare(*start_) < 0));
}
bool IteratorNext (std::vector<std::pair<std::string, std::string> >& result) {
size_t size = 0;
uint32_t cacheSize = 0;
while (true) {
std::string key, value;
bool ok = Read(key, value);
if (ok) {
result.push_back(std::make_pair(key, value));
if (!landed_) {
landed_ = true;
return true;
}
size = size + key.size() + value.size();
if (size > highWaterMark_) return true;
// Limit the size of the cache to prevent starving the event loop
// in JS-land while we're recursively calling process.nextTick().
if (++cacheSize >= 1000) return true;
} else {
return false;
}
}
}
Database* database_;
uint32_t id_;
std::string* start_;
std::string* end_;
bool reverse_;
bool keys_;
bool values_;
int limit_;
std::string* lt_;
std::string* lte_;
std::string* gt_;
std::string* gte_;
bool keyAsBuffer_;
bool valueAsBuffer_;
uint32_t highWaterMark_;
leveldb::Iterator* dbIterator_;
int count_;
bool seeking_;
bool landed_;
bool nexting_;
bool ended_;
leveldb::ReadOptions* options_;
EndWorker* endWorker_;
private:
napi_ref ref_;
};
/**
* Returns a context object for a database.
*/
NAPI_METHOD(db_init) {
Database* database = new Database(env);
napi_value result;
NAPI_STATUS_THROWS(napi_create_external(env, database,
FinalizeDatabase,
NULL, &result));
return result;
}
/**
* Worker class for opening a database.
*/
struct OpenWorker final : public BaseWorker {
OpenWorker (napi_env env,
Database* database,
napi_value callback,
const std::string& location,
bool createIfMissing,
bool errorIfExists,
bool compression,
uint32_t writeBufferSize,
uint32_t blockSize,
uint32_t maxOpenFiles,
uint32_t blockRestartInterval,
uint32_t maxFileSize)
: BaseWorker(env, database, callback, "leveldown.db.open"),
location_(location) {
options_.block_cache = database->blockCache_;
options_.filter_policy = database->filterPolicy_;
options_.create_if_missing = createIfMissing;
options_.error_if_exists = errorIfExists;
options_.compression = compression
? leveldb::kSnappyCompression
: leveldb::kNoCompression;
options_.write_buffer_size = writeBufferSize;
options_.block_size = blockSize;
options_.max_open_files = maxOpenFiles;
options_.block_restart_interval = blockRestartInterval;
options_.max_file_size = maxFileSize;
}
~OpenWorker () {}
void DoExecute () override {
SetStatus(database_->Open(options_, location_.c_str()));
}
leveldb::Options options_;
std::string location_;
};
/**
* Open a database.
*/
NAPI_METHOD(db_open) {
NAPI_ARGV(4);
NAPI_DB_CONTEXT();
NAPI_ARGV_UTF8_NEW(location, 1);
napi_value options = argv[2];
bool createIfMissing = BooleanProperty(env, options, "createIfMissing", true);
bool errorIfExists = BooleanProperty(env, options, "errorIfExists", false);
bool compression = BooleanProperty(env, options, "compression", true);
uint32_t cacheSize = Uint32Property(env, options, "cacheSize", 8 << 20);
uint32_t writeBufferSize = Uint32Property(env, options , "writeBufferSize" , 4 << 20);
uint32_t blockSize = Uint32Property(env, options, "blockSize", 4096);
uint32_t maxOpenFiles = Uint32Property(env, options, "maxOpenFiles", 1000);
uint32_t blockRestartInterval = Uint32Property(env, options,
"blockRestartInterval", 16);
uint32_t maxFileSize = Uint32Property(env, options, "maxFileSize", 2 << 20);
database->blockCache_ = leveldb::NewLRUCache(cacheSize);
napi_value callback = argv[3];
OpenWorker* worker = new OpenWorker(env, database, callback, location,
createIfMissing, errorIfExists,
compression, writeBufferSize, blockSize,
maxOpenFiles, blockRestartInterval,
maxFileSize);
worker->Queue();
delete [] location;
NAPI_RETURN_UNDEFINED();
}
/**
* Worker class for closing a database
*/
struct CloseWorker final : public BaseWorker {
CloseWorker (napi_env env,
Database* database,
napi_value callback)
: BaseWorker(env, database, callback, "leveldown.db.close") {}
~CloseWorker () {}
void DoExecute () override {
database_->CloseDatabase();
}
};
napi_value noop_callback (napi_env env, napi_callback_info info) {
return 0;
}
/**
* Close a database.
*/
NAPI_METHOD(db_close) {
NAPI_ARGV(2);
NAPI_DB_CONTEXT();
napi_value callback = argv[1];
CloseWorker* worker = new CloseWorker(env, database, callback);
if (!database->HasPriorityWork()) {
worker->Queue();
NAPI_RETURN_UNDEFINED();
}
database->pendingCloseWorker_ = worker;
napi_value noop;
napi_create_function(env, NULL, 0, noop_callback, NULL, &noop);
std::map<uint32_t, Iterator*> iterators = database->iterators_;
std::map<uint32_t, Iterator*>::iterator it;
for (it = iterators.begin(); it != iterators.end(); ++it) {
iterator_end_do(env, it->second, noop);
}
NAPI_RETURN_UNDEFINED();
}
/**
* Worker class for putting key/value to the database
*/
struct PutWorker final : public PriorityWorker {
PutWorker (napi_env env,
Database* database,
napi_value callback,
leveldb::Slice key,
leveldb::Slice value,
bool sync)
: PriorityWorker(env, database, callback, "leveldown.db.put"),
key_(key), value_(value) {
options_.sync = sync;
}
~PutWorker () {
DisposeSliceBuffer(key_);
DisposeSliceBuffer(value_);
}
void DoExecute () override {
SetStatus(database_->Put(options_, key_, value_));
}
leveldb::WriteOptions options_;
leveldb::Slice key_;
leveldb::Slice value_;
};
/**
* Puts a key and a value to a database.
*/
NAPI_METHOD(db_put) {
NAPI_ARGV(5);
NAPI_DB_CONTEXT();
leveldb::Slice key = ToSlice(env, argv[1]);
leveldb::Slice value = ToSlice(env, argv[2]);
bool sync = BooleanProperty(env, argv[3], "sync", false);
napi_value callback = argv[4];
PutWorker* worker = new PutWorker(env, database, callback, key, value, sync);
worker->Queue();
NAPI_RETURN_UNDEFINED();
}
/**
* Worker class for getting a value from a database.
*/
struct GetWorker final : public PriorityWorker {
GetWorker (napi_env env,
Database* database,
napi_value callback,
leveldb::Slice key,
bool asBuffer,
bool fillCache)
: PriorityWorker(env, database, callback, "leveldown.db.get"),
key_(key),
asBuffer_(asBuffer) {
options_.fill_cache = fillCache;
}
~GetWorker () {
DisposeSliceBuffer(key_);
}
void DoExecute () override {
SetStatus(database_->Get(options_, key_, value_));
}
void HandleOKCallback () override {
napi_value argv[2];
napi_get_null(env_, &argv[0]);
if (asBuffer_) {
napi_create_buffer_copy(env_, value_.size(), value_.data(), NULL, &argv[1]);
} else {
napi_create_string_utf8(env_, value_.data(), value_.size(), &argv[1]);
}
napi_value callback;
napi_get_reference_value(env_, callbackRef_, &callback);
CallFunction(env_, callback, 2, argv);
}
leveldb::ReadOptions options_;
leveldb::Slice key_;
std::string value_;
bool asBuffer_;
};
/**
* Gets a value from a database.
*/
NAPI_METHOD(db_get) {
NAPI_ARGV(4);
NAPI_DB_CONTEXT();
leveldb::Slice key = ToSlice(env, argv[1]);
napi_value options = argv[2];
bool asBuffer = BooleanProperty(env, options, "asBuffer", true);
bool fillCache = BooleanProperty(env, options, "fillCache", true);
napi_value callback = argv[3];
GetWorker* worker = new GetWorker(env, database, callback, key, asBuffer,
fillCache);
worker->Queue();
NAPI_RETURN_UNDEFINED();
}
/**
* Worker class for deleting a value from a database.
*/
struct DelWorker final : public PriorityWorker {
DelWorker (napi_env env,
Database* database,
napi_value callback,
leveldb::Slice key,
bool sync)
: PriorityWorker(env, database, callback, "leveldown.db.del"),
key_(key) {
options_.sync = sync;
}
~DelWorker () {
DisposeSliceBuffer(key_);
}