-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathDB.cs
1053 lines (878 loc) · 40.7 KB
/
DB.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
/***********************************************************************
Copyright 2024 CodeX Enterprises LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Major Changes:
12/2017 0.2 Initial release (Joel Champagne)
***********************************************************************/
#nullable enable
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using CodexMicroORM.Core.Helper;
using CodexMicroORM.Providers;
namespace CodexMicroORM.Core.Services
{
public class DBService : ICEFDataHost
{
const int MAX_WAIT_TIME_MS = 40000;
#region "Static state"
private const int PARALLEL_THRESHOLD_FOR_PARSE = 100;
// Can declare what DB schemas any object belongs to (if not expressed in GetSchemaName())
private static readonly ConcurrentDictionary<Type, string> _schemaTypeMap = new(Globals.DefaultCollectionConcurrencyLevel, Globals.DefaultDictionaryCapacity);
// Providers can be set, by type
private static readonly ConcurrentDictionary<Type, IDBProvider> _providerTypeMap = new(Globals.DefaultCollectionConcurrencyLevel, Globals.DefaultDictionaryCapacity);
// Field names can differ from OM and storage
private static readonly ConcurrentDictionary<Type, ConcurrentDictionary<string, string>> _typeFieldNameMap = new(Globals.DefaultCollectionConcurrencyLevel, Globals.DefaultDictionaryCapacity);
// Entity names can differ from OM and storage
private static readonly ConcurrentDictionary<Type, string> _typeEntityNameMap = new(Globals.DefaultCollectionConcurrencyLevel, Globals.DefaultDictionaryCapacity);
// Fields can have defaults (can match simple SQL DEFAULTs, for example)
private static readonly ConcurrentDictionary<Type, List<(string prop, object? value, object? def, Type proptype)>> _typePropDefaults = new(Globals.DefaultCollectionConcurrencyLevel, Globals.DefaultDictionaryCapacity);
// Property values can be "copied" from contained objects for DB persistence
private static readonly ConcurrentDictionary<Type, List<(string prop, Type proptype, string prefix)>> _typePropGroups = new(Globals.DefaultCollectionConcurrencyLevel, Globals.DefaultDictionaryCapacity);
// Properties on an object can be saved to a parent 1:0/1 in the DB
private static readonly ConcurrentDictionary<Type, (string? schema, string name)> _typeParentSave = new(Globals.DefaultCollectionConcurrencyLevel, Globals.DefaultDictionaryCapacity);
#endregion
#region "Private state"
private readonly ConcurrentDictionary<Type, Func<RetrievalIdentityMode, object[], IEnumerable>> _retrieveByKeyCache = new(Globals.DefaultCollectionConcurrencyLevel, Globals.DefaultDictionaryCapacity);
#endregion
#region "Constructors"
public DBService()
{
}
public static DBService Create(IDBProvider defaultProvider)
{
DefaultProvider = defaultProvider;
return new DBService();
}
#endregion
#region "Static methods"
public static IDBProvider? DefaultProvider
{
get;
set;
}
public static void RegisterSchema<T>(string schema)
{
CEF.RegisterForType<T>(new DBService());
_schemaTypeMap[typeof(T)] = schema;
}
public static void RegisterOnSaveParentSave<T>(string name, string? schema = null) where T : class
{
CEF.RegisterForType<T>(new DBService());
_typeParentSave[typeof(T)] = (schema, name);
}
public static void RegisterPropertyGroup<T, V>(string propName, string prefix = "") where T : class where V : class
{
CEF.RegisterForType<T>(new DBService());
_typePropGroups.TryGetValue(typeof(T), out List<(string prop, Type proptype, string prefix)>? vl);
vl ??= [];
vl.Add((propName, typeof(V), prefix ?? propName));
_typePropGroups[typeof(T)] = vl;
}
public static void RegisterDefault<T, V>(string propName, V defaultValue) where T : class
{
CEF.RegisterForType<T>(new DBService());
_typePropDefaults.TryGetValue(typeof(T), out var vl);
vl ??= [];
vl.Add((propName, defaultValue, default(V), typeof(V)));
_typePropDefaults[typeof(T)] = vl;
}
public static void RegisterStorageEntityName<T>(string entityName) where T : class
{
CEF.RegisterForType<T>(new DBService());
_typeEntityNameMap[typeof(T)] = entityName;
}
public static void RegisterStorageFieldName<T>(string propName, string storeName) where T : class
{
CEF.RegisterForType<T>(new DBService());
_typeFieldNameMap.TryGetValue(typeof(T), out ConcurrentDictionary<string, string>? vl);
vl ??= [];
vl[storeName] = propName;
_typeFieldNameMap[typeof(T)] = vl;
}
#endregion
public static IDBProvider GetProviderForType(Type bt)
{
if (_providerTypeMap.TryGetValue(bt, out IDBProvider? prov))
{
return prov;
}
if (DefaultProvider == null)
{
throw new CEFInvalidStateException(InvalidStateType.MissingService, $"Could not find a default data provider based on type {bt.Name}.");
}
return DefaultProvider;
}
public string GetEntityNameByType(Type bt, ICEFWrapper? w)
{
if (w != null && _typeEntityNameMap.TryGetValue(w.GetBaseType(), out string? name))
{
return name;
}
if (w != null)
{
return w.GetBaseType().Name;
}
if (_typeEntityNameMap.TryGetValue(bt, out name))
{
return name;
}
return bt.Name;
}
public string? GetSchemaNameByType(Type bt)
{
if (_schemaTypeMap.TryGetValue(bt, out string? sn))
{
return sn;
}
return null;
}
public string GetPropertyNameFromStorageName(Type baseType, string storeName)
{
if (baseType != null)
{
if (_typeFieldNameMap.TryGetValue(baseType, out ConcurrentDictionary<string, string>? vl))
{
if (vl.TryGetValue(storeName, out string? propName))
{
return propName;
}
}
}
return storeName;
}
public void FixupPropertyStorageNames(object o)
{
var bt = o.GetBaseType();
if (_typeFieldNameMap.TryGetValue(bt, out ConcurrentDictionary<string, string>? vl))
{
var iw = o.AsInfraWrapped();
if (iw != null)
{
var set = false;
foreach (var v in (from a in vl where iw.HasProperty(a.Key) select a))
{
iw.SetValue(v.Value, iw.GetValue(v.Key));
set = true;
}
if (set)
{
iw.AcceptChanges();
}
}
}
}
public IEnumerable<string> GetPropertyGroupFields(Type t)
{
if (_typePropGroups.TryGetValue(t, out List<(string prop, Type proptype, string prefix)>? vl))
{
foreach (var (prop, proptype, prefix) in vl)
{
foreach (var pi in proptype.GetProperties())
{
var fn = string.Concat(prefix, pi.Name);
yield return fn;
}
}
}
}
public void ExpandPropertyGroupValues(object o)
{
var bt = o.GetBaseType();
if (_typePropGroups.TryGetValue(bt, out List<(string prop, Type proptype, string prefix)>? vl))
{
var iw = o.AsInfraWrapped();
var set = false;
foreach (var (prop, proptype, prefix) in vl)
{
var pv = o.FastGetValue(prop);
if (pv == null)
{
pv = proptype.FastCreateNoParm();
o.FastSetValue(prop, pv);
set = true;
}
foreach (var pi in proptype.GetProperties())
{
var fn = string.Concat(prefix, pi.Name);
if (pv != null && iw != null && iw.HasProperty(fn))
{
pv.FastSetValue(pi.Name, iw.GetValue(fn));
set = true;
}
}
}
if (set)
{
iw?.AcceptChanges();
}
}
}
public void InitializeObjectsWithoutCorrespondingIDs(object o)
{
var bt = o.GetBaseType();
var ks = CEF.CurrentKeyService(o);
var rim = CEF.CurrentServiceScope.ResolvedRetrievalIdentityMode(o);
if (ks != null)
{
var iw = o.AsInfraWrapped();
if (iw != null)
{
var set = false;
foreach (var k in ks.GetRelationsForChild(bt))
{
// If we are missing the ID values (on CLR) but we do have a parent property...
if (!string.IsNullOrEmpty(k.ParentPropertyName) && (from a in k.ChildRoleName ?? k.ParentKey where !o.FastPropertyReadable(a) && iw.HasProperty(a) select a).Any())
{
if (iw.GetValue(k.ParentPropertyName!) == null && k.ParentType != null)
{
// Do a retrieve by key on the parent type
var parentSet = RetrieveByKeyNonGeneric(rim, k.ParentType, (from a in k.ChildRoleName ?? k.ParentKey select iw.GetValue(a)).ToList()).GetEnumerator();
if (parentSet.MoveNext())
{
o.FastSetValue(k.ParentPropertyName!, parentSet.Current);
set = true;
}
}
}
}
if (set)
{
iw.AcceptChanges();
}
}
}
}
public void CopyPropertyGroupValues(object? o)
{
if (o == null)
{
return;
}
if (_typePropGroups.TryGetValue(o.GetBaseType(), out List<(string prop, Type proptype, string prefix)>? vl))
{
var iw = o.AsInfraWrapped();
if (iw != null)
{
foreach (var (prop, proptype, prefix) in vl)
{
var val = iw.GetValue(prop);
foreach (var pi in (from a in proptype.GetProperties() where a.CanRead select a))
{
var targName = string.Concat(prefix, pi.Name);
if (val != null)
{
iw.SetValue(targName, val.FastGetValue(pi.Name));
}
else
{
iw.SetValue(targName, null);
}
}
}
}
}
}
IList<Type> ICEFService.RequiredServices() => [ typeof(ICEFPersistenceHost), typeof(ICEFKeyHost) ];
public void WaitOnCompletions()
{
var sst = CEF.CurrentServiceScope.GetServiceState<DBServiceState>();
if (sst != null)
{
while (sst.Completions.TryDequeue(out Task? t))
{
if (!t.Wait(MAX_WAIT_TIME_MS))
{
throw new TimeoutException($"Waited {MAX_WAIT_TIME_MS} ms for data operation - failed to complete.");
}
}
lock (sst.Sync)
{
if (sst.Exceptions.Count > 0)
{
var toThrow = sst.Exceptions.ToArray();
sst.Exceptions.Clear();
throw new AggregateException(toThrow);
}
}
}
}
public void AddCompletionException(Exception ex)
{
var sst = CEF.CurrentServiceScope.GetServiceState<DBServiceState>();
if (sst != null)
{
lock (sst.Sync)
{
sst.Exceptions.Add(ex);
}
}
}
public static void ExecuteRaw(ConnectionScope cs, string cmdText, bool doThrow = true, bool stopOnError = true)
{
if (DefaultProvider == null)
{
throw new CEFInvalidStateException(InvalidStateType.MissingInit, "Data provider not set.");
}
DefaultProvider.ExecuteRaw(cs, cmdText, doThrow, stopOnError);
}
/// <summary>
/// Primary entry point for saving one or more "rows" of data, sourced from entities.
/// </summary>
/// <param name="rows"></param>
/// <param name="ss"></param>
/// <param name="settings"></param>
/// <returns></returns>
public IList<(object item, string? message, int status)> Save(IList<ICEFInfraWrapper> rows, ServiceScope ss, DBSaveSettings settings)
{
List<(object item, string? message, int status)> results = [];
string? schemaOverride = null;
string? nameOverride = null;
if (!string.IsNullOrEmpty(settings.EntityPersistName))
{
var (schema, name) = settings.EntityPersistName!.SplitIntoSchemaAndName();
schemaOverride = schema;
nameOverride = name;
}
var cs = CEF.CurrentConnectionScope;
var aud = CEF.CurrentAuditService();
var ks = CEF.CurrentKeyService();
// Ordering of rows supports foreign key dependencies: insert/update top-down, delete bottom-up.
// Different order #'s require sequential processing, so we group by order # - within an order group/table, we should be able to issue parallel requests
// We also offer a way to "preview" what will be saved and adjust if needed
// By grouping by provider type, we support hybrid data sources, by type
Dictionary<IDBProvider, Dictionary<int, Dictionary<ObjectState, List<(string? schema, string name, Type basetype, ICEFInfraWrapper row)>>>> grouped = [];
var loader = new Action<ICEFInfraWrapper>((a) =>
{
using (CEF.UseServiceScope(ss))
{
var uw = a.AsUnwrapped();
var bt = uw?.GetBaseType();
if (bt != null && uw != null && (settings.LimitToSingleType == null || settings.LimitToSingleType.Equals(bt)))
{
var (cansave, treatas) = (settings.RowSavePreview == null ? (true, null) : settings.RowSavePreview.Invoke(a));
var rs = treatas.GetValueOrDefault(a.GetRowState());
if ((rs != ObjectState.Unchanged && rs != ObjectState.Unlinked) && cansave && ((cs.ToAcceptList?.Count).GetValueOrDefault() == 0 || !cs.ToAcceptList!.Contains(a)))
{
var w = a.GetWrappedObject() as ICEFWrapper;
var prov = GetProviderForType(bt);
var level = settings.LimitToSingleType != null ? 1 : ks.GetObjectNestLevel(uw);
var schema = (settings.EntityPersistType == bt ? schemaOverride : null) ?? w?.GetSchemaName() ?? GetSchemaNameByType(bt);
var name = (settings.EntityPersistType == bt ? nameOverride : null) ?? GetEntityNameByType(bt, w);
var row = (aud == null ? a : aud.SavePreview(ss, a, rs, settings));
lock (grouped)
{
if (!grouped.TryGetValue(prov, out var cprov))
{
cprov = [];
grouped[prov] = cprov;
}
if (!cprov.TryGetValue(level, out var clevel))
{
clevel = [];
cprov[level] = clevel;
}
if (!clevel.TryGetValue(rs, out var crs))
{
crs = [];
clevel[rs] = crs;
}
crs.Add((schema, name, bt, row));
}
}
}
}
});
if (rows.Count > PARALLEL_THRESHOLD_FOR_PARSE)
{
Parallel.ForEach(rows, new ParallelOptions() { MaxDegreeOfParallelism = settings.MaxDegreeOfParallelism }, loader);
}
else
{
foreach (var a in rows)
{
loader(a);
}
}
if ((settings.AllowedOperations & DBSaveSettings.Operations.Update) != 0)
{
foreach (var provkvp in grouped)
{
foreach (var levelkvp in (from a in provkvp.Value orderby a.Key select a))
{
if (levelkvp.Value.TryGetValue(ObjectState.ModifiedPriority, out var filteredrows))
{
var parentRows = (from a in filteredrows
where _typeParentSave.ContainsKey(a.basetype)
let pn = _typeParentSave[a.basetype]
select (pn.schema ?? a.schema, pn.name, a.basetype, a.row));
if (parentRows.Any())
{
try
{
settings.NoAcceptChanges = true;
provkvp.Key.UpdateRows(cs, parentRows, settings);
}
finally
{
settings.NoAcceptChanges = false;
}
}
results.AddRange(from a in provkvp.Key.UpdateRows(cs, filteredrows, settings) select (a.row.GetWrappedObject(), a.msg, a.status));
}
}
}
}
if ((settings.AllowedOperations & DBSaveSettings.Operations.Delete) != 0)
{
foreach (var provkvp in grouped)
{
foreach (var levelkvp in (from a in provkvp.Value orderby a.Key descending select a))
{
if (levelkvp.Value.TryGetValue(ObjectState.Deleted, out var filteredrows))
{
results.AddRange(from a in provkvp.Key.DeleteRows(cs, filteredrows, settings) select (a.row.GetWrappedObject(), a.msg, a.status));
var parentRows = (from a in filteredrows
where _typeParentSave.ContainsKey(a.basetype)
let pn = _typeParentSave[a.basetype]
select (pn.schema ?? a.schema, pn.name, a.basetype, a.row));
if (parentRows.Any())
{
try
{
settings.NoAcceptChanges = true;
provkvp.Key.DeleteRows(cs, parentRows, settings);
}
finally
{
settings.NoAcceptChanges = false;
}
}
}
}
}
}
// Walk down, level by level; perform updates then inserts at the same level - versus separate passes where updates might be needed to link properly as go deeper
foreach (var provkvp in grouped)
{
foreach (var levelkvp in (from a in provkvp.Value orderby a.Key select a))
{
if ((settings.AllowedOperations & DBSaveSettings.Operations.Update) != 0)
{
if (levelkvp.Value.TryGetValue(ObjectState.Modified, out var filteredrows))
{
var parentRows = (from a in filteredrows
where _typeParentSave.ContainsKey(a.basetype)
let pn = _typeParentSave[a.basetype]
select (pn.schema ?? a.schema, pn.name, a.basetype, a.row));
if (parentRows.Any())
{
try
{
settings.NoAcceptChanges = true;
provkvp.Key.UpdateRows(cs, parentRows, settings);
}
finally
{
settings.NoAcceptChanges = false;
}
}
results.AddRange(from a in provkvp.Key.UpdateRows(cs, filteredrows, settings) select (a.row.GetWrappedObject(), a.msg, a.status));
}
}
if ((settings.AllowedOperations & DBSaveSettings.Operations.Insert) != 0)
{
if (levelkvp.Value.TryGetValue(ObjectState.Added, out var filteredrows))
{
var isLeaf = (levelkvp.Key == provkvp.Value.Keys.Max());
var parentRows = (from a in filteredrows
where _typeParentSave.ContainsKey(a.basetype)
let pn = _typeParentSave[a.basetype]
select (pn.schema ?? a.schema, pn.name, a.basetype, a.row));
if (parentRows.Any())
{
try
{
settings.NoAcceptChanges = true;
provkvp.Key.InsertRows(cs, parentRows, isLeaf, settings);
}
finally
{
settings.NoAcceptChanges = false;
}
}
results.AddRange(from a in provkvp.Key.InsertRows(cs, filteredrows, isLeaf, settings) select (a.row.GetWrappedObject(), a.msg, a.status));
}
}
}
}
cs.DoneWork();
// We need to do the cache update at the end since we could have assigned values, etc. during the above save step - cache the final values!
ICEFCachingHost? cache = CEF.CurrentCacheService();
if (cache != null && results.Count > 0)
{
var forCaching = (from a in results
let bt = a.item.GetBaseType()
let cb = ss.ResolvedCacheBehaviorForType(bt)
where cb != 0
let iw = a.item.AsInfraWrapped()
where iw != null
let rs = iw.GetRowState()
group new { a, iw } by new { Type = bt, CacheMode = cb, RowState = rs } into g
select (g.Key.Type, g.Key.CacheMode, g.Key.RowState, Rows: (from c in g select c.iw.GetAllValues(true, true)).ToList())).ToList();
void act(object state)
{
try
{
cache.DoingWork();
using (CEF.UseServiceScope(ss))
{
var list = ((IEnumerable<(Type Type, CacheBehavior CacheMode, ObjectState RowState, List<IDictionary<string, object>> Rows)>)state);
// Update by identity entries with new values (or invalidate for deletions)
foreach (var ci in (from a in list where (a.CacheMode & CacheBehavior.IdentityBased) != 0 select a))
{
if (ci.RowState == ObjectState.Deleted || ci.RowState == ObjectState.Unlinked)
{
foreach (var r in ci.Rows)
{
cache.InvalidateIdentityEntry(ci.Type, r);
}
}
else
{
foreach (var r in ci.Rows)
{
cache.UpdateByIdentity(ci.Type, r);
}
}
}
// Invalidate all by query entries for any types contained in the save
foreach (var invType in (from a in list where (a.CacheMode & (CacheBehavior.QueryBased | CacheBehavior.OnlyForAllQuery)) != 0 select a.Type).Distinct())
{
cache.InvalidateForByQuery(invType, Globals.TypeSpecificCacheEvictionsOnUpdates);
}
}
}
catch (Exception ex)
{
AddCompletionException(ex);
CEFDebug.WriteInfo($"Cache error on DBSave: {ex.Message}");
}
finally
{
cache.DoneWork();
}
}
if (settings.AsyncCacheUpdates.GetValueOrDefault(ss.Settings.AsyncCacheUpdates.GetValueOrDefault(Globals.AsyncCacheUpdates)))
{
AddCompletionTask(Task.Factory.StartNew(act!, forCaching));
}
else
{
act(forCaching);
}
}
return results;
}
public void AddCompletionTask(Task t)
{
var sst = CEF.CurrentServiceScope.GetServiceState<DBServiceState>();
if (sst != null)
{
if (Globals.MaximumCompletionItemsQueued > 0)
{
while (sst.Completions.Count >= Globals.MaximumCompletionItemsQueued)
{
if (sst.Completions.TryDequeue(out Task? t2))
{
if (!t2.Wait(MAX_WAIT_TIME_MS))
{
throw new TimeoutException($"Waited {MAX_WAIT_TIME_MS} ms for data operation - failed to complete.");
}
}
}
}
sst.Completions.Enqueue(t);
}
}
public T ExecuteScalar<T>(string cmdText)
{
if (DefaultProvider == null)
{
throw new CEFInvalidStateException(InvalidStateType.MissingInit, "Data provider not set.");
}
var cs = CEF.CurrentConnectionScope;
var res = DefaultProvider.ExecuteScalar<T>(cs, cmdText);
cs.DoneWork();
return res;
}
public void ExecuteNoResultSet(CommandType cmdType, string cmdText, params object?[] args)
{
if (DefaultProvider == null)
{
throw new CEFInvalidStateException(InvalidStateType.MissingInit, "Data provider not set.");
}
var cs = CEF.CurrentConnectionScope;
DefaultProvider.ExecuteNoResultSet(cs, cmdType, cmdText, args);
cs.DoneWork();
}
public void ExecuteRaw(string command, bool doThrow = true, bool stopOnError = true)
{
if (DefaultProvider == null)
{
throw new CEFInvalidStateException(InvalidStateType.MissingInit, "Data provider not set.");
}
var cs = CEF.CurrentConnectionScope;
DefaultProvider.ExecuteRaw(cs, command, doThrow, stopOnError);
cs.DoneWork();
}
internal IEnumerable RetrieveByKeyNonGeneric(RetrievalIdentityMode identityMode, Type bt, params object[] key)
{
// Possibility that list was passed in as first element of an enumerable, unwap if needed
if (key.Length == 1 && key[0] is IEnumerable asenum)
{
key = asenum.Cast<object>().ToArray();
}
if (_retrieveByKeyCache.TryGetValue(bt, out Func<RetrievalIdentityMode, object[], IEnumerable>? vl))
{
return vl.Invoke(identityMode, key);
}
System.Reflection.MethodInfo mi = this.GetType().GetMethod("InternalRetrieveByKey", System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!;
mi = mi.MakeGenericMethod(bt);
var funcWrap = (Func<RetrievalIdentityMode, object[], IEnumerable>) mi.Invoke(this, [])!;
_retrieveByKeyCache[bt] = funcWrap;
return funcWrap(identityMode, key);
}
// Do not remove, used internally by reflection
#pragma warning disable IDE0051 // Remove unused private members
private Func<RetrievalIdentityMode, object[], IEnumerable> InternalRetrieveByKey<T>() where T : class, new() => new((rim, k) => { return RetrieveByKey<T>(rim, k); });
#pragma warning restore IDE0051 // Remove unused private members
public IEnumerable<T> RetrieveByKey<T>(RetrievalIdentityMode identityMode, params object[] key) where T : class, new()
{
var ss = CEF.CurrentServiceScope;
var sst = ss.GetServiceState<DBServiceState>();
var cb = CEF.CurrentServiceScope.ResolvedCacheBehaviorForType(typeof(T));
// Special situation we look for: async saving can result in unsaved objects, where we're better off to pull from that which might still be in memory
if (sst?.Completions.Count > 0 && ((ss.Settings.MergeBehavior & MergeBehavior.CheckScopeIfPending) != 0))
{
var kss = ss.GetServiceState<KeyService.KeyServiceState>();
if (kss != null)
{
var eto = kss.GetTrackedByPKValue(typeof(T), key);
if (eto != null && eto.IsAlive)
{
if (eto.GetWrapperTarget() is T ett)
{
return [ ett ];
}
}
}
}
ICEFCachingHost? cache = null;
if ((cb & CacheBehavior.IdentityBased) != 0)
{
// If caching is present, see if this identity is already in cache and return it if so
cache = CEF.CurrentCacheService();
var cached = cache?.GetByIdentity<T>(key);
if (cached != null)
{
return [ cached ];
}
}
var cs = CEF.CurrentConnectionScope;
var res = GetProviderForType(typeof(T)).RetrieveByKey<T>(identityMode, this, cs, true, key);
if (cs.IsStandalone)
{
// If it's a List, we know it's got to be a snapshot already, no need to do this again!
if (res is not List<T>)
{
res = res.ToArray();
}
cs.DoneWork();
}
// If caching is present, call out to it to potentially cache results (by identity)
if (cache != null && cb != CacheBehavior.Off)
{
if (!cs.IsStandalone)
{
// If it's a List, we know it's got to be a snapshot already, no need to do this again!
if (res is not List<T>)
{
res = res.ToArray();
}
}
var fr = res.FirstOrDefault();
if (fr != null)
{
cache.AddByIdentity(fr, key);
}
}
return res;
}
public IEnumerable<T> RetrieveByQuery<T>(RetrievalIdentityMode identityMode, CommandType cmdType, string cmdText, CEF.ColumnDefinitionCallback? cc, params object?[] parms) where T : class, new()
{
ICEFCachingHost? cache = null;
var cb = CEF.CurrentServiceScope.ResolvedCacheBehaviorForType(typeof(T));
if ((cb & CacheBehavior.QueryBased) != 0 && (cb & CacheBehavior.OnlyForAllQuery) == 0)
{
// If caching is present, see if this identity is already in cache and return it if so
cache = CEF.CurrentCacheService();
var cached = cache?.GetByQuery<T>(cmdText, parms);
if (cached != null)
{
return cached;
}
}
var cs = CEF.CurrentConnectionScope;
var res = GetProviderForType(typeof(T)).RetrieveByQuery<T>(identityMode, this, cs, true, cmdType, cmdText, cc, parms);
if (cs.IsStandalone)
{
// If it's a List, we know it's got to be a snapshot already, no need to do this again!
if (res is not List<T>)
{
res = res.ToArray();
}
cs.DoneWork();
}
if (cache == null && (cb & CacheBehavior.ConvertQueryToIdentity) != 0)
{
cache = CEF.CurrentCacheService();
}
if (cache != null && cb != CacheBehavior.Off)
{
if (!cs.IsStandalone)
{
// If it's a List, we know it's got to be a snapshot already, no need to do this again!
if (res is not List<T>)
{
res = res.ToArray();
}
}
cache.AddByQuery(res, cmdText, parms, null, cb);
}
return res;
}
public IEnumerable<T> RetrieveAll<T>(RetrievalIdentityMode identityMode) where T : class, new()
{
ICEFCachingHost? cache = null;
var ss = CEF.CurrentServiceScope;
var cb = ss.ResolvedCacheBehaviorForType(typeof(T));
if ((cb & CacheBehavior.QueryBased) != 0)
{
// If caching is present, see if this identity is already in cache and return it if so
cache = CEF.CurrentCacheService();
var cached = cache?.GetByQuery<T>("ALL", null);
if (cached != null)
{
return cached;
}
}
var cs = CEF.CurrentConnectionScope;
var res = GetProviderForType(typeof(T)).RetrieveAll<T>(identityMode, this, cs, true);
if (cs.IsStandalone)
{
// If it's a List, we know it's got to be a snapshot already, no need to do this again!
if (res is not List<T>)
{
res = res.ToArray();
}
cs.DoneWork();
}
if (cache != null && cb != CacheBehavior.Off)
{
if (!cs.IsStandalone)
{
// If it's a List, we know it's got to be a snapshot already, no need to do this again!
if (res is not List<T>)
{
res = res.ToArray();
}
}
cache.AddByQuery(res, "ALL", null, null, cb);
}
return res;
}
Type ICEFService.IdentifyStateType(object o, ServiceScope ss, bool isNew)
{
return typeof(DBServiceState);
}
WrappingSupport ICEFService.IdentifyInfraNeeds(object o, object? replaced, ServiceScope ss, bool isNew)
{
if ((replaced ?? o) is INotifyPropertyChanged)
{
return WrappingSupport.OriginalValues | WrappingSupport.PropertyBag;
}
else
{
return WrappingSupport.Notifications | WrappingSupport.OriginalValues | WrappingSupport.PropertyBag;
}
}
void ICEFService.FinishSetup(ServiceScope.TrackedObject to, ServiceScope ss, bool isNew, IDictionary<string, object?>? props, ICEFServiceObjState? state, bool initFromTemplate, RetrievalIdentityMode identityMode)
{
if (isNew && to.BaseType != null)
{
if (_typePropDefaults.TryGetValue(to.BaseType, out var defbytype))
{
var t = to.GetInfraWrapperTarget();
foreach (var (prop, value, def, proptype) in defbytype)
{
// If the underlying prop is not nullable, we only overwrite if NOT init from a template object, otherwise can lose purposeful sets on that template object
if (Nullable.GetUnderlyingType(proptype) != null || !initFromTemplate)
{