| | | 1 | | using System.Buffers; |
| | | 2 | | using System.Collections; |
| | | 3 | | using System.Text; |
| | | 4 | | using NGql.Core; |
| | | 5 | | using NGql.Core.Abstractions; |
| | | 6 | | using NGql.Core.Caching; |
| | | 7 | | using NGql.Core.Extensions; |
| | | 8 | | |
| | | 9 | | namespace NGql.Core.Builders; |
| | | 10 | | |
| | | 11 | | internal sealed class QueryTextBuilder |
| | | 12 | | { |
| | | 13 | | private readonly StringBuilder _stringBuilder; |
| | | 14 | | |
| | | 15 | | // Constructor for creating new instances |
| | 708 | 16 | | private QueryTextBuilder() => _stringBuilder = new StringBuilder(); |
| | | 17 | | |
| | | 18 | | private const int IndentSize = 4; |
| | | 19 | | private const int MaxBuilderCapacity = 256 * 1024; // 256KB threshold before reset |
| | | 20 | | |
| | | 21 | | // Pre-allocated padding strings for common indentation levels to avoid repeated allocations |
| | 6 | 22 | | private static readonly string[] PaddingCache = new string[20]; |
| | | 23 | | |
| | | 24 | | // Singleton comparer — Dictionary<string,FieldDefinition> is unordered, so we sort at render time. |
| | | 25 | | // Static readonly avoids any per-call allocation; the static lambda is stored as a cached delegate. |
| | 6 | 26 | | private static readonly IComparer<FieldDefinition> FieldSortComparer = |
| | 6 | 27 | | Comparer<FieldDefinition>.Create(static (a, b) => |
| | 37653 | 28 | | StringComparer.OrdinalIgnoreCase.Compare(a.Alias ?? a.Name, b.Alias ?? b.Name)); |
| | | 29 | | |
| | | 30 | | // SHARED thread-local builder pool used by both QueryBlock and QueryDefinition |
| | | 31 | | // This consolidates the pooling strategy and prevents duplicate ThreadLocal instances |
| | 6 | 32 | | private static readonly ThreadLocal<Stack<QueryTextBuilder>> SharedBuilderStack = |
| | 357 | 33 | | new(() => new Stack<QueryTextBuilder>()); |
| | | 34 | | |
| | | 35 | | private const int MaxPooledBuilders = 4; |
| | | 36 | | |
| | | 37 | | static QueryTextBuilder() |
| | | 38 | | { |
| | 252 | 39 | | for (int i = 0; i < PaddingCache.Length; i++) |
| | | 40 | | { |
| | 120 | 41 | | PaddingCache[i] = new string(' ', i * IndentSize); |
| | | 42 | | } |
| | 6 | 43 | | } |
| | | 44 | | |
| | | 45 | | /// <summary> |
| | | 46 | | /// Gets a builder instance from the thread-local pool or creates a new one. |
| | | 47 | | /// Caller must return the builder via <see cref="ReturnToPool(QueryTextBuilder)"/>. |
| | | 48 | | /// </summary> |
| | | 49 | | internal static QueryTextBuilder GetFromPool() |
| | | 50 | | { |
| | 8319 | 51 | | var stack = SharedBuilderStack.Value!; |
| | 8319 | 52 | | return stack.Count > 0 ? stack.Pop() : new QueryTextBuilder(); |
| | | 53 | | } |
| | | 54 | | |
| | | 55 | | /// <summary> |
| | | 56 | | /// Returns a builder to the thread-local pool for reuse. |
| | | 57 | | /// Clears the builder and checks capacity to prevent unbounded memory growth. |
| | | 58 | | /// </summary> |
| | | 59 | | internal static void ReturnToPool(QueryTextBuilder builder) |
| | | 60 | | { |
| | 8319 | 61 | | builder._stringBuilder.Clear(); |
| | | 62 | | |
| | | 63 | | // Don't repool builders that have grown too large (prevents memory leak) |
| | 8319 | 64 | | if (builder._stringBuilder.Capacity > MaxBuilderCapacity) |
| | | 65 | | { |
| | 3 | 66 | | return; |
| | | 67 | | } |
| | | 68 | | |
| | 8316 | 69 | | var stack = SharedBuilderStack.Value!; |
| | 8316 | 70 | | if (stack.Count < MaxPooledBuilders) |
| | | 71 | | { |
| | 8316 | 72 | | stack.Push(builder); |
| | | 73 | | } |
| | | 74 | | // If pool is full, let GC handle it |
| | 8316 | 75 | | } |
| | | 76 | | |
| | | 77 | | /// <summary> |
| | | 78 | | /// Gets padding string for the specified indent level, using cache for common levels. |
| | | 79 | | /// </summary> |
| | | 80 | | /// <param name="indent">Indentation level</param> |
| | | 81 | | /// <returns>Padding string</returns> |
| | | 82 | | private static string GetPadding(int indent) |
| | | 83 | | { |
| | 29805 | 84 | | var paddingLevel = indent / IndentSize; |
| | 29805 | 85 | | return paddingLevel < PaddingCache.Length |
| | 29805 | 86 | | ? PaddingCache[paddingLevel] |
| | 29805 | 87 | | : new string(' ', indent); |
| | | 88 | | } |
| | | 89 | | |
| | | 90 | | public string Build(QueryBlock queryBlock, int indent = 0, string? prefix = null) |
| | | 91 | | { |
| | | 92 | | // Clear only at the top-level call; recursive sub-query calls (indent > 0) accumulate. |
| | 639 | 93 | | if (indent == 0) _stringBuilder.Clear(); |
| | | 94 | | |
| | 432 | 95 | | var pad = GetPadding(indent); |
| | 432 | 96 | | var prevPad = pad; |
| | | 97 | | |
| | 432 | 98 | | if (!string.IsNullOrWhiteSpace(queryBlock.Alias) && indent != 0) |
| | | 99 | | { |
| | 108 | 100 | | _stringBuilder.Append(pad); |
| | 108 | 101 | | _stringBuilder.Append(queryBlock.Alias); |
| | 108 | 102 | | _stringBuilder.Append(':'); |
| | 108 | 103 | | pad = ""; |
| | | 104 | | } |
| | | 105 | | |
| | 432 | 106 | | _stringBuilder.Append(pad); |
| | 432 | 107 | | if (!string.IsNullOrWhiteSpace(prefix)) |
| | | 108 | | { |
| | 198 | 109 | | _stringBuilder.Append(prefix).Append(' '); |
| | | 110 | | } |
| | | 111 | | |
| | 432 | 112 | | _stringBuilder.Append(queryBlock.Name); |
| | | 113 | | |
| | 432 | 114 | | AddArguments(queryBlock, indent == 0); |
| | 432 | 115 | | indent += IndentSize; |
| | | 116 | | |
| | 432 | 117 | | AddFields(queryBlock, prevPad, indent); |
| | 432 | 118 | | return _stringBuilder.ToString(); |
| | | 119 | | } |
| | | 120 | | |
| | | 121 | | public string Build(QueryDefinition queryDefinition) |
| | | 122 | | { |
| | 8106 | 123 | | _stringBuilder.Clear(); |
| | 8106 | 124 | | _stringBuilder.Append(queryDefinition.OperationType == OperationType.Mutation ? "mutation " : "query "); |
| | | 125 | | |
| | 8106 | 126 | | if (!string.IsNullOrEmpty(queryDefinition.Name)) |
| | | 127 | | { |
| | 8106 | 128 | | _stringBuilder.Append(queryDefinition.Name); |
| | | 129 | | } |
| | | 130 | | |
| | 8106 | 131 | | if (queryDefinition._variables?.Count > 0) |
| | | 132 | | { |
| | 33 | 133 | | _stringBuilder.Append('('); |
| | 33 | 134 | | bool first = true; |
| | 180 | 135 | | foreach (var variable in queryDefinition._variables) |
| | | 136 | | { |
| | 57 | 137 | | if (!first) |
| | | 138 | | { |
| | 24 | 139 | | _stringBuilder.Append(", "); |
| | | 140 | | } |
| | | 141 | | |
| | 57 | 142 | | first = false; |
| | 57 | 143 | | variable.Print(_stringBuilder, variable.Name, true); |
| | | 144 | | } |
| | | 145 | | |
| | 33 | 146 | | _stringBuilder.Append(')'); |
| | | 147 | | } |
| | | 148 | | |
| | 8106 | 149 | | _stringBuilder.AppendLine("{"); |
| | | 150 | | |
| | 8106 | 151 | | BuildFieldDefinitions(queryDefinition.Fields, IndentSize); |
| | | 152 | | |
| | 8106 | 153 | | _stringBuilder.Append("}"); |
| | 8106 | 154 | | return _stringBuilder.ToString(); |
| | | 155 | | } |
| | | 156 | | |
| | | 157 | | private void BuildFieldDefinitions(FieldChildren children, int indent) |
| | | 158 | | { |
| | 20901 | 159 | | var count = children.Count; |
| | 20901 | 160 | | var arr = ArrayPool<FieldDefinition>.Shared.Rent(count); |
| | | 161 | | try |
| | | 162 | | { |
| | 20901 | 163 | | children.AsSpan().CopyTo(arr); |
| | 20901 | 164 | | RenderSortedFields(arr, count, indent); |
| | 20901 | 165 | | } |
| | | 166 | | finally |
| | | 167 | | { |
| | 20901 | 168 | | Array.Clear(arr, 0, count); |
| | 20901 | 169 | | ArrayPool<FieldDefinition>.Shared.Return(arr, clearArray: false); |
| | 20901 | 170 | | } |
| | 20901 | 171 | | } |
| | | 172 | | |
| | | 173 | | private void BuildFieldDefinitions(Dictionary<string, FieldDefinition> fields, int indent) |
| | | 174 | | { |
| | 8106 | 175 | | var count = fields.Count; |
| | 8133 | 176 | | if (count == 0) return; |
| | | 177 | | |
| | | 178 | | // Dictionary<TKey,TValue> is insertion-ordered, not alphabetical. Copy values to a |
| | | 179 | | // pooled buffer so RenderSortedFields can sort once and render with a stable order. |
| | 8079 | 180 | | var arr = ArrayPool<FieldDefinition>.Shared.Rent(count); |
| | | 181 | | try |
| | | 182 | | { |
| | 8079 | 183 | | int i = 0; |
| | 50538 | 184 | | foreach (var f in fields.Values) arr[i++] = f; |
| | 8079 | 185 | | RenderSortedFields(arr, count, indent); |
| | 8079 | 186 | | } |
| | | 187 | | finally |
| | | 188 | | { |
| | 8079 | 189 | | Array.Clear(arr, 0, count); |
| | 8079 | 190 | | ArrayPool<FieldDefinition>.Shared.Return(arr, clearArray: false); |
| | 8079 | 191 | | } |
| | 8079 | 192 | | } |
| | | 193 | | |
| | | 194 | | /// <summary> |
| | | 195 | | /// Sorts <paramref name="arr"/> in place via <see cref="FieldSortComparer"/> and writes the |
| | | 196 | | /// rendered fields into <see cref="_stringBuilder"/>. Shared rendering core for both backing |
| | | 197 | | /// collection types (Dictionary at the root, FieldChildren for nested levels). |
| | | 198 | | /// </summary> |
| | | 199 | | private void RenderSortedFields(FieldDefinition[] arr, int count, int indent) |
| | | 200 | | { |
| | 28980 | 201 | | Array.Sort(arr, 0, count, FieldSortComparer); |
| | 28980 | 202 | | var padding = GetPadding(indent); |
| | | 203 | | |
| | 136128 | 204 | | for (int j = 0; j < count; j++) |
| | | 205 | | { |
| | 39084 | 206 | | var field = arr[j]; |
| | 39084 | 207 | | _stringBuilder.Append(padding); |
| | | 208 | | |
| | 39084 | 209 | | if (field.Alias != null) |
| | | 210 | | { |
| | 837 | 211 | | _stringBuilder.Append(field.Alias); |
| | 837 | 212 | | _stringBuilder.Append(':'); |
| | | 213 | | } |
| | | 214 | | |
| | 39084 | 215 | | _stringBuilder.Append(field.Name); |
| | | 216 | | |
| | 39084 | 217 | | if (field._arguments is { Count: > 0 }) |
| | | 218 | | { |
| | 7023 | 219 | | BuildFieldArguments(field._arguments); |
| | | 220 | | } |
| | | 221 | | |
| | | 222 | | // A field gets a `{ … }` block when it has either child fields OR inline fragments. |
| | | 223 | | // Plain leaf fields (no children, no fragments) render as a bare name + newline. |
| | 39084 | 224 | | var hasChildren = field._children is { Count: > 0 }; |
| | 39084 | 225 | | var hasFragments = field._fragments is { Count: > 0 }; |
| | | 226 | | |
| | 39084 | 227 | | if (hasChildren || hasFragments) |
| | | 228 | | { |
| | 20889 | 229 | | _stringBuilder.AppendLine("{"); |
| | 20889 | 230 | | if (hasChildren) |
| | | 231 | | { |
| | 20865 | 232 | | BuildFieldDefinitions(field._children!, indent + IndentSize); |
| | | 233 | | } |
| | 20889 | 234 | | if (hasFragments) |
| | | 235 | | { |
| | 27 | 236 | | BuildInlineFragments(field._fragments!, indent + IndentSize); |
| | | 237 | | } |
| | 20889 | 238 | | _stringBuilder.Append(padding); |
| | 20889 | 239 | | _stringBuilder.AppendLine("}"); |
| | | 240 | | } |
| | | 241 | | else |
| | | 242 | | { |
| | 18195 | 243 | | _stringBuilder.AppendLine(); |
| | | 244 | | } |
| | | 245 | | } |
| | 28980 | 246 | | } |
| | | 247 | | |
| | | 248 | | /// <summary> |
| | | 249 | | /// Renders the inline fragments attached to a field. Each fragment is written as |
| | | 250 | | /// <c>... on TypeName { … }</c> with its own selection set rendered recursively. |
| | | 251 | | /// Fragments are sorted alphabetically by type name (case-sensitive — GraphQL type names |
| | | 252 | | /// are case-sensitive) for deterministic output. |
| | | 253 | | /// </summary> |
| | | 254 | | private void BuildInlineFragments(Dictionary<string, InlineFragmentDefinition> fragments, int indent) |
| | | 255 | | { |
| | 30 | 256 | | if (fragments.Count == 0) return; |
| | | 257 | | |
| | | 258 | | // Snapshot type names into a pooled buffer and sort, mirroring how fields are sorted |
| | | 259 | | // before rendering — keeps the output stable regardless of insertion order. |
| | 30 | 260 | | var typeNames = ArrayPool<string>.Shared.Rent(fragments.Count); |
| | | 261 | | try |
| | | 262 | | { |
| | 30 | 263 | | int i = 0; |
| | 168 | 264 | | foreach (var key in fragments.Keys) typeNames[i++] = key; |
| | 30 | 265 | | Array.Sort(typeNames, 0, fragments.Count, StringComparer.Ordinal); |
| | | 266 | | |
| | 30 | 267 | | var padding = GetPadding(indent); |
| | 132 | 268 | | for (int j = 0; j < fragments.Count; j++) |
| | | 269 | | { |
| | 36 | 270 | | var fragment = fragments[typeNames[j]]; |
| | 36 | 271 | | _stringBuilder.Append(padding); |
| | 36 | 272 | | _stringBuilder.Append("... on "); |
| | 36 | 273 | | _stringBuilder.Append(fragment.TypeName); |
| | 36 | 274 | | _stringBuilder.AppendLine("{"); |
| | | 275 | | |
| | 36 | 276 | | if (fragment._fields is { Count: > 0 }) |
| | | 277 | | { |
| | 36 | 278 | | BuildFieldDefinitions(fragment._fields, indent + IndentSize); |
| | | 279 | | } |
| | 36 | 280 | | if (fragment._fragments is { Count: > 0 }) |
| | | 281 | | { |
| | 3 | 282 | | BuildInlineFragments(fragment._fragments, indent + IndentSize); |
| | | 283 | | } |
| | | 284 | | |
| | 36 | 285 | | _stringBuilder.Append(padding); |
| | 36 | 286 | | _stringBuilder.AppendLine("}"); |
| | | 287 | | } |
| | 30 | 288 | | } |
| | | 289 | | finally |
| | | 290 | | { |
| | 30 | 291 | | Array.Clear(typeNames, 0, fragments.Count); |
| | 30 | 292 | | ArrayPool<string>.Shared.Return(typeNames, clearArray: false); |
| | 30 | 293 | | } |
| | 30 | 294 | | } |
| | | 295 | | |
| | | 296 | | private void BuildFieldArguments(IReadOnlyDictionary<string, object?> arguments) |
| | | 297 | | { |
| | 7023 | 298 | | _stringBuilder.Append('('); |
| | | 299 | | |
| | 7023 | 300 | | bool first = true; |
| | 41784 | 301 | | foreach (var (key, value) in arguments) |
| | | 302 | | { |
| | 13869 | 303 | | if (!first) |
| | | 304 | | { |
| | 6846 | 305 | | _stringBuilder.Append(", "); |
| | | 306 | | } |
| | | 307 | | |
| | 13869 | 308 | | first = false; |
| | | 309 | | |
| | 13869 | 310 | | _stringBuilder.Append(key); |
| | 13869 | 311 | | _stringBuilder.Append(':'); |
| | 13869 | 312 | | WriteObject(_stringBuilder, value); |
| | | 313 | | } |
| | | 314 | | |
| | 7023 | 315 | | _stringBuilder.Append(')'); |
| | 7023 | 316 | | } |
| | | 317 | | |
| | | 318 | | internal static void WriteObject(StringBuilder builder, object? value) |
| | | 319 | | { |
| | 16920 | 320 | | if (value is null) |
| | | 321 | | { |
| | 27 | 322 | | builder.Append("null"); |
| | 27 | 323 | | return; |
| | | 324 | | } |
| | | 325 | | |
| | 16893 | 326 | | if (ValueFormatter.TryAppendPrimitive(value, builder)) |
| | 14655 | 327 | | return; |
| | | 328 | | |
| | 2238 | 329 | | var valueType = value.GetType(); |
| | 3519 | 330 | | if (ExtractKeyValuePairProperties(builder, value, valueType)) return; |
| | | 331 | | |
| | | 332 | | switch (value) |
| | | 333 | | { |
| | | 334 | | case IList listValue: |
| | | 335 | | { |
| | 84 | 336 | | Helpers.WriteCollection('[', ']', listValue, builder, WriteObject); |
| | 84 | 337 | | break; |
| | | 338 | | } |
| | | 339 | | |
| | | 340 | | case IDictionary dictValue: |
| | | 341 | | { |
| | 828 | 342 | | Helpers.WriteCollection('{', '}', dictValue, builder, WriteObject); |
| | 828 | 343 | | break; |
| | | 344 | | } |
| | | 345 | | |
| | | 346 | | default: |
| | | 347 | | { |
| | 45 | 348 | | WriteObjectReflection(builder, value, valueType); |
| | | 349 | | break; |
| | | 350 | | } |
| | | 351 | | } |
| | 45 | 352 | | } |
| | | 353 | | |
| | | 354 | | private static bool ExtractKeyValuePairProperties(StringBuilder builder, object value, Type valueType) |
| | | 355 | | { |
| | 2238 | 356 | | if (!valueType.IsGenericType || valueType.GetGenericTypeDefinition() != typeof(KeyValuePair<,>)) |
| | | 357 | | { |
| | 957 | 358 | | return false; |
| | | 359 | | } |
| | | 360 | | |
| | | 361 | | // KeyValuePair<,> is a sealed BCL struct that always exposes Key and Value properties — |
| | | 362 | | // GetProperty cannot return null here, so cache the pair without nullable wrapping. |
| | 1281 | 363 | | var (keyProp, valueProp) = TypeMetadataCache.KvpPropertyCache.GetOrAdd( |
| | 1281 | 364 | | valueType, |
| | 1296 | 365 | | static t => (t.GetProperty("Key")!, t.GetProperty("Value")!)); |
| | | 366 | | |
| | 1281 | 367 | | builder.Append(keyProp.GetValue(value)); |
| | 1281 | 368 | | builder.Append(':'); |
| | 1281 | 369 | | WriteObject(builder, valueProp.GetValue(value)); |
| | 1281 | 370 | | return true; |
| | | 371 | | } |
| | | 372 | | |
| | | 373 | | private static void WriteObjectReflection(StringBuilder builder, object value, Type valueType) |
| | | 374 | | { |
| | 84 | 375 | | var props = TypeMetadataCache.ObjectPropertyCache.GetOrAdd(valueType, static t => t.GetProperties()); |
| | 45 | 376 | | builder.Append('{'); |
| | 45 | 377 | | bool first = true; |
| | 240 | 378 | | foreach (var prop in props) |
| | | 379 | | { |
| | 111 | 380 | | if (!first) builder.Append(", "); |
| | 75 | 381 | | first = false; |
| | 75 | 382 | | builder.Append(prop.Name); |
| | 75 | 383 | | builder.Append(':'); |
| | 75 | 384 | | WriteObject(builder, prop.GetValue(value)); |
| | | 385 | | } |
| | 45 | 386 | | builder.Append('}'); |
| | 45 | 387 | | } |
| | | 388 | | |
| | | 389 | | private void AddFields(QueryBlock queryBlock, string prevPad, int indent = 0) |
| | | 390 | | { |
| | 432 | 391 | | if (queryBlock.IsEmpty) |
| | | 392 | | { |
| | 69 | 393 | | return; |
| | | 394 | | } |
| | | 395 | | |
| | 363 | 396 | | _stringBuilder.AppendLine("{"); |
| | 363 | 397 | | var padding = GetPadding(indent); |
| | | 398 | | |
| | | 399 | | // Sort fields by their effective name. QueryBlock.HandleAddField rejects everything |
| | | 400 | | // except string and QueryBlock at insert time, so a single ternary covers every |
| | | 401 | | // reachable case without a switch default. |
| | 363 | 402 | | var orderedFields = queryBlock.FieldsList |
| | 462 | 403 | | .OrderBy(field => field is QueryBlock block ? (block.Alias ?? block.Name) : (string)field, |
| | 363 | 404 | | StringComparer.OrdinalIgnoreCase); |
| | | 405 | | |
| | 1650 | 406 | | foreach (var field in orderedFields) |
| | | 407 | | { |
| | | 408 | | switch (field) |
| | | 409 | | { |
| | | 410 | | case string strValue: |
| | 237 | 411 | | _stringBuilder.Append(padding); |
| | 237 | 412 | | _stringBuilder.AppendLine(strValue); |
| | 237 | 413 | | break; |
| | | 414 | | case QueryBlock subQuery: |
| | 225 | 415 | | this.Build(subQuery, indent); |
| | 225 | 416 | | _stringBuilder.AppendLine(); |
| | | 417 | | break; |
| | | 418 | | } |
| | | 419 | | } |
| | | 420 | | |
| | 363 | 421 | | _stringBuilder.Append(prevPad); |
| | 363 | 422 | | _stringBuilder.Append('}'); |
| | 363 | 423 | | } |
| | | 424 | | |
| | | 425 | | private void AddArguments(QueryBlock queryBlock, bool isRootElement) |
| | | 426 | | { |
| | 432 | 427 | | var arguments = queryBlock.GetArguments(isRootElement); |
| | | 428 | | |
| | 432 | 429 | | if (arguments.Count == 0) |
| | | 430 | | { |
| | 273 | 431 | | return; |
| | | 432 | | } |
| | | 433 | | |
| | 159 | 434 | | _stringBuilder.Append('('); |
| | | 435 | | |
| | 159 | 436 | | bool first = true; |
| | 846 | 437 | | foreach (var (key, value) in arguments) |
| | | 438 | | { |
| | 264 | 439 | | if (!first) |
| | | 440 | | { |
| | 105 | 441 | | _stringBuilder.Append(", "); |
| | | 442 | | } |
| | | 443 | | |
| | 264 | 444 | | first = false; |
| | 264 | 445 | | if (value is Variable variable) |
| | | 446 | | { |
| | 141 | 447 | | variable.Print(_stringBuilder, key, isRootElement); |
| | 141 | 448 | | continue; |
| | | 449 | | } |
| | | 450 | | |
| | 123 | 451 | | _stringBuilder.Append(key); |
| | 123 | 452 | | _stringBuilder.Append(':'); |
| | | 453 | | |
| | 123 | 454 | | WriteObject(_stringBuilder, value); |
| | | 455 | | } |
| | | 456 | | |
| | 159 | 457 | | _stringBuilder.Append(')'); |
| | 159 | 458 | | } |
| | | 459 | | } |