-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathKey.cs
2135 lines (1762 loc) · 88.2 KB
/
Key.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.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using CodexMicroORM.Core.Collections;
using System.Collections.Immutable;
using CodexMicroORM.Core.Helper;
using System.Threading;
namespace CodexMicroORM.Core.Services
{
public class KeyService : ICEFKeyHost
{
public const char SHADOW_PROP_PREFIX = '\\';
public const char SPECIAL_PROP_PREFIX = '~';
#region "Internal state"
private static long _lowLongKey = long.MinValue;
private static int _lowIntKey = int.MinValue;
private static int _lowShortKey = short.MinValue;
// Populated during startup, represents all object primary keys we track - should be eastablished prior to relationships!
private static readonly ConcurrentDictionary<Type, IList<string>> _primaryKeys = new(Globals.DefaultCollectionConcurrencyLevel, Globals.DefaultDictionaryCapacity);
private static readonly ConcurrentDictionary<Type, Type> _keyKnownTypes = new(Globals.DefaultCollectionConcurrencyLevel, Globals.DefaultDictionaryCapacity);
// Populated during startup, represents all object relationships we track
private static readonly ConcurrentIndexedList<TypeChildRelationship> _relations = new(
nameof(TypeChildRelationship.ParentType),
nameof(TypeChildRelationship.ChildType),
nameof(TypeChildRelationship.FullParentChildPropertyName),
nameof(TypeChildRelationship.FullChildParentPropertyName));
#endregion
public KeyService()
{
}
#region "Public state"
public static HashSet<Type> HavePKForTypes => new(_primaryKeys.Keys);
public static bool DefaultPrimaryKeysCanBeDBAssigned
{
get;
set;
} = true;
public static MergeBehavior DefaultMergeBehavior
{
get;
set;
} = Globals.DefaultMergeBehavior;
#endregion
#region "Static methods"
public static TypeChildRelationship? GetMappedPropertyByFieldName(string fn)
{
var pcr = _relations.GetFirstByName(nameof(TypeChildRelationship.FullParentChildPropertyName), fn);
if (pcr != null)
{
return pcr;
}
return _relations.GetFirstByName(nameof(TypeChildRelationship.FullChildParentPropertyName), fn);
}
/// <summary>
/// For type T, register one or more properties that represent its primary key (unique, non-null).
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fields"></param>
public static void RegisterKey<T>(params string[] fields)
{
if (fields == null || fields.Length == 0)
throw new CEFInvalidStateException(InvalidStateType.BadParameterValue, "Fields must be non-blank.");
_primaryKeys[typeof(T)] = fields;
CEF.RegisterForType<T>(new KeyService());
}
/// <summary>
/// For type T, register a specific field with a known data type as its primary key.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="field"></param>
/// <param name="knownType"></param>
public static void RegisterKeyWithType<T>(string field, Type knownType)
{
if (string.IsNullOrEmpty(field))
throw new CEFInvalidStateException(InvalidStateType.BadParameterValue, "Field must be non-blank.");
_primaryKeys[typeof(T)] = [ field ];
_keyKnownTypes[typeof(T)] = knownType;
CEF.RegisterForType<T>(new KeyService());
}
/// <summary>
/// For parent type T, register a relationship to a child entity (optional child role name and property accessor names).
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="relations"></param>
public static void RegisterRelationship<T>(params TypeChildRelationship[] relations)
{
if (relations == null || relations.Length == 0)
throw new CEFInvalidStateException(InvalidStateType.BadParameterValue, "Relations must be non-blank.");
foreach (var r in relations)
{
if (!_primaryKeys.TryGetValue(typeof(T), out var parentPk))
{
throw new CEFInvalidStateException(InvalidStateType.MissingKey, typeof(T).Name);
}
r.ParentKey = parentPk;
r.ParentType = typeof(T);
_relations.Add(r);
}
CEF.RegisterForType<T>(new KeyService());
}
public static IList<string> ResolveKeyDefinitionForType(Type t, RetrievalIdentityMode? identityMode = null)
{
if (identityMode.GetValueOrDefault(Globals.DefaultRetrievalIdentityMode) == RetrievalIdentityMode.AllowMultipleWithShadowProp)
{
return ["_ID"];
}
if (_primaryKeys.TryGetValue(t, out IList<string>? pk))
{
return pk;
}
else
{
return [];
}
}
/// <summary>
/// Returns all possible child role names associated with this child type.
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
private static List<string> ResolveChildRolesForType(Type t)
{
return (from a in _relations.GetAllByName(nameof(TypeChildRelationship.ChildType), t) select a.ChildRoleName ?? a.ParentKey).SelectMany((p) => p).ToList();
}
private static IEnumerable<object> InternalGetParentObjects(KeyServiceState state, ServiceScope ss, object o, RelationTypes types, HashSet<object> visits)
{
if (state == null)
throw new CEFInvalidStateException(InvalidStateType.ArgumentNull, nameof(state));
if (ss == null)
throw new CEFInvalidStateException(InvalidStateType.ArgumentNull, nameof(ss));
if (o == null)
throw new CEFInvalidStateException(InvalidStateType.ArgumentNull, nameof(o));
var uw = o.AsUnwrapped();
if (uw == null || visits.Contains(uw))
{
yield break;
}
var to = ss.Objects.GetFirstByName(nameof(ServiceScope.TrackedObject.Target), uw);
if (to != null)
{
var tot = to.GetTarget();
if (tot != null)
{
visits.Add(tot);
foreach (var fk in state.AllParents(uw))
{
var pot = fk.Parent.GetTarget();
if (pot != null)
{
if (!visits.Contains(pot))
{
yield return fk.Parent.GetInfraWrapperTarget();
foreach (var n in InternalGetParentObjects(state, ss, pot, types, visits))
{
yield return n;
}
}
}
}
//foreach (var fk in state.AllParents(uw))
//{
// var pot = fk.Parent.GetTarget();
// if (pot != null)
// {
// foreach (var n in InternalGetParentObjects(state, ss, pot, types, visits))
// {
// yield return n;
// }
// }
// yield return fk.Parent.GetInfraWrapperTarget();
//}
if ((types & RelationTypes.Children) != 0)
{
foreach (var fk in state.AllChildren(uw))
{
var ch = fk.Child.GetTarget();
if (ch != null)
{
if (!visits.Contains(ch))
{
yield return fk.Child.GetInfraWrapperTarget();
foreach (var nc in InternalGetChildObjects(state, ss, ch, types, visits))
{
yield return nc;
}
}
}
}
}
}
}
}
private static IEnumerable<object> InternalGetChildObjects(KeyServiceState state, ServiceScope ss, object o, RelationTypes types, HashSet<object> visits)
{
if (state == null)
throw new CEFInvalidStateException(InvalidStateType.ArgumentNull, nameof(state));
if (ss == null)
throw new CEFInvalidStateException(InvalidStateType.ArgumentNull, nameof(ss));
if (o == null)
throw new CEFInvalidStateException(InvalidStateType.ArgumentNull, nameof(o));
var uw = o.AsUnwrapped();
if (uw == null || visits.Contains(uw))
{
yield break;
}
var to = ss.Objects.GetFirstByName(nameof(ServiceScope.TrackedObject.Target), uw);
if (to != null)
{
var cur = to.GetTarget();
if (cur != null)
{
visits.Add(cur);
foreach (var fk in state.AllChildren(uw))
{
var cot = fk.Child.GetTarget();
if (cot != null)
{
foreach (var n in InternalGetChildObjects(state, ss, cot, types, visits))
{
yield return n;
}
}
yield return fk.Child.GetInfraWrapperTarget();
}
if ((types & RelationTypes.Parents) != 0)
{
foreach (var fk in state.AllParents(uw))
{
var par = fk.Parent.GetTarget();
if (par != null)
{
if (!visits.Contains(par))
{
yield return fk.Parent.GetInfraWrapperTarget();
foreach (var np in InternalGetParentObjects(state, ss, par, types, visits))
{
yield return np;
}
}
}
}
}
}
}
}
private static void InternalGetChildTypes(Type t, IDictionary<Type, IList<string>> visits, bool all)
{
if (visits.ContainsKey(t))
{
return;
}
var children = _relations.GetAllByName(nameof(TypeChildRelationship.ParentType), t);
foreach (var child in (from a in children select a.ChildType).Distinct())
{
if (_primaryKeys.TryGetValue(child, out IList<string>? pk))
{
visits[child] = pk;
}
if (all)
{
InternalGetChildTypes(child, visits, all);
}
}
}
private static void InternalGetParentTypes(Type t, IDictionary<Type, IList<string>> visits, bool all)
{
if (visits.ContainsKey(t))
{
return;
}
var parents = _relations.GetAllByName(nameof(TypeChildRelationship.ChildType), t);
foreach (var parent in (from a in parents select a.ParentType).Distinct())
{
if (_primaryKeys.TryGetValue(parent, out IList<string>? pk))
{
visits[parent] = pk;
}
if (all)
{
InternalGetParentTypes(parent, visits, all);
}
}
}
#endregion
public IEnumerable<TypeChildRelationship> GetRelationsForChild(Type childType) => _relations.GetAllByName(nameof(TypeChildRelationship.ChildType), childType);
IList<Type>? ICEFService.RequiredServices() => null;
Type ICEFService.IdentifyStateType(object o, ServiceScope ss, bool isNew) => typeof(KeyServiceState);
WrappingSupport ICEFService.IdentifyInfraNeeds(object o, object? replaced, ServiceScope ss, bool isNew)
{
// If you're using shadow properties, you definitely need a property bag and notification to know when a key might be changed/assigned
if (Globals.UseShadowPropertiesForNew)
{
return WrappingSupport.PropertyBag | WrappingSupport.Notifications;
}
var need = WrappingSupport.None;
if (o != null)
{
// Need prop bag only if does not contain key fields or child role names, plus require notifications to track changes in these values
foreach (var field in ResolveKeyDefinitionForType(o.GetBaseType()).Union(ResolveChildRolesForType(o.GetBaseType())))
{
if ((replaced ?? o).GetType().GetProperty(field) == null)
{
need = WrappingSupport.PropertyBag | WrappingSupport.Notifications;
break;
}
}
}
return need;
}
void ICEFService.FinishSetup(ServiceScope.TrackedObject to, ServiceScope ss, bool isNew, IDictionary<string, object?>? props, ICEFServiceObjState? state, bool initFromTemplate, RetrievalIdentityMode identityMode)
{
var uw = to.GetTarget();
if (uw == null)
return;
var pkFields = ResolveKeyDefinitionForType(uw.GetBaseType(), identityMode);
// If we have no key fields, nothing we can do here!
if (pkFields == null || pkFields.Count == 0)
return;
Type? prefKeyType = null;
bool needsKeyAssign = false;
// Case where not "new" row but still missing a key value - still need to generate it as such, for uniqueness!
if (!isNew)
{
if (pkFields.Count == 1)
{
if (props != null && !props.ContainsKey(pkFields[0]))
{
_keyKnownTypes.TryGetValue(uw.GetBaseType(), out prefKeyType);
if (prefKeyType != null)
{
needsKeyAssign = true;
}
else
{
if (identityMode == RetrievalIdentityMode.AllowMultipleWithShadowProp)
{
needsKeyAssign = true;
}
}
}
}
}
// Assign keys - new or not, we rely on unqiue values
if (isNew || needsKeyAssign)
{
foreach (var k in pkFields)
{
// Don't overwrite properties that we may have copied!
if (props == null || !props.TryGetValue(k, out var kval))
{
var (setter, type) = ss.GetSetter(uw, k);
if (type == null)
{
type = prefKeyType;
}
// Shadow props in use, we rely on the above for the data type, but we'll be updating the shadow prop instead
var kssp = (!Globals.UseShadowPropertiesForNew || (type != null && type.Equals(typeof(Guid))) ? (null, null) : ss.GetSetter(uw, SHADOW_PROP_PREFIX + k));
var rset = (kssp.setter ?? setter);
if (rset != null)
{
var keyType = (type ?? kssp.type) ?? Globals.DefaultKeyType;
if (keyType.Equals(typeof(int)))
{
rset.Invoke(System.Threading.Interlocked.Increment(ref _lowIntKey));
}
else
{
if (keyType.Equals(typeof(short)))
{
rset.Invoke(Convert.ToInt16(System.Threading.Interlocked.Increment(ref _lowShortKey)));
}
else
{
if (keyType.Equals(typeof(long)))
{
rset.Invoke(System.Threading.Interlocked.Increment(ref _lowLongKey));
}
else
{
// Only do this if no current value assigned
var kg = ss.GetGetter(uw, k);
if (kg.getter != null)
{
var cv = kg.getter();
if (keyType.Equals(typeof(Guid)))
{
if (cv == null || Guid.Empty.Equals(cv))
{
rset.Invoke(Guid.NewGuid());
}
}
else
{
if (keyType.Equals(typeof(string)))
{
if (cv == null || string.Empty.Equals(cv))
{
rset.Invoke(Guid.NewGuid());
}
}
}
}
}
}
}
}
}
else
{
if (props != null && Globals.UseShadowPropertiesForNew && props.ContainsKey(k) && props.ContainsKey(SHADOW_PROP_PREFIX + k))
{
var spval = props[SHADOW_PROP_PREFIX + k];
var defVal = WrappingHelper.GetDefaultForType(spval?.GetType() ?? throw new CEFInvalidStateException(InvalidStateType.ObjectTrackingIssue));
if (defVal.IsSame(kval) && !defVal.IsSame(spval))
{
var sptype = spval.GetType();
if (sptype.Equals(typeof(int)))
{
while (Interlocked.Increment(ref _lowIntKey) < (int)spval) ;
}
else
{
if (sptype.Equals(typeof(short)))
{
while (Convert.ToInt16(Interlocked.Increment(ref _lowShortKey)) < (short)spval) ;
}
else
{
if (sptype.Equals(typeof(long)))
{
while (Interlocked.Increment(ref _lowLongKey) < (long)spval) ;
}
}
}
}
}
}
}
}
var keystate = (KeyServiceState?)state ?? throw new CEFInvalidStateException(InvalidStateType.MissingServiceState, "Key");
keystate.AddPK(ss, to, to.GetNotifyFriendly(), pkFields, (changedPK, oldval, newval) =>
{
// Tracking dictionary may no longer correctly reflect composite key - force an update
keystate.UpdatePK((KeyServiceState.CompositeWrapper)oldval, (KeyServiceState.CompositeWrapper)newval);
});
LinkByValuesInScope(to, ss, keystate);
}
public object? RemoveFK(ServiceScope ss, TypeChildRelationship key, ServiceScope.TrackedObject parent, ServiceScope.TrackedObject child, INotifyPropertyChanged? parentWrapped, bool nullifyChild)
{
return ss.GetServiceState<KeyServiceState>()?.RemoveFK(ss, key, parent, child, parentWrapped, nullifyChild);
}
public IEnumerable<object> GetParentObjects(ServiceScope ss, object o, RelationTypes types = RelationTypes.None)
{
return InternalGetParentObjects(ss.GetServiceState<KeyServiceState>() ?? throw new CEFInvalidStateException(InvalidStateType.MissingServiceState, "Key"), ss, o, types, []);
}
public IEnumerable<object> GetChildObjects(ServiceScope ss, object o, RelationTypes types = RelationTypes.None)
{
return InternalGetChildObjects(ss.GetServiceState<KeyServiceState>() ?? throw new CEFInvalidStateException(InvalidStateType.MissingServiceState, "Key"), ss, o, types, []);
}
public void UpdateBoundKeys(ServiceScope.TrackedObject to, ServiceScope ss, string fieldName, object? oval, object? nval)
{
var tot = to.GetTarget() ?? throw new CEFInvalidStateException(InvalidStateType.ObjectTrackingIssue);
foreach (var rel in _relations.GetAllByName(nameof(TypeChildRelationship.FullChildParentPropertyName), $"{tot.GetBaseType().Name}.{fieldName}"))
{
if (nval != null)
{
var toParent = ss.Objects.GetFirstByName(nameof(ServiceScope.TrackedObject.Target), nval);
if (toParent != null)
{
foreach (var (ordinal, name, value) in GetKeyValues(toParent.GetInfraWrapperTarget()))
{
var (setter, _) = ss.GetSetter(to.GetInfraWrapperTarget(), rel.ChildResolvedKey[ordinal]);
setter?.Invoke(value);
}
}
}
}
}
internal void LinkByValuesInScope(ServiceScope.TrackedObject to, ServiceScope ss, KeyServiceState objstate)
{
var iw = to.GetCreateInfra(ss);
if (iw != null)
{
var uw = to.GetTarget();
if (uw == null)
return;
var w = to.GetWrapper();
bool didLink = false;
bool didAdd = false;
var childRels = _relations.GetAllByName(nameof(TypeChildRelationship.ChildType), uw.GetBaseType()).ToArray();
Dictionary<TypeChildRelationship, List<(int ordinal, string name, object? value)>> kvCache = [];
List<(int ordinal, string name, object? value)>? curPK = null;
foreach (var rel in (from a in childRels where !string.IsNullOrEmpty(a.ParentPropertyName) select a))
{
if (rel.ParentPropertyName != null)
{
var val = iw.GetValue(rel.ParentPropertyName);
if (val != null)
{
var testParent = ss.GetTrackedByWrapperOrTarget(val);
if (testParent != null)
{
var prs = testParent.Infra?.GetRowState();
if (prs != null && prs != ObjectState.Deleted)
{
objstate.AddFK(ss, rel, testParent, to, testParent.GetNotifyFriendly(), true, false, prs == ObjectState.Added);
didAdd = true;
}
}
else
{
objstate.TrackMissingParentByRef(rel, val, to);
}
}
else
{
var chRoleVals = GetKeyValues(uw, rel.ChildResolvedKey);
kvCache[rel] = chRoleVals;
if (rel.ParentType != null)
{
var testParent = objstate.GetTrackedByPKValue(rel.ParentType, (from a in chRoleVals select a.value));
if (testParent != null)
{
iw.SetValue(rel.ParentPropertyName, testParent.GetWrapperTarget());
objstate.AddFK(ss, rel, testParent, to, testParent.GetNotifyFriendly(), true, false, false);
didAdd = true;
}
else
{
if (Globals.ResolveForArbitraryLoadOrder)
{
// We only track this case when asked to: it's more expensive and usually unnecessary, but during ZDB load phase, things can get loaded out-of-order due to async nature
objstate.TrackMissingParentByValue(rel, to, rel.ParentType, (from a in chRoleVals select a.value));
}
}
}
}
}
}
foreach (var rel in (from a in childRels where !string.IsNullOrEmpty(a.ChildPropertyName) && a.ParentType != null select a))
{
// Current entity role name used to look up any existing parent and add to their child collection if not already there
var chRoleVals = kvCache.TestAssignReturn(rel, () => { return GetKeyValues(uw, rel.ChildResolvedKey); });
if ((from a in chRoleVals where a.value != null select a).Any())
{
var testParent = objstate.GetTrackedByPKValue(rel.ParentType!, (from a in chRoleVals select a.value));
if (testParent != null)
{
var (getter, type) = ss.GetGetter(testParent.GetInfraWrapperTarget(), rel.ChildPropertyName!);
if (type != null && getter != null && WrappingHelper.IsWrappableListType(type, null))
{
var parVal = getter.Invoke();
if (parVal == null)
{
var tpuw = testParent.AsUnwrapped();
if (tpuw != null)
{
parVal = WrappingHelper.CreateWrappingList(ss, type, tpuw, rel.ChildPropertyName!);
var parChildSet = ss.GetSetter(testParent.GetInfraWrapperTarget(), rel.ChildPropertyName!);
parChildSet.setter?.Invoke(parVal);
}
}
if (parVal is ICEFList asCefList)
{
if (asCefList.AddWrappedItem(w ?? uw, !didAdd))
{
objstate.AddFK(ss, rel, testParent, to, testParent.GetNotifyFriendly(), true, false, true);
didLink = true;
}
}
}
}
else
{
if (Globals.ResolveForArbitraryLoadOrder)
{
// We only track this case when asked to: it's more expensive and usually unnecessary, but during ZDB load phase, things can get loaded out-of-order due to async nature
objstate.TrackMissingParentChildLinkback(rel, to, rel.ParentType!, (from a in chRoleVals select a.value));
}
}
}
}
var parentRels = _relations.GetAllByName(nameof(TypeChildRelationship.ParentType), uw.GetBaseType());
foreach (var rel in (from a in parentRels where !string.IsNullOrEmpty(a.ParentPropertyName) select a))
{
foreach (var testChild in objstate.GetMissingChildrenForParentByRef(rel, w ?? uw))
{
var (getter, type) = ss.GetGetter(testChild.GetInfraWrapperTarget(), rel.ParentPropertyName!);
if (getter != null)
{
var val = getter.Invoke();
if (val != null)
{
if (val.Equals(uw) || val.Equals(w))
{
objstate.AddFK(ss, rel, to, testChild, to.GetNotifyFriendly(), true, true, false);
didLink = true;
}
}
}
}
// Special case where a child record refers to a parent record by ID - normally would load parent *first*, but if misordered, we go back to the current scope and look for it now
if (!didLink && Globals.ResolveForArbitraryLoadOrder)
{
var parKeyVal = kvCache.TestAssignReturn(rel, () => { return GetKeyValues(uw, rel.ParentKey); });
curPK = parKeyVal;
// Maintaining an unlinked list for "child with no parent by value", look for cases that meet this condition now (parent appears, need to update child to point at "this" parent)
foreach (var testChild in objstate.GetMissingChildrenByValue(rel, (from a in parKeyVal select a.value)))
{
var (setter, type) = ss.GetSetter(testChild.Child.GetInfraWrapperTarget(), rel.ParentPropertyName!);
if (setter != null)
{
setter.Invoke(to.GetWrapperTarget());
objstate.AddFK(ss, rel, to, testChild.Child, to.GetNotifyFriendly(), true, true, false);
testChild.Processed = true;
didLink = true;
}
}
}
}
foreach (var rel in (from a in parentRels where !string.IsNullOrEmpty(a.ChildPropertyName) select a))
{
var (getter, type) = ss.GetGetter(iw, rel.ChildPropertyName!);
if (getter != null && type != null)
{
if (type != null && WrappingHelper.IsWrappableListType(type, null))
{
var parVal = getter.Invoke();
if (parVal != null)
{
var sValEnum = ((System.Collections.IEnumerable)parVal).GetEnumerator();
while (sValEnum.MoveNext())
{
var chVal = sValEnum.Current;
var chTo = ss.GetTrackedByWrapperOrTarget(chVal);
if (chTo != null)
{
objstate.AddFK(ss, rel, to, chTo, to.GetNotifyFriendly(), true, false, chTo.Infra?.GetRowState() == ObjectState.Added);
}
}
}
}
}
}
if (Globals.ResolveForArbitraryLoadOrder)
{
// In this mode, we try to identify if the current object was previously passed over for linking as a child ref
// Normally this should not occur if we populate in a "good order" - but when loading from data store in parallel, could encounter out-of-order
curPK ??= GetKeyValues(uw);
if (curPK?.Count > 0)
{
foreach (var pobj in objstate.GetMissingChildLinkbacksForParentByValue(to.BaseType ?? throw new CEFInvalidStateException(InvalidStateType.ObjectTrackingIssue), (from k in curPK select k.value)))
{
if (!string.IsNullOrEmpty(pobj?.Relationship?.ChildPropertyName))
{
var (getter, type) = ss.GetGetter(to.GetInfraWrapperTarget(), pobj!.Relationship!.ChildPropertyName!);
if (type != null && getter != null && WrappingHelper.IsWrappableListType(type, null))
{
var parVal = getter.Invoke();
if (parVal == null)
{
var wt = to.GetWrapperTarget();
if (wt != null)
{
parVal = WrappingHelper.CreateWrappingList(ss, type, wt, pobj.Relationship.ChildPropertyName);
}
var parChildSet = ss.GetSetter(to.GetInfraWrapperTarget(), pobj.Relationship.ChildPropertyName!);
parChildSet.setter?.Invoke(parVal);
}
if (parVal is ICEFList asCefList)
{
var wt = pobj.Child.GetWrapperTarget();
if (wt != null && asCefList.AddWrappedItem(wt))
{
objstate.AddFK(ss, pobj.Relationship, to, pobj.Child, to.GetNotifyFriendly(), false, false, false);
pobj.Processed = true;
}
}
didLink = true;
}
}
}
}
}
if (didLink)
{
// Short-circuit - we did what's below previously
return;
}
foreach (var rel in (from a in parentRels where !string.IsNullOrEmpty(a.ChildPropertyName) && a.ChildType == uw.GetBaseType() select a))
{
var chRoleVals = kvCache.TestAssignReturn(rel, () => { return GetKeyValues(uw, rel.ChildResolvedKey); });
if (rel.ParentType != null && (from a in chRoleVals where a.value != null select a).Any())
{
var testParent = objstate.GetTrackedByPKValue(rel.ParentType, (from a in chRoleVals select a.value));
if (testParent != null)
{
var (getter, type) = ss.GetGetter(testParent.GetInfraWrapperTarget(), rel.ChildPropertyName!);
if (getter != null)
{
var parVal = getter.Invoke();
var asCefList = parVal as ICEFList;
if (parVal == null)
{
// If this is a wrappable type, create instance now to host the child value
if (type != null && WrappingHelper.IsWrappableListType(type, parVal))
{
parVal = WrappingHelper.CreateWrappingList(ss, type, testParent.AsUnwrapped(), rel.ChildPropertyName!);
var parSet = ss.GetSetter(testParent.GetInfraWrapperTarget(), rel.ChildPropertyName!);
parSet.setter?.Invoke(parVal);
asCefList = parVal as ICEFList;
}
}
else
{
// Parent value might not be a CEF list type, see if we can convert it to be one now
if (asCefList == null && parVal is System.Collections.IEnumerable enumerable && type != null && WrappingHelper.IsWrappableListType(type, parVal))
{
asCefList = WrappingHelper.CreateWrappingList(ss, type, testParent.AsUnwrapped(), rel.ChildPropertyName!);
var sValEnum = enumerable.GetEnumerator();
while (sValEnum.MoveNext())
{
var toAdd = sValEnum.Current;
var toAddWrapped = ss.GetDynamicWrapperFor(toAdd, false);
var toAddTracked = ss.InternalCreateAddBase(toAdd, toAddWrapped != null && toAddWrapped.GetRowState() == ObjectState.Added, null, null, null, null, true, false, ss.ResolvedRetrievalIdentityMode(toAdd)) ?? throw new CEFInvalidStateException(InvalidStateType.ObjectTrackingIssue);
if (asCefList != null && !asCefList.ContainsItem(toAddTracked))
{
asCefList.AddWrappedItem(toAddTracked);
}
}
var parSet = ss.GetSetter(testParent.GetInfraWrapperTarget(), rel.ChildPropertyName!);
parSet.setter?.Invoke(asCefList);
didLink = true;
}
}
if (asCefList != null)
{
if (!asCefList.ContainsItem(w ?? uw))
{
if (asCefList.AddWrappedItem(w ?? uw))
{
objstate.AddFK(ss, rel, testParent, to, testParent.GetNotifyFriendly(), true, false, true);
didLink = true;
}
}
}
}
}
}
}
if (!didLink)
{
// Check based on values, not properties - only really need to do if nothing else worked above!
foreach (var rel in (from a in childRels where a.ChildType == uw.GetBaseType() select a))
{
var chRoleVals = kvCache.TestAssignReturn(rel, () => { return GetKeyValues(uw, rel.ChildResolvedKey); });
if (rel.ParentType != null && (from a in chRoleVals where a.value != null select a).Any())
{
var testParent = objstate.GetTrackedByPKValue(rel.ParentType, (from a in chRoleVals select a.value));
if (testParent != null)
{
objstate.AddFK(ss, rel, testParent, to, testParent.GetNotifyFriendly(), false, false, true);
}
}
}
}
}
}
public List<(int ordinal, string name, object? value)> GetKeyValues(object o, IEnumerable<string>? cols = null)
{
if (o == null)
throw new CEFInvalidStateException(InvalidStateType.ArgumentNull, nameof(o));
var ss = CEF.CurrentServiceScope;
if (cols == null)
{
cols = ResolveKeyDefinitionForType(o.GetBaseType());
if (cols == null)
{
throw new CEFInvalidStateException(InvalidStateType.MissingKey, o.GetType().Name);
}
}
List<(int ordinal, string name, object? value)> values = [];
int ordinal = 0;
foreach (var kf in cols)
{
var (getter, _) = ss.GetGetter(o, kf);
if (getter != null)
{
values.Add((ordinal, kf, getter.Invoke()));
}
++ordinal;
}
return values;
}
public void UnlinkChildFromParentContainer(ServiceScope ss, string parentTypeName, string parentFieldName, object parContainer, object child)
{
string key = $"{parentTypeName}.{parentFieldName}";
var ki = KeyService.GetMappedPropertyByFieldName(key);
if (ki != null)
{
var top = ss.GetTrackedByWrapperOrTarget(parContainer);
if (top != null)
{
var toc = ss.GetTrackedByWrapperOrTarget(child);
if (toc != null)
{
var kss = ss.GetServiceState<KeyServiceState>();
kss?.RemoveFK(ss, ki, top, toc, top.GetNotifyFriendly(), true);
}
}
}
}