forked from Softmotions/ejdb-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathejdb_native.cc
More file actions
1867 lines (1704 loc) · 71.7 KB
/
ejdb_native.cc
File metadata and controls
1867 lines (1704 loc) · 71.7 KB
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
/**************************************************************************************************
* EJDB database library http://ejdb.org
* Copyright (C) 2012-2013 Softmotions Ltd <info@softmotions.com>
*
* This file is part of EJDB.
* EJDB is free software; you can redistribute it and/or modify it under the terms of
* the GNU Lesser General Public License as published by the Free Software Foundation; either
* version 2.1 of the License or any later version. EJDB is distributed in the hope
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
* You should have received a copy of the GNU Lesser General Public License along with EJDB;
* if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA.
*************************************************************************************************/
#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <ejdb_private.h>
#include "ejdb_args.h"
#include "ejdb_cmd.h"
#include "ejdb_logging.h"
#include "ejdb_thread.h"
#include <math.h>
#include <vector>
#include <sstream>
#include <locale.h>
#include <stdint.h>
#include <string.h>
#ifdef _MSC_VER
#include <unordered_set>
#else
#include <ext/hash_set>
#ifdef __GNUC__
using namespace __gnu_cxx;
#endif
#endif
using namespace node;
using namespace v8;
static const int CMD_RET_ERROR = 1;
#define DEFINE_INT64_CONSTANT(target, constant) \
(target)->Set(String::NewSymbol(#constant), \
Number::New((int64_t) constant), \
static_cast<PropertyAttribute>( \
ReadOnly|DontDelete))
namespace ejdb {
///////////////////////////////////////////////////////////////////////////
// Some symbols //
///////////////////////////////////////////////////////////////////////////
static Persistent<String> sym_large;
static Persistent<String> sym_compressed;
static Persistent<String> sym_records;
static Persistent<String> sym_cachedrecords;
static Persistent<String> sym_explain;
static Persistent<String> sym_merge;
static Persistent<String> sym_name;
static Persistent<String> sym_iname;
static Persistent<String> sym_field;
static Persistent<String> sym_indexes;
static Persistent<String> sym_options;
static Persistent<String> sym_file;
static Persistent<String> sym_buckets;
static Persistent<String> sym_type;
///////////////////////////////////////////////////////////////////////////
// Fetch functions //
///////////////////////////////////////////////////////////////////////////
enum eFetchStatus {
FETCH_NONE,
FETCH_DEFAULT,
FETCH_VAL
};
char* fetch_string_data(Handle<Value> sobj, eFetchStatus* fs, const char* def) {
HandleScope scope;
if (sobj->IsNull() || sobj->IsUndefined()) {
if (fs) {
*fs = FETCH_DEFAULT;
}
return def ? strdup(def) : strdup("");
}
String::Utf8Value value(sobj);
const char* data = *value;
if (fs) {
*fs = FETCH_VAL;
}
return data ? strdup(data) : strdup("");
}
int64_t fetch_int_data(Handle<Value> sobj, eFetchStatus* fs, int64_t def) {
HandleScope scope;
if (!(sobj->IsNumber() || sobj->IsInt32() || sobj->IsUint32())) {
if (fs) {
*fs = FETCH_DEFAULT;
}
return def;
}
if (fs) {
*fs = FETCH_VAL;
}
return sobj->ToNumber()->IntegerValue();
}
bool fetch_bool_data(Handle<Value> sobj, eFetchStatus* fs, bool def) {
HandleScope scope;
if (sobj->IsNull() || sobj->IsUndefined()) {
if (fs) {
*fs = FETCH_DEFAULT;
}
return def;
}
if (fs) {
*fs = FETCH_VAL;
}
return sobj->BooleanValue();
}
double fetch_real_data(Handle<Value> sobj, eFetchStatus* fs, double def) {
HandleScope scope;
if (!(sobj->IsNumber() || sobj->IsInt32())) {
if (fs) {
*fs = FETCH_DEFAULT;
}
return def;
}
if (fs) {
*fs = FETCH_VAL;
}
return sobj->ToNumber()->NumberValue();
}
struct V8ObjHash {
size_t operator()(const Handle<Object>& obj) const {
return (size_t) obj->GetIdentityHash();
}
};
struct V8ObjEq {
bool operator()(const Handle<Object>& o1, const Handle<Object>& o2) const {
return (o1 == o2);
}
};
#ifdef _MSC_VER
typedef std::unordered_set<Handle<Object>, V8ObjHash, V8ObjEq> V8ObjSet;
#else
typedef hash_set<Handle<Object>, V8ObjHash, V8ObjEq> V8ObjSet;
#endif
struct TBSONCTX {
V8ObjSet tset; //traversed objects set
int nlevel;
bool inquery;
TBSONCTX() : nlevel(0), inquery(false) {
}
};
static Handle<Object> toV8Object(bson_iterator *it, bson_type obt = BSON_OBJECT);
static Handle<Value> toV8Value(bson_iterator *it);
static void toBSON0(Handle<Object> obj, bson *bs, TBSONCTX *ctx);
static Handle<Value> toV8Value(bson_iterator *it) {
HandleScope scope;
bson_type bt = bson_iterator_type(it);
switch (bt) {
case BSON_OID:
{
char xoid[25];
bson_oid_to_string(bson_iterator_oid(it), xoid);
return scope.Close(String::New(xoid, 24));
}
case BSON_STRING:
case BSON_SYMBOL:
return scope.Close(String::New(bson_iterator_string(it), bson_iterator_string_len(it) - 1));
case BSON_NULL:
return scope.Close(Null());
case BSON_UNDEFINED:
return scope.Close(Undefined());
case BSON_INT:
return scope.Close(Integer::New(bson_iterator_int_raw(it)));
case BSON_LONG:
return scope.Close(Number::New((double) bson_iterator_long_raw(it)));
case BSON_DOUBLE:
return scope.Close(Number::New(bson_iterator_double_raw(it)));
case BSON_BOOL:
return scope.Close(Boolean::New(bson_iterator_bool_raw(it) ? true : false));
case BSON_OBJECT:
case BSON_ARRAY:
{
bson_iterator nit;
bson_iterator_subiterator(it, &nit);
return scope.Close(toV8Object(&nit, bt));
}
case BSON_DATE:
return scope.Close(Date::New((double) bson_iterator_date(it)));
case BSON_BINDATA:
//TODO test it!
return scope.Close(Buffer::New(String::New(bson_iterator_bin_data(it), bson_iterator_bin_len(it))));
case BSON_REGEX:
{
const char *re = bson_iterator_regex(it);
const char *ro = bson_iterator_regex_opts(it);
int rflgs = RegExp::kNone;
for (int i = ((int) strlen(ro) - 1); i >= 0; --i) {
if (ro[i] == 'i') {
rflgs |= RegExp::kIgnoreCase;
} else if (ro[i] == 'g') {
rflgs |= RegExp::kGlobal;
} else if (ro[i] == 'm') {
rflgs |= RegExp::kMultiline;
}
}
return scope.Close(RegExp::New(String::New(re), (RegExp::Flags) rflgs));
}
default:
break;
}
return scope.Close(Undefined());
}
static Handle<Object> toV8Object(bson_iterator *it, bson_type obt) {
HandleScope scope;
Local<Object> ret;
uint32_t knum = 0;
if (obt == BSON_ARRAY) {
ret = Array::New();
} else if (obt == BSON_OBJECT) {
ret = Object::New();
} else {
assert(0);
}
bson_type bt;
while ((bt = bson_iterator_next(it)) != BSON_EOO) {
const char *key = bson_iterator_key(it);
if (obt == BSON_ARRAY) {
knum = (uint32_t) tcatoi(key);
}
switch (bt) {
case BSON_OID:
{
char xoid[25];
bson_oid_to_string(bson_iterator_oid(it), xoid);
if (obt == BSON_ARRAY) {
ret->Set(knum, String::New(xoid, 24));
} else {
ret->Set(String::New(key), String::New(xoid, 24));
}
break;
}
case BSON_STRING:
case BSON_SYMBOL:
if (obt == BSON_ARRAY) {
ret->Set(knum,
String::New(bson_iterator_string(it), bson_iterator_string_len(it) - 1));
} else {
ret->Set(String::New(key),
String::New(bson_iterator_string(it), bson_iterator_string_len(it) - 1));
}
break;
case BSON_NULL:
if (obt == BSON_ARRAY) {
ret->Set(knum, Null());
} else {
ret->Set(String::New(key), Null());
}
break;
case BSON_UNDEFINED:
if (obt == BSON_ARRAY) {
ret->Set(knum, Undefined());
} else {
ret->Set(String::New(key), Undefined());
}
break;
case BSON_INT:
if (obt == BSON_ARRAY) {
ret->Set(knum, Integer::New(bson_iterator_int_raw(it)));
} else {
ret->Set(String::New(key), Integer::New(bson_iterator_int_raw(it)));
}
break;
case BSON_LONG:
if (obt == BSON_ARRAY) {
ret->Set(knum, Number::New((double) bson_iterator_long_raw(it)));
} else {
ret->Set(String::New(key), Number::New((double) bson_iterator_long_raw(it)));
}
break;
case BSON_DOUBLE:
if (obt == BSON_ARRAY) {
ret->Set(knum, Number::New(bson_iterator_double_raw(it)));
} else {
ret->Set(String::New(key), Number::New(bson_iterator_double_raw(it)));
}
break;
case BSON_BOOL:
if (obt == BSON_ARRAY) {
ret->Set(knum, Boolean::New(bson_iterator_bool_raw(it) ? true : false));
} else {
ret->Set(String::New(key), Boolean::New(bson_iterator_bool_raw(it) ? true : false));
}
break;
case BSON_OBJECT:
case BSON_ARRAY:
{
bson_iterator nit;
bson_iterator_subiterator(it, &nit);
if (obt == BSON_ARRAY) {
ret->Set(knum, toV8Object(&nit, bt));
} else {
ret->Set(String::New(key), toV8Object(&nit, bt));
}
break;
}
case BSON_DATE:
if (obt == BSON_ARRAY) {
ret->Set(knum, Date::New((double) bson_iterator_date(it)));
} else {
ret->Set(String::New(key), Date::New((double) bson_iterator_date(it)));
}
break;
case BSON_BINDATA:
if (obt == BSON_ARRAY) {
ret->Set(knum,
Buffer::New(String::New(bson_iterator_bin_data(it),
bson_iterator_bin_len(it))));
} else {
ret->Set(String::New(key),
Buffer::New(String::New(bson_iterator_bin_data(it),
bson_iterator_bin_len(it))));
}
break;
case BSON_REGEX:
{
const char *re = bson_iterator_regex(it);
const char *ro = bson_iterator_regex_opts(it);
int rflgs = RegExp::kNone;
for (int i = ((int) strlen(ro) - 1); i >= 0; --i) {
if (ro[i] == 'i') {
rflgs |= RegExp::kIgnoreCase;
} else if (ro[i] == 'g') {
rflgs |= RegExp::kGlobal;
} else if (ro[i] == 'm') {
rflgs |= RegExp::kMultiline;
}
}
if (obt == BSON_ARRAY) {
ret->Set(knum, RegExp::New(String::New(re), (RegExp::Flags) rflgs));
} else {
ret->Set(String::New(key), RegExp::New(String::New(re), (RegExp::Flags) rflgs));
}
break;
}
default:
if (obt == BSON_ARRAY) {
ret->Set(knum, Undefined());
} else {
ret->Set(String::New(key), Undefined());
}
break;
}
}
return scope.Close(ret);
}
static void toBSON0(Handle<Object> obj, bson *bs, TBSONCTX *ctx) {
HandleScope scope;
assert(ctx && obj->IsObject());
V8ObjSet::iterator it = ctx->tset.find(obj);
if (it != ctx->tset.end()) {
bs->err = BSON_ERROR_ANY;
bs->errstr = strdup("Converting circular structure to JSON");
return;
}
ctx->nlevel++;
ctx->tset.insert(obj);
Local<Array> pnames = obj->GetOwnPropertyNames();
for (uint32_t i = 0; i < pnames->Length(); ++i) {
if (bs->err) {
break;
}
Local<Value> pn = pnames->Get(i);
String::Utf8Value spn(pn);
Local<Value> pv = obj->Get(pn);
if (!ctx->inquery && ctx->nlevel == 1 && !strcmp(JDBIDKEYNAME, *spn)) { //top level _id key
if (pv->IsNull() || pv->IsUndefined()) { //skip _id addition for null or undefined vals
continue;
}
String::Utf8Value idv(pv->ToString());
if (ejdbisvalidoidstr(*idv)) {
bson_oid_t oid;
bson_oid_from_string(&oid, *idv);
bson_append_oid(bs, JDBIDKEYNAME, &oid);
} else {
bs->err = BSON_ERROR_ANY;
bs->errstr = strdup("Invalid bson _id field value");
break;
}
}
if (pv->IsString()) {
String::Utf8Value val(pv);
bson_append_string(bs, *spn, *val);
} else if (pv->IsInt32()) {
bson_append_int(bs, *spn, pv->Int32Value());
} else if (pv->IsUint32()) {
bson_append_long(bs, *spn, pv->Uint32Value());
} else if (pv->IsNumber()) {
double nv = pv->NumberValue();
double ipart;
if (modf(nv, &ipart) == 0.0) {
bson_append_long(bs, *spn, pv->IntegerValue());
} else {
bson_append_double(bs, *spn, nv);
}
} else if (pv->IsNull()) {
bson_append_null(bs, *spn);
} else if (pv->IsUndefined()) {
bson_append_undefined(bs, *spn);
} else if (pv->IsBoolean()) {
bson_append_bool(bs, *spn, pv->BooleanValue());
} else if (pv->IsDate()) {
bson_append_date(bs, *spn, Handle<Date>::Cast(pv)->IntegerValue());
} else if (pv->IsRegExp()) {
Handle<RegExp> regexp = Handle<RegExp>::Cast(pv);
int flags = regexp->GetFlags();
String::Utf8Value sr(regexp->GetSource());
std::string sf;
if (flags & RegExp::kIgnoreCase) {
sf.append("i");
}
if (flags & RegExp::kGlobal) {
sf.append("g");
}
if (flags & RegExp::kMultiline) {
sf.append("m");
}
bson_append_regex(bs, *spn, *sr, sf.c_str());
} else if (Buffer::HasInstance(pv)) {
bson_append_binary(bs, *spn, BSON_BIN_BINARY,
Buffer::Data(Handle<Object>::Cast(pv)),
(int) Buffer::Length(Handle<Object>::Cast(pv)));
} else if (pv->IsObject() || pv->IsArray()) {
if (pv->IsArray()) {
bson_append_start_array(bs, *spn);
} else {
bson_append_start_object(bs, *spn);
}
toBSON0(Handle<Object>::Cast(pv), bs, ctx);
if (bs->err) {
break;
}
if (pv->IsArray()) {
bson_append_finish_array(bs);
} else {
bson_append_finish_object(bs);
}
}
}
ctx->nlevel--;
it = ctx->tset.find(obj);
if (it != ctx->tset.end()) {
ctx->tset.erase(it);
}
}
/** Convert V8 object into binary json instance. After usage, it must be freed by bson_del() */
static void toBSON(Handle<Object> obj, bson *bs, bool inquery) {
HandleScope scope;
TBSONCTX ctx;
ctx.inquery = inquery;
toBSON0(obj, bs, &ctx);
}
class NodeEJDBCursor;
class NodeEJDB;
///////////////////////////////////////////////////////////////////////////
// Main NodeEJDB //
///////////////////////////////////////////////////////////////////////////
class NodeEJDB : public ObjectWrap {
enum { //Commands
cmdSave = 1, //Save JSON object
cmdLoad = 2, //Load BSON by oid
cmdRemove = 3, //Remove BSON by oid
cmdQuery = 4, //Query collection
cmdRemoveColl = 5, //Remove collection
cmdSetIndex = 6, //Set index
cmdSync = 7, //Sync database
cmdTxBegin = 8, //Begin collection transaction
cmdTxAbort = 9, //Abort collection transaction
cmdTxCommit = 10, //Commit collection transaction
cmdTxStatus = 11, //Get collection transaction status
cmdCmd = 12 //Execute EJDB command
};
struct BSONCmdData { //Any bson related cmd data
std::string cname; //Name of collection
std::vector<bson*> bsons; //bsons to save|query
std::vector<bson_oid_t> ids; //saved updated oids
bson_oid_t ref; //Bson ref
bool merge; //Merge bson on save
BSONCmdData(const char* _cname) : cname(_cname), merge(false) {
memset(&ref, 0, sizeof (ref));
}
virtual ~BSONCmdData() {
std::vector<bson*>::iterator it;
for (it = bsons.begin(); it < bsons.end(); it++) {
bson *bs = *(it);
if (bs) bson_del(bs);
}
}
};
struct BSONQCmdData : public BSONCmdData { //Query cmd data
TCLIST *res;
int qflags;
uint32_t count;
TCXSTR *log;
BSONQCmdData(const char *_cname, int _qflags) :
BSONCmdData(_cname), res(NULL), qflags(_qflags), count(0), log(NULL) {
}
virtual ~BSONQCmdData() {
if (res) {
tclistdel(res);
}
if (log) {
tcxstrdel(log);
}
}
};
struct RMCollCmdData { //Remove collection command data
std::string cname; //Name of collection
bool prune;
RMCollCmdData(const char* _cname, bool _prune) : cname(_cname), prune(_prune) {
}
};
struct SetIndexCmdData { //Set index command data
std::string cname; //Name of collection
std::string ipath; //JSON field path for index
int flags; //set index op flags
SetIndexCmdData(const char *_cname, const char *_ipath, int _flags) :
cname(_cname), ipath(_ipath), flags(_flags) {
}
};
struct TxCmdData { //Transaction control command data
std::string cname; //Name of collection
bool txactive; //If true we are in transaction
TxCmdData(const char *_name) : cname(_name), txactive(false) {
}
};
typedef EIOCmdTask<NodeEJDB> EJBTask; //Most generic task
typedef EIOCmdTask<NodeEJDB, BSONCmdData> BSONCmdTask; //Any bson related task
typedef EIOCmdTask<NodeEJDB, BSONQCmdData> BSONQCmdTask; //Query task
typedef EIOCmdTask<NodeEJDB, RMCollCmdData> RMCollCmdTask; //Remove collection
typedef EIOCmdTask<NodeEJDB, SetIndexCmdData> SetIndexCmdTask; //Set index command
typedef EIOCmdTask<NodeEJDB, TxCmdData> TxCmdTask; //Transaction control command
static Persistent<FunctionTemplate> constructor_template;
EJDB *m_jb;
static Handle<Value> s_new_object(const Arguments& args) {
HandleScope scope;
REQ_STR_ARG(0, dbPath);
REQ_INT32_ARG(1, mode);
NodeEJDB *njb = new NodeEJDB();
if (!njb->open(*dbPath, mode)) {
std::ostringstream os;
os << "Unable to open database: " << (*dbPath) << " error: " << njb->_jb_error_msg();
EJ_LOG_ERROR("%s", os.str().c_str());
delete njb;
return scope.Close(ThrowException(Exception::Error(String::New(os.str().c_str()))));
}
njb->Wrap(args.This());
return scope.Close(args.This());
}
static void s_exec_cmd_eio(uv_work_t *req) {
EJBTask *task = (EJBTask*) (req->data);
NodeEJDB *njb = task->wrapped;
assert(njb);
njb->exec_cmd(task);
}
static void s_exec_cmd_eio_after(uv_work_t *req) {
EJBTask *task = (EJBTask*) (req->data);
NodeEJDB *njb = task->wrapped;
assert(njb);
njb->exec_cmd_after(task);
delete task;
}
static Handle<Value> s_close(const Arguments& args) {
HandleScope scope;
NodeEJDB *njb = ObjectWrap::Unwrap< NodeEJDB > (args.This());
if (!njb->close()) {
return scope.Close(ThrowException(Exception::Error(String::New(njb->_jb_error_msg()))));
}
return scope.Close(Undefined());
}
static Handle<Value> s_load(const Arguments& args) {
HandleScope scope;
REQ_ARGS(2);
REQ_STR_ARG(0, cname); //Collection name
REQ_STR_ARG(1, soid); //String OID
if (!ejdbisvalidoidstr(*soid)) {
return scope.Close(ThrowException(Exception::Error(String::New("Argument 2: Invalid OID string"))));
}
Local<Function> cb;
bson_oid_t oid;
bson_oid_from_string(&oid, *soid);
BSONCmdData *cmdata = new BSONCmdData(*cname);
cmdata->ref = oid;
NodeEJDB *njb = ObjectWrap::Unwrap< NodeEJDB > (args.This());
if (args[2]->IsFunction()) {
cb = Local<Function>::Cast(args[2]);
BSONCmdTask *task = new BSONCmdTask(cb, njb, cmdLoad, cmdata, BSONCmdTask::delete_val);
uv_queue_work(uv_default_loop(), &task->uv_work, s_exec_cmd_eio, (uv_after_work_cb)s_exec_cmd_eio_after);
return scope.Close(Undefined());
} else {
BSONCmdTask task(cb, njb, cmdLoad, cmdata, BSONCmdTask::delete_val);
njb->load(&task);
return scope.Close(njb->load_after(&task));
}
}
static Handle<Value> s_remove(const Arguments& args) {
HandleScope scope;
REQ_ARGS(2);
REQ_STR_ARG(0, cname); //Collection name
REQ_STR_ARG(1, soid); //String OID
if (!ejdbisvalidoidstr(*soid)) {
return scope.Close(ThrowException(Exception::Error(String::New("Argument 2: Invalid OID string"))));
}
Local<Function> cb;
bson_oid_t oid;
bson_oid_from_string(&oid, *soid);
BSONCmdData *cmdata = new BSONCmdData(*cname);
cmdata->ref = oid;
NodeEJDB *njb = ObjectWrap::Unwrap< NodeEJDB > (args.This());
if (args[2]->IsFunction()) {
cb = Local<Function>::Cast(args[2]);
BSONCmdTask *task = new BSONCmdTask(cb, njb, cmdRemove, cmdata, BSONCmdTask::delete_val);
uv_queue_work(uv_default_loop(), &task->uv_work, s_exec_cmd_eio, (uv_after_work_cb)s_exec_cmd_eio_after);
return scope.Close(Undefined());
} else {
BSONCmdTask task(cb, njb, cmdRemove, cmdata, BSONCmdTask::delete_val);
njb->remove(&task);
return scope.Close(njb->remove_after(&task));
}
}
static Handle<Value> s_save(const Arguments& args) {
HandleScope scope;
REQ_ARGS(3);
REQ_STR_ARG(0, cname); //Collection name
REQ_ARR_ARG(1, oarr); //Array of JSON objects
REQ_OBJ_ARG(2, opts); //Options obj
Local<Function> cb;
BSONCmdData *cmdata = new BSONCmdData(*cname);
for (uint32_t i = 0; i < oarr->Length(); ++i) {
Local<Value> v = oarr->Get(i);
if (!v->IsObject()) {
cmdata->bsons.push_back(NULL);
continue;
}
bson *bs = bson_create();
assert(bs);
bson_init(bs);
toBSON(Handle<Object>::Cast(v), bs, false);
if (bs->err) {
Local<String> msg = String::New(bson_first_errormsg(bs));
bson_del(bs);
delete cmdata;
return scope.Close(ThrowException(Exception::Error(msg)));
}
bson_finish(bs);
cmdata->bsons.push_back(bs);
}
if (opts->Get(sym_merge)->BooleanValue()) {
cmdata->merge = true;
}
NodeEJDB *njb = ObjectWrap::Unwrap< NodeEJDB > (args.This());
if (args[3]->IsFunction()) { //callback provided
cb = Local<Function>::Cast(args[3]);
BSONCmdTask *task = new BSONCmdTask(cb, njb, cmdSave, cmdata, BSONCmdTask::delete_val);
uv_queue_work(uv_default_loop(), &task->uv_work, s_exec_cmd_eio, (uv_after_work_cb)s_exec_cmd_eio_after);
return scope.Close(Undefined());
} else {
BSONCmdTask task(cb, njb, cmdSave, cmdata, BSONCmdTask::delete_val);
njb->save(&task);
return scope.Close(njb->save_after(&task));
}
}
static Handle<Value> s_cmd(const Arguments& args) {
HandleScope scope;
REQ_ARGS(1);
REQ_OBJ_ARG(0, cmdobj);
Local<Function> cb;
BSONQCmdData *cmdata = new BSONQCmdData("", 0);
bson *bs = bson_create();
bson_init_as_query(bs);
toBSON(cmdobj, bs, false);
if (bs->err) {
Local<String> msg = String::New(bson_first_errormsg(bs));
bson_del(bs);
delete cmdata;
return scope.Close(ThrowException(Exception::Error(msg)));
}
bson_finish(bs);
cmdata->bsons.push_back(bs);
NodeEJDB *njb = ObjectWrap::Unwrap< NodeEJDB > (args.This());
if (args[1]->IsFunction()) { //callback provided
cb = Local<Function>::Cast(args[1]);
BSONQCmdTask *task = new BSONQCmdTask(cb, njb, cmdCmd, cmdata, BSONQCmdTask::delete_val);
uv_queue_work(uv_default_loop(), &task->uv_work, s_exec_cmd_eio, (uv_after_work_cb)s_exec_cmd_eio_after);
return scope.Close(Undefined());
} else {
BSONQCmdTask task(cb, njb, cmdCmd, cmdata, BSONQCmdTask::delete_val);
njb->ejdbcmd(&task);
return scope.Close(njb->ejdbcmd_after(&task));
}
}
static Handle<Value> s_query(const Arguments& args) {
HandleScope scope;
REQ_ARGS(3);
REQ_STR_ARG(0, cname)
REQ_ARR_ARG(1, qarr);
REQ_INT32_ARG(2, qflags);
if (qarr->Length() == 0) {
return scope.Close(ThrowException(Exception::Error(String::New("Query array must have at least one element"))));
}
Local<Function> cb;
BSONQCmdData *cmdata = new BSONQCmdData(*cname, qflags);
uint32_t len = qarr->Length();
for (uint32_t i = 0; i < len; ++i) {
Local<Value> qv = qarr->Get(i);
if (i > 0 && i == len - 1 && (qv->IsNull() || qv->IsUndefined())) { //Last hints element can be NULL
cmdata->bsons.push_back(NULL);
continue;
} else if (!qv->IsObject()) {
delete cmdata;
return scope.Close(ThrowException(
Exception::Error(
String::New("Each element of query array must be an object (except last hints element)"))
));
}
bson *bs = bson_create();
bson_init_as_query(bs);
toBSON(Local<Object>::Cast(qv), bs, true);
bson_finish(bs);
if (bs->err) {
Local<String> msg = String::New(bson_first_errormsg(bs));
bson_del(bs);
delete cmdata;
return scope.Close(ThrowException(Exception::Error(msg)));
}
cmdata->bsons.push_back(bs);
}
if (len > 1 && qarr->Get(len - 1)->IsObject()) {
Local<Object> hints = Local<Object>::Cast(qarr->Get(len - 1));
if (hints->Get(sym_explain)->BooleanValue()) {
cmdata->log = tcxstrnew();
}
}
NodeEJDB *njb = ObjectWrap::Unwrap< NodeEJDB > (args.This());
if (args[3]->IsFunction()) { //callback provided
cb = Local<Function>::Cast(args[3]);
BSONQCmdTask *task = new BSONQCmdTask(cb, njb, cmdQuery, cmdata, BSONQCmdTask::delete_val);
uv_queue_work(uv_default_loop(), &task->uv_work, s_exec_cmd_eio, (uv_after_work_cb)s_exec_cmd_eio_after);
return scope.Close(Undefined());
} else {
BSONQCmdTask task(cb, njb, cmdQuery, cmdata, BSONQCmdTask::delete_val);
njb->query(&task);
return scope.Close(njb->query_after(&task));
}
}
static Handle<Value> s_set_index(const Arguments& args) {
HandleScope scope;
REQ_ARGS(3);
REQ_STR_ARG(0, cname)
REQ_STR_ARG(1, ipath)
REQ_INT32_ARG(2, flags);
NodeEJDB *njb = ObjectWrap::Unwrap< NodeEJDB > (args.This());
SetIndexCmdData *cmdata = new SetIndexCmdData(*cname, *ipath, flags);
Local<Function> cb;
if (args[3]->IsFunction()) {
cb = Local<Function>::Cast(args[3]);
SetIndexCmdTask *task = new SetIndexCmdTask(cb, njb, cmdSetIndex, cmdata, SetIndexCmdTask::delete_val);
uv_queue_work(uv_default_loop(), &task->uv_work, s_exec_cmd_eio, (uv_after_work_cb)s_exec_cmd_eio_after);
} else {
SetIndexCmdTask task(cb, njb, cmdSetIndex, cmdata, SetIndexCmdTask::delete_val);
njb->set_index(&task);
njb->set_index_after(&task);
if (task.cmd_ret) {
return scope.Close(Exception::Error(String::New(task.cmd_ret_msg.c_str())));
}
}
return scope.Close(Undefined());
}
static Handle<Value> s_sync(const Arguments& args) {
HandleScope scope;
NodeEJDB *njb = ObjectWrap::Unwrap< NodeEJDB > (args.This());
Local<Function> cb;
if (args[0]->IsFunction()) {
cb = Local<Function>::Cast(args[0]);
EJBTask *task = new EJBTask(cb, njb, cmdSync, NULL, NULL);
uv_queue_work(uv_default_loop(), &task->uv_work, s_exec_cmd_eio, (uv_after_work_cb)s_exec_cmd_eio_after);
} else {
EJBTask task(cb, njb, cmdSync, NULL, NULL);
njb->sync(&task);
njb->sync_after(&task);
if (task.cmd_ret) {
return scope.Close(Exception::Error(String::New(task.cmd_ret_msg.c_str())));
}
}
return scope.Close(Undefined());
}
static Handle<Value> s_db_meta(const Arguments& args) {
HandleScope scope;
NodeEJDB *njb = ObjectWrap::Unwrap< NodeEJDB > (args.This());
if (!ejdbisopen(njb->m_jb)) {
return scope.Close(ThrowException(Exception::Error(String::New("Operation on closed EJDB instance"))));
}
bson *meta = ejdbmeta(njb->m_jb);
if (!meta) {
return scope.Close(ThrowException(Exception::Error(String::New(njb->_jb_error_msg()))));
}
bson_iterator it;
bson_iterator_init(&it, meta);
Handle<Object> ret = toV8Object(&it);
bson_del(meta);
return scope.Close(ret);
}
//transaction control handlers
static Handle<Value> s_coll_txctl(const Arguments& args) {
HandleScope scope;
REQ_STR_ARG(0, cname);
//operation values:
//cmdTxBegin = 8, //Begin collection transaction
//cmdTxAbort = 9, //Abort collection transaction
//cmdTxCommit = 10, //Commit collection transaction
//cmdTxStatus = 11 //Get collection transaction status
REQ_INT32_ARG(1, op);
//Arg 2 is the optional function callback arg
if (!(op == cmdTxBegin ||
op == cmdTxAbort ||
op == cmdTxCommit ||
op == cmdTxStatus)) {
return scope.Close(ThrowException(Exception::Error(String::New("Invalid value of 1 argument"))));
}
NodeEJDB *njb = ObjectWrap::Unwrap< NodeEJDB > (args.This());
assert(njb);
EJDB *jb = njb->m_jb;
if (!ejdbisopen(jb)) {
return scope.Close(ThrowException(Exception::Error(String::New("Operation on closed EJDB instance"))));
}
TxCmdData *cmdata = new TxCmdData(*cname);
Local<Function> cb;
if (args[2]->IsFunction()) {
cb = Local<Function>::Cast(args[2]);
TxCmdTask *task = new TxCmdTask(cb, njb, op, cmdata, TxCmdTask::delete_val);
uv_queue_work(uv_default_loop(), &task->uv_work, s_exec_cmd_eio, (uv_after_work_cb)s_exec_cmd_eio_after);
return scope.Close(Undefined());
} else {
TxCmdTask task(cb, njb, op, cmdata, NULL);
njb->txctl(&task);
return scope.Close(njb->txctl_after(&task));
}
}
static Handle<Value> s_ecode(const Arguments& args) {
HandleScope scope;
NodeEJDB *njb = ObjectWrap::Unwrap< NodeEJDB > (args.This());
if (!njb->m_jb) { //not using ejdbisopen()
return scope.Close(ThrowException(Exception::Error(String::New("Operation on closed EJDB instance"))));
}
return scope.Close(Integer::New(ejdbecode(njb->m_jb)));
}
static Handle<Value> s_ensure_collection(const Arguments& args) {
HandleScope scope;
REQ_STR_ARG(0, cname);
REQ_OBJ_ARG(1, copts);
NodeEJDB *njb = ObjectWrap::Unwrap< NodeEJDB > (args.This());
if (!ejdbisopen(njb->m_jb)) {
return scope.Close(ThrowException(Exception::Error(String::New("Operation on closed EJDB instance"))));
}
EJCOLLOPTS jcopts;
memset(&jcopts, 0, sizeof (jcopts));
jcopts.cachedrecords = (int) fetch_int_data(copts->Get(sym_cachedrecords), NULL, 0);
jcopts.compressed = fetch_bool_data(copts->Get(sym_compressed), NULL, false);
jcopts.large = fetch_bool_data(copts->Get(sym_large), NULL, false);
jcopts.records = fetch_int_data(copts->Get(sym_records), NULL, 0);
EJCOLL *coll = ejdbcreatecoll(njb->m_jb, *cname, &jcopts);
if (!coll) {
return scope.Close(ThrowException(Exception::Error(String::New(njb->_jb_error_msg()))));
}
return scope.Close(Undefined());
}
static Handle<Value> s_rm_collection(const Arguments& args) {
HandleScope scope;
REQ_STR_ARG(0, cname);
REQ_VAL_ARG(1, prune);
REQ_FUN_ARG(2, cb);
NodeEJDB *njb = ObjectWrap::Unwrap< NodeEJDB > (args.This());
if (!ejdbisopen(njb->m_jb)) {
return scope.Close(ThrowException(Exception::Error(String::New("Operation on closed EJDB instance"))));
}
RMCollCmdData *cmdata = new RMCollCmdData(*cname, prune->BooleanValue());
RMCollCmdTask *task = new RMCollCmdTask(cb, njb, cmdRemoveColl, cmdata, RMCollCmdTask::delete_val);
uv_queue_work(uv_default_loop(), &task->uv_work, s_exec_cmd_eio, (uv_after_work_cb)s_exec_cmd_eio_after);
return scope.Close(Undefined());
}
static Handle<Value> s_is_open(const Arguments& args) {
HandleScope scope;
NodeEJDB *njb = ObjectWrap::Unwrap< NodeEJDB > (args.This());
return scope.Close(Boolean::New(ejdbisopen(njb->m_jb)));
}
///////////////////////////////////////////////////////////////////////////
// Instance methods //
///////////////////////////////////////////////////////////////////////////
void exec_cmd(EJBTask *task) {
int cmd = task->cmd;
switch (cmd) {
case cmdQuery:
query((BSONQCmdTask*) task);
break;
case cmdLoad:
load((BSONCmdTask*) task);
break;
case cmdSave:
save((BSONCmdTask*) task);
break;
case cmdRemove:
remove((BSONCmdTask*) task);
break;
case cmdRemoveColl:
rm_collection((RMCollCmdTask*) task);
break;
case cmdSetIndex:
set_index((SetIndexCmdTask*) task);
break;