-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFigaroContext.cs
More file actions
1470 lines (1350 loc) · 51.1 KB
/
FigaroContext.cs
File metadata and controls
1470 lines (1350 loc) · 51.1 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
/*************************************************************************************************
*
* THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
* PARTICULAR PURPOSE.
*
*************************************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Figaro.Utilities.Common;
using Figaro.Utilities.Resources;
namespace Figaro.Utilities
{
public class FigaroContext : IDisposable
{
private readonly XmlManager mgr;
private readonly DbxmlOptions opts;
private readonly Stack<Container> containers;
private readonly UpdateContext updateContext;
private string path;
private readonly QueryContext queryContext;
private XmlResults queryResults;
private XQueryExpression queryExpression;
private QueryOptions queryOptions;
#if !DS
// ReSharper disable once UnassignedReadonlyField.Compiler
private readonly FigaroEnv env;
#endif
#if TDS || HA
private XmlTransaction trans;
#endif
// ReSharper disable UnusedMember.Local
private FigaroContext() { }
// ReSharper restore UnusedMember.Local
public FigaroContext(DbxmlOptions options)
{
containers = new Stack<Container>();
opts = options;
SetWorkingDirectory();
#if TDS || HA
bool opened = false;
bool adopt = true;
env = new FigaroEnv();
env.OnErr += env_OnErr;
env.OnMessage += env_OnMessage;
if (opts.Verbose)
{
env.SetVerbose(VerboseOption.WaitsFor, true);
env.SetVerbose(VerboseOption.Register, true);
env.SetVerbose(VerboseOption.Recovery, true);
env.SetVerbose(VerboseOption.Deadlock, true);
LogConfiguration.SetCategory(LogConfigurationCategory.All, true);
LogConfiguration.SetLogLevel(LogConfigurationLevel.All, true);
}
else
{
LogConfiguration.SetCategory(LogConfigurationCategory.All, true);
LogConfiguration.SetLogLevel(LogConfigurationLevel.Error, true);
}
if (!string.IsNullOrEmpty(opts.Password))
{
env.SetEncryption(opts.Password, true);
}
#if TDS || HA
env.SetLogOptions(EnvLogOptions.AutoRemove, true);
#endif
env.MessageEventEnabled = true;
env.ErrEventEnabled = true;
var cache = new EnvCacheSize(0, opts.CacheSize > 0 ? opts.CacheSize * 1024 * 1024 : 64 * 1024 * 1024);
env.SetCacheSize(cache, 5);
env.SetMaxLockers(10000);
env.SetMaxLocks(10000);
env.SetMaxLockedObjects(10000);
// ReSharper disable JoinDeclarationAndInitializer
EnvOpenOptions openOpts;
// ReSharper restore JoinDeclarationAndInitializer
#if TDS || HA
openOpts = EnvOpenOptions.InitMemoryBufferPool |
EnvOpenOptions.InitLock |
EnvOpenOptions.UseEnvironment;
#endif
msg("attempting to join environment {0}...", path);
#if TDS || HA
if (opts.Transactional)
{
openOpts |= EnvOpenOptions.TransactionDefaults;
}
#endif
try
{
env.Open(path, openOpts);
opened = true;
#if TDS || HA
if (opts.Transactional)
env.SetEnvironmentTransactionCheckpoint(false, 1, 0);
#endif
}
catch (FigaroEnvException fee)
{
if (opts.Create)
{
openOpts ^= EnvOpenOptions.UseEnvironment;
openOpts |= EnvOpenOptions.Create;
// if the create flag is set, run recovery mode - just in case
if (opts.Transactional)
{
openOpts |= EnvOpenOptions.Recover;
}
}
else
{
Verbose("Error opening environment: {0}", fee.Message);
Verbose(
"Skipping environment usage. To explicitly use an environment where none exist, specify the create flag at startup.");
adopt = false;
#if TDS || HA
if (options.Transactional)
{
options.Transactional = false;
Warn("Switching to non-transactional mode.");
}
#endif
env.Close();
env.Dispose(); // get rid of it
env = null;
}
}
catch (RunRecoveryException)
{
#if TDS || HA
openOpts ^= EnvOpenOptions.Register;
openOpts |= EnvOpenOptions.Recover;
#endif
// recover flag requires create to be specified
if (openOpts.ToString().Contains(EnvOpenOptions.UseEnvironment.ToString()))
openOpts ^= EnvOpenOptions.UseEnvironment;
}
// try again
#if TDS || HA
if (openOpts.ToString().Contains(EnvOpenOptions.InitLog.ToString()))
if (env != null) env.SetLogOptions(EnvLogOptions.AutoRemove, true);
#endif
if (adopt)
{
if (!opened) env.Open(path, openOpts);
msg("Environment opened successfully.");
}
#endif
#if TDS || HA
mgr = adopt ? new XmlManager(env, ManagerInitOptions.AllOptions) :
new XmlManager(ManagerInitOptions.AllowAutoOpen | ManagerInitOptions.AllowExternalAccess);
#else
mgr = new XmlManager(ManagerInitOptions.AllowAutoOpen | ManagerInitOptions.AllowExternalAccess);
#endif
updateContext = mgr.CreateUpdateContext();
queryContext = mgr.CreateQueryContext(EvaluationType.Eager);
}
#if TDS || HA
static void env_OnMessage(object sender, MsgEventArgs e)
{
msg("{0}", e.Message);
}
void env_OnErr(object sender, ErrEventArgs e)
{
Error("{0} {1}", e.Prefix ?? "[FigaroEnv]", e.Message);
}
#endif
public void Abort()
{
#if TDS || HA
if (env == null || trans == null) return;
trans.Abort();
trans.Dispose();
trans = null;
msg("Transaction aborted.");
#endif
}
public void AddAlias(string alias)
{
if (containers.Count < 1)
{
Error("You must create and/or open a container first!");
return;
}
containers.Peek().AddAlias(alias);
msg("alias '{0}' added to container '{1}'.", alias, containers.Peek().Name);
}
public void AddAlias(string containerName, string alias)
{
var c = (from cont in containers where cont.Name == containerName select cont).ToList();
if (!c.Any())
{
Error("Container {0} not found in the stack.", containerName);
return;
}
c.First().AddAlias(alias);
msg("alias '{0}' added to container '{1}'.", alias, containerName);
}
public void AddIndex(string ns, string nodeName, string index)
{
var idx = new IndexingStrategy(index);
#if TDS || HA
if (env != null && env.Transactional)
{
containers.Peek().AddIndex(trans, ns, nodeName, idx, updateContext);
}
else
{
#endif
containers.Peek().AddIndex(ns, nodeName, idx, updateContext);
#if TDS || HA
}
#endif
var sb = new StringBuilder();
sb.AppendFormat(DbxmlResources.SuccessfulAddIndex,
idx.Unique ? DbxmlResources.Unique : DbxmlResources.NonUnique,
idx.NodeType,
idx.KeyType,
idx.PathType,
idx.NodeType,
string.IsNullOrEmpty(nodeName) ? DbxmlResources.None : nodeName,
string.IsNullOrEmpty(ns) ? DbxmlResources.None : ns);
msg(sb.ToString());
}
public void OpenContainer(string containerName, bool validate)
{
var cfg = new ContainerConfig
{
AllowValidation = validate
};
#if TDS || HA
if (env != null && env.Transactional)
{
containers.Push(mgr.OpenContainer(trans, containerName, cfg));
return;
}
#endif
containers.Push(mgr.OpenContainer(containerName, cfg));
if (string.IsNullOrEmpty(containerName))
msg("in-memory container created");
msg("container {0} opened.", containerName);
Verbose("You have {0} {1} open.", containers.Count, containers.Count == 1 ? "container" : "containers");
}
public void Preload(string containerName)
{
Container c = null;
if (containers.Count > 0)
c = containers.Pop();
#if TDS
if (env != null && env.Transactional)
{
containers.Push(mgr.OpenContainer(trans, containerName));
msg("preloaded {0}",containerName);
}
else
{
#endif
containers.Push(mgr.OpenContainer(containerName));
msg("preloaded {0}", containerName);
#if TDS
}
#endif
if (c != null) containers.Push(c);
}
public void Prepare(string query)
{
if (queryExpression != null)
{
queryExpression.Dispose();
queryExpression = null;
}
#if TDS || HA
if (env != null && env.Transactional)
{
queryExpression = mgr.Prepare(trans, query, queryContext);
}
else
{
#endif
queryExpression = mgr.Prepare(query, queryContext);
#if TDS || HA
}
#endif
Verbose("\r\n{0} expression '{1}' prepared.\r\n", queryExpression.IsUpdateExpression ? "update" : "query",query);
}
public void PrintResults(int count, string outputPath)
{
if (queryResults == null || queryResults.Count == 0)
{
Warn("No results to print.");
return;
}
if (count == 0) count = queryResults.Count;
if (count < 0) count = int.MaxValue;
StreamWriter sw = null;
if (!string.IsNullOrEmpty(outputPath))
sw = new StreamWriter(outputPath, false);
try
{
msg(string.Empty);
var j = 0;
while (queryResults.HasNext() && j < count)
{
var doc = queryResults.NextDocument();
msg(doc.ToString());
if (sw != null) sw.WriteLine(doc.ToString());
msg(string.Empty);
j++;
}
if (sw != null)
{
sw.Flush();
sw.Close();
msg("output written to {0}.", outputPath);
}
queryResults.Reset();
}
catch (XmlValueException)
{
int k = 0;
while (queryResults.HasNext() && k < count)
{
var val = queryResults.NextValue().ToString();
msg(val);
if (sw != null) sw.WriteLine(val);
k++;
}
if (sw != null)
{
sw.Flush();
sw.Close();
msg("output written to {0}", outputPath);
}
queryResults.Reset();
}
}
public void PrintNames(int count, string filePath)
{
if (queryResults == null)
{
Warn("No results to print.");
return;
}
if (count == 0) count = queryResults.Count;
//encounter the lazy load scenario
if (count < 0) count = int.MaxValue;
try
{
StreamWriter sw = null;
if (!string.IsNullOrEmpty(filePath))
{
sw = new StreamWriter(filePath, false);
}
var i = 0;
while (queryResults.HasNext() && i < count)
{
var doc = queryResults.NextDocument();
msg(doc.Name);
if (sw != null) sw.WriteLine(doc.Name);
i++;
}
if (sw != null)
{
sw.Flush();
sw.Close();
}
msg(string.Empty);
}
catch (XmlValueException)
{
Warn("query result set is of XmlValue type - no names are available.");
}
}
public void CreateContainer(string containerName, string options, bool validate)
{
var cfg = new ContainerConfig
{
AllowValidation = validate
};
if (options.Equals("in") || options.Equals("n"))
cfg.ContainerType = XmlContainerType.NodeContainer;
if (options.Equals("d") || options.Equals("id"))
cfg.ContainerType = XmlContainerType.WholeDocContainer;
cfg.IndexNodes = options.Equals("id") || options.Equals("in")
? ConfigurationState.On
: ConfigurationState.UseDefault;
#if TDS || HA
if (env != null && env.Transactional)
{
containers.Push(mgr.CreateContainer(trans, containerName, cfg));
return;
}
#endif
containers.Push(mgr.CreateContainer(containerName, cfg));
msg("{0} created and opened.", string.IsNullOrEmpty(containerName) ? "in-memory container" : containerName);
Verbose("You have {0} {1} open.", containers.Count, containers.Count == 1 ? "container" : "containers");
}
public void BeginTransaction()
{
#if TDS || HA
if (env == null || !env.Transactional)
{
Warn(DbxmlResources.TransactionsNotEnabled);
return;
}
if (trans != null)
{
Verbose("Committing transaction before beginning new one...");
trans.Commit(true);
trans.Dispose();
trans = null;
}
trans = mgr.CreateTransaction();
Verbose("Transaction created successfully.");
#endif
}
public void Close(string container)
{
if (containers.Count < 1)
{
msg("no containers to close.\r\n");
return;
}
int i = 0;
#if DEBUG
try
{
#endif
if (string.IsNullOrEmpty(container))
{
// close them all
while (containers.Count > 0)
{
i++;
var c = containers.Pop();
Verbose("closing container {0}...", c.Name);
c.Dispose();
}
msg("closed {0} containers.", i);
return;
}
var l = new List<Container>();
while (containers.Count > 0)
{
var c = containers.Pop();
if (c.Name.Equals(container))
{
msg("container {0} closed.",c.Name);
c.Dispose();
continue;
}
l.Add(c);
}
if (l.Count == 0 && containers.Count == 0) return;
l.Reverse();
i = 0;
foreach (Container cont in l)
{
i++;
containers.Push(cont);
}
msg("You have {0} containers open.\r\n", i);
l.Clear();
#if DEBUG
}
finally
{
GC.Collect(0, GCCollectionMode.Forced);
}
#endif
}
public void Commit()
{
#if TDS || HA
if (env != null && !env.Transactional)
{
Warn(DbxmlResources.TransactionsNotEnabled);
return;
}
if (trans == null)
{
Warn("No transaction exists!");
return;
}
trans.Commit();
trans.Dispose();
trans = null;
Verbose("Transaction committed.");
#endif
}
public void CompactContainer(string containerName)
{
#if TDS || HA
if (env != null && trans != null)
{
mgr.CompactContainer(trans, containerName, updateContext);
msg("Container compacted: {0}", containerName);
return;
}
#endif
mgr.CompactContainer(containerName, updateContext);
msg("Container compacted: {0}", containerName);
}
public void CQuery(string query)
{
#if TDS || HA
if (env != null && env.Transactional)
{
queryResults = mgr.Query(trans, query, queryContext);
msg("{0} objects returned for eager expression '{1}'.", queryResults.Count, query);
return;
}
#endif
if (queryResults != null) queryResults.Dispose();
queryResults = mgr.Query(query, queryContext);
msg("{0} objects returned for eager expression '{1}'.", queryResults.Count, query);
}
public void ContextQuery(string query)
{
#if TDS || HA
if (env != null && env.Transactional)
{
using (var exp = mgr.Prepare(trans, query, queryContext))
{
Verbose("query: \r\n{0}\r\nquery plan: \r\n{1}\r\n", exp.Query, exp.QueryPlan);
queryResults.Reset();
var tmpRes = mgr.CreateXmlResults();
int j = 0;
while (queryResults.HasNext())
{
var xv = queryResults.NextValue();
using (var val = exp.Execute(trans, xv, queryContext, queryOptions))
{
while (val.HasNext())
{
tmpRes.Add(val.NextValue());
j++;
}
}
}
msg("query returned {0} results.", j);
// last known results, even if nothing returned
queryResults.Dispose();
queryResults = tmpRes;
}
return;
}
#endif
using (var exp = mgr.Prepare(query, queryContext))
{
Verbose("query: \r\n{0}\r\nquery plan: \r\n{1}\r\n", exp.Query, exp.QueryPlan);
queryResults.Reset();
var tmpRes = mgr.CreateXmlResults();
int j = 0;
while (queryResults.HasNext())
{
var xv = queryResults.NextValue();
using (var val = exp.Execute(xv, queryContext, queryOptions))
{
while (val.HasNext())
{
tmpRes.Add(val.NextValue());
j++;
}
}
}
msg("query returned {0} results.", j);
// last known results, even if nothing returned
queryResults.Dispose();
queryResults = tmpRes;
}
}
public void DeleteIndex(string ns, string nodeName, string index)
{
#if TDS || HA
if (env != null && env.Transactional)
{
containers.Peek().DeleteIndex(trans, ns, nodeName, index, updateContext);
msg("index {0} deleted from container {1}.", index, containers.Peek().Name);
return;
}
#endif
containers.Peek().DeleteIndex(ns, nodeName, index, updateContext);
msg("index {0} deleted from container {1}.", index, containers.Peek().Name);
}
public void GetDocuments(string docName)
{
if (queryResults != null)
queryResults.Dispose();
#if TDS || HA
if (env != null && env.Transactional)
{
if (!string.IsNullOrEmpty(docName))
{
queryResults = mgr.CreateXmlResults();
using (var lookup = mgr.CreateIndexLookup(containers.Peek(), "http://www.sleepycat.com/2002/dbxml", "name",
"node-metadata-equality-string", new XmlValue(docName), IndexLookupOperation.Equal))
{
queryResults = lookup.Execute(trans, queryContext, IndexLookupOptions.CacheDocuments);
}
}
else
{
queryResults = containers.Peek().GetAllDocuments(trans, GetAllDocumentOptions.None);
}
// everything comes back lazy - so count it the hard way.
if (queryResults.Count < 0)
{
int i = 0;
if (queryResults.Current != null)
{
while (queryResults.HasNext())
{
queryResults.NextValue();
i++;
}
queryResults.Reset();
}
msg("{0} {1} retrieved.", i, queryResults.Count == 1 ? "document" : "documents");
}
else
msg("{0} {1} retrieved.", queryResults.Count, queryResults.Count == 1 ? "document" : "documents");
return;
}
#endif
if (!string.IsNullOrEmpty(docName))
{
queryResults = mgr.CreateXmlResults();
using (var lookup = mgr.CreateIndexLookup(containers.Peek(), "http://www.sleepycat.com/2002/dbxml", "name",
"node-metadata-equality-string", new XmlValue(docName), IndexLookupOperation.Equal))
{
queryResults = lookup.Execute(queryContext, IndexLookupOptions.CacheDocuments);
}
}
else
{
queryResults = containers.Peek().GetAllDocuments();
}
// it came back lazy - so count it the hard way.
if (queryResults.Count < 0)
{
int i = 0;
if (queryResults.Current != null)
{
while (queryResults.HasNext())
{
queryResults.NextValue();
i++;
}
queryResults.Reset();
}
msg("{0} {1} retrieved.", i, queryResults.Count == 1 ? "document" : "documents");
}
else
msg("{0} {1} retrieved.", queryResults.Count, queryResults.Count == 1 ? "document" : "documents");
}
public void GetMetadata(string docName)
{
XmlDocument doc;
#if TDS || HA
if (env != null && env.Transactional)
{
doc = containers.Peek().GetDocument(trans, docName, RetrievalModes.None);
}
else
{
#endif
doc = containers.Peek().GetDocument(docName, RetrievalModes.None);
#if TDS || HA
}
#endif
var iter = doc.GetMetadataIterator();
msg("Metadata for document {0}:", doc.Name);
while (iter.Next())
{
msg("{0}:{1}\t{2}", string.IsNullOrEmpty(iter.Uri) ? "{}" : "{" + iter.Uri + "}", iter.Name, iter.Value);
}
msg(string.Empty);
}
public void Info(bool all)
{
if (!all)
{
msg("Container name: {0}", containers.Peek().Name);
msg(" compression enabled: {0}", containers.Peek().CompressionEnabled);
msg(" container state: {0}", containers.Peek().ContainerState);
msg(" container type: {0}", containers.Peek().ContainerType);
msg(" index nodes: {0}", containers.Peek().IndexNodes);
msg(" page size: {0}", containers.Peek().PageSize);
msg(" transactional: {0}", containers.Peek().Transactional);
msg(" alias: {0}", containers.Peek().Settings.Alias);
msg(" allow validation: {0}", containers.Peek().Settings.AllowValidation);
msg(" checksum enabled: {0}", containers.Peek().Settings.Checksum);
#if TDS
msg(" encrypted: {0}", containers.Peek().Settings.Encrypted);
msg(" multiversion concurrency control (MVCC): {0}", containers.Peek().Settings.MultiVersion);
msg(" memory mapped: {0}", containers.Peek().Settings.NoMMap);
msg(" read-only: {0}", containers.Peek().Settings.ReadOnly);
msg(" threaded: {0}", containers.Peek().Settings.Threaded);
#endif
#if TDS
msg(" read uncommitted: {0}", containers.Peek().Settings.ReadUncommitted);
msg(" non-durable transactions: {0}", containers.Peek().Settings.TransactionNotDurable);
#endif
msg(" document id sequence increment: {0}", containers.Peek().Settings.SequenceIncrement);
return;
}
foreach (var container in containers)
{
msg("==========================");
msg("Container name: {0}", container.Name);
msg(" compression enabled: {0}", container.CompressionEnabled);
msg(" container state: {0}", container.ContainerState);
msg(" container type: {0}", container.ContainerType);
msg(" index nodes: {0}", container.IndexNodes);
msg(" page size: {0}", container.PageSize);
msg(" transactional: {0}", container.Transactional);
msg(" alias: {0}", container.Settings.Alias);
msg(" allow validation: {0}", container.Settings.AllowValidation);
msg(" checksum enabled: {0}", container.Settings.Checksum);
#if TDS
msg(" encrypted: {0}", container.Settings.Encrypted);
msg(" multiversion concurrency control (MVCC): {0}", container.Settings.MultiVersion);
msg(" memory mapped: {0}", container.Settings.NoMMap);
msg(" threaded: {0}", container.Settings.Threaded);
msg(" read-only: {0}", container.Settings.ReadOnly);
#endif
msg(" document id sequence increment: {0}", container.Settings.SequenceIncrement);
#if TDS
msg(" read uncommitted: {0}", container.Settings.ReadUncommitted);
msg(" non-durable transactions: {0}", container.Settings.TransactionNotDurable);
#endif
}
}
public void ListIndexes()
{
var spec = containers.Peek().GetIndexSpecification();
msg("===");
int i = 0;
var idx = spec.Next();
while (idx != null)
{
i++;
msg("Index: {0}\r\n\tfor node ({1}):{2}", idx.Index, idx.Namespace, idx.NodeName);
idx = spec.Next();
}
msg("{0} indexes found in {1}.\r\n", i, containers.Peek().Name);
}
public void LookupEdgeIndex(string index, string namespaceUri, string nodeName,
string parentNamespaceUri, string parentNodeName, string operation, string value)
{
var lookup = mgr.CreateIndexLookup(containers.Peek(), namespaceUri, nodeName, index, string.IsNullOrEmpty(value) ? null : new XmlValue(value),
string.IsNullOrEmpty(operation) ? IndexLookupOperation.None : getOperation(operation));
#if TDS || HA
if (env != null && env.Transactional)
{
queryResults = lookup.Execute(trans, queryContext);
msg("lookup retrieved {0} records.", GetCount());
return;
}
#endif
queryResults = lookup.Execute(queryContext);
msg("lookup retrieved {0} records.", GetCount());
}
public void LookupIndex(string index, string namespaceUri, string nodeName,
string operation, string value)
{
var lookup = mgr.CreateIndexLookup(containers.Peek(), namespaceUri, nodeName, index, string.IsNullOrEmpty(value) ? null : new XmlValue(value),
string.IsNullOrEmpty(operation) ? IndexLookupOperation.None : getOperation(operation));
#if TDS || HA
if (env != null && env.Transactional)
{
queryResults = lookup.Execute(trans, queryContext);
if (queryContext.EvaluationType == EvaluationType.Eager)
msg("objects returned for eager index lookup '{0}': {1} objects", index, queryResults.Count);
else
{
msg("lazy index lookup '{0}' completed.", index);
}
return;
}
#endif
queryResults = lookup.Execute(queryContext);
if (queryContext.EvaluationType == EvaluationType.Eager)
msg("objects returned for eager index lookup '{0}': {1} objects", index, queryResults.Count);
else
{
msg("lazy index lookup '{0}' completed.", index);
}
}
public void LookupStatistics(string index, string namespaceUri, string nodeName,
string parentNamespaceUri, string parentNodeName, string value)
{
KeyStatistics stats;
if (string.IsNullOrEmpty(parentNamespaceUri))
{
#if TDS || HA
if (env != null && env.Transactional)
{
stats = containers.Peek().LookupStatistics(trans, namespaceUri, nodeName, index,
string.IsNullOrEmpty(value) ? null : new XmlValue(value));
}
else
{
#endif
stats = containers.Peek().LookupStatistics(namespaceUri, nodeName, index,
string.IsNullOrEmpty(value) ? null : new XmlValue(value));
#if TDS || HA
}
#endif
}
else
{
#if TDS || HA
if (env != null && env.Transactional)
{
stats = containers.Peek().LookupStatistics(trans, namespaceUri, nodeName, parentNamespaceUri, parentNodeName,
index, string.IsNullOrEmpty(value) ? null : new XmlValue(value));
}
else
{
#endif
stats = containers.Peek().LookupStatistics(namespaceUri, nodeName, parentNamespaceUri, parentNodeName,
index, string.IsNullOrEmpty(value) ? null : new XmlValue(value));
#if TDS || HA
}
#endif
}
msg("Number of indexed keys: {0} Number of unique keys: {1} Sum key value size: {2}", (long)stats.IndexedKeys, stats.UniqueKeys, (long)stats.SumKeyValueSize);
}
private int GetCount()
{
if (queryResults.Count >= 0) return queryResults.Count;
var i = 0;
while (queryResults.HasNext())
{
queryResults.NextValue();
i++;
}
queryResults.Reset();
return i;
}
private static IndexLookupOperation getOperation(string op)
{
switch (op.Trim())
{
case ">":
return IndexLookupOperation.GreaterThan;
case ">=":
case "=>":
return IndexLookupOperation.GreaterThanOrEqual;
case "<":
return IndexLookupOperation.LessThan;
case "<=":
case "=<":
return IndexLookupOperation.LessThanOrEqual;
default:
return IndexLookupOperation.Equal;
}
}
public void PutDocuments(string filesPath, string filter)
{
if (containers.Count < 1)
{
Warn("You must open a container first.");
return;
}
if (string.IsNullOrEmpty(filter)) filter = "*.xml";
var files = Directory.GetFiles(filesPath, filter, SearchOption.TopDirectoryOnly);
#if TDS
XmlTransaction t = null;
if (env != null && env.Transactional)
t = trans.CreateChild(TransactionType.SyncTransaction);
#endif
foreach (var file in files)
{
Verbose("inserting document {0}...", Path.GetFileNameWithoutExtension(file));
#if TDS
if (env != null && env.Transactional)
{
containers.Peek().PutDocument(t, file, updateContext);
}
else
{
#endif
containers.Peek().PutDocument(file, updateContext);
#if TDS
}
#endif
}
#if TDS
if (t != null)
{
Verbose("Committing child transaction...");
t.Commit(true);
}
#endif
Verbose("syncing container {0}...", containers.Peek().Name);
containers.Peek().Sync();
msg("{0} documents inserted into {1} container.", files.Length, containers.Peek().Name);
}
public void PutDocumentByFile(string filePath)
{
#if TDS
if (env != null && trans != null)
{
containers.Peek().PutDocument(trans, filePath, updateContext);
return;
}
#endif
containers.Peek().PutDocument(filePath, updateContext, PutDocumentOptions.None);
}
public void PutDocumentByString(string contents, string name)
{
#if TDS
if (env != null && trans != null)
{
containers.Peek().PutDocument(trans, name, contents, updateContext,
string.IsNullOrEmpty(name)
? PutDocumentOptions.GenerateFileName
: PutDocumentOptions.None);
return;
}
#endif
containers.Peek().PutDocument(name, contents, updateContext,
string.IsNullOrEmpty(name)