| | | 1 | | using System.Runtime.CompilerServices; |
| | | 2 | | using NGql.Core.Abstractions; |
| | | 3 | | using NGql.Core.Builders; |
| | | 4 | | using NGql.Core.Extensions; |
| | | 5 | | |
| | | 6 | | namespace NGql.Core.Features; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Extension methods for preserving specific QueryBuilder fields based on specified paths. |
| | | 10 | | /// </summary> |
| | | 11 | | internal static class PreserveExtensions |
| | | 12 | | { |
| | | 13 | | /// <summary> |
| | | 14 | | /// Preserves only the fields that match or are descendants of the specified paths. |
| | | 15 | | /// </summary> |
| | | 16 | | /// <param name="query">The query builder to preserve fields from.</param> |
| | | 17 | | /// <param name="fieldPaths">The field paths to preserve.</param> |
| | | 18 | | /// <returns>A new QueryBuilder instance with only the preserved fields.</returns> |
| | | 19 | | public static QueryBuilder Preserve(this QueryBuilder query, params string[]? fieldPaths) |
| | | 20 | | { |
| | 1017 | 21 | | if (fieldPaths == null || fieldPaths.Length == 0) |
| | 6 | 22 | | return query; |
| | | 23 | | |
| | 1011 | 24 | | var newQuery = QueryBuilder.CreateDefaultBuilder(query.Definition.Name); |
| | | 25 | | |
| | | 26 | | // Copy merging strategy and metadata |
| | 1011 | 27 | | newQuery.Definition.MergingStrategy = query.Definition.MergingStrategy; |
| | 1011 | 28 | | if (query.Definition._metadata != null) |
| | | 29 | | { |
| | 60 | 30 | | foreach (var metadata in query.Definition.Metadata) |
| | | 31 | | { |
| | 18 | 32 | | newQuery.Definition.MetadataInternal[metadata.Key] = metadata.Value; |
| | | 33 | | } |
| | | 34 | | } |
| | | 35 | | |
| | 8898 | 36 | | foreach (var targetPath in fieldPaths) |
| | | 37 | | { |
| | 3438 | 38 | | ExtractMatchingFields(query.Definition.FieldsInternal, newQuery.Definition.FieldsInternal, targetPath.AsSpan |
| | | 39 | | } |
| | | 40 | | |
| | | 41 | | // Carry over the named-fragment definitions the preserved tree still references — |
| | | 42 | | // spreads without their definitions render as broken GraphQL the server rejects. |
| | 1011 | 43 | | CopyReferencedNamedFragments(query.Definition, newQuery.Definition); |
| | | 44 | | |
| | | 45 | | // Extract variables from all preserved fields |
| | 1011 | 46 | | ExtractVariablesFromFields(newQuery.Definition.FieldsInternal, newQuery.Definition.Variables); |
| | | 47 | | |
| | 1011 | 48 | | return newQuery; |
| | | 49 | | } |
| | | 50 | | |
| | | 51 | | /// <summary> |
| | | 52 | | /// Copies into <paramref name="targetDefinition"/> every named-fragment definition that the |
| | | 53 | | /// preserved field tree references via spreads, following spreads transitively through the |
| | | 54 | | /// copied fragments themselves. Unreferenced definitions are skipped — GraphQL rejects |
| | | 55 | | /// operations with unused fragments. Undeclared spread names are left alone (NGql is |
| | | 56 | | /// schemaless; they render verbatim and the server reports them). |
| | | 57 | | /// </summary> |
| | | 58 | | private static void CopyReferencedNamedFragments(QueryDefinition sourceDefinition, QueryDefinition targetDefinition) |
| | | 59 | | { |
| | 1011 | 60 | | var declared = sourceDefinition._namedFragments; |
| | 2010 | 61 | | if (declared is not { Count: > 0 } || targetDefinition._fields is not { Count: > 0 }) return; |
| | | 62 | | |
| | 12 | 63 | | var seen = new HashSet<string>(StringComparer.Ordinal); |
| | 12 | 64 | | var pending = new Stack<string>(); |
| | 48 | 65 | | foreach (var field in targetDefinition._fields.Values) |
| | | 66 | | { |
| | 12 | 67 | | CollectSpreadNames(field, seen, pending); |
| | | 68 | | } |
| | | 69 | | |
| | 27 | 70 | | while (pending.Count > 0) |
| | | 71 | | { |
| | 15 | 72 | | var name = pending.Pop(); |
| | 15 | 73 | | if (!declared.TryGetValue(name, out var fragment)) continue; |
| | | 74 | | |
| | 15 | 75 | | var clone = fragment.DeepClone(); |
| | 15 | 76 | | targetDefinition._namedFragments ??= new Dictionary<string, NamedFragmentDefinition>(StringComparer.Ordinal) |
| | 15 | 77 | | targetDefinition._namedFragments[name] = clone; |
| | | 78 | | |
| | 15 | 79 | | if (clone._fields is { Count: > 0 }) |
| | | 80 | | { |
| | 15 | 81 | | ExtractVariablesFromFields(clone._fields, targetDefinition.Variables); |
| | | 82 | | } |
| | 15 | 83 | | CollectFragmentBodySpreadNames(clone._fields, clone._fragments, clone._spreadFragments, seen, pending); |
| | | 84 | | } |
| | 12 | 85 | | } |
| | | 86 | | |
| | | 87 | | private static void CollectSpreadNames(FieldDefinition field, HashSet<string> seen, Stack<string> pending) |
| | 30 | 88 | | => CollectFragmentBodySpreadNames(field._children, field._fragments, field._spreadFragments, seen, pending); |
| | | 89 | | |
| | | 90 | | [System.Diagnostics.CodeAnalysis.SuppressMessage( |
| | | 91 | | "Major Code Smell", "S3267:Loops should be simplified using the \"Where\" LINQ method", |
| | | 92 | | Justification = "HashSet.Add is the filter AND the side effect — a Where(seen.Add) would hide the mutation; plai |
| | | 93 | | private static void CollectFragmentBodySpreadNames( |
| | | 94 | | FieldChildren? fields, |
| | | 95 | | Dictionary<string, InlineFragmentDefinition>? fragments, |
| | | 96 | | List<string>? spreads, |
| | | 97 | | HashSet<string> seen, |
| | | 98 | | Stack<string> pending) |
| | | 99 | | { |
| | 48 | 100 | | if (spreads is { Count: > 0 }) |
| | | 101 | | { |
| | 60 | 102 | | foreach (var name in spreads) |
| | | 103 | | { |
| | 30 | 104 | | if (seen.Add(name)) pending.Push(name); |
| | | 105 | | } |
| | | 106 | | } |
| | | 107 | | |
| | 48 | 108 | | if (fragments is { Count: > 0 }) |
| | | 109 | | { |
| | 12 | 110 | | foreach (var fragment in fragments.Values) |
| | | 111 | | { |
| | 3 | 112 | | CollectFragmentBodySpreadNames(fragment._fields, fragment._fragments, fragment._spreadFragments, seen, p |
| | | 113 | | } |
| | | 114 | | } |
| | | 115 | | |
| | 48 | 116 | | if (fields is { Count: > 0 }) |
| | | 117 | | { |
| | 72 | 118 | | foreach (var child in fields.AsSpan()) |
| | | 119 | | { |
| | 18 | 120 | | CollectSpreadNames(child, seen, pending); |
| | | 121 | | } |
| | | 122 | | } |
| | 48 | 123 | | } |
| | | 124 | | |
| | | 125 | | private static void ExtractMatchingFields(Dictionary<string, FieldDefinition> sourceFields, |
| | | 126 | | Dictionary<string, FieldDefinition> targetFields, ReadOnlySpan<char> path) |
| | | 127 | | { |
| | 3438 | 128 | | var isLeafPath = SplitFirstSegment(path, out var currentSegment, out var remainingPath); |
| | | 129 | | |
| | 3438 | 130 | | var match = FindFieldByNameOrAlias(sourceFields, currentSegment); |
| | 3462 | 131 | | if (!match.HasValue) return; |
| | | 132 | | |
| | 3414 | 133 | | var (fieldKey, fieldDef) = match.Value; |
| | | 134 | | |
| | 3414 | 135 | | if (isLeafPath) |
| | | 136 | | { |
| | | 137 | | // Deep-clone the preserved subtree: storing the source reference would alias the |
| | | 138 | | // two builders, letting later mutations of either leak into the other (the |
| | | 139 | | // role-based filtering scenario hands the preserved query out while the source |
| | | 140 | | // keeps evolving). |
| | 492 | 141 | | targetFields[fieldKey] = fieldDef.DeepClone(); |
| | 492 | 142 | | return; |
| | | 143 | | } |
| | | 144 | | |
| | 2928 | 145 | | if (fieldDef._children is null) return; |
| | | 146 | | |
| | 2916 | 147 | | var existing = GetOrAddTargetChild(targetFields, fieldKey, fieldDef); |
| | 2916 | 148 | | ExtractMatchingFields(fieldDef._children, existing._children!, remainingPath); |
| | 2916 | 149 | | } |
| | | 150 | | |
| | | 151 | | private static void ExtractMatchingFields(FieldChildren sourceFields, FieldChildren targetFields, ReadOnlySpan<char> |
| | | 152 | | { |
| | 4932 | 153 | | var isLeafPath = SplitFirstSegment(path, out var currentSegment, out var remainingPath); |
| | | 154 | | |
| | 4941 | 155 | | if (!TryFindByNameOrAlias(sourceFields, currentSegment, out var fieldKey, out var fieldDef)) return; |
| | | 156 | | |
| | 4923 | 157 | | if (isLeafPath) |
| | | 158 | | { |
| | | 159 | | // Same isolation rule as the Dictionary variant above: the preserved tree must |
| | | 160 | | // never share FieldDefinition instances with the source. |
| | 2904 | 161 | | targetFields.Set(fieldKey, fieldDef.DeepClone()); |
| | 2904 | 162 | | return; |
| | | 163 | | } |
| | | 164 | | |
| | 2022 | 165 | | if (fieldDef._children is null) return; |
| | | 166 | | |
| | 2016 | 167 | | var targetChild = GetOrAddTargetChild(targetFields, fieldKey, fieldDef); |
| | 2016 | 168 | | ExtractMatchingFields(fieldDef._children, targetChild._children!, remainingPath); |
| | 2016 | 169 | | } |
| | | 170 | | |
| | | 171 | | private static bool SplitFirstSegment(ReadOnlySpan<char> path, out ReadOnlySpan<char> current, out ReadOnlySpan<char |
| | | 172 | | { |
| | 8370 | 173 | | var dot = path.IndexOf('.'); |
| | 8370 | 174 | | if (dot < 0) |
| | | 175 | | { |
| | 3411 | 176 | | current = path; |
| | 3411 | 177 | | remaining = ReadOnlySpan<char>.Empty; |
| | 3411 | 178 | | return true; |
| | | 179 | | } |
| | 4959 | 180 | | current = path[..dot]; |
| | 4959 | 181 | | remaining = path[(dot + 1)..]; |
| | 4959 | 182 | | return false; |
| | | 183 | | } |
| | | 184 | | |
| | | 185 | | private static bool TryFindByNameOrAlias(FieldChildren children, ReadOnlySpan<char> nameOrAlias, out string key, out |
| | | 186 | | { |
| | 17919 | 187 | | foreach (var f in children.AsSpan()) |
| | | 188 | | { |
| | 6489 | 189 | | if (f.Name.AsSpan().Equals(nameOrAlias, StringComparison.OrdinalIgnoreCase) |
| | 6489 | 190 | | || (f.Alias is { Length: > 0 } alias && alias.AsSpan().Equals(nameOrAlias, StringComparison.OrdinalIgnor |
| | | 191 | | { |
| | 4923 | 192 | | key = f.Name; |
| | 4923 | 193 | | field = f; |
| | 4923 | 194 | | return true; |
| | | 195 | | } |
| | | 196 | | } |
| | 9 | 197 | | key = string.Empty; |
| | 9 | 198 | | field = null!; |
| | 9 | 199 | | return false; |
| | | 200 | | } |
| | | 201 | | |
| | | 202 | | private static FieldDefinition GetOrAddTargetChild(Dictionary<string, FieldDefinition> target, string fieldKey, Fiel |
| | | 203 | | { |
| | 2916 | 204 | | if (!target.TryGetValue(fieldKey, out var existing)) |
| | | 205 | | { |
| | 1500 | 206 | | existing = CloneFieldWithoutChildren(source); |
| | 1500 | 207 | | target[fieldKey] = existing; |
| | | 208 | | } |
| | 2916 | 209 | | existing._children ??= new FieldChildren(); |
| | 2916 | 210 | | return existing; |
| | | 211 | | } |
| | | 212 | | |
| | | 213 | | private static FieldDefinition GetOrAddTargetChild(FieldChildren targetFields, string fieldKey, FieldDefinition sour |
| | | 214 | | { |
| | 2016 | 215 | | if (!targetFields.TryGetValue(fieldKey, out var existing) || existing is null) |
| | | 216 | | { |
| | 1152 | 217 | | existing = CloneFieldWithoutChildren(source); |
| | 1152 | 218 | | targetFields.Set(fieldKey, existing); |
| | | 219 | | } |
| | 2016 | 220 | | existing._children ??= new FieldChildren(); |
| | 2016 | 221 | | return existing; |
| | | 222 | | } |
| | | 223 | | |
| | | 224 | | /// <summary> |
| | | 225 | | /// Creates a shallow clone of a field without its children, preserving arguments, metadata, |
| | | 226 | | /// and directives. |
| | | 227 | | /// </summary> |
| | | 228 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 229 | | private static FieldDefinition CloneFieldWithoutChildren(FieldDefinition source) |
| | | 230 | | { |
| | | 231 | | // FieldDefinition._type is always set by every constructor; the null-coalesce was |
| | | 232 | | // a defensive guard for the rare `with { Type = null }` path and never fires here. |
| | | 233 | | // Arguments are copied, not referenced — intermediate path nodes must be isolated |
| | | 234 | | // from the source the same way leaf subtrees are (Where on a preserved intermediate |
| | | 235 | | // would otherwise mutate the source's argument dictionary). |
| | 2652 | 236 | | var cloned = new FieldDefinition( |
| | 2652 | 237 | | source.Name, |
| | 2652 | 238 | | source._type!, |
| | 2652 | 239 | | source.Alias, |
| | 2652 | 240 | | source._arguments is null ? null : new SortedDictionary<string, object?>(source._arguments, StringComparer.O |
| | 2652 | 241 | | { |
| | 2652 | 242 | | Path = source.Path |
| | 2652 | 243 | | }; |
| | | 244 | | |
| | 2652 | 245 | | cloned.IsNeverMerge = source.IsNeverMerge; |
| | | 246 | | |
| | 2652 | 247 | | if (source._metadata != null) |
| | | 248 | | { |
| | 18 | 249 | | foreach (var meta in source._metadata) |
| | | 250 | | { |
| | 6 | 251 | | cloned.Metadata[meta.Key] = meta.Value; |
| | | 252 | | } |
| | | 253 | | } |
| | | 254 | | |
| | | 255 | | // An intermediate node on a preserved path (e.g. "user" when preserving "user.id") can |
| | | 256 | | // itself carry a conditional include/skip directive that gates the whole subtree beneath |
| | | 257 | | // it — dropping it here would silently make the preserved projection unconditional where |
| | | 258 | | // the source was conditional. FieldDirective is an immutable record, so sharing the list |
| | | 259 | | // entries is safe; only the LIST needs to be a fresh instance so mutating the clone's |
| | | 260 | | // directives can never reach back into the source. |
| | 2652 | 261 | | cloned._directives = source._directives is { Count: > 0 } |
| | 2652 | 262 | | ? new List<FieldDirective>(source._directives) |
| | 2652 | 263 | | : null; |
| | | 264 | | |
| | 2652 | 265 | | return cloned; |
| | | 266 | | } |
| | | 267 | | |
| | | 268 | | // All call sites pre-check the fields collection for null (NavigatePath, PreserveAtPath, |
| | | 269 | | // QueryDefinitionExtensions.NavigatePath); the parameter could safely be tightened but |
| | | 270 | | // is kept nullable to preserve the existing internal API signature. |
| | | 271 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 272 | | internal static KeyValuePair<string, FieldDefinition>? FindFieldByNameOrAlias(IReadOnlyDictionary<string, FieldDefin |
| | | 273 | | { |
| | 15897 | 274 | | foreach (var kvp in fields!) |
| | | 275 | | { |
| | 5694 | 276 | | if (MatchesKeyNameOrAlias(kvp, nameOrAlias)) |
| | | 277 | | { |
| | 4311 | 278 | | return kvp; |
| | | 279 | | } |
| | | 280 | | } |
| | | 281 | | |
| | 99 | 282 | | return null; |
| | 4311 | 283 | | } |
| | | 284 | | |
| | | 285 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 286 | | private static bool MatchesKeyNameOrAlias(KeyValuePair<string, FieldDefinition> kvp, ReadOnlySpan<char> nameOrAlias) |
| | 5694 | 287 | | => nameOrAlias.Equals(kvp.Key.AsSpan(), StringComparison.OrdinalIgnoreCase) |
| | 5694 | 288 | | || nameOrAlias.Equals(kvp.Value.Name.AsSpan(), StringComparison.OrdinalIgnoreCase) |
| | 5694 | 289 | | || (!string.IsNullOrEmpty(kvp.Value.Alias) && nameOrAlias.Equals(kvp.Value.Alias.AsSpan(), StringComparison.Ordi |
| | | 290 | | |
| | | 291 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 292 | | private static void ExtractVariablesFromFields(FieldChildren children, SortedSet<Variable> variables) |
| | | 293 | | { |
| | 14100 | 294 | | foreach (var field in children.AsSpan()) |
| | | 295 | | { |
| | 4227 | 296 | | ExtractVariablesFromField(field, variables); |
| | | 297 | | } |
| | 2823 | 298 | | } |
| | | 299 | | |
| | | 300 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 301 | | private static void ExtractVariablesFromFields(Dictionary<string, FieldDefinition> fields, SortedSet<Variable> varia |
| | | 302 | | { |
| | 5274 | 303 | | foreach (var field in fields.Values) |
| | | 304 | | { |
| | 1626 | 305 | | ExtractVariablesFromField(field, variables); |
| | | 306 | | } |
| | 1011 | 307 | | } |
| | | 308 | | |
| | | 309 | | // A preserved field's conditional-include directive — or any custom directive carrying a |
| | | 310 | | // Variable argument — must keep its variable declared in the projected query's signature, |
| | | 311 | | // exactly like a field argument does. Without this, a preserved field with an include/skip |
| | | 312 | | // condition would render referencing a variable never declared, which a GraphQL server rejects. |
| | | 313 | | [System.Diagnostics.CodeAnalysis.SuppressMessage( |
| | | 314 | | "Major Code Smell", "S3267:Loops should be simplified using the \"Where\" LINQ method", |
| | | 315 | | Justification = "Plain foreach avoids a Where enumerator allocation on the preservation hot path.")] |
| | | 316 | | private static void ExtractVariablesFromField(FieldDefinition field, SortedSet<Variable> variables) |
| | | 317 | | { |
| | 5853 | 318 | | if (field._arguments?.Count > 0) |
| | | 319 | | { |
| | 15 | 320 | | Helpers.ExtractVariablesFromValue(field._arguments, variables); |
| | | 321 | | } |
| | 5853 | 322 | | if (field._directives is { Count: > 0 } directives) |
| | | 323 | | { |
| | 24 | 324 | | foreach (var directive in directives) |
| | | 325 | | { |
| | 6 | 326 | | if (directive.Arguments is { Count: > 0 }) |
| | | 327 | | { |
| | 6 | 328 | | Helpers.ExtractVariablesFromValue(directive.Arguments, variables); |
| | | 329 | | } |
| | | 330 | | } |
| | | 331 | | } |
| | 5853 | 332 | | if (field._children is { Count: > 0 }) |
| | | 333 | | { |
| | 2808 | 334 | | ExtractVariablesFromFields(field._children, variables); |
| | | 335 | | } |
| | 5853 | 336 | | } |
| | | 337 | | } |