-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathANamespaceAccess.cs
2644 lines (2382 loc) · 118 KB
/
ANamespaceAccess.cs
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
// Ignore Spelling: Pnamespace
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Aerospike.Client;
using LINQPad;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using LPU = LINQPad.Util;
namespace Aerospike.Database.LINQPadDriver.Extensions
{
/// <summary>
/// The different Aerospike DB Platforms
/// </summary>
public enum DBPlatforms
{
None = -1,
/// <summary>
/// The non-managed platform
/// </summary>
Native = 0,
/// <summary>
/// The DBaaS platform
/// </summary>
Cloud = 1
}
/// <summary>
/// A class used to define Aerospike Namespaces.
/// </summary>
[DebuggerDisplay("{ToString()}")]
public class ANamespaceAccess
{
private readonly static List<ANamespaceAccess> ANamespacesList = new List<ANamespaceAccess>();
#region Constructors
private ANamespaceAccess(string ns,
string[] binNames,
AerospikeConnection dbConnection,
Policy readPolicy,
WritePolicy writePolicy,
QueryPolicy queryPolicy,
ScanPolicy scanPolicy,
List<SetRecords> sets = null)
{
this.AerospikeConnection = dbConnection;
this.Namespace = ns;
this.BinNames = binNames is null
? Array.Empty<string>()
: Helpers.RemoveDups(binNames);
this.DefaultWritePolicy = writePolicy ?? new WritePolicy();
this.DefaultQueryPolicy = queryPolicy ?? new QueryPolicy();
this.DefaultReadPolicy = readPolicy ?? new QueryPolicy();
this.DefaultScanPolicy = scanPolicy ?? new ScanPolicy();
if(sets is not null)
this._sets = sets;
}
/// <summary>
/// Used for a placeholder.
/// </summary>
/// <param name="ns">Namespace</param>
/// <param name="binNames">A array of bin names associated to this namespace</param>
public ANamespaceAccess(string ns, string[] binNames = null)
: this(ns, binNames, null, null, null, null, null)
{
lock(ANamespacesList)
{
ANamespacesList.RemoveAll(i => i.Namespace == this.Namespace);
ANamespacesList.Add(this);
}
}
public ANamespaceAccess(IDbConnection dbConnection, string ns, string[] binNames, bool sc)
: this(dbConnection as AerospikeConnection,
ns,
binNames,
sc)
{ }
public ANamespaceAccess(AerospikeConnection dbConnection, string ns, string[] binNames, bool sc)
: this(ns,
binNames,
dbConnection,
new QueryPolicy(dbConnection.AerospikeClient.QueryPolicyDefault),
new WritePolicy(dbConnection.AerospikeClient.WritePolicyDefault),
new QueryPolicy(dbConnection.AerospikeClient.QueryPolicyDefault),
new ScanPolicy(dbConnection.AerospikeClient.ScanPolicyDefault))
{
lock(ANamespacesList)
{
ANamespacesList.RemoveAll(i => i.Namespace == this.Namespace);
ANamespacesList.Add(this);
}
this.IsStrongConsistencyMode = sc;
}
public ANamespaceAccess(IDbConnection dbConnection,
LPNamespace lpNamespace,
string ns,
string[] binNames,
bool sc)
: this(dbConnection as AerospikeConnection,
ns,
binNames,
sc)
{
this.LPnamespace = lpNamespace;
}
public ANamespaceAccess(ANamespaceAccess clone, Expression expression)
: this(clone.Namespace,
clone.BinNames,
clone.AerospikeConnection,
new(clone.DefaultReadPolicy)
{
filterExp = expression
},
new(clone.DefaultWritePolicy),
new(clone.DefaultQueryPolicy)
{
filterExp = expression
},
new(clone.DefaultScanPolicy),
clone._sets)
{
this.LPnamespace = clone.LPnamespace;
this.IsStrongConsistencyMode = clone.IsStrongConsistencyMode;
this.AerospikeTxn = clone.AerospikeTxn;
}
public ANamespaceAccess(ANamespaceAccess clone,
Policy readPolicy = null,
WritePolicy writePolicy = null,
QueryPolicy queryPolicy = null,
ScanPolicy scanPolicy = null)
: this(clone.Namespace,
clone.BinNames,
clone.AerospikeConnection,
readPolicy ?? new(clone.DefaultReadPolicy),
writePolicy ?? new(clone.DefaultWritePolicy),
queryPolicy ?? new(clone.DefaultQueryPolicy),
scanPolicy ?? new(clone.DefaultScanPolicy),
clone._sets)
{
this.LPnamespace = clone.LPnamespace;
this.IsStrongConsistencyMode = clone.IsStrongConsistencyMode;
this.AerospikeTxn = clone.AerospikeTxn;
}
/// <summary>
/// Initializes a new instance of <see cref="ANamespaceAccess"/> as an Aerospike transactional unit.
/// If <see cref="Commit"/> method is not called the server will abort (rollback) this transaction.
/// </summary>
/// <param name="baseNS">Base Namespace instance</param>
/// <param name="txn">The Aerospike <see cref="Txn"/> instance</param>
/// <exception cref="System.ArgumentNullException">txn</exception>
/// <exception cref="System.ArgumentNullException">clone</exception>
/// <seealso cref="CreateTransaction(int)"/>
/// <seealso cref="Commit"/>
/// <seealso cref="Abort"/>
public ANamespaceAccess(ANamespaceAccess baseNS, Txn txn)
: this(baseNS,
new(baseNS.DefaultReadPolicy)
{
Txn = txn
},
new(baseNS.DefaultWritePolicy)
{
Txn = txn
},
new(baseNS.DefaultQueryPolicy)
{
Txn = txn
},
new(baseNS.DefaultScanPolicy)
{
Txn = txn
})
{
if(txn is null) throw new ArgumentNullException(nameof(txn));
this.AerospikeTxn = txn;
this._sets = this._sets.Select(s => s.TurnIntoTrx(this)).ToList();
if(!this.IsStrongConsistencyMode)
{
Console.Write(LINQPad.Util.WithStyle("Warning", "color:black;background-color:orange"));
Console.Write(": ");
Console.WriteLine(LINQPad.Util.WithStyle($"MRTs should be used within a Strong Consistency namespace. {this.Namespace} is an AP namespace.", "color:darkgreen"));
}
}
/// <summary>
/// Clones the specified instance providing new policies, if provided.
/// </summary>
/// <param name="newReadPolicy">The new read policy.</param>
/// <param name="newWritePolicy">The new write policy.</param>
/// <param name="newQueryPolicy">The new query policy.</param>
/// <param name="newScanPolicy">The new scan policy.</param>
/// <returns>New clone of <see cref="ANamespaceAccess"/> instance.</returns>
public ANamespaceAccess Clone(Policy newReadPolicy = null,
WritePolicy newWritePolicy = null,
QueryPolicy newQueryPolicy = null,
ScanPolicy newScanPolicy = null)
=> new ANamespaceAccess(this,
newReadPolicy,
newWritePolicy,
newQueryPolicy,
newScanPolicy);
#endregion
#region methods and properties
/// <summary>
/// The Aerospike Platform this namespace is associated. <see cref="DBPlatforms"/>
/// </summary>
public DBPlatforms DBPlatform { get => this.AerospikeConnection?.DBPlatform ?? DBPlatforms.None; }
/// <summary>
/// Finds the namespace.
/// </summary>
/// <param name="nsName">Name of the namespace.</param>
/// <returns>ANamespaceAccess or null</returns>
public static ANamespaceAccess FindNamespace(string nsName)
{
lock(ANamespacesList)
{
return ANamespacesList.FirstOrDefault(i => i.Namespace == nsName);
}
}
internal static long ForceExplorerRefresh = 0;
/// <summary>
/// Refreshes the Connection Explorer
/// </summary>
#pragma warning disable CA1822 // Mark members as static
public async void RefreshExplorer()
#pragma warning restore CA1822 // Mark members as static
{
await DynamicDriver.GetConnection()?.CXInfo?.ForceRefresh();
}
internal static void UpdateExplorer()
{
Interlocked.Increment(ref ForceExplorerRefresh);
}
/// <summary>
/// This will add a new set that wasn't already created.
/// </summary>
/// <param name="setName"></param>
/// <param name="bins"></param>
/// <returns></returns>
private bool AddDynamicSet(string setName, IEnumerable<Bin> bins)
{
//System.Diagnostics.Debugger.Launch();
if (string.IsNullOrEmpty(setName))
return false;
var existingBins = bins.Where(b => b.value.Object != null);
var removedBins = bins.Where(b => b.value.Object is null || b.value.IsNull);
var result = false;
if(existingBins.Any())
result = this.AddDynamicSet(setName,
existingBins.Select(b => new LPSet.BinType(b.name,
b.value.Object.GetType(),
false,
false)));
return result;
}
private bool AddDynamicSet(string setName, IEnumerable<LPSet.BinType> bins)
{
if (string.IsNullOrEmpty(setName))
return false;
lock (this)
{
var recordSet = this.Sets.FirstOrDefault(s => s.SetName == setName);
if (recordSet == null)
{
var binNames = bins?.Select(b => b.BinName).ToArray();
var lpSet = new LPSet(this.LPnamespace, setName, bins);
var accessSet = new SetRecords(lpSet, this, setName, binNames);
this.LPnamespace?.TryAddSet(setName, bins);
this._sets.Add(accessSet);
this.BinNames = this.BinNames.Concat(binNames)
.Distinct().ToArray();
if (this.NullSet == null)
{
this.AddDynamicSet(LPSet.NullSetName, bins);
}
else
{
foreach (var b in bins)
{
this.NullSet.TryAddBin(b.BinName, b.DataType, false);
}
}
this.TryAddBins(accessSet, bins, true);
return true;
}
return this.TryAddBins(recordSet, bins);
}
}
private bool RemoveBinsFromSet(string setName, IEnumerable<LPSet.BinType> removeBins)
{
if (string.IsNullOrEmpty(setName))
return false;
lock (this)
{
var recordSet = this.Sets.FirstOrDefault(s => s.SetName == setName);
if (recordSet != null)
{
var binNames = removeBins?.Select(b => b.BinName).ToArray();
this.LPnamespace?.TryRemoveSet(setName, removeBins);
this.BinNames = this.BinNames
.Where(n => !removeBins.Any(b => b.BinName == n))
.ToArray();
this.TryRemoveBins(recordSet, removeBins, true);
return true;
}
return false;
}
}
private bool TryAddBins(SetRecords set, IEnumerable<LPSet.BinType> bins, bool forceExplorerUpdate = false)
{
bool result = false;
foreach (var b in bins)
{
result = set.TryAddBin(b.BinName, b.DataType, false) || result;
if (this.NullSet != null)
result = this.NullSet.TryAddBin(b.BinName, b.DataType, false) || result;
}
if (result || forceExplorerUpdate)
UpdateExplorer();
return result;
}
internal bool TryAddBin(string binName)
{
if(this.BinNames.Contains(binName)) return false;
this.BinNames = this.BinNames.Append(binName).ToArray();
return true;
}
private bool TryRemoveBins(SetRecords set, IEnumerable<LPSet.BinType> removeBins, bool forceExplorerUpdate)
{
bool result = false;
foreach (var b in removeBins)
{
result = set.TryRemoveBin(b.BinName, false) || result;
if (this.NullSet != null)
result = this.NullSet.TryRemoveBin(b.BinName, false) || result;
}
if (result || forceExplorerUpdate)
UpdateExplorer();
return result;
}
internal bool TryRemoveBin(string binName)
{
if (this.BinNames.Contains(binName))
{
this.BinNames = this.BinNames
.Where(n => n != binName).ToArray();
return true;
}
return false;
}
public LPNamespace LPnamespace { get; }
private List<SetRecords> _sets = new List<SetRecords>();
/// <summary>
/// Returns the associated set instances for this namespace.
/// </summary>
/// <remarks>
/// The drag and drop set instances from the connection pane in LinqPad are different instances as defined here...
/// </remarks>
/// <seealso cref="this[string]"/>
/// <seealso cref="Exists(string)"/>
public IEnumerable<SetRecords> Sets
{
get
{
lock (this)
{
if (this._sets.Any()) return this._sets;
}
var setProps = this.GetType().GetProperties()
.Where(p => p.PropertyType.IsSubclassOf(typeof(SetRecords)))
.Select(p => p.PropertyType);
var setInstances = new List<SetRecords>();
foreach (var prop in setProps)
{
setInstances.Add((SetRecords)Activator.CreateInstance(prop, this));
}
return this._sets = setInstances.ToList();
}
}
/// <summary>
/// Gets the names of th sets associate with this namespace.
/// </summary>
/// <value>A collection of name of sets.</value>
public IEnumerable<string> SetNames => this.Sets.Select(s => s.SetName ?? LPSet.NullSetName);
/// <summary>
/// Returns the Set instance or null indicating the set doesn't exists in this namespace.
/// </summary>
/// <param name="setName">The name of the Aerospike set</param>
/// <returns>A <see cref="SetRecords"/> instance or null</returns>
/// <seealso cref="Exists(string)"/>
public SetRecords this[string setName]
{
get => setName == LPSet.NullSetName
? this.Sets.FirstOrDefault(s => s.SetName is null)
: this.Sets.FirstOrDefault(s => s.SetName == setName);
}
/// <summary>
/// Gets a value indicating whether this namespace is in strong consistency mode.
/// </summary>
/// <value><c>true</c> if this instance is strong consistency mode; otherwise, <c>false</c>.</value>
/// <seealso href="https://aerospike.com/docs/server/guide/consistency"/>
public bool IsStrongConsistencyMode { get; }
public override string ToString()
{
string txn = string.Empty;
if(this.TransactionId.HasValue)
txn = " TXN";
if(this.BinNames.Length == 0)
return $"{this.Namespace}{txn}";
return $"{this.Namespace}{{{string.Join(',', this.BinNames)}}} {txn}";
}
#endregion
#region Aerospike API items
/// <summary>
/// Determines if a set exists within this namespace.
/// </summary>
/// <param name="setName">set name</param>
/// <returns>
/// True if the sets exists, otherwise false.
/// </returns>
/// <seealso cref="this[string]"/>
public bool Exists(string setName) => setName == LPSet.NullSetName || this.Sets.Any(s => s.SetName == setName);
/// <summary>
/// Returns the Aerospike Null Set for this namespace.
/// The Null Set will contain all the records with a namespace.
/// </summary>
public SetRecords NullSet { get => this[LPSet.NullSetName]; }
public string Namespace { get; }
//public string Name { get; }
/// <summary>
/// Returns all the bins used within this namespace.
/// </summary>
public string[] BinNames { get; private set; }
public AerospikeConnection AerospikeConnection { get; }
/// <summary>
/// <see href="https://docs.aerospike.com/apidocs/csharp/html/t_aerospike_client_querypolicy"/>
/// </summary>
public QueryPolicy DefaultQueryPolicy { get; }
/// <summary>
/// <see href="https://docs.aerospike.com/apidocs/csharp/html/t_aerospike_client_querypolicy"/>
/// </summary>
public WritePolicy DefaultWritePolicy { get; }
/// <summary>
/// <see href="https://docs.aerospike.com/apidocs/csharp/html/t_aerospike_client_policy"/>
/// </summary>
public Policy DefaultReadPolicy { get; }
/// <summary>
/// <see href="https://docs.aerospike.com/apidocs/csharp/html/t_aerospike_client_scanpolicy"/>
/// </summary>
public ScanPolicy DefaultScanPolicy { get; }
/// <summary>
/// Gets the aerospike <see cref="Aerospike.Client.Txn"/> instance or null to indicate that it is not within a transaction.
/// </summary>
/// <value>The aerospike <see cref="Aerospike.Client.Txn"/> instance or null</value>
public Txn AerospikeTxn { get; }
/// <summary>
/// Returns the transaction identifier or null to indicate not a transactional unit.
/// </summary>
public long? TransactionId => this.AerospikeTxn?.Id;
/// <summary>
/// Creates an Aerospike transaction where all operations will be included in this transactional unit.
/// </summary>
/// <param name="timeout">
/// MRT timeout in seconds. The timer starts when the MRT monitor record is created.
/// This occurs when the first command in the MRT is executed. If the timeout is reached before
/// a commit or abort is called, the server will expire and rollback the MRT.
/// Defaults to 10 seconds.
/// </param>
/// <returns>Transaction Namespace instance</returns>
/// <seealso cref="CreateTransaction(string, int)"/>
/// <seealso cref="Commit"/>
/// <seealso cref="Abort"/>
public ANamespaceAccess CreateTransaction(int timeout = 10) => new(this, new Txn() { Timeout = timeout });
/// <summary>
/// Creates an Aerospike transaction where all operations will be included in this transactional unit.
/// </summary>
/// <param name="setName">
/// Name of the set to create the transaction on.
/// If the set does not exists, it will be dynamically created.
/// </param>
/// <param name="timeout">
/// MRT timeout in seconds. The timer starts when the MRT monitor record is created.
/// This occurs when the first command in the MRT is executed. If the timeout is reached before
/// a commit or abort is called, the server will expire and rollback the MRT.
/// Defaults to 10 seconds.
/// </param>
/// <returns>Transaction Set instance</returns>
/// <seealso cref="CreateTransaction(int)"/>
public SetRecords CreateTransaction(string setName, int timeout = 10)
{
var set = this[setName];
if(set is null)
{
this.AddDynamicSet(setName, Enumerable.Empty<LPSet.BinType>());
set = this[setName];
}
return set.CreateTransaction(timeout);
}
/// <summary>
/// Attempt to commit the given multi-record transaction. First, the expected record versions are
/// sent to the server nodes for verification.If all nodes return success, the command is
/// committed. Otherwise, the transaction is aborted.
/// <p>
/// Requires server version 8.0+
/// </p>
/// </summary>
/// <param name="useTxn">
/// If provide, this <see cref="Txn"/> is used, instead of the namespace's Txn (if thee is one).
/// </param>
/// <seealso cref="CreateTransaction(int)"/>
/// <seealso cref="Abort"/>
public CommitStatus.CommitStatusType Commit(Txn useTxn = null)
=> this.AerospikeTxn is null && useTxn is null
? CommitStatus.CommitStatusType.CLOSE_ABANDONED
: this.AerospikeConnection.Commit(useTxn ?? this.AerospikeTxn);
/// <summary>
/// Abort and rollback the given multi-record transaction.
/// <p>
/// Requires server version 8.0+
/// </p>
/// </summary>
/// <param name="useTxn">
/// If provide, this <see cref="Txn"/> is used, instead of the namespace's Txn (if thee is one).
/// </param>
/// <seealso cref="CreateTransaction(int)"/>
/// <seealso cref="Commit"/>
public AbortStatus.AbortStatusType Abort(Txn useTxn = null)
=> this.AerospikeTxn is null && useTxn is null
? AbortStatus.AbortStatusType.ROLL_BACK_ABANDONED
: this.AerospikeConnection.Abort(useTxn ?? this.AerospikeTxn);
#region Get Methods
/// <summary>
/// Gets all records in a set
/// </summary>
/// <param name="setName">Set name or null for the null set</param>
/// <param name="bins">bins you wish to get. If not provided all bins for a record</param>
/// <returns>An array of records in the set</returns>
/// <seealso cref="AsEnumerable(string, Exp)"/>
/// <seealso cref="GetRecords(string, string, string[])"/>
/// <seealso cref="DefaultQueryPolicy"/>
public ARecord[] GetRecords(string setName, params string[] bins)
=> GetRecords(this.Namespace, setName, bins);
/// <summary>
/// Gets all records in a namespace and/or set
/// </summary>
/// <param name="nsName">namespace</param>
/// <param name="setName">Set name or null for the null set</param>
/// <param name="bins">bins you wish to get. If not provided all bins for a record</param>
/// <returns>An array of records in the set</returns>
/// <seealso cref="AsEnumerable(string, Exp)"/>
/// <seealso cref="GetRecords(string, string[])"/>
/// <seealso cref="DefaultQueryPolicy"/>
public ARecord[] GetRecords([NotNull] string nsName, string setName, params string[] bins)
{
var recordSets = new List<ARecord>();
using(var recordset = this.AerospikeConnection
.AerospikeClient
.Query(this.DefaultQueryPolicy,
string.IsNullOrEmpty(setName) || setName == LPSet.NullSetName
? new Statement() { Namespace = nsName, BinNames = bins }
: new Statement() { Namespace = nsName, SetName = setName, BinNames = bins }))
while(recordset.Next())
{
recordSets.Add(new ARecord(this,
recordset.Key,
recordset.Record,
bins,
dumpType: this.AerospikeConnection.RecordView));
}
return recordSets.ToArray();
}
/// <summary>
/// Returns IEnumerable><see cref="ARecord"/>< for the records of this set based on <see cref="DefaultScanPolicy"/> or <paramref name="filterExpression"/>.
/// Note: The records' return order may vary between executions.
/// </summary>
/// <param name="setName">Set name or null for the null set</param>
/// <param name="filterExpression">A Filter <see cref="Client.Exp"/> used to obtain the collection of records.</param>
/// <seealso cref="GetRecords(string, string[])"/>
/// <seealso cref="GetRecords(string, string, string[])"/>
/// <seealso cref="DefaultScanPolicy"/>
public IEnumerable<ARecord> AsEnumerable(string setName, Client.Exp filterExpression = null)
{
var scanPolicy = filterExpression == null
? this.DefaultScanPolicy
: new ScanPolicy(this.DefaultScanPolicy)
{ filterExp = Exp.Build(filterExpression) };
var allRecords = new ConcurrentQueue<ARecord>();
var allTask = Task.Factory.StartNew(() =>
this.AerospikeConnection
.AerospikeClient
.ScanAll(scanPolicy,
this.Namespace,
string.IsNullOrEmpty(setName) || setName == LPSet.NullSetName
? null
: setName,
(key, record)
=> allRecords
.Enqueue(new ARecord(this,
key,
record,
null,
dumpType: this.AerospikeConnection.RecordView))),
cancellationToken: CancellationToken.None,
creationOptions: TaskCreationOptions.DenyChildAttach
| TaskCreationOptions.LongRunning,
scheduler: TaskScheduler.Current);
while(!allTask.IsCompleted)
{
if(allRecords.TryDequeue(out ARecord value))
yield return value;
}
foreach(var record in allRecords.TakeWhile(rec => rec is not null))
{
yield return record;
}
if(allTask.IsFaulted && allTask.Exception is not null)
throw allTask.Exception.InnerExceptions.Count == 1
? allTask.Exception.InnerExceptions[0]
: allTask.Exception;
}
/// <summary>
/// Will retrieve a record based on the <paramref name="primaryKey"/>.
/// </summary>
/// <param name="setName">The name of the Aerospike set</param>
/// <param name="primaryKey">
/// Primary AerospikeKey.
/// This can be a <see cref="Client.Key"/>, <see cref="Value"/>, or <see cref="Bin"/> object besides a native, collection, etc. value/object.
/// </param>
/// <param name="bins">The bins that will be returned</param>
/// <returns>
/// The <see cref="ARecord"/> or null
/// </returns>
/// <seealso cref="Put(string, dynamic, IEnumerable{Bin}, WritePolicy, TimeSpan?)"/>
/// <seealso cref="Put{T}(string, dynamic, string, IEnumerable{T}, WritePolicy, TimeSpan?)"/>
/// <seealso cref="Put{T}(string, dynamic, string, IList{T}, WritePolicy, TimeSpan?)"/>
/// <seealso cref="Put{V}(string, dynamic, IDictionary{string, V}, WritePolicy, TimeSpan?)"/>
/// <seealso cref="Put(string, dynamic, string, object, WritePolicy, TimeSpan?)"/>
/// <seealso cref="Put(ARecord, string, WritePolicy, TimeSpan?)"/>
/// <seealso cref="WriteObject{T}(string, dynamic, T, Func{string, string, object, bool, object}, string, WritePolicy, TimeSpan?)"/>
public ARecord Get(string setName, dynamic primaryKey, params string[] bins)
{
Client.Key pk = Helpers.DetermineAerospikeKey(primaryKey, this.Namespace, setName);
var policy = this.DefaultReadPolicy;
if(pk.userKey.IsNull && policy.sendKey)
{
policy = policy.Clone();
policy.sendKey = false;
}
var record = this.AerospikeConnection
.AerospikeClient
.Get(policy, pk, bins);
var setAccess = this[setName];
return new ARecord(this,
pk,
record,
setAccess?.BinNames,
dumpType: this.AerospikeConnection.RecordView);
}
#endregion
#region Put Methods
/// <summary>
/// Puts (Writes) a DB record based on the provided record including Expiration.
/// Note that if the namespace and/or set is different, this instances's values are used except
/// in the case where the primary key is a digest. In these cases, an <see cref="InvalidOperationException"/> is thrown.
/// </summary>
/// <param name="record">
/// A <see cref="ARecord"/> object used to add or update the associated record.
/// </param>
/// <param name="setName">Set name or null to use the set name defined in the record (default)</param>
/// <param name="writePolicy">
/// The write policy. If not provided , the default policy is used.
/// <seealso cref="WritePolicy"/>
/// </param>
/// <param name="ttl">
/// Time-to-live of the record.
/// If null (default), the TTL of <paramref name="record"/> is used.
/// </param>
/// <exception cref="InvalidOperationException">
/// If the record's primary key is a digest (not an actual value). This exception will be thrown,
/// since a digest has the namespace and set of where this record was retrieved from.
/// </exception>
/// <seealso cref="Get(string, dynamic, string[])"/>
/// <seealso cref="BatchWriteRecord{R}(IEnumerable{R}, BatchPolicy, BatchWritePolicy, ParallelOptions)"/>
public void Put([NotNull] ARecord record,
string setName = null,
WritePolicy writePolicy = null,
TimeSpan? ttl = null)
{
this.Put(setName ?? record.Aerospike.SetName,
record.Aerospike.Key,
record.Aerospike.GetValues(),
writePolicy,
ttl ?? record.Aerospike.TTL);
}
/// <summary>
/// Puts (Writes) a DB record based on the provided key and bin values.
/// Note that if the namespace and/or set is different, this instances's values are used.
/// </summary>
/// <param name="primaryKey">
/// Primary AerospikeKey.
/// This can be a <see cref="Client.Key"/>, <see cref="Value"/>, or <see cref="Bin"/> object besides a native, collection, etc. value/object.
/// </param>
/// <param name="binValues">
/// A dictionary where the key is the bin and the value is the bin's value.
/// </param>
/// <param name="setName">Set name or null for the null set</param>
/// <param name="writePolicy">
/// The write policy. If not provided , the default policy is used.
/// <seealso cref="WritePolicy"/>
/// </param>
/// <param name="ttl">Time-to-live of the record</param>
/// <seealso cref="BatchWrite{P,V}(string, IEnumerable{ValueTuple{P, IDictionary{string, V}}}, BatchPolicy, BatchWritePolicy, ParallelOptions)"/>
public void Put<V>(string setName,
[NotNull] dynamic primaryKey,
[NotNull] IDictionary<string, V> binValues,
WritePolicy writePolicy = null,
TimeSpan? ttl = null)
{
var writePolicyPut = writePolicy ?? this.DefaultWritePolicy;
if (ttl.HasValue)
{
writePolicyPut = new WritePolicy(writePolicyPut) { expiration = SetRecords.DetermineExpiration(ttl.Value) };
}
var bins = Helpers.CreateBinRecord(binValues);
this.AerospikeConnection
.AerospikeClient.Put(writePolicyPut,
Helpers.DetermineAerospikeKey(primaryKey, this.Namespace, setName),
bins);
this.AddDynamicSet(setName, bins);
}
/// <summary>
/// Puts (writes) a bin to the DB record.
/// Note that if the namespace and/or set is different, this instances's values are used.
/// </summary>
/// <param name="primaryKey">
/// Primary AerospikeKey.
/// This can be a <see cref="Client.Key"/>, <see cref="Value"/>, or <see cref="Bin"/> object besides a native, collection, etc. value/object.
/// </param>
/// <param name="bin">BinName Name</param>
/// <param name="binValue">
/// BinName's Value.
/// If null, the bin is removed from the record.
/// </param>
/// <param name="setName">Set name or null for the null set</param>
/// <param name="writePolicy">
/// The write policy. If not provided , the default policy is used.
/// <seealso cref="WritePolicy"/>
/// </param>
/// <param name="ttl">Time-to-live of the record</param>
public void Put(string setName,
[NotNull] dynamic primaryKey,
[NotNull] string bin,
[NotNull] object binValue,
WritePolicy writePolicy = null,
TimeSpan? ttl = null)
{
var writePolicyPut = writePolicy ?? this.DefaultWritePolicy;
if (ttl.HasValue)
{
writePolicyPut = new WritePolicy(writePolicyPut) { expiration = SetRecords.DetermineExpiration(ttl.Value) };
}
var bins = Helpers.CreateBinRecord(binValue, bin);
this.AerospikeConnection
.AerospikeClient.Put(writePolicyPut,
Helpers.DetermineAerospikeKey(primaryKey, this.Namespace, setName),
bins);
this.AddDynamicSet(setName, bins);
}
/// <summary>
/// Puts (writes) a bin to the DB record.
/// Note that if the namespace and/or set is different, this instances's values are used.
/// </summary>
/// <param name="primaryKey">
/// Primary AerospikeKey.
/// This can be a <see cref="Client.Key"/>, <see cref="Value"/>, or <see cref="Bin"/> object besides a native, collection, etc. value/object.
/// </param>
/// <param name="bin">BinName Name</param>
/// <param name="binValue">
/// BinName's Value.
/// If null, the bin is removed from the record.
/// </param>
/// <param name="setName">Set name or null for the null set</param>
/// <param name="writePolicy">
/// The write policy. If not provided , the default policy is used.
/// <seealso cref="WritePolicy"/>
/// </param>
/// <param name="ttl">Time-to-live of the record</param>
public void Put(string setName,
[NotNull] dynamic primaryKey,
[NotNull] string bin,
[NotNull] string binValue,
WritePolicy writePolicy = null,
TimeSpan? ttl = null)
=> this.Put(setName, primaryKey, bin, (object) binValue, writePolicy: writePolicy, ttl: ttl);
/// <summary>
/// Puts (writes) a bin to the DB record.
/// Note that if the namespace and/or set is different, this instances's values are used.
/// </summary>
/// <param name="primaryKey">
/// Primary AerospikeKey.
/// This can be a <see cref="Client.Key"/>, <see cref="Value"/>, or <see cref="Bin"/> object besides a native, collection, etc. value/object.
/// </param>
/// <param name="bin">BinName Name</param>
/// <param name="listValue">
/// BinName's Value.
/// If null, the bin is removed from the record.
/// </param>
/// <param name="setName">Set name or null for the null set</param>
/// <param name="writePolicy">
/// The write policy. If not provided , the default policy is used.
/// <seealso cref="WritePolicy"/>
/// </param>
/// <param name="ttl">Time-to-live of the record</param>
public void Put<T>(string setName,
[NotNull] dynamic primaryKey,
[NotNull] string bin,
[NotNull] IList<T> listValue,
WritePolicy writePolicy = null,
TimeSpan? ttl = null)
{
var writePolicyPut = writePolicy ?? this.DefaultWritePolicy;
if (ttl.HasValue)
{
writePolicyPut = new WritePolicy(writePolicyPut) { expiration = SetRecords.DetermineExpiration(ttl.Value) };
}
var cbin = Helpers.CreateBinRecord(listValue, bin);
this.AerospikeConnection
.AerospikeClient.Put(writePolicyPut,
Helpers.DetermineAerospikeKey(primaryKey, this.Namespace, setName),
cbin);
this.AddDynamicSet(setName, new Bin[] { cbin });
}
/// <summary>
/// Puts (writes) a bin to the DB record.
/// Note that if the namespace and/or set is different, this instances's values are used.
/// </summary>
/// <param name="primaryKey">
/// Primary AerospikeKey.
/// This can be a <see cref="Client.Key"/>, <see cref="Value"/>, or <see cref="Bin"/> object besides a native, collection, etc. value/object.
/// </param>
/// <param name="bin">BinName Name</param>
/// <param name="collectionValue">
/// BinName's Value.
/// If null, the bin is removed from the record.
/// </param>
/// <param name="setName">Set name or null for the null set</param>
/// <param name="writePolicy">
/// The write policy. If not provided , the default policy is used.
/// <seealso cref="WritePolicy"/>
/// </param>
/// <param name="ttl">Time-to-live of the record</param>
public void Put<K,V>(string setName,
[NotNull] dynamic primaryKey,
[NotNull] string bin,
[NotNull] IDictionary<K,V> collectionValue,
WritePolicy writePolicy = null,
TimeSpan? ttl = null)
{
var writePolicyPut = writePolicy ?? this.DefaultWritePolicy;
if (ttl.HasValue)
{
writePolicyPut = new WritePolicy(writePolicyPut) { expiration = SetRecords.DetermineExpiration(ttl.Value) };
}
var cBin = Helpers.CreateBinRecord((IEnumerable<KeyValuePair<K,V>>) collectionValue, bin);
this.AerospikeConnection
.AerospikeClient.Put(writePolicyPut,
Helpers.DetermineAerospikeKey(primaryKey, this.Namespace, setName),
cBin);
this.AddDynamicSet(setName, new Bin[] { cBin });
}
/// <summary>
/// Puts (writes) a bin to the DB record.
/// Note that if the namespace and/or set is different, this instances's values are used.
/// </summary>
/// <param name="primaryKey">
/// Primary AerospikeKey.
/// This can be a <see cref="Client.Key"/>, <see cref="Value"/>, or <see cref="Bin"/> object besides a native, collection, etc. value/object.