| | | 1 | | using System.Runtime.CompilerServices; |
| | | 2 | | using NGql.Core.Abstractions; |
| | | 3 | | using NGql.Core.Exceptions; |
| | | 4 | | using NGql.Core.Features; |
| | | 5 | | |
| | | 6 | | namespace NGql.Core.Extensions; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Extension methods and utilities for FieldDefinition operations. |
| | | 10 | | /// </summary> |
| | | 11 | | internal static class FieldDefinitionExtensions |
| | | 12 | | { |
| | | 13 | | /// <summary> |
| | | 14 | | /// Determines if two fields can be merged based on their structure and arguments. |
| | | 15 | | /// The recursion is bounded by the field tree's depth — the public API does not allow |
| | | 16 | | /// constructing cyclic trees (FieldDefinition.Fields is get-only, _children is internal), |
| | | 17 | | /// so the recursion always terminates. A library bug introducing a cycle would surface as |
| | | 18 | | /// a StackOverflowException, which is louder and more actionable than a swallowed throw. |
| | | 19 | | /// </summary> |
| | | 20 | | internal static bool CanMergeFields(FieldDefinition existingField, FieldDefinition incomingField) |
| | | 21 | | { |
| | 192 | 22 | | if (!Helpers.AreArgumentsEqual(existingField._arguments, incomingField._arguments)) |
| | 39 | 23 | | return false; |
| | 153 | 24 | | return AreNestedFieldsCompatible(existingField, incomingField); |
| | | 25 | | } |
| | | 26 | | |
| | | 27 | | private static bool AreNestedFieldsCompatible(FieldDefinition existingField, FieldDefinition incomingField) |
| | 354 | 28 | | => IncomingChildrenCompatible(existingField._children, incomingField._children) |
| | 354 | 29 | | && ExistingExtrasCompatible(existingField, incomingField._children); |
| | | 30 | | |
| | | 31 | | private static bool IncomingChildrenCompatible(FieldChildren? existingChildren, FieldChildren? incomingChildren) |
| | | 32 | | { |
| | 408 | 33 | | if (incomingChildren is not { Count: > 0 }) return true; |
| | | 34 | | |
| | 300 | 35 | | var span = incomingChildren.AsSpan(); |
| | 1218 | 36 | | for (int i = 0; i < span.Length; i++) |
| | | 37 | | { |
| | 339 | 38 | | if (!IsIncomingChildCompatible(existingChildren, span[i])) |
| | 30 | 39 | | return false; |
| | | 40 | | } |
| | 270 | 41 | | return true; |
| | | 42 | | } |
| | | 43 | | |
| | | 44 | | private static bool IsIncomingChildCompatible(FieldChildren? existingChildren, FieldDefinition incomingChild) |
| | | 45 | | { |
| | 348 | 46 | | if (existingChildren is null) return !HasAnyArguments(incomingChild); |
| | 447 | 47 | | if (!existingChildren.TryGetValue(incomingChild.Name, out var existingChild)) return !HasAnyArguments(incomingCh |
| | 213 | 48 | | return Helpers.AreArgumentsEqual(existingChild!._arguments, incomingChild._arguments) |
| | 213 | 49 | | && AreNestedFieldsCompatible(existingChild, incomingChild); |
| | | 50 | | } |
| | | 51 | | |
| | | 52 | | // Skip the existing-not-in-incoming check entirely when nothing in the existing subtree |
| | | 53 | | // could ever fail it — early-out when no field in the existing subtree carries arguments. |
| | | 54 | | private static bool ExistingExtrasCompatible(FieldDefinition existingField, FieldChildren? incomingChildren) |
| | | 55 | | { |
| | 324 | 56 | | var existingChildren = existingField._children; |
| | 324 | 57 | | if (existingChildren is not { Count: > 0 } || !SubtreeHasAnyArguments(existingField)) |
| | 300 | 58 | | return true; |
| | | 59 | | |
| | 24 | 60 | | var span = existingChildren.AsSpan(); |
| | 84 | 61 | | for (int i = 0; i < span.Length; i++) |
| | | 62 | | { |
| | 24 | 63 | | var existingChild = span[i]; |
| | 24 | 64 | | if (!IsExistingExtraCompatible(existingChild, incomingChildren)) |
| | 6 | 65 | | return false; |
| | | 66 | | } |
| | 18 | 67 | | return true; |
| | | 68 | | } |
| | | 69 | | |
| | | 70 | | private static bool IsExistingExtraCompatible(FieldDefinition existingChild, FieldChildren? incomingChildren) |
| | | 71 | | { |
| | 27 | 72 | | if (incomingChildren is null) return !HasAnyArguments(existingChild); |
| | 21 | 73 | | return incomingChildren.Find(existingChild.Name) is not null || !HasAnyArguments(existingChild); |
| | | 74 | | } |
| | | 75 | | |
| | | 76 | | private static bool SubtreeHasAnyArguments(FieldDefinition field) |
| | | 77 | | { |
| | 876 | 78 | | if (field._subtreeHasAnyArguments is { } cached) return cached; |
| | | 79 | | |
| | 474 | 80 | | var result = field._arguments is { Count: > 0 } || AnyChildHasArguments(field._children); |
| | 474 | 81 | | field._subtreeHasAnyArguments = result; |
| | 474 | 82 | | return result; |
| | | 83 | | } |
| | | 84 | | |
| | | 85 | | private static bool AnyChildHasArguments(FieldChildren? children) |
| | | 86 | | { |
| | 621 | 87 | | if (children is null || children.Count == 0) return false; |
| | 297 | 88 | | var span = children.AsSpan(); |
| | 1368 | 89 | | for (int i = 0; i < span.Length; i++) |
| | | 90 | | { |
| | 423 | 91 | | if (SubtreeHasAnyArguments(span[i])) return true; |
| | | 92 | | } |
| | 279 | 93 | | return false; |
| | | 94 | | } |
| | | 95 | | |
| | | 96 | | private static bool HasAnyArguments(FieldDefinition field) |
| | | 97 | | { |
| | 201 | 98 | | if (field._arguments is { Count: > 0 }) return true; |
| | 291 | 99 | | if (field._children is null) return false; |
| | 171 | 100 | | foreach (var child in field._children.AsSpan()) |
| | | 101 | | { |
| | 51 | 102 | | if (HasAnyArguments(child)) return true; |
| | | 103 | | } |
| | 36 | 104 | | return false; |
| | | 105 | | } |
| | | 106 | | |
| | | 107 | | /// <summary> |
| | | 108 | | /// Deep-clones <paramref name="source"/> producing a new <see cref="FieldDefinition"/> that |
| | | 109 | | /// shares no mutable state with the original. Used by <see cref="QueryMerger"/> when adding an |
| | | 110 | | /// incoming field reference into the target dictionary, so subsequent in-place merges into the |
| | | 111 | | /// target do not leak back into the source builder. |
| | | 112 | | /// </summary> |
| | | 113 | | internal static FieldDefinition DeepClone(this FieldDefinition source) |
| | | 114 | | { |
| | 774 | 115 | | var clone = new FieldDefinition( |
| | 774 | 116 | | source.Name, |
| | 774 | 117 | | source._type!, |
| | 774 | 118 | | source._alias, |
| | 774 | 119 | | source._arguments is null ? null : new SortedDictionary<string, object?>(source._arguments, StringComparer.O |
| | 774 | 120 | | { |
| | 774 | 121 | | Path = source.Path, |
| | 774 | 122 | | IsNeverMerge = source.IsNeverMerge, |
| | 774 | 123 | | }; |
| | | 124 | | |
| | 774 | 125 | | if (source._metadata is { Count: > 0 }) |
| | | 126 | | { |
| | 0 | 127 | | foreach (var kvp in source._metadata) clone.Metadata[kvp.Key] = kvp.Value; |
| | | 128 | | } |
| | | 129 | | |
| | 774 | 130 | | if (source._children is { Count: > 0 }) |
| | | 131 | | { |
| | 414 | 132 | | clone._children = new FieldChildren(); |
| | 1836 | 133 | | foreach (var child in source._children.AsSpan()) |
| | 504 | 134 | | clone._children.Append(child.DeepClone()); |
| | | 135 | | } |
| | | 136 | | |
| | 774 | 137 | | return clone; |
| | | 138 | | } |
| | | 139 | | |
| | | 140 | | /// <summary> |
| | | 141 | | /// Merges <paramref name="incoming"/> INTO <paramref name="existing"/>, mutating its child collection |
| | | 142 | | /// and argument dictionary in place. The caller must own <paramref name="existing"/> exclusively |
| | | 143 | | /// (no external aliases) — used by <see cref="QueryMerger"/> when the result will overwrite the |
| | | 144 | | /// dictionary entry that holds <paramref name="existing"/>. |
| | | 145 | | /// </summary> |
| | | 146 | | /// <returns><paramref name="existing"/> after mutation.</returns> |
| | | 147 | | internal static FieldDefinition MergeFieldsInPlace(FieldDefinition existing, FieldDefinition incoming) |
| | | 148 | | { |
| | 315 | 149 | | ThrowIfTypesConflict(existing, incoming); |
| | 306 | 150 | | MergeIncomingChildrenInPlace(existing, incoming._children); |
| | 294 | 151 | | MergeIncomingArgumentsInPlace(existing, incoming._arguments); |
| | 294 | 152 | | return existing; |
| | | 153 | | } |
| | | 154 | | |
| | | 155 | | private static void ThrowIfTypesConflict(FieldDefinition existing, FieldDefinition incoming) |
| | | 156 | | { |
| | | 157 | | // _type defaults to Constants.DefaultFieldType in every public constructor and is |
| | | 158 | | // never null on the merge path through Include — the field is always touched by |
| | | 159 | | // QueryBuilder.AddField which goes through FieldFactory.CreateFieldDefinition. |
| | 621 | 160 | | if (existing._type!.AsSpan().Equals(incoming._type!.AsSpan(), StringComparison.OrdinalIgnoreCase)) return; |
| | 9 | 161 | | throw new QueryMergeException($"Type conflict: existing field has type '{existing._type}', incoming field has ty |
| | | 162 | | } |
| | | 163 | | |
| | | 164 | | private static void MergeIncomingChildrenInPlace(FieldDefinition existing, FieldChildren? incomingChildren) |
| | | 165 | | { |
| | 351 | 166 | | if (incomingChildren is null) return; |
| | | 167 | | |
| | | 168 | | // Existing._children is non-null on every path that reaches here through the public |
| | | 169 | | // Include API: type-compatibility means both sides are object-typed, and object-typed |
| | | 170 | | // FieldDefinitions get a children collection from QueryBuilder.AddField at construction |
| | | 171 | | // time. Trust the invariant. |
| | 261 | 172 | | var existingChildren = existing._children!; |
| | 261 | 173 | | var span = incomingChildren.AsSpan(); |
| | 1092 | 174 | | for (int i = 0; i < span.Length; i++) |
| | | 175 | | { |
| | 297 | 176 | | MergeChildInPlace(existingChildren, span[i]); |
| | | 177 | | } |
| | 249 | 178 | | existing._subtreeHasAnyArguments = null; |
| | 249 | 179 | | } |
| | | 180 | | |
| | | 181 | | private static void MergeIncomingArgumentsInPlace(FieldDefinition existing, SortedDictionary<string, object?>? incom |
| | | 182 | | { |
| | 573 | 183 | | if (incomingArguments is not { Count: > 0 }) return; |
| | 15 | 184 | | existing.MergeFieldArgumentsInPlace(incomingArguments); |
| | 15 | 185 | | existing._subtreeHasAnyArguments = null; |
| | 15 | 186 | | } |
| | | 187 | | |
| | | 188 | | private static void MergeChildInPlace(FieldChildren existingChildren, FieldDefinition incomingChild) |
| | | 189 | | { |
| | 297 | 190 | | if (existingChildren.TryGetValue(incomingChild.Name, out var existingNested) && existingNested != null) |
| | | 191 | | { |
| | 192 | 192 | | MergeFieldsInPlace(existingNested, incomingChild); |
| | 180 | 193 | | return; |
| | | 194 | | } |
| | | 195 | | |
| | | 196 | | // Deep-clone so target's tree never references nodes owned by the source builder. Any |
| | | 197 | | // later in-place merges into existingChildren must not propagate back to the source. |
| | 105 | 198 | | var clone = incomingChild.DeepClone(); |
| | | 199 | | |
| | | 200 | | // Effective-name conflict can only occur when the incoming field carries an alias |
| | | 201 | | // distinct from its name; otherwise the Name lookup above would have caught it. |
| | 105 | 202 | | if (!ReferenceEquals(incomingChild._effectiveName, incomingChild.Name) && |
| | 105 | 203 | | HasEffectiveNameConflict(existingChildren, incomingChild._effectiveName)) |
| | | 204 | | { |
| | 3 | 205 | | var uniqueAlias = KeyGenerator.GenerateUniqueKey(incomingChild._effectiveName, existingChildren.AsSpan()); |
| | 3 | 206 | | existingChildren.Append(clone with { Alias = uniqueAlias }); |
| | | 207 | | } |
| | | 208 | | else |
| | | 209 | | { |
| | 102 | 210 | | existingChildren.Append(clone); |
| | | 211 | | } |
| | 102 | 212 | | } |
| | | 213 | | |
| | | 214 | | private static bool HasEffectiveNameConflict(FieldChildren children, string effectiveName) |
| | | 215 | | { |
| | 237 | 216 | | foreach (var f in children.AsSpan()) |
| | | 217 | | { |
| | 81 | 218 | | if (string.Equals(f._effectiveName, effectiveName, StringComparison.OrdinalIgnoreCase)) |
| | 3 | 219 | | return true; |
| | | 220 | | } |
| | 36 | 221 | | return false; |
| | | 222 | | } |
| | | 223 | | |
| | | 224 | | /// <summary> |
| | | 225 | | /// Merges <paramref name="newArguments"/> into <paramref name="existingField"/>'s argument |
| | | 226 | | /// dictionary in place. Caller (MergeFieldsInPlace via CanMergeFields) guarantees that |
| | | 227 | | /// <c>existingField._arguments</c> already has the same keys as <paramref name="newArguments"/>; |
| | | 228 | | /// the merge here only refines values for keys that hold nested dictionaries. |
| | | 229 | | /// </summary> |
| | | 230 | | // Callers (MergeFieldsInPlace via CanMergeFields) guarantee newArguments has Count > 0 |
| | | 231 | | // and existingField._arguments is non-null with the same keys. |
| | | 232 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 233 | | internal static void MergeFieldArgumentsInPlace(this FieldDefinition existingField, IDictionary<string, object?> new |
| | | 234 | | { |
| | 15 | 235 | | var target = existingField._arguments!; |
| | 60 | 236 | | foreach (var (key, newValue) in newArguments) |
| | | 237 | | { |
| | 15 | 238 | | if (target.TryGetValue(key, out var existingValue) |
| | 15 | 239 | | && existingValue is IDictionary<string, object?> existingDict |
| | 15 | 240 | | && newValue is IDictionary<string, object?> newDict) |
| | | 241 | | { |
| | 6 | 242 | | target[key] = Helpers.MergeNullableDictionaries(existingDict, newDict); |
| | 6 | 243 | | continue; |
| | | 244 | | } |
| | 9 | 245 | | target[key] = newValue; |
| | | 246 | | } |
| | 15 | 247 | | } |
| | | 248 | | |
| | | 249 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 250 | | internal static FieldDefinition MergeFieldArguments(this FieldDefinition existingField, IDictionary<string, object?> |
| | | 251 | | { |
| | 474 | 252 | | if (newArguments is not { Count: > 0 }) return existingField; |
| | | 253 | | |
| | 372 | 254 | | if (existingField._arguments is null || existingField._arguments.Count == 0) |
| | | 255 | | { |
| | 327 | 256 | | return existingField with { _arguments = AsSortedCaseInsensitive(newArguments) }; |
| | | 257 | | } |
| | | 258 | | |
| | 45 | 259 | | var merged = CopyToSortedCaseInsensitive(existingField._arguments); |
| | 45 | 260 | | ApplyArgumentOverrides(merged, newArguments); |
| | 45 | 261 | | return existingField with { _arguments = merged }; |
| | | 262 | | } |
| | | 263 | | |
| | | 264 | | private static SortedDictionary<string, object?> AsSortedCaseInsensitive(IDictionary<string, object?> source) |
| | 327 | 265 | | => source is SortedDictionary<string, object?> sd |
| | 327 | 266 | | ? sd |
| | 327 | 267 | | : new SortedDictionary<string, object?>(source, StringComparer.OrdinalIgnoreCase); |
| | | 268 | | |
| | | 269 | | private static SortedDictionary<string, object?> CopyToSortedCaseInsensitive(IDictionary<string, object?> source) |
| | | 270 | | { |
| | 45 | 271 | | var copy = new SortedDictionary<string, object?>(StringComparer.OrdinalIgnoreCase); |
| | 243 | 272 | | foreach (var (key, value) in source) copy[key] = value; |
| | 45 | 273 | | return copy; |
| | | 274 | | } |
| | | 275 | | |
| | | 276 | | private static void ApplyArgumentOverrides(SortedDictionary<string, object?> target, IDictionary<string, object?> ov |
| | | 277 | | { |
| | 192 | 278 | | foreach (var (key, newValue) in overrides) |
| | | 279 | | { |
| | 51 | 280 | | target[key] = MergedArgumentValue(target, key, newValue); |
| | | 281 | | } |
| | 45 | 282 | | } |
| | | 283 | | |
| | | 284 | | private static object? MergedArgumentValue(SortedDictionary<string, object?> target, string key, object? newValue) |
| | | 285 | | { |
| | 51 | 286 | | if (target.TryGetValue(key, out var existingValue) |
| | 51 | 287 | | && existingValue is IDictionary<string, object?> existingDict |
| | 51 | 288 | | && newValue is IDictionary<string, object?> newDict) |
| | | 289 | | { |
| | 3 | 290 | | return Helpers.MergeNullableDictionaries(existingDict, newDict); |
| | | 291 | | } |
| | 48 | 292 | | return newValue; |
| | | 293 | | } |
| | | 294 | | } |