-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSetRecords.cs
3141 lines (2830 loc) · 149 KB
/
SetRecords.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: Pset
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.IO;
using Aerospike.Client;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Text.RegularExpressions;
namespace Aerospike.Database.LINQPadDriver.Extensions
{
[DebuggerDisplay("{ToString()}")]
public abstract class SetRecords<T> : SetRecords, IEnumerable<T>
where T : ARecord
{
#region Constructors
public SetRecords([NotNull] LPSet lpSet,
[NotNull] ANamespaceAccess setAccess,
[NotNull] string setName,
params string[] bins)
: base(lpSet, setAccess, setName, bins)
{ }
public SetRecords([NotNull] ANamespaceAccess setAccess,
[NotNull] string setName,
params string[] bins)
: base(setAccess, setName, bins)
{ }
public SetRecords([NotNull] SetRecords<T> clone,
Policy readPolicy = null,
WritePolicy writePolicy = null,
QueryPolicy queryPolicy = null,
ScanPolicy scanPolicy = null)
: base(clone, readPolicy, writePolicy, queryPolicy, scanPolicy)
{ }
/// <summary>
/// Initializes a new instance of <see cref="SetRecords{T}"/> as an Aerospike transactional unit.
/// If <see cref="SetRecords.Commit"/> method is not called the server will abort (rollback) this transaction.
/// </summary>
/// <param name="baseSet">Base Aerospike Set instance</param>
/// <param name="txn">
/// The Aerospike <see cref="Txn"/> instance or null to create a new transactional unit.
/// </param>
/// <param name="newNSAccess">
/// An new <see cref="ANamespaceAccess"/> instance to use with the transaction.
/// </param>
/// <seealso cref="SetRecords.CreateTransaction(int)"/>
/// <seealso cref="SetRecords.CreateTransaction(Txn)"/>
/// <seealso cref="SetRecords.Commit"/>
/// <seealso cref="SetRecords.Abort"/>
public SetRecords([NotNull] SetRecords baseSet,
[AllowNull] Txn txn,
[AllowNull] ANamespaceAccess newNSAccess = null)
: base(baseSet, txn, newNSAccess)
{ }
/// <summary>
/// Changes how records are displayed using the LinqPad <see cref="LINQPad.Extensions.Dump{T}(T)"/> method.
/// </summary>
/// <param name="newRecordView">See <see cref="ARecord.DumpTypes"/> for more information.</param>
/// <returns>This instance</returns>
/// <seealso cref="ARecord.DumpTypes"/>
/// <seealso cref="SetRecords.DefaultRecordView"/>
public new SetRecords<T> ChangeRecordView(ARecord.DumpTypes newRecordView)
{
this.DefaultRecordView = newRecordView;
return this;
}
#endregion
#region Get Methods
/// <summary>
/// Returns the record based on the primary key
/// </summary>
/// <param name="primaryKey">
/// The primary key can be a <see cref="Aerospike.Client.Key"/>, <see cref="Aerospike.Client.Value"/>, digest (byte[]), or a .net type.
/// </param>
/// <param name="bins">
/// An optional arguments, if provided only those bins are returned.
/// </param>
/// <returns>
/// A record if the primary key is found otherwise null.
/// </returns>
/// <seealso cref="Get(dynamic, Expression, string[])"/>
public new T Get([NotNull] dynamic primaryKey, params string[] bins)
{
Client.Key key = Helpers.DetermineAerospikeKey(primaryKey, this.Namespace, this.SetName);
var policy = this.DefaultReadPolicy;
if(key.userKey.IsNull && policy.sendKey)
{
policy = policy.Clone();
policy.sendKey = false;
}
var record = this.SetAccess
.AerospikeConnection
.AerospikeClient
.Get(policy, key, bins.Length == 0 ? null : bins);
if (record == null) return null;
return (T) CreateRecord(this.SetAccess,
key,
record,
this._bins,
this.BinsHashCode,
recordView: this.DefaultRecordView,
fkBins: this.DetermineFKBins(record));
}
/// <summary>
/// Returns the record based on the primary key
/// </summary>
/// <param name="primaryKey">
/// The primary key can be a <see cref="Aerospike.Client.Key"/>, <see cref="Aerospike.Client.Value"/>, digest (byte[]), or a .net type.
/// </param>
/// <param name="filterExpression">
/// A filter expression that is applied after obtaining the record via the primary key.
/// </param>
/// <param name="bins">
/// An optional arguments, if provided only those bins are returned.
/// </param>
/// <returns>
/// A record if the primary key is found otherwise null.
/// </returns>
/// <seealso cref="Get(dynamic, string[])"/>
public new T Get([NotNull] dynamic primaryKey, Expression filterExpression, params string[] bins)
{
Client.Key key = Helpers.DetermineAerospikeKey(primaryKey, this.Namespace, this.SetName);
var policy = new Client.Policy(this.DefaultReadPolicy) { filterExp = filterExpression };
if(key.userKey.IsNull && policy.sendKey)
{
policy.sendKey = false;
}
var record = this.SetAccess
.AerospikeConnection
.AerospikeClient
.Get(policy, key, bins.Length == 0 ? null : bins);
if (record == null) return null;
return (T)CreateRecord(this.SetAccess,
key,
record,
this._bins,
this.BinsHashCode,
recordView: this.DefaultRecordView,
fkBins: this.DetermineFKBins(record));
}
#endregion
#region Query Methods
/// <summary>
/// Returns all the records based on the associated bins.
/// </summary>
/// <param name="bins">Only include these bins in the result.</param>
/// <returns>
/// A collection of all records
/// </returns>
/// <exception cref="AerospikeException">Thrown if an index cannot be found to match the filter</exception>
/// <seealso cref="Query(Filter, Exp, string[])"/>
/// <seealso cref="Query(Filter, string[])"/>
/// <seealso cref="Query(Exp, string[])"/>
new public IEnumerable<T> Query(params string[] bins)
{
var queryPolicy = new QueryPolicy(this.DefaultQueryPolicy);
var stmt = new Statement();
stmt.SetNamespace(this.Namespace);
if (!string.IsNullOrEmpty(this.SetName) && this.SetName != LPSet.NullSetName)
stmt.SetSetName(this.SetName);
stmt.SetBinNames(bins);
using var recordset = this.SetAccess.AerospikeConnection
.AerospikeClient
.Query(queryPolicy, stmt);
while (recordset.Next())
{
yield return (T)CreateRecord(this.SetAccess,
recordset.Key,
recordset.Record,
this._bins,
this.BinsHashCode,
recordView: this.DefaultRecordView,
fkBins: this.DetermineFKBins(recordset.Record));
}
}
/// <summary>
/// Performs a <see cref="Client.AerospikeClient.Query(QueryPolicy, Statement)"/> applying the expression filter.
/// </summary>
/// <param name="filterExpression">
/// The Aerospike filter <see cref="Client.Exp"/> that will be applied.
/// <seealso cref="Aerospike.Client.ListExp"/>
/// <seealso cref="Aerospike.Client.MapExp"/>
/// <seealso cref="Aerospike.Client.BitExp"/>
/// <seealso cref="Aerospike.Client.HLLExp"/>
/// </param>
/// <param name="bins">Return only the bins provided in the result set</param>
/// <returns>
/// The result set based on the expression filter.
/// </returns>
/// <seealso cref="Query(Filter, Exp, string[])"/>
/// <seealso cref="Query(Filter, string[])"/>
/// <seealso cref="Query(string[])"/>
/// <seealso cref="Operation"/>
new public IEnumerable<T> Query([NotNull] Client.Exp filterExpression, params string[] bins)
{
var queryPolicy = new QueryPolicy(this.DefaultQueryPolicy) { filterExp = Exp.Build(filterExpression) };
using var recordset = this.SetAccess.AerospikeConnection
.AerospikeClient
.Query(queryPolicy,
string.IsNullOrEmpty(this.SetName) || this.SetName == LPSet.NullSetName
? new Statement() { Namespace = this.Namespace, BinNames = bins }
: new Statement() { Namespace = this.Namespace, SetName = this.SetName, BinNames = bins });
while (recordset.Next())
{
yield return (T)CreateRecord(this.SetAccess,
recordset.Key,
recordset.Record,
this._bins,
this.BinsHashCode,
recordView: this.DefaultRecordView,
fkBins: this.DetermineFKBins(recordset.Record));
}
}
/// <summary>
/// Performs a secondary index query using the provided <see cref="Client.Filter"/>.
/// </summary>
/// <param name="secondaryIdxFilter">The filter used against the secondary index</param>
/// <param name="bins">Only include these bins in the result.</param>
/// <returns>
/// A collection of records that match the filter.
/// </returns>
/// <exception cref="AerospikeException">Thrown if an index cannot be found to match the filter</exception>
/// <seealso cref="Query(Filter, Exp, string[])"/>
/// <seealso cref="Query(Exp, string[])"/>
/// <seealso cref="Query(string[])"/>
/// <seealso cref="CreateIndex(string, string, IndexType)"/>
/// <seealso cref="CreateIndex(string, string, IndexType, IndexCollectionType, CTX[])"/>
new public IEnumerable<T> Query([NotNull] Client.Filter secondaryIdxFilter, params string[] bins)
{
var queryPolicy = new QueryPolicy(this.DefaultQueryPolicy);
var stmt = new Statement();
stmt.SetNamespace(this.Namespace);
if (!string.IsNullOrEmpty(this.SetName) && this.SetName != LPSet.NullSetName)
stmt.SetSetName(this.SetName);
stmt.SetFilter(secondaryIdxFilter);
stmt.SetBinNames(bins);
using var recordset = this.SetAccess.AerospikeConnection
.AerospikeClient
.Query(queryPolicy, stmt);
while (recordset.Next())
{
yield return (T)CreateRecord(this.SetAccess,
recordset.Key,
recordset.Record,
this._bins,
this.BinsHashCode,
recordView: this.DefaultRecordView,
fkBins: this.DetermineFKBins(recordset.Record));
}
}
/// <summary>
/// Performs a secondary index query using the provided <see cref="Client.Filter"/> and than apply the filter expression.
/// </summary>
/// <param name="secondaryIdxFilter">The filter used against the secondary index</param>
/// <param name="filterExpression">
/// The Aerospike filter <see cref="Client.Exp"/> that will be applied after the index filter is applied.
/// <seealso cref="Aerospike.Client.ListExp"/>
/// <seealso cref="Aerospike.Client.MapExp"/>
/// <seealso cref="Aerospike.Client.BitExp"/>
/// <seealso cref="Aerospike.Client.HLLExp"/>
/// </param>
/// <param name="bins">Only include these bins in the result.</param>
/// <returns>
/// A collection of records that match the <paramref name="filterExpression"/>.
/// </returns>
/// <exception cref="AerospikeException">Thrown if an index cannot be found to match the filter</exception>
/// <seealso cref="Query(Filter, string[])"/>
/// <seealso cref="Query(string[])"/>
/// <seealso cref="Query(Exp, string[])"/>
/// <seealso cref="CreateIndex(string, string, IndexType)"/>
/// <seealso cref="CreateIndex(string, string, IndexType, IndexCollectionType, CTX[])"/>
new public IEnumerable<T> Query([NotNull] Client.Filter secondaryIdxFilter, Client.Exp filterExpression, params string[] bins)
{
var queryPolicy = filterExpression == null
? this.DefaultQueryPolicy
: new QueryPolicy(this.DefaultQueryPolicy) { filterExp = Exp.Build(filterExpression) };
var stmt = new Statement();
stmt.SetNamespace(this.Namespace);
if (!string.IsNullOrEmpty(this.SetName) && this.SetName != LPSet.NullSetName)
stmt.SetSetName(this.SetName);
stmt.SetFilter(secondaryIdxFilter);
stmt.SetBinNames(bins);
using var recordset = this.SetAccess.AerospikeConnection
.AerospikeClient
.Query(queryPolicy, stmt);
while (recordset.Next())
{
yield return (T)CreateRecord(this.SetAccess,
recordset.Key,
recordset.Record,
this._bins,
this.BinsHashCode,
recordView: this.DefaultRecordView,
fkBins: this.DetermineFKBins(recordset.Record));
}
}
#endregion
#region Batch Methods
/// <summary>
/// Writes a collection of <see cref="ARecord"/> as a <seealso cref="Aerospike.Client.BatchPolicy"/> operation.
/// </summary>
/// <param name="writeRecords">
/// A collection of <see cref="ARecord"/>.
/// </param>
/// <param name="batchPolicy">
/// <seealso cref="BatchPolicy"/>
/// </param>
/// <param name="batchWritePolicy">
/// <seealso cref="BatchWritePolicy"/>
/// </param>
/// <param name="parallelOptions">
/// <seealso cref="ParallelOptions"/>
/// </param>
/// <returns>True if successful</returns>
/// <seealso cref="ANamespaceAccess.BatchWriteRecord{R}(IEnumerable{R}, BatchPolicy, BatchWritePolicy, ParallelOptions)"/>
public bool BatchWrite([NotNull] IEnumerable<T> writeRecords,
BatchPolicy batchPolicy = null,
BatchWritePolicy batchWritePolicy = null,
ParallelOptions parallelOptions = null)
=> this.SetAccess.BatchWriteRecord(writeRecords,
batchPolicy ?? new BatchPolicy(this.DefaultWritePolicy),
batchWritePolicy,
parallelOptions);
/// <summary>
/// Return a collection of <see cref="ARecord"/> based on <paramref name="primaryKeys"/>
/// </summary>
/// <typeparam name="P">Primary Key Type</typeparam>
/// <param name="primaryKeys">A collection of Primarily Keys that will be part of the collection</param>
/// <param name="batchPolicy">
/// <seealso cref="BatchPolicy"/>
/// </param>
/// <param name="batchReadPolicy">
/// <seealso cref="BatchReadPolicy"/>
/// </param>
/// <param name="filterExpression">The expression that will be applied to the result set. Can be null.</param>
/// <param name="returnBins">A collection of bins that are returned</param>
/// <returns>A collection of records based on <paramref name="primaryKeys"/> or an empty collection</returns>
public new IEnumerable<T> BatchRead<P>([NotNull] IEnumerable<P> primaryKeys,
BatchPolicy batchPolicy = null,
BatchReadPolicy batchReadPolicy = null,
Expression filterExpression = null,
string[] returnBins = null)
{
batchPolicy ??= new BatchPolicy(this.DefaultReadPolicy)
{
maxRetries = 2,
maxConcurrentThreads = 1,
filterExp = filterExpression,
Txn = this.AerospikeTxn
};
batchReadPolicy ??= new BatchReadPolicy()
{
filterExp = filterExpression
};
var batchList = new List<BatchRead>(primaryKeys.Count());
foreach (var pk in primaryKeys)
{
if (returnBins is null)
batchList.Add(new BatchRead(batchReadPolicy,
Helpers.DetermineAerospikeKey(pk, this.Namespace, this.SetName),
true));
else
batchList.Add(new BatchRead(batchReadPolicy,
Helpers.DetermineAerospikeKey(pk, this.Namespace, this.SetName),
returnBins));
};
this.SetAccess
.AerospikeConnection
.AerospikeClient
.Get(batchPolicy, batchList);
foreach (var batch in batchList)
{
yield return (T)CreateRecord(this.SetAccess,
batch.key,
batch.record,
this._bins,
this.BinsHashCode,
recordView: this.DefaultRecordView);
}
}
#endregion
#region Linq Type Methods
/// <summary>
/// Returns the top number of records from the set based on <see cref="SetRecords.DefaultQueryPolicy"/> or <paramref name="filterExpression"/>.
/// </summary>
/// <param name="numberRecords">Number of records to return</param>
/// <param name="filterExpression">A Filter <see cref="Client.Exp"/> used to obtain the collection of records.</param>
/// <returns>A collection of records or empty set</returns>
/// <seealso cref="First(Exp)"/>
/// <seealso cref="FirstOrDefault(Client.Exp)"/>
/// <seealso cref="AsEnumerable(Client.Exp)"/>
/// <seealso cref="Get(dynamic, string[])"/>
/// <seealso cref="SetRecords.Operate(dynamic, Operation[])"/>
/// <seealso cref="SetRecords.DefaultQueryPolicy"/>
public new IEnumerable<T> Take(int numberRecords, Client.Exp filterExpression = null)
{
if (numberRecords <= 0) yield break;
var queryPolicy = filterExpression == null
? this.DefaultQueryPolicy
: new QueryPolicy(this.DefaultQueryPolicy) { filterExp = Exp.Build(filterExpression) };
using var recordset = this.SetAccess.AerospikeConnection
.AerospikeClient
.Query(queryPolicy,
string.IsNullOrEmpty(this.SetName) || this.SetName == LPSet.NullSetName
? new Statement() { Namespace = this.Namespace, MaxRecords = numberRecords }
: new Statement() { Namespace = this.Namespace, SetName = this.SetName, MaxRecords = numberRecords });
while (recordset.Next())
{
yield return (T) CreateRecord(this.SetAccess,
recordset.Key,
recordset.Record,
this._bins,
this.BinsHashCode,
recordView: this.DefaultRecordView,
fkBins: this.DetermineFKBins(recordset.Record));
}
}
/// <summary>
/// Returns the first record from the set based on <see cref="SetRecords.DefaultQueryPolicy"/> or <paramref name="filterExpression"/>.
/// </summary>
/// <param name="filterExpression">A Filter <see cref="Client.Exp"/> used to obtain the collection of records.</param>
/// <returns></returns>
/// <seealso cref="Take(int, Client.Exp)"/>
/// <see cref="First(Func{T, bool}, Exp)"/>
/// <seealso cref="FirstOrDefault(Client.Exp)"/>
/// <seealso cref="FirstOrDefault(Func{T, bool}, Exp)"/>
/// <seealso cref="AsEnumerable(Client.Exp)"/>
/// <seealso cref="Get(dynamic, string[])"/>
/// <seealso cref="SetRecords.Operate(dynamic, Operation[])"/>
/// <seealso cref="SetRecords.DefaultQueryPolicy"/>
public new T First(Client.Exp filterExpression = null)
=> this.Take(1, filterExpression).First();
/// <summary>
/// Returns the first record or null from the set based on <see cref="SetRecords.DefaultQueryPolicy"/> or <paramref name="filterExpression"/>.
/// </summary>
/// <param name="filterExpression">A Filter <see cref="Client.Exp"/> used to obtain the collection of records.</param>
/// <returns></returns>
/// <seealso cref="Take(int, Client.Exp)"/>
/// <seealso cref="First(Client.Exp)"/>
/// <seealso cref="First(Func{T, bool}, Exp)"/>
/// <seealso cref="FirstOrDefault(Func{T, bool}, Exp)"/>
/// <seealso cref="AsEnumerable(Client.Exp)"/>
/// <seealso cref="Get(dynamic, string[])"/>
/// <seealso cref="SetRecords.Operate(dynamic, Operation[])"/>
/// <seealso cref="SetRecords.DefaultQueryPolicy"/>
public new T FirstOrDefault(Client.Exp filterExpression = null)
=> this.Take(1, filterExpression).FirstOrDefault();
/// <summary>
/// Returns the first record from the set based on <see cref="SetRecords.DefaultScanPolicy"/> or <paramref name="filterExpression"/>.
/// </summary>
/// <param name="predicate">
/// Predicate used to find the first occurrence.
/// </param>
/// <param name="filterExpression">A Filter <see cref="Client.Exp"/> used to obtain the collection of records.</param>
/// <returns></returns>
/// <seealso cref="Take(int, Client.Exp)"/>
/// <seealso cref="FirstOrDefault(Client.Exp)"/>
/// <seealso cref="First(Exp)"/>
/// <seealso cref="First(Func{T, bool}, Exp)"/>
/// <seealso cref="AsEnumerable(Client.Exp)"/>
/// <seealso cref="Get(dynamic, string[])"/>
/// <seealso cref="SetRecords.Operate(dynamic, Operation[])"/>
/// <seealso cref="SetRecords.DefaultScanPolicy"/>
public T First(Func<T, bool> predicate, Client.Exp filterExpression = null)
=> this.AsEnumerable(filterExpression).First(predicate);
/// <summary>
/// Returns the first record or null from the set based on <see cref="SetRecords.DefaultScanPolicy"/> or <paramref name="filterExpression"/>.
/// </summary>
/// <param name="predicate">
/// Predicate used to find the first occurrence.
/// </param>
/// <param name="filterExpression">A Filter <see cref="Client.Exp"/> used to obtain the collection of records.</param>
/// <returns></returns>
/// <seealso cref="Take(int, Client.Exp)"/>
/// <seealso cref="First(Client.Exp)"/>
/// <seealso cref="First(Func{T, bool}, Exp)"/>
/// <seealso cref="FirstOrDefault(Exp)"/>
/// <seealso cref="AsEnumerable(Client.Exp)"/>
/// <seealso cref="Get(dynamic, string[])"/>
/// <seealso cref="SetRecords.Operate(dynamic, Operation[])"/>
/// <seealso cref="SetRecords.DefaultScanPolicy"/>
public T FirstOrDefault(Func<T, bool> predicate, Client.Exp filterExpression = null)
=> this.AsEnumerable(filterExpression).FirstOrDefault(predicate);
/// <summary>
/// Skips the number of records from the set based on <see cref="SetRecords.DefaultQueryPolicy"/> or <paramref name="filterExpression"/>.
/// </summary>
/// <param name="numberRecords">Number of records to skip</param>
/// <param name="filterExpression">A Filter <see cref="Client.Exp"/> used to obtain the collection of records.</param>
/// <returns></returns>
/// <seealso cref="Take(int, Client.Exp)"/>
/// <seealso cref="First(Client.Exp)"/>
/// <seealso cref="FirstOrDefault(Client.Exp)"/>
/// <seealso cref="AsEnumerable(Client.Exp)"/>
/// <seealso cref="Get(dynamic, string[])"/>
/// <seealso cref="SetRecords.Operate(dynamic, Operation[])"/>
/// <seealso cref="SetRecords.DefaultQueryPolicy"/>
public new IEnumerable<T> Skip(int numberRecords, Client.Exp filterExpression = null)
{
int currentIdx = 0;
var queryPolicy = filterExpression == null
? this.DefaultQueryPolicy
: new QueryPolicy(this.DefaultQueryPolicy) { filterExp = Exp.Build(filterExpression) };
using var recordset = this.SetAccess.AerospikeConnection
.AerospikeClient
.Query(queryPolicy,
string.IsNullOrEmpty(this.SetName) || this.SetName == LPSet.NullSetName
? new Statement() { Namespace = this.Namespace }
: new Statement() { Namespace = this.Namespace, SetName = this.SetName });
while (recordset.Next())
{
if (++currentIdx > numberRecords)
yield return (T) CreateRecord(this.SetAccess,
recordset.Key,
recordset.Record,
this._bins,
this.BinsHashCode,
recordView: this.DefaultRecordView,
fkBins: this.DetermineFKBins(recordset.Record));
}
}
/// <summary>
/// Filters a collection based on <paramref name="predicate"/>.
/// </summary>
/// <param name="predicate">A function that is used to determine if the item should be returned</param>
/// <returns>
/// A collection of filtered items.
/// </returns>
public IEnumerable<T> Where(Func<T, bool> predicate)
=> this.AsEnumerable().Where(predicate);
/// <summary>
/// Projects each element of an <see cref="ARecord"/> into a new form.
/// </summary>
/// <typeparam name="TResult">
/// The type of the value returned by <paramref name="selector"/>.
/// </typeparam>
/// <param name="selector">
/// A transform function to apply to each element.
/// </param>
/// <returns>
/// An IEnumerable<T> whose elements are the result of invoking the transform function on each element of <paramref name="selector"/>.
/// </returns>
public IEnumerable<TResult> Select<TResult>(Func<T, TResult> selector)
=> this.AsEnumerable().Select(selector);
/// <summary>
/// Returns IEnumerable><see cref="ARecord"/>< for the records of this set based on <see cref="SetRecords.DefaultScanPolicy"/> or <paramref name="filterExpression"/>.
/// Note: The records' return order may vary between executions.
/// </summary>
/// <param name="filterExpression">A Filter <see cref="Client.Exp"/> used to obtain the collection of records.</param>
/// <seealso cref="Take(int, Client.Exp)"/>
/// <seealso cref="First(Client.Exp)"/>
/// <seealso cref="FirstOrDefault(Client.Exp)"/>
/// <seealso cref="Get(dynamic, string[])"/>
/// <seealso cref="SetRecords.Operate(dynamic, Operation[])"/>
/// <seealso cref="SetRecords.DefaultScanPolicy"/>
public new IEnumerable<T> AsEnumerable(Client.Exp filterExpression = null)
{
var scanPolicy = filterExpression == null
? this.DefaultScanPolicy
: new ScanPolicy(this.DefaultScanPolicy)
{ filterExp = Exp.Build(filterExpression) };
var allRecords = new ConcurrentQueue<T>();
var allTask = Task.Factory.StartNew(() =>
this.SetAccess.AerospikeConnection
.AerospikeClient
.ScanAll(scanPolicy,
this.Namespace,
string.IsNullOrEmpty(this.SetName) || this.SetName == LPSet.NullSetName
? null
: this.SetName,
(key, record)
=> allRecords
.Enqueue((T) CreateRecord(this.SetAccess,
key,
record,
this._bins,
this.BinsHashCode,
recordView: this.DefaultRecordView,
fkBins: this.DetermineFKBins(record)))),
cancellationToken: CancellationToken.None,
creationOptions: TaskCreationOptions.DenyChildAttach
| TaskCreationOptions.LongRunning,
scheduler: TaskScheduler.Current);
while(!allTask.IsCompleted)
{
if(allRecords.TryDequeue(out T value))
yield return value;
}
foreach(var record in allRecords.TakeWhile(record => record 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;
}
#endregion
#region Idx Methods
/// <summary>
/// Creates a secondary index on this set for a bin <see href="https://docs.aerospike.com/server/guide/query"/>
/// </summary>
/// <param name="idxName">The name of the index</param>
/// <param name="idxOnBin">The bin's values that will be used to build the index</param>
/// <param name="indexType">The type of index to be built</param>
/// <seealso cref="Query(Filter, Exp, string[])"/>
/// <seealso cref="Query(Filter, string[])"/>
/// <seealso cref="CreateIndex(string, string, IndexType, IndexCollectionType, CTX[])"/>
/// <seealso cref="DropIndex(string)"/>
new public SetRecords<T> CreateIndex(string idxName, string idxOnBin, Client.IndexType indexType)
{
base.CreateIndex(idxName, idxOnBin, indexType);
return this;
}
/// <summary>
/// Creates a secondary index on this set for a bin <see href="https://docs.aerospike.com/server/guide/query"/>
/// </summary>
/// <param name="idxName">The name of the index</param>
/// <param name="idxOnBin">The bin's values that will be used to build the index</param>
/// <param name="indexType">The type of index to be built</param>
/// <param name="indexCollectionType">The bin must be a collection and this determines on to build the index on the collection.</param>
/// <param name="ctx">Provides additional processing of the collection</param>
/// <seealso cref="Query(Filter, Exp, string[])"/>
/// <seealso cref="Query(Filter, string[])"/>
/// <seealso cref="CreateIndex(string, string, IndexType)"/>
/// <seealso cref="DropIndex(string)"/>
new public SetRecords<T> CreateIndex(string idxName, string idxOnBin,
Client.IndexType indexType,
Client.IndexCollectionType indexCollectionType, params Client.CTX[] ctx)
{
base.CreateIndex(idxName, idxOnBin, indexType, indexCollectionType, ctx);
return this;
}
/// <summary>
/// Drops a secondary index.
/// </summary>
/// <param name="idxName">The name of the index</param>
/// <returns></returns>
/// <seealso cref="CreateIndex(string, string, IndexType)"/>
/// <seealso cref="CreateIndex(string, string, IndexType, IndexCollectionType, CTX[])"/>
new public SetRecords<T> DropIndex(string idxName)
{
base.DropIndex(idxName);
return this;
}
#endregion
#region IEnumerable
abstract protected ARecord CreateRecord([NotNull] ANamespaceAccess setAccess,
[NotNull] Client.Key key,
[NotNull] Record record,
string[] binNames,
int binsHashCode,
ARecord.DumpTypes recordView = ARecord.DumpTypes.Record,
IEnumerable<LPSet.BinType> fkBins = null);
public new IEnumerator<T> GetEnumerator()
{
var allRecords = new ConcurrentQueue<T>();
var allTask = Task.Factory.StartNew(() =>
this.SetAccess.AerospikeConnection
.AerospikeClient
.ScanAll(this.DefaultScanPolicy,
this.Namespace,
string.IsNullOrEmpty(this.SetName) || this.SetName == LPSet.NullSetName
? null
: this.SetName,
(key, record)
=> allRecords
.Enqueue((T) CreateRecord(this.SetAccess,
key,
record,
this._bins,
this.BinsHashCode,
recordView: this.DefaultRecordView,
fkBins: this.DetermineFKBins(record)))),
cancellationToken: CancellationToken.None,
creationOptions: TaskCreationOptions.DenyChildAttach
| TaskCreationOptions.LongRunning,
scheduler: TaskScheduler.Current);
while(!allTask.IsCompleted)
{
if(allRecords.TryDequeue(out T value))
yield return value;
}
foreach(var record in allRecords.TakeWhile(record => record 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;
}
IEnumerator IEnumerable.GetEnumerator()
=> this.GetEnumerator();
public new T[] ToArray() => this.AsEnumerable().ToArray();
public new List<T> ToList() => this.AsEnumerable().ToList();
#endregion
#region Copy Methods
/// <inheritdoc cref="LPDHelpers.CopyRecords(IEnumerable{ARecord}, SetRecords, Func{ARecord, dynamic}, WritePolicy, ParallelOptions)"/>
public SetRecords<C> CopyRecords<C>([NotNull] SetRecords<C> targetSet,
Func<T, dynamic> newPrimaryKeyValue,
WritePolicy writePolity = null,
ParallelOptions parallelOptions = null)
where C : ARecord
=> (SetRecords<C>) LPDHelpers.CopyRecords<T>(this.AsEnumerable(),
targetSet,
newPrimaryKeyValue,
writePolity,
parallelOptions);
/// <inheritdoc cref="CopyRecords(ANamespaceAccess, string, Func{T, dynamic}, WritePolicy, ParallelOptions)"/>
public SetRecords CopyRecords([NotNull] SetRecords targetSet,
Func<T, dynamic> newPrimaryKeyValue,
WritePolicy writePolity = null,
ParallelOptions parallelOptions = null)
=> LPDHelpers.CopyRecords<T>(this.AsEnumerable(),
targetSet,
newPrimaryKeyValue,
writePolity,
parallelOptions);
/// <inheritdoc cref="LPDHelpers.CopyRecords(IEnumerable{ARecord}, ANamespaceAccess, string, Func{ARecord, dynamic}, WritePolicy, ParallelOptions)"/>
public SetRecords CopyRecords([NotNull] ANamespaceAccess targetNamespace,
string targetSetName,
Func<T, dynamic> newPrimaryKeyValue,
WritePolicy writePolity = null,
ParallelOptions parallelOptions = null)
=> LPDHelpers.CopyRecords<T>(this.AsEnumerable(),
targetNamespace,
targetSetName,
newPrimaryKeyValue,
writePolity,
parallelOptions);
/// <inheritdoc cref="LPDHelpers.CopyRecords(IEnumerable{ARecord}, SetRecords, WritePolicy, ParallelOptions)"/>
public SetRecords<C> CopyRecords<C>([NotNull] SetRecords<C> targetSet,
WritePolicy writePolity = null,
ParallelOptions parallelOptions = null)
where C : ARecord
=> (SetRecords<C>) LPDHelpers.CopyRecords<T>(this.AsEnumerable(),
targetSet,
writePolity,
parallelOptions);
#endregion
}
/// <summary>
/// Represents information about an Aerospike set within a namespace.
/// It also contains the complete result set of this Aerospike set and is Enumerable returning a collection of <see cref="ARecord"/>s.
/// </summary>
[DebuggerDisplay("{ToString()}")]
public class SetRecords : IEnumerable<ARecord>, IEquatable<ARecord>, IEquatable<SetRecords>
{
#region Constructors
public SetRecords([NotNull] LPSet lpSet,
[NotNull] ANamespaceAccess setAccess,
[NotNull] string setName,
params string[] bins)
: this(setAccess, setName, bins)
{
this.LPset = lpSet;
}
public SetRecords([NotNull] ANamespaceAccess setAccess,
[NotNull] string setName,
params string[] bins)
{
this.SetName = setName == LPSet.NullSetName ? null : setName;
this.SetAccess = setAccess;
this.SetFullName = $"{this.Namespace}.{this.SetName ?? LPSet.NullSetName}";
this._bins = Helpers.RemoveDups(bins);
this.IsNullSet = setName == LPSet.NullSetName;
this.AerospikeTxn = this.SetAccess.AerospikeTxn;
this.DefaultWritePolicy = new WritePolicy(this.SetAccess.DefaultWritePolicy);
this.DefaultReadPolicy = new Policy(this.SetAccess.DefaultReadPolicy);
this.DefaultQueryPolicy = new QueryPolicy(this.SetAccess.DefaultQueryPolicy);
this.DefaultScanPolicy = new ScanPolicy(this.SetAccess.DefaultScanPolicy);
this.DefaultRecordView = this.SetAccess.AerospikeConnection?.RecordView ?? ARecord.DumpTypes.Dynamic;
}
public SetRecords([NotNull] SetRecords clone,
Policy readPolicy = null,
WritePolicy writePolicy = null,
QueryPolicy queryPolicy = null,
ScanPolicy scanPolicy = null)
{
this.LPset = clone.LPset;
this.SetName = clone.SetName;
this.SetAccess = clone.SetAccess;
this._bins = clone._bins;
this._binsHashCode= clone._binsHashCode;
this.FKBins = clone.FKBins;
this.SetFullName= clone.SetFullName;
this.DefaultRecordView = clone.DefaultRecordView;
this.IsNullSet = clone.IsNullSet;
if(writePolicy?.Txn is not null)
this.AerospikeTxn = writePolicy.Txn;
else if(readPolicy?.Txn is not null)
this.AerospikeTxn = readPolicy.Txn;
else
this.AerospikeTxn = clone.AerospikeTxn;
this.DefaultWritePolicy = writePolicy ?? new WritePolicy(clone.DefaultWritePolicy);
this.DefaultReadPolicy = readPolicy ?? new Policy(clone.DefaultReadPolicy);
this.DefaultQueryPolicy = queryPolicy ?? new QueryPolicy(clone.DefaultQueryPolicy);
this.DefaultScanPolicy = scanPolicy ?? new ScanPolicy(clone.DefaultScanPolicy);
}
/// <summary>
/// Initializes a new instance of <see cref="SetRecords"/> as an Aerospike transactional unit.
/// If <see cref="Commit"/> method is not called the server will abort (rollback) this transaction.
/// </summary>
/// <param name="baseSet">Base Aerospike Set instance</param>
/// <param name="txn">
/// The Aerospike <see cref="Txn"/> instance or null to create a new transactional unit.
/// </param>
/// <param name="newNSAccess">
/// An new <see cref="ANamespaceAccess"/> instance to use with the transaction.
/// </param>
/// <seealso cref="CreateTransaction(int)"/>
/// <seealso cref="CreateTransaction(Txn)"/>
/// <seealso cref="Commit"/>
/// <seealso cref="Abort"/>
public SetRecords([NotNull] SetRecords baseSet,
[AllowNull] Txn txn,
[AllowNull] ANamespaceAccess newNSAccess = null)
{
this.LPset = baseSet.LPset;
this.SetName = baseSet.SetName;
this.SetAccess = newNSAccess ?? baseSet.SetAccess;
this._bins = baseSet._bins;
this._binsHashCode = baseSet._binsHashCode;
this.FKBins = baseSet.FKBins;
this.SetFullName = baseSet.SetFullName;
this.DefaultRecordView = baseSet.DefaultRecordView;
this.IsNullSet = baseSet.IsNullSet;
txn ??= new Txn();
this.AerospikeTxn = txn;
this.DefaultWritePolicy = new(baseSet.DefaultWritePolicy)
{
Txn = txn
};
this.DefaultReadPolicy = new(baseSet.DefaultReadPolicy)
{
Txn = txn
};
this.DefaultQueryPolicy = new(baseSet.DefaultQueryPolicy)
{
Txn= txn
};
this.DefaultScanPolicy = new(baseSet.DefaultScanPolicy)
{
Txn= txn
};
if(!this.SetAccess?.IsStrongConsistencyMode ?? true)
{
Console.Write(LINQPad.Util.WithStyle("Warning", "color:black;background-color:orange"));
Console.Write(": ");
var setName = this.IsNullSet || this.SetName is null ? LPSet.NullSetName : this.SetName;
Console.WriteLine(LINQPad.Util.WithStyle($"MRTs should be used within a Strong Consistency namespace. '{this.Namespace}' is an AP namespace for set '{setName}'.", "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="SetRecords"/> instance.</returns>
public SetRecords Clone(Policy newReadPolicy = null,
WritePolicy newWritePolicy = null,
QueryPolicy newQueryPolicy = null,
ScanPolicy newScanPolicy = null)
=> new SetRecords(this,
newReadPolicy,
newWritePolicy,
newQueryPolicy,
newScanPolicy);
#endregion
#region Settings, Record State, etc.
public LPSet LPset { get; }
internal bool TryAddBin(string binName, Type dataType, bool updateNamespace)
{
lock (this)
{
var added = this.LPset?.AddBin(binName, dataType ?? typeof(AValue)) ?? false;
if (updateNamespace)
added = this.SetAccess.TryAddBin(binName) || added;
if (this._bins.Length == 0)
{
if (this.BinNames.Contains(binName)) return added;
this._bins = this.SetAccess.BinNames;