summaryrefslogtreecommitdiff
path: root/nejdb/Ejdb.DB/EJDB.cs
blob: c19a6c7bc7f65d5242941becf0a25cd4733c92b3 (plain)
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
// ============================================================================================
//   .NET API for 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.
// ============================================================================================
using System;
using System.Runtime.InteropServices;
using Mono.Unix;
using System.Text;
using Ejdb.BSON;

namespace Ejdb.DB {

	/// <summary>
	/// Corresponds to <c>EJCOLLOPTS</c> in ejdb.h
	/// </summary>
	public struct EJDBCollectionOptionsN {
		[MarshalAs(UnmanagedType.U1)]
		public bool large;

		[MarshalAs(UnmanagedType.U1)]
		public bool compressed;

		public long records;

		public int cachedrecords;
	}

	/// <summary>
	/// EJDB database native wrapper.
	/// </summary>
	public class EJDB : IDisposable {
		//.//////////////////////////////////////////////////////////////////
		// 						Native open modes									  
		//.//////////////////////////////////////////////////////////////////
		/// <summary>
		/// Open as a reader.
		/// </summary>
		public const int JBOREADER = 1 << 0;

		/// <summary>
		/// Open as a writer.
		/// </summary>
		public const int JBOWRITER = 1 << 1;

		/// <summary>
		/// Create if db file not exists. 
		/// </summary>
		public const int JBOCREAT = 1 << 2;

		/// <summary>
		/// Truncate db on open.
		/// </summary>
		public const int JBOTRUNC = 1 << 3;

		/// <summary>
		/// Open without locking. 
		/// </summary>
		public const int JBONOLCK = 1 << 4;

		/// <summary>
		/// Lock without blocking.
		/// </summary>
		public const int JBOLCKNB = 1 << 5;

		/// <summary>
		/// Synchronize every transaction with storage.
		/// </summary>
		public const int JBOTSYNC = 1 << 6;

		/// <summary>
		/// The default open mode <c>(JBOWRITER | JBOCREAT)</c>
		/// </summary>
		public const int DEFAULT_OPEN_MODE = (JBOWRITER | JBOCREAT);
		//.//////////////////////////////////////////////////////////////////
		// 				 Native index operations & types (ejdb.h)									  
		//.//////////////////////////////////////////////////////////////////
		/// <summary>
		/// Drop index.
		/// </summary>
		const int JBIDXDROP = 1 << 0;

		/// <summary>
		/// Drop index for all types.
		/// </summary>
		const int JBIDXDROPALL = 1 << 1;

		/// <summary>
		/// Optimize indexes.
		/// </summary>
		const int JBIDXOP = 1 << 2;

		/// <summary>
		/// Rebuild index.
		/// </summary>
		const int JBIDXREBLD = 1 << 3;

		/// <summary>
		/// Number index.
		/// </summary>
		const int JBIDXNUM = 1 << 4;

		/// <summary>
		/// String index.
		/// </summary>
		const int JBIDXSTR = 1 << 5;

		/// <summary>
		/// Array token index.
		/// </summary>
		const int JBIDXARR = 1 << 6;

		/// <summary>
		/// Case insensitive string index.
		/// </summary>
		const int JBIDXISTR = 1 << 7;

		/// <summary>
		/// The EJDB library version
		/// </summary>
		static string _LIBVERSION;

		/// <summary>
		/// The EJDB library version hex code.
		/// </summary>
		static long _LIBHEXVERSION;

		/// <summary>
		/// Name if EJDB library
		/// </summary>
		#if EJDBDLL
		public const string EJDB_LIB_NAME = "tcejdbdll";
#else
		public const string EJDB_LIB_NAME = "tcejdb";
		#endif
		/// <summary>
		/// Pointer to the native EJDB instance.
		/// </summary>
		IntPtr _db = IntPtr.Zero;

		bool _throwonfail = true;
		//.//////////////////////////////////////////////////////////////////
		//   				Native functions refs									  
		//.//////////////////////////////////////////////////////////////////
		#region NativeRefs
        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbnew", CallingConvention = CallingConvention.Cdecl)]
		internal static extern IntPtr _ejdbnew();

        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbdel", CallingConvention = CallingConvention.Cdecl)]
		internal static extern IntPtr _ejdbdel([In] IntPtr db);

        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbopen", CallingConvention = CallingConvention.Cdecl)]
		internal static extern bool _ejdbopen([In] IntPtr db, [In] IntPtr path, int mode);

		internal static bool _ejdbopen(IntPtr db, string path, int mode) {
			IntPtr pptr = UnixMarshal.StringToHeap(path, Encoding.UTF8);
			try {
				return _ejdbopen(db, pptr, mode);
			} finally {
				UnixMarshal.FreeHeap(pptr);
			}
		}

        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbclose", CallingConvention = CallingConvention.Cdecl)]
		internal static extern bool _ejdbclose([In] IntPtr db);

        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbisopen", CallingConvention = CallingConvention.Cdecl)]
		internal static extern bool _ejdbisopen([In] IntPtr db);

        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbecode", CallingConvention = CallingConvention.Cdecl)]
		internal static extern int _ejdbecode([In] IntPtr db);

        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdberrmsg", CallingConvention = CallingConvention.Cdecl)]
		internal static extern IntPtr _ejdberrmsg(int ecode);

        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbgetcoll", CallingConvention = CallingConvention.Cdecl)]
		internal static extern IntPtr _ejdbgetcoll([In] IntPtr db, [In] IntPtr cname);

		internal static IntPtr _ejdbgetcoll(IntPtr db, string cname) {
			IntPtr cptr = UnixMarshal.StringToHeap(cname, Encoding.UTF8);
			try {
				return _ejdbgetcoll(db, cptr);
			} finally {
				UnixMarshal.FreeHeap(cptr);
			}
		}

        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbcreatecoll", CallingConvention = CallingConvention.Cdecl)]
		internal static extern IntPtr _ejdbcreatecoll([In] IntPtr db, [In] IntPtr cname, IntPtr opts);

        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbcreatecoll", CallingConvention = CallingConvention.Cdecl)]
		internal static extern IntPtr _ejdbcreatecoll([In] IntPtr db, [In] IntPtr cname, ref EJDBCollectionOptionsN opts);

		internal static IntPtr _ejdbcreatecoll(IntPtr db, String cname, EJDBCollectionOptionsN? opts) {
			IntPtr cptr = UnixMarshal.StringToHeap(cname, Encoding.UTF8);
			try {
				if (opts == null) {
					return _ejdbcreatecoll(db, cptr, IntPtr.Zero);
				} else {
					EJDBCollectionOptionsN nopts = (EJDBCollectionOptionsN) opts;
					return _ejdbcreatecoll(db, cptr, ref nopts);
				}
			} finally {
				UnixMarshal.FreeHeap(cptr);
			}
		}
		//EJDB_EXPORT bool ejdbrmcoll(EJDB *jb, const char *colname, bool unlinkfile);
        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbrmcoll", CallingConvention = CallingConvention.Cdecl)]
		internal static extern bool _ejdbrmcoll([In] IntPtr db, [In] IntPtr cname, bool unlink);

		internal static bool _ejdbrmcoll(IntPtr db, string cname, bool unlink) {
			IntPtr cptr = UnixMarshal.StringToHeap(cname, Encoding.UTF8);
			try {
				return _ejdbrmcoll(db, cptr, unlink);
			} finally {
				UnixMarshal.FreeHeap(cptr);
			}
		}
		//EJDB_EXPORT bson* ejdbcommand(EJDB *jb, bson *cmd);
        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbcommand2", CallingConvention = CallingConvention.Cdecl)]
		internal static extern IntPtr _ejdbcommand([In] IntPtr db, [In] byte[] cmd);
		//EJDB_EXPORT bool ejdbsavebson3(EJCOLL *jcoll, void *bsdata, bson_oid_t *oid, bool merge);
        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbsavebson3", CallingConvention = CallingConvention.Cdecl)]
		internal static extern bool _ejdbsavebson([In] IntPtr coll, [In] byte[] bsdata, [Out] byte[] oid, [In] bool merge);
		//EJDB_EXPORT bson* ejdbloadbson(EJCOLL *coll, const bson_oid_t *oid);
        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbloadbson", CallingConvention = CallingConvention.Cdecl)]
		internal static extern IntPtr _ejdbloadbson([In] IntPtr coll, [In] byte[] oid);
		//EJDB_EXPORT const char* bson_data2(const bson *b, int *bsize);
        [DllImport(EJDB_LIB_NAME, EntryPoint = "bson_data2", CallingConvention = CallingConvention.Cdecl)]
		internal static extern IntPtr _bson_data2([In] IntPtr bsptr, out int size);
		//EJDB_EXPORT void bson_del(bson *b);
        [DllImport(EJDB_LIB_NAME, EntryPoint = "bson_del", CallingConvention = CallingConvention.Cdecl)]
		internal static extern void _bson_del([In] IntPtr bsptr);
		//EJDB_EXPORT bool ejdbrmbson(EJCOLL *coll, bson_oid_t *oid);
        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbrmbson", CallingConvention = CallingConvention.Cdecl)]
		internal static extern bool _ejdbrmbson([In] IntPtr cptr, [In] byte[] oid);
		//EJDB_EXPORT bool ejdbsyncdb(EJDB *jb)
        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbsyncdb", CallingConvention = CallingConvention.Cdecl)]
		internal static extern bool _ejdbsyncdb([In] IntPtr db);
		//EJDB_EXPORT bool ejdbsyncoll(EJDB *jb)
        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbsyncoll", CallingConvention = CallingConvention.Cdecl)]
		internal static extern bool _ejdbsyncoll([In] IntPtr coll);
		//EJDB_EXPORT bool ejdbsetindex(EJCOLL *coll, const char *ipath, int flags);
        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbsetindex", CallingConvention = CallingConvention.Cdecl)]
		internal static extern bool _ejdbsetindex([In] IntPtr coll, [In] IntPtr ipathptr, int flags);
		//EJDB_EXPORT bson* ejdbmeta(EJDB *jb)
        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbmeta", CallingConvention = CallingConvention.Cdecl)]
		internal static extern IntPtr _ejdbmeta([In] IntPtr db);
		//EJDB_EXPORT bool ejdbtranbegin(EJCOLL *coll);
        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbtranbegin", CallingConvention = CallingConvention.Cdecl)]
		internal static extern bool _ejdbtranbegin([In] IntPtr coll);
		//EJDB_EXPORT bool ejdbtrancommit(EJCOLL *coll);
        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbtrancommit", CallingConvention = CallingConvention.Cdecl)]
		internal static extern bool _ejdbtrancommit([In] IntPtr coll);
		//EJDB_EXPORT bool ejdbtranabort(EJCOLL *coll);
        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbtranabort", CallingConvention = CallingConvention.Cdecl)]
		internal static extern bool _ejdbtranabort([In] IntPtr coll);
		//EJDB_EXPORT bool ejdbtranstatus(EJCOLL *jcoll, bool *txactive);
        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbtranstatus", CallingConvention = CallingConvention.Cdecl)]
		internal static extern bool _ejdbtranstatus([In] IntPtr coll, out bool txactive);
		//EJDB_EXPORT const char *ejdbversion();
        [DllImport(EJDB_LIB_NAME, EntryPoint = "ejdbversion", CallingConvention = CallingConvention.Cdecl)]
		internal static extern IntPtr _ejdbversion();

		internal static bool _ejdbsetindex(IntPtr coll, string ipath, int flags) {
			IntPtr ipathptr = UnixMarshal.StringToHeap(ipath, Encoding.UTF8);
			try {
				return _ejdbsetindex(coll, ipathptr, flags);
			} finally {
				UnixMarshal.FreeHeap(ipathptr);
			}
		}
		#endregion
		/// <summary>
		/// If true <see cref="Ejdb.DB.EJDBException"/> will be thrown in the case of failed operation 
		/// otherwise method will return boolean status flag. Default value: <c>true</c> 
		/// </summary>
		/// <value><c>true</c> if throw exception on fail; otherwise, <c>false</c>.</value>
		public bool ThrowExceptionOnFail {
			get {
				return _throwonfail;
			}
			set {
				_throwonfail = value;
			}
		}

		/// <summary>
		/// Gets the last DB error code or <c>null</c> if underlying native database object does not exist.
		/// </summary>
		/// <value>The last DB error code.</value>
		public int? LastDBErrorCode {
			get {
				return (_db != IntPtr.Zero) ? (int?) _ejdbecode(_db) : null;
			}
		}

		/// <summary>
		/// Gets the last DB error message or <c>null</c> if underlying native database object does not exist.
		/// </summary>
		public string LastDBErrorMsg {
			get {		
				int? ecode = LastDBErrorCode;
				if (ecode == null) {
					return null;
				}
				return UnixMarshal.PtrToString(_ejdberrmsg((int) ecode), Encoding.UTF8);
			}
		}

		/// <summary>
		/// Gets a value indicating whether this EJDB databse is open.
		/// </summary>
		/// <value><c>true</c> if this instance is open; otherwise, <c>false</c>.</value>
		public bool IsOpen {
			get {
				return _ejdbisopen(_db);
			}
		}

		/// <summary>
		/// Gets info of EJDB database itself and its collections.
		/// </summary>
		/// <value>The DB meta.</value>
		public BSONDocument DBMeta {
			get {
				CheckDisposed(true);
				//internal static extern IntPtr _ejdbmeta([In] IntPtr db);
				IntPtr bsptr = _ejdbmeta(_db);
				if (bsptr == IntPtr.Zero) {
					throw new EJDBException(this);
				}
				try {
					int size;
					IntPtr bsdataptr = _bson_data2(bsptr, out size);
					byte[] bsdata = new byte[size];
					Marshal.Copy(bsdataptr, bsdata, 0, bsdata.Length);
					return new BSONDocument(bsdata);
				} finally {
					_bson_del(bsptr);
				}
			}
		}

		/// <summary>
		/// Gets the EJDB library version.
		/// </summary>
		/// <value>The LIB version.</value>
		public static string LIBVersion {
			get {
				if (_LIBVERSION != null) {
					return _LIBVERSION;
				}
				lock (typeof(EJDB)) {
					if (_LIBVERSION != null) {
						return _LIBVERSION;
					}
					IntPtr vres = _ejdbversion();
					if (vres == IntPtr.Zero) {
						throw new Exception("Unable to get ejdb library version");
					}
					_LIBVERSION = UnixMarshal.PtrToString(vres, Encoding.UTF8);
				}
				return _LIBVERSION;
			}		
		}

		/// <summary>
		/// Gets the EJDB library hex encoded version.
		/// </summary>
		/// <remarks>
		/// E.g: for the version "1.1.13" return value will be: 0x1113
		/// </remarks>
		/// <value>The lib hex version.</value>
		public static long LibHexVersion {
			get {
				if (_LIBHEXVERSION != 0) {
					return _LIBHEXVERSION;
				}
				lock (typeof(EJDB)) {
					if (_LIBHEXVERSION != 0) {
						return _LIBHEXVERSION;
					}
					_LIBHEXVERSION = Convert.ToInt64("0x" + LIBVersion.Replace(".", ""), 16);
				}
				return _LIBHEXVERSION;
			}
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="Ejdb.DB.EJDB"/> class.
		/// </summary>
		/// <param name="path">The main database file path.</param>
		/// <param name="omode">Open mode.</param>
		public EJDB(string path, int omode=DEFAULT_OPEN_MODE) {		
			if (EJDB.LibHexVersion < 0x1113) {
				throw new EJDBException("EJDB library version must be at least '1.1.13' or greater");
			}
			bool rv;
			_db = _ejdbnew();
			if (_db == IntPtr.Zero) {
				throw new EJDBException("Unable to create ejdb instance");
			}
			try {
				rv = _ejdbopen(_db, path, omode); 
			} catch (Exception) {
				Dispose();
				throw;
			}
			if (!rv) {
				throw new EJDBException(this);
			}
		}

		~EJDB() {
			Dispose();
		}

		public void Dispose() {
			if (_db != IntPtr.Zero) {
				IntPtr db = _db;
				_db = IntPtr.Zero;
				if (db != IntPtr.Zero) {
					_ejdbdel(db);
				}
			}
		}

		/// <summary>
		/// Automatically creates new collection if it does't exists.
		/// </summary>
		/// <remarks>
		/// Collection options <c>copts</c> are applied only for newly created collection.
		/// For existing collections <c>copts</c> has no effect.
		/// </remarks>
		/// <returns><c>false</c> error ocurried.</returns>
		/// <param name="cname">Name of collection.</param>
		/// <param name="copts">Collection options.</param>
		public bool EnsureCollection(string cname, EJDBCollectionOptionsN? copts = null) {
			CheckDisposed();
			IntPtr cptr = _ejdbcreatecoll(_db, cname, copts);		
			bool rv = (cptr != IntPtr.Zero);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		/// <summary>
		/// Removes collection indetified by <c>cname</c>.
		/// </summary>
		/// <returns><c>false</c>, if error occurred.</returns>
		/// <param name="cname">Name of the collection.</param>
		/// <param name="unlink">If set to <c>true</c> then the collection data file will be removed.</param>
		public bool DropCollection(string cname, bool unlink = false) {
			CheckDisposed();
			bool rv = _ejdbrmcoll(_db, cname, unlink);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		/// <summary>
		/// Synchronize entire EJDB database and
		/// all of its collections with storage.
		/// </summary>
		/// <returns><c>false</c>, if error occurred.</returns>
		public bool Sync() {
			CheckDisposed();
			//internal static extern bool _ejdbsyncdb([In] IntPtr db);
			bool rv = _ejdbsyncdb(_db);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		/// <summary>
		/// Synchronize content of a EJDB collection database with the file on device.
		/// </summary>
		/// <returns><c>false</c>, if error occurred.</returns>
		/// <param name="cname">Name of collection.</param>
		public bool SyncCollection(string cname) {
			CheckDisposed();
			IntPtr cptr = _ejdbgetcoll(_db, cname);
			if (cptr == IntPtr.Zero) {
				return true;
			}
			//internal static extern bool _ejdbsyncoll([In] IntPtr coll);
			bool rv = _ejdbsyncoll(cptr);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		/// <summary>
		/// DROP indexes of all types for JSON field path.
		/// </summary>
		/// <returns><c>false</c>, if error occurred.</returns>
		/// <param name="cname">Name of collection.</param>
		/// <param name="ipath">JSON indexed field path</param>
		public bool DropIndexes(string cname, string ipath) {
			bool rv = IndexOperation(cname, ipath, JBIDXDROPALL);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		/// <summary>
		/// OPTIMIZE indexes of all types for JSON field path.
		/// </summary>
		/// <remarks>
		/// Performs B+ tree index file optimization.
		/// </remarks>
		/// <returns><c>false</c>, if error occurred.</returns>
		/// <param name="cname">Name of collection.</param>
		/// <param name="ipath">JSON indexed field path</param>
		public bool OptimizeIndexes(string cname, string ipath) {
			bool rv = IndexOperation(cname, ipath, JBIDXOP);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		/// <summary>
		/// Ensure index presence of String type for JSON field path.
		/// </summary>
		/// <returns><c>false</c>, if error occurred.</returns>
		/// <param name="cname">Name of collection.</param>
		/// <param name="ipath">JSON indexed field path</param>
		public bool EnsureStringIndex(string cname, string ipath) {
			bool rv = IndexOperation(cname, ipath, JBIDXSTR);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		/// <summary>
		/// Rebuild index of String type for JSON field path.
		/// </summary>
		/// <returns><c>false</c>, if error occurred.</returns>
		/// <param name="cname">Name of collection.</param>
		/// <param name="ipath">JSON indexed field path</param>
		public bool RebuildStringIndex(string cname, string ipath) {
			bool rv = IndexOperation(cname, ipath, JBIDXSTR | JBIDXREBLD);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		/// <summary>
		/// Drop index of String type for JSON field path.
		/// </summary>
		/// <returns><c>false</c>, if error occurred.</returns>
		/// <param name="cname">Name of collection.</param>
		/// <param name="ipath">JSON indexed field path</param>
		public bool DropStringIndex(string cname, string ipath) {
			bool rv = IndexOperation(cname, ipath, JBIDXSTR | JBIDXDROP);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		/// <summary>
		/// Ensure case insensitive String index for JSON field path.
		/// </summary>
		/// <returns><c>false</c>, if error occurred.</returns>
		/// <param name="cname">Name of collection.</param>
		/// <param name="ipath">JSON indexed field path</param>
		public bool EnsureIStringIndex(string cname, string ipath) {
			bool rv = IndexOperation(cname, ipath, JBIDXISTR);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		/// <summary>
		/// Rebuild case insensitive String index for JSON field path.
		/// </summary>
		/// <returns><c>false</c>, if error occurred.</returns>
		/// <param name="cname">Name of collection.</param>
		/// <param name="ipath">JSON indexed field path</param>
		public bool RebuildIStringIndex(string cname, string ipath) {
			bool rv = IndexOperation(cname, ipath, JBIDXISTR | JBIDXREBLD);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		/// <summary>
		/// Drop case insensitive String index for JSON field path.
		/// </summary>
		/// <returns><c>false</c>, if error occurred.</returns>
		/// <param name="cname">Name of collection.</param>
		/// <param name="ipath">JSON indexed field path</param>
		public bool DropIStringIndex(string cname, string ipath) {
			bool rv = IndexOperation(cname, ipath, JBIDXISTR | JBIDXDROP);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		/// <summary>
		/// Ensure index presence of Number type for JSON field path.
		/// </summary>
		/// <returns><c>false</c>, if error occurred.</returns>
		/// <param name="cname">Name of collection.</param>
		/// <param name="ipath">JSON indexed field path</param>
		public bool EnsureNumberIndex(string cname, string ipath) {
			bool rv = IndexOperation(cname, ipath, JBIDXNUM);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		/// <summary>
		/// Rebuild index of Number type for JSON field path.
		/// </summary>
		/// <returns><c>false</c>, if error occurred.</returns>
		/// <param name="cname">Name of collection.</param>
		/// <param name="ipath">JSON indexed field path</param>
		public bool RebuildNumberIndex(string cname, string ipath) {
			bool rv = IndexOperation(cname, ipath, JBIDXNUM | JBIDXREBLD);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		/// <summary>
		/// Drop index of Number type for JSON field path.
		/// </summary>
		/// <returns><c>false</c>, if error occurred.</returns>
		/// <param name="cname">Name of collection.</param>
		/// <param name="ipath">JSON indexed field path</param>
		public bool DropNumberIndex(string cname, string ipath) {
			bool rv = IndexOperation(cname, ipath, JBIDXNUM | JBIDXDROP);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		/// <summary>
		/// Ensure index presence of Array type for JSON field path.
		/// </summary>
		/// <returns><c>false</c>, if error occurred.</returns>
		/// <param name="cname">Name of collection.</param>
		/// <param name="ipath">JSON indexed field path</param>
		public bool EnsureArrayIndex(string cname, string ipath) {
			bool rv = IndexOperation(cname, ipath, JBIDXARR);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		/// <summary>
		/// Rebuild index of Array type for JSON field path.
		/// </summary>
		/// <returns><c>false</c>, if error occurred.</returns>
		/// <param name="cname">Name of collection.</param>
		/// <param name="ipath">JSON indexed field path</param>
		public bool RebuildArrayIndex(string cname, string ipath) {
			bool rv = IndexOperation(cname, ipath, JBIDXARR | JBIDXREBLD);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		/// <summary>
		/// Drop index of Array type for JSON field path.
		/// </summary>
		/// <returns><c>false</c>, if error occurred.</returns>
		/// <param name="cname">Name of collection.</param>
		/// <param name="ipath">JSON indexed field path</param>
		public bool DropArrayIndex(string cname, string ipath) {
			bool rv = IndexOperation(cname, ipath, JBIDXARR | JBIDXDROP);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		/// <summary>
		/// Begin transaction for EJDB collection.
		/// </summary>
		/// <returns><c>true</c>, if begin was transactioned, <c>false</c> otherwise.</returns>
		/// <param name="cname">Cname.</param>
		public bool TransactionBegin(string cname) {
			CheckDisposed();
			IntPtr cptr = _ejdbgetcoll(_db, cname);
			if (cptr == IntPtr.Zero) {
				return true;
			}
			//internal static extern bool _ejdbtranbegin([In] IntPtr coll);
			bool rv = _ejdbtranbegin(cptr);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		/// <summary>
		/// Commit the transaction.
		/// </summary>
		/// <returns><c>false</c>, if error occurred.</returns>
		public bool TransactionCommit(string cname) {
			CheckDisposed();
			IntPtr cptr = _ejdbgetcoll(_db, cname);
			if (cptr == IntPtr.Zero) {
				return true;
			}
			//internal static extern bool _ejdbtrancommit([In] IntPtr coll);
			bool rv = _ejdbtrancommit(cptr);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		/// <summary>
		/// Abort the transaction.
		/// </summary>
		/// <returns><c>false</c>, if error occurred.</returns>
		public bool AbortTransaction(string cname) {
			CheckDisposed();
			IntPtr cptr = _ejdbgetcoll(_db, cname);
			if (cptr == IntPtr.Zero) {
				return true;
			}
			//internal static extern bool _ejdbtranabort([In] IntPtr coll);
			bool rv = _ejdbtranabort(cptr);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		/// <summary>
		/// Get the transaction status.
		/// </summary>
		/// <returns><c>false</c>, if error occurred.</returns>
		/// <param name="cname">Name of collection.</param>
		/// <param name="active">Out parameter. It <c>true</c> transaction is active.</param>
		public bool TransactionStatus(string cname, out bool active) {
			CheckDisposed();
			IntPtr cptr = _ejdbgetcoll(_db, cname);
			if (cptr == IntPtr.Zero) {
				active = false;
				return true;
			}
			bool rv = _ejdbtranstatus(cptr, out active);
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return rv;
		}

		public bool Save(string cname, params object[] docs) {
			CheckDisposed();
			IntPtr cptr = _ejdbcreatecoll(_db, cname, null);
			if (cptr == IntPtr.Zero) {
				if (_throwonfail) {
					throw new EJDBException(this);
				} else {
					return false;
				}
			}
			foreach (var doc in docs) {
				if (!Save(cptr, BSONDocument.ValueOf(doc), false)) {
					if (_throwonfail) {
						throw new EJDBException(this);
					} else {
						return false;
					}
				}
			}
			return true;
		}

		/// <summary>
		/// Executes EJDB command.
		/// </summary>
		/// <remarks>
		/// Supported commands:
		///
		/// 1) Exports database collections data. See ejdbexport() method.
		/// 
		/// 	"export" : {
		/// 	"path" : string,                    //Exports database collections data
		/// 	"cnames" : [string array]|null,     //List of collection names to export
		/// 	"mode" : int|null                   //Values: null|`JBJSONEXPORT` See ejdb.h#ejdbexport() method
		/// }
		/// 
		/// Command response:
		/// {
		/// 	"log" : string,        //Diagnostic log about executing this command
		/// 	"error" : string|null, //ejdb error message
		/// 	"errorCode" : int|0,   //ejdb error code
		/// }
		/// 
		/// 2) Imports previously exported collections data into ejdb.
		/// 
		/// 	"import" : {
		/// 	"path" : string                     //The directory path in which data resides
		/// 		"cnames" : [string array]|null,     //List of collection names to import
		/// 		"mode" : int|null                //Values: null|`JBIMPORTUPDATE`|`JBIMPORTREPLACE` See ejdb.h#ejdbimport() method
		/// }
		/// 
		/// Command response:
		/// {
		/// 	"log" : string,        //Diagnostic log about executing this command
		/// 	"error" : string|null, //ejdb error message
		/// 	"errorCode" : int|0,   //ejdb error code
		/// }
		/// </remarks>
		/// <param name="cmd">Command object</param>
		/// <returns>Command response.</returns>
		public BSONDocument Command(BSONDocument cmd)  {
			CheckDisposed();
			byte[] cmdata = cmd.ToByteArray();
			//internal static extern IntPtr _ejdbcommand([In] IntPtr db, [In] byte[] cmd);
			IntPtr cmdret = _ejdbcommand(_db, cmdata);
			if (cmdret == IntPtr.Zero) {
				return null;
			}
			byte[] bsdata = BsonPtrIntoByteArray(cmdret);
			if (bsdata.Length == 0) {
				return null;
			}
			BSONIterator it = new BSONIterator(bsdata);
			return it.ToBSONDocument();
		}

		/// <summary>
		/// Save the BSON document doc into the collection.
		/// </summary>
		/// <param name="cname">Name of collection.</param>
		/// <param name="docs">BSON documents to save.</param>
		/// <returns>True on success.</returns>
		public bool Save(string cname, params BSONDocument[] docs) {
			CheckDisposed();
			IntPtr cptr = _ejdbcreatecoll(_db, cname, null);
			if (cptr == IntPtr.Zero) {
				if (_throwonfail) {
					throw new EJDBException(this);
				} else {
					return false;
				}
			}
			foreach (var doc in docs) {
				if (!Save(cptr, doc, false)) {
					if (_throwonfail) {
						throw new EJDBException(this);
					} else {
						return false;
					}
				}
			}
			return true;
		}

		/// <summary>
		/// Save the BSON document doc into the collection.
		/// And merge each doc object identified by <c>_id</c> with doc stored in DB.
		/// </summary>
		/// <param name="cname">Name of collection.</param>
		/// <param name="docs">BSON documents to save.</param>
		/// <returns>True on success.</returns>
		public bool SaveMerge(string cname, params BSONDocument[] docs) {
			CheckDisposed();
			IntPtr cptr = _ejdbcreatecoll(_db, cname, null);
			if (cptr == IntPtr.Zero) {
				if (_throwonfail) {
					throw new EJDBException(this);
				} else {
					return false;
				}
			}
			foreach (var doc in docs) {
				if (!Save(cptr, doc, true)) {
					if (_throwonfail) {
						throw new EJDBException(this);
					} else {
						return false;
					}
				}
			}
			return true;
		}
	

		bool Save(IntPtr cptr, BSONDocument doc, bool merge) {
			bool rv;
			BSONValue bv = doc.GetBSONValue("_id");
			byte[] bsdata = doc.ToByteArray();
			byte[] oiddata = new byte[12];
			//static extern bool _ejdbsavebson([In] IntPtr coll, [In] byte[] bsdata, [Out] byte[] oid, bool merge);
			rv = _ejdbsavebson(cptr, bsdata, oiddata, merge);
			if (rv && bv == null) {
				doc.SetOID("_id", new BSONOid(oiddata));
			}
			if (_throwonfail && !rv) {
				throw new EJDBException(this);
			}
			return  rv;
		}

		/// <summary>
		/// Loads JSON object identified by OID from the collection.
		/// </summary>
		/// <remarks>
		/// Returns <c>null</c> if object is not found.
		/// </remarks>
		/// <param name="cname">Cname.</param>
		/// <param name="oid">Oid.</param>
		public BSONIterator Load(string cname, BSONOid oid) {
			CheckDisposed();
			IntPtr cptr = _ejdbgetcoll(_db, cname);
			if (cptr == IntPtr.Zero) {
				return null;
			}
			//static extern IntPtr _ejdbloadbson([In] IntPtr coll, [In] byte[] oid);
			byte[] bsdata = BsonPtrIntoByteArray(_ejdbloadbson(cptr, oid.ToBytes()));
			if (bsdata.Length == 0) {
				return null;
			}
			return new BSONIterator(bsdata);
		}

		/// <summary>
		/// Removes stored objects from the collection.
		/// </summary>
		/// <param name="cname">Name of collection.</param>
		/// <param name="oids">Object identifiers.</param>
		public bool Remove(string cname, params BSONOid[] oids) {
			CheckDisposed();
			IntPtr cptr = _ejdbgetcoll(_db, cname);
			if (cptr == IntPtr.Zero) {
				return true;
			}
			//internal static extern bool _ejdbrmbson([In] IntPtr cptr, [In] byte[] oid);
			foreach (var oid in oids) {
				if (!_ejdbrmbson(cptr, oid.ToBytes())) {
					if (_throwonfail) {
						throw new EJDBException(this);
					} else {
						return false;
					}
				}
			}
			return true;
		}

		/// <summary>
		/// Creates the query.
		/// </summary>
		/// <returns>The query object.</returns>
		/// <param name="qdoc">BSON query spec.</param>
		/// <param name="defaultcollection">Name of the collection used by default.</param>
		public EJDBQuery CreateQuery(object qv = null, string defaultcollection = null) {
			CheckDisposed();
			return new EJDBQuery(this, BSONDocument.ValueOf(qv), defaultcollection);
		}

		public EJDBQuery CreateQueryFor(string defaultcollection) {
			CheckDisposed();
			return new EJDBQuery(this, new BSONDocument(), defaultcollection);
		}
		//.//////////////////////////////////////////////////////////////////
		// 						 Private staff							   //	  
		//.//////////////////////////////////////////////////////////////////
		internal IntPtr DBPtr {
			get {
				CheckDisposed();
				return _db;
			}
		}

		byte[] BsonPtrIntoByteArray(IntPtr bsptr, bool deletebsptr = true) {
			if (bsptr == IntPtr.Zero) {
				return new byte[0];
			}
			int size;
			IntPtr bsdataptr = _bson_data2(bsptr, out size);
			byte[] bsdata = new byte[size];
			Marshal.Copy(bsdataptr, bsdata, 0, bsdata.Length);
			if (deletebsptr) {
				_bson_del(bsptr);
			}
			return bsdata;
		}

		bool IndexOperation(string cname, string ipath, int flags) {
			CheckDisposed(true);
			IntPtr cptr = _ejdbgetcoll(_db, cname);
			if (cptr == IntPtr.Zero) {
				return true;
			}
			//internal static bool _ejdbsetindex(IntPtr coll, string ipath, int flags)
			return _ejdbsetindex(cptr, ipath, flags);
		}

		internal void CheckDisposed(bool checkopen = false) {
			if (_db == IntPtr.Zero) {
				throw new ObjectDisposedException("Database is disposed");
			}
			if (checkopen) {
				if (!IsOpen) {
					throw new ObjectDisposedException("Operation on closed EJDB instance"); 
				}
			}
		}
	}
}