-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterceptorCodeGenerator.Query.cs
More file actions
821 lines (732 loc) · 36.7 KB
/
Copy pathInterceptorCodeGenerator.Query.cs
File metadata and controls
821 lines (732 loc) · 36.7 KB
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
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Quarry.Generators.Models;
using Quarry.Generators.Sql;
using Quarry;
using Quarry.Generators.Projection;
using Quarry.Generators.Translation;
namespace Quarry.Generators.Generation;
internal static partial class InterceptorCodeGenerator
{
/// <summary>
/// Generates an interceptor method for a usage site.
/// </summary>
private static void GenerateInterceptorMethod(
StringBuilder sb,
UsageSiteInfo site,
List<CachedExtractorField> staticFields,
Dictionary<string, PrebuiltChainInfo> chainLookup,
Dictionary<string, int> clauseBitMap,
Dictionary<string, PrebuiltChainInfo> chainClauseLookup,
HashSet<string> firstClauseIds)
{
// Check for skippable Select sites BEFORE emitting the attribute
if (site.Kind == InterceptorKind.Select && ShouldSkipSelectInterceptor(site))
{
return; // Don't emit anything for this site
}
// Limit/Offset/Distinct are tracked for chain analysis only — they don't need
// their own interceptor methods. The builder methods are simple property setters.
if (site.Kind is InterceptorKind.Limit or InterceptorKind.Offset or InterceptorKind.Distinct)
{
return;
}
// For execution interceptors: only emit if we have a pre-built chain for this site
// AND we can resolve the result type. Otherwise skip — the built-in execution methods
// work correctly via the Select interceptor.
if (site.Kind is InterceptorKind.ExecuteFetchAll or InterceptorKind.ExecuteFetchFirst
or InterceptorKind.ExecuteFetchFirstOrDefault or InterceptorKind.ExecuteFetchSingle
or InterceptorKind.ToAsyncEnumerable)
{
if (!chainLookup.TryGetValue(site.UniqueId, out var chain))
return;
// Skip chains with unmatched fluent methods (Limit, Offset, AddWhereClause, etc.)
// whose effects are invisible to the pre-built SQL.
if (chain.Analysis.UnmatchedMethodNames != null)
return;
// Resolve the best available result type. The site/chain result types come from the
// semantic model and may be empty or broken for source-generated entity types.
// The enriched ProjectionInfo.ResultTypeName is rebuilt from entity metadata and is
// authoritative for tuples and single-column projections.
var rawResult = ResolveExecutionResultType(site.ResultTypeName, chain.ResultTypeName, chain.ProjectionInfo);
if (string.IsNullOrEmpty(rawResult))
return;
// Must have a reader delegate
if (chain.ReaderDelegateCode == null)
return;
// Skip chains with projections that have SqlExpression set alongside ColumnName.
// CompileTimeSqlBuilder uses SqlExpression (e.g., "LOWER(col)") but the runtime path
// uses ColumnName and quotes it. These produce different SQL.
// Only allow execution interceptors when the SQL will be byte-identical.
if (chain.ProjectionInfo != null)
{
var hasAmbiguousColumns = chain.ProjectionInfo.Columns.Any(c =>
c.SqlExpression != null && !string.IsNullOrEmpty(c.ColumnName));
if (hasAmbiguousColumns)
return;
}
}
else if (site.Kind is InterceptorKind.ExecuteScalar)
{
if (!chainLookup.TryGetValue(site.UniqueId, out var scalarChain))
return;
if (scalarChain.Analysis.UnmatchedMethodNames != null)
return;
// ExecuteScalar doesn't need a reader delegate — just pre-built SQL
var rawScalarResult = ResolveExecutionResultType(site.ResultTypeName, scalarChain.ResultTypeName, scalarChain.ProjectionInfo);
if (string.IsNullOrEmpty(rawScalarResult))
return;
}
else if (site.Kind is InterceptorKind.ExecuteNonQuery)
{
if (!chainLookup.TryGetValue(site.UniqueId, out var nqChain))
return;
// Validate that all SQL variants are non-empty and well-formed
if (nqChain.SqlMap.Values.Any(v => string.IsNullOrWhiteSpace(v.Sql)
|| (nqChain.QueryKind == QueryKind.Update && v.Sql.Contains("SET "))))
return;
}
else if (site.Kind is InterceptorKind.ToSql)
{
if (!chainLookup.TryGetValue(site.UniqueId, out var toSqlChain))
return;
if (toSqlChain.Analysis.UnmatchedMethodNames != null)
return;
}
// Skip clause interceptors where the clause could not be translated to SQL.
// The original runtime method will run instead. A QRY019 diagnostic is reported separately.
if (ShouldSkipNonTranslatableClause(site))
{
return;
}
var methodName = $"{site.MethodName}_{site.UniqueId}";
// Determine chain analysis status for remarks
PrebuiltChainInfo? chainForRemarks = null;
chainLookup.TryGetValue(site.UniqueId, out chainForRemarks);
if (chainForRemarks == null)
chainClauseLookup.TryGetValue(site.UniqueId, out chainForRemarks);
// XML documentation
sb.AppendLine($" /// <summary>");
sb.AppendLine($" /// Intercepts {site.MethodName}() call at {GetRelativePath(site.FilePath)}:{site.Line}:{site.Column}");
sb.AppendLine($" /// </summary>");
if (chainForRemarks != null)
sb.AppendLine($" /// <remarks>Chain: Fully Analyzed ({chainForRemarks.Analysis.Tier})</remarks>");
else
sb.AppendLine($" /// <remarks>Chain: Not Analyzed (standalone interceptor)</remarks>");
// InterceptsLocation attribute - use new format with version and data if available
if (!string.IsNullOrEmpty(site.InterceptableLocationData))
{
sb.AppendLine($" [InterceptsLocation({site.InterceptableLocationVersion}, \"{site.InterceptableLocationData}\")]");
}
else
{
// Fallback: skip this site if we don't have valid location data
sb.AppendLine($" // WARNING: Could not generate InterceptsLocation for this call site");
return;
}
// Check if this is on a joined builder type
var isJoinedBuilder = site.JoinedEntityTypeNames != null && site.JoinedEntityTypeNames.Count >= 2;
// Look up clause bitmask bit index for conditional clause interceptors
clauseBitMap.TryGetValue(site.UniqueId, out var rawBit);
int? clauseBit = clauseBitMap.ContainsKey(site.UniqueId) ? rawBit : null;
// Resolve prebuilt chain membership for clause sites
chainClauseLookup.TryGetValue(site.UniqueId, out var prebuiltClauseChain);
var isFirstClauseInChain = prebuiltClauseChain != null && firstClauseIds.Contains(site.UniqueId);
// Generate method based on kind
switch (site.Kind)
{
case InterceptorKind.Select:
if (isJoinedBuilder)
GenerateJoinedSelectInterceptor(sb, site, methodName, prebuiltClauseChain, isFirstClauseInChain);
else
GenerateSelectInterceptor(sb, site, methodName, prebuiltClauseChain, isFirstClauseInChain);
break;
case InterceptorKind.Where:
if (isJoinedBuilder)
GenerateJoinedWhereInterceptor(sb, site, methodName, staticFields, clauseBit, prebuiltClauseChain, isFirstClauseInChain);
else
GenerateWhereInterceptor(sb, site, methodName, staticFields, clauseBit, prebuiltClauseChain, isFirstClauseInChain);
break;
case InterceptorKind.OrderBy:
case InterceptorKind.ThenBy:
if (isJoinedBuilder)
GenerateJoinedOrderByInterceptor(sb, site, methodName, clauseBit, prebuiltClauseChain, isFirstClauseInChain);
else
GenerateOrderByInterceptor(sb, site, methodName, clauseBit, prebuiltClauseChain, isFirstClauseInChain);
break;
case InterceptorKind.GroupBy:
GenerateGroupByInterceptor(sb, site, methodName, clauseBit, prebuiltClauseChain, isFirstClauseInChain);
break;
case InterceptorKind.Having:
GenerateHavingInterceptor(sb, site, methodName, clauseBit, prebuiltClauseChain, isFirstClauseInChain);
break;
case InterceptorKind.Set:
GenerateSetInterceptor(sb, site, methodName, clauseBit, prebuiltClauseChain, isFirstClauseInChain);
break;
case InterceptorKind.Join:
case InterceptorKind.LeftJoin:
case InterceptorKind.RightJoin:
GenerateJoinInterceptor(sb, site, methodName, prebuiltClauseChain, isFirstClauseInChain);
break;
case InterceptorKind.ExecuteFetchAll:
case InterceptorKind.ExecuteFetchFirst:
case InterceptorKind.ExecuteFetchFirstOrDefault:
case InterceptorKind.ExecuteFetchSingle:
case InterceptorKind.ExecuteScalar:
case InterceptorKind.ToAsyncEnumerable:
if (chainLookup.TryGetValue(site.UniqueId, out var selectChain))
{
if (selectChain.IsJoinChain)
GeneratePrebuiltJoinExecutionInterceptor(sb, site, methodName, selectChain);
else
GeneratePrebuiltSelectExecutionInterceptor(sb, site, methodName, selectChain);
}
break;
case InterceptorKind.ExecuteNonQuery:
if (chainLookup.TryGetValue(site.UniqueId, out var nonQueryChain))
GeneratePrebuiltNonQueryExecutionInterceptor(sb, site, methodName, nonQueryChain);
break;
case InterceptorKind.ToSql:
if (chainLookup.TryGetValue(site.UniqueId, out var toSqlChain))
GeneratePrebuiltToSqlInterceptor(sb, site, methodName, toSqlChain);
break;
case InterceptorKind.DeleteWhere:
GenerateDeleteWhereInterceptor(sb, site, methodName, staticFields, clauseBit, prebuiltClauseChain, isFirstClauseInChain);
break;
case InterceptorKind.UpdateSet:
GenerateUpdateSetInterceptor(sb, site, methodName, clauseBit, prebuiltClauseChain, isFirstClauseInChain);
break;
case InterceptorKind.UpdateSetPoco:
GenerateUpdateSetPocoInterceptor(sb, site, methodName);
break;
case InterceptorKind.UpdateWhere:
GenerateUpdateWhereInterceptor(sb, site, methodName, staticFields, clauseBit, prebuiltClauseChain, isFirstClauseInChain);
break;
case InterceptorKind.InsertExecuteNonQuery:
GenerateInsertExecuteNonQueryInterceptor(sb, site, methodName);
break;
case InterceptorKind.InsertExecuteScalar:
GenerateInsertExecuteScalarInterceptor(sb, site, methodName);
break;
case InterceptorKind.InsertToSql:
GenerateInsertToSqlInterceptor(sb, site, methodName);
break;
case InterceptorKind.RawSqlAsync:
GenerateRawSqlAsyncInterceptor(sb, site, methodName);
break;
case InterceptorKind.RawSqlScalarAsync:
GenerateRawSqlScalarAsyncInterceptor(sb, site, methodName);
break;
default:
GeneratePlaceholderInterceptor(sb, site, methodName);
break;
}
sb.AppendLine();
}
/// <summary>
/// Generates a Select() interceptor with column list and typed reader delegate.
/// </summary>
private static void GenerateSelectInterceptor(StringBuilder sb, UsageSiteInfo site, string methodName,
PrebuiltChainInfo? prebuiltChain = null, bool isFirstInChain = false)
{
var entityType = GetShortTypeName(site.EntityTypeName);
var projection = site.ProjectionInfo;
// Simplified prebuilt chain path: AsProjected instead of SelectWithReader
if (prebuiltChain != null && projection != null && projection.IsOptimalPath && projection.Columns.Count > 0)
{
var resultType = GetShortTypeName(projection.ResultTypeName);
var thisType = site.BuilderTypeName;
var concreteType = ToConcreteTypeName(thisType);
sb.AppendLine($" public static {thisType}<{entityType}, {resultType}> {methodName}(");
sb.AppendLine($" this {thisType}<{entityType}> builder,");
sb.AppendLine($" Func<{entityType}, {resultType}> _)");
sb.AppendLine($" {{");
sb.AppendLine($" var __b = Unsafe.As<{concreteType}<{entityType}>>(builder);");
if (isFirstInChain && prebuiltChain.MaxParameterCount > 0)
sb.AppendLine($" __b.AllocatePrebuiltParams({prebuiltChain.MaxParameterCount});");
sb.AppendLine($" return __b.AsProjected<{resultType}>();");
sb.AppendLine($" }}");
return;
}
// If we have projection info and it's optimal, generate the full interceptor
if (projection != null &&
projection.IsOptimalPath &&
projection.Columns.Count > 0)
{
GenerateOptimalSelectInterceptor(sb, site, methodName, entityType, projection);
}
else
{
// Fallback - delegate to the original method
GenerateFallbackSelectInterceptor(sb, site, methodName, entityType);
}
}
/// <summary>
/// Generates an optimal Select() interceptor with compile-time column binding.
/// </summary>
private static void GenerateOptimalSelectInterceptor(
StringBuilder sb,
UsageSiteInfo site,
string methodName,
string entityType,
ProjectionInfo projection)
{
// Generate column list SQL using the dialect resolved from the owning context
var columnList = ReaderCodeGenerator.GenerateColumnList(projection, site.Dialect ?? SqlDialect.PostgreSQL);
// Generate column names array
var columnNames = ReaderCodeGenerator.GenerateColumnNamesArray(projection);
// Generate reader delegate
var readerDelegate = ReaderCodeGenerator.GenerateReaderDelegate(projection, entityType);
// At this point, skippable cases (anonymous, tuple, unknown) have already been
// filtered out by ShouldSkipSelectInterceptor, so we can generate the interceptor
{
var resultType = GetShortTypeName(projection.ResultTypeName);
var thisType = site.BuilderTypeName;
var concreteType = ToConcreteTypeName(thisType);
sb.AppendLine($" public static {thisType}<{entityType}, {resultType}> {methodName}(");
sb.AppendLine($" this {thisType}<{entityType}> builder,");
sb.AppendLine($" Func<{entityType}, {resultType}> _)");
sb.AppendLine($" {{");
sb.AppendLine($" // Generated column list: {columnList}");
sb.AppendLine($" var __b = Unsafe.As<{concreteType}<{entityType}>>(builder);");
sb.AppendLine($" return __b.SelectWithReader(");
sb.AppendLine($" {columnNames},");
sb.AppendLine($" {readerDelegate});");
sb.AppendLine($" }}");
}
}
/// <summary>
/// Generates a fallback Select() interceptor that delegates to the original method.
/// </summary>
private static void GenerateFallbackSelectInterceptor(
StringBuilder sb,
UsageSiteInfo site,
string methodName,
string entityType)
{
// Interceptor arity must match the combined class + method type parameters.
// QueryBuilder<T>.Select<TResult> has total arity 2 (T + TResult).
// Use arity 2 so the interceptor can match any Select<TResult> call.
var thisType = site.BuilderTypeName;
var concreteType = ToConcreteTypeName(thisType);
sb.AppendLine($" public static {thisType}<T, TResult> {methodName}<T, TResult>(");
sb.AppendLine($" this {thisType}<T> builder,");
sb.AppendLine($" Func<T, TResult> selector) where T : class");
sb.AppendLine($" {{");
sb.AppendLine($" // Fallback path - projection not fully analyzed at compile time");
sb.AppendLine($" var __b = Unsafe.As<{concreteType}<T>>(builder);");
sb.AppendLine($" return __b.Select(selector);");
sb.AppendLine($" }}");
}
/// <summary>
/// Generates a Where() interceptor with SQL fragment and parameter binder.
/// </summary>
private static void GenerateWhereInterceptor(StringBuilder sb, UsageSiteInfo site, string methodName, List<CachedExtractorField> staticFields, int? clauseBit = null,
PrebuiltChainInfo? prebuiltChain = null, bool isFirstInChain = false)
{
var entityType = GetShortTypeName(site.EntityTypeName);
var clauseInfo = site.ClauseInfo;
// Check if there are captured parameters that need runtime extraction
var hasAnyParams = clauseInfo?.Parameters.Count > 0;
var hasResolvableCapturedParams = clauseInfo?.Parameters.Any(p => p.IsCaptured && p.CanGenerateDirectPath) == true;
var exprParamName = hasResolvableCapturedParams ? "expr" : "_";
// Emit trim suppression if we'll use FieldInfo.GetValue inline
var methodFields = staticFields.Where(f => f.MethodName == methodName).ToList();
if (methodFields.Count > 0)
{
sb.AppendLine($" [UnconditionalSuppressMessage(\"Trimming\", \"IL2075\",");
sb.AppendLine($" Justification = \"Closure fields are preserved by the expression tree that references them.\")]");
}
var thisType = site.BuilderTypeName;
var concreteType = ToConcreteTypeName(thisType);
// Check if this is on QueryBuilder<T> or QueryBuilder<T, TResult>
if (site.ResultTypeName != null)
{
var resultType = SanitizeTupleResultType(GetShortTypeName(site.ResultTypeName));
sb.AppendLine($" public static {thisType}<{entityType}, {resultType}> {methodName}(");
sb.AppendLine($" this {thisType}<{entityType}, {resultType}> builder,");
sb.AppendLine($" Expression<Func<{entityType}, bool>> {exprParamName})");
}
else
{
sb.AppendLine($" public static {thisType}<{entityType}> {methodName}(");
sb.AppendLine($" this {thisType}<{entityType}> builder,");
sb.AppendLine($" Expression<Func<{entityType}, bool>> {exprParamName})");
}
sb.AppendLine($" {{");
if (clauseInfo == null || !clauseInfo.IsSuccess)
{
// Non-translatable clause — skip interceptor entirely so the original method runs
return;
}
// Cast to concrete type (receiver is always an interface)
if (site.ResultTypeName != null)
{
var resultType = SanitizeTupleResultType(GetShortTypeName(site.ResultTypeName));
sb.AppendLine($" var __b = Unsafe.As<{concreteType}<{entityType}, {resultType}>>(builder);");
}
else
{
sb.AppendLine($" var __b = Unsafe.As<{concreteType}<{entityType}>>(builder);");
}
var builderVar = "__b";
// Simplified prebuilt chain path: BindParam instead of AddWhereClause
if (prebuiltChain != null)
{
if (isFirstInChain && prebuiltChain.MaxParameterCount > 0)
sb.AppendLine($" {builderVar}.AllocatePrebuiltParams({prebuiltChain.MaxParameterCount});");
if (hasAnyParams == true)
{
if (hasResolvableCapturedParams)
GenerateCachedExtraction(sb, methodFields);
var allParams = clauseInfo!.Parameters.OrderBy(p => p.Index).ToList();
foreach (var p in allParams)
{
var expr = p.IsCaptured ? $"p{p.Index}" : p.ValueExpression;
sb.AppendLine($" {builderVar}.BindParam({WrapWithToDb(expr, p)});");
}
}
if (clauseBit.HasValue)
sb.AppendLine($" return {builderVar}.SetClauseBit({clauseBit.Value});");
else
sb.AppendLine($" return {builderVar};");
sb.AppendLine($" }}");
return;
}
{
// Generate optimized interceptor with pre-computed SQL
var escapedSql = EscapeStringLiteral(clauseInfo.SqlFragment);
// Check if any captured parameters lack extraction paths (e.g., captured variables in subqueries)
var hasUnresolvableCaptured = clauseInfo.Parameters.Any(p => p.IsCaptured && !p.CanGenerateDirectPath);
var bitSuffix = ClauseBitSuffix(clauseBit);
if (hasUnresolvableCaptured)
{
// Emit SQL-only clause (parameters cannot be extracted at compile time)
var resolvableParams = clauseInfo.Parameters
.Where(p => !p.IsCaptured)
.OrderBy(p => p.Index)
.ToList();
if (resolvableParams.Count > 0)
{
var paramArgs = string.Join(", ", resolvableParams.Select(p => WrapWithToDb(p.ValueExpression, p)));
sb.AppendLine($" return {builderVar}.AddWhereClause(@\"{escapedSql}\", {paramArgs}){bitSuffix};");
}
else
{
sb.AppendLine($" return {builderVar}.AddWhereClause(@\"{escapedSql}\"){bitSuffix};");
}
}
else if (hasAnyParams)
{
if (hasResolvableCapturedParams)
GenerateCachedExtraction(sb, methodFields);
// Build args in index order, mixing captured extractions + literal values
var allParams = clauseInfo.Parameters.OrderBy(p => p.Index).ToList();
var paramArgs = string.Join(", ", allParams.Select(p =>
{
var expr = p.IsCaptured ? $"p{p.Index}" : p.ValueExpression;
return WrapWithToDb(expr, p);
}));
sb.AppendLine($" return {builderVar}.AddWhereClause(@\"{escapedSql}\", {paramArgs}){bitSuffix};");
}
else
{
sb.AppendLine($" return {builderVar}.AddWhereClause(@\"{escapedSql}\"){bitSuffix};");
}
}
sb.AppendLine($" }}");
}
/// <summary>
/// Generates an OrderBy/ThenBy interceptor with SQL fragment.
/// </summary>
private static void GenerateOrderByInterceptor(StringBuilder sb, UsageSiteInfo site, string methodName, int? clauseBit = null,
PrebuiltChainInfo? prebuiltChain = null, bool isFirstInChain = false)
{
var entityType = GetShortTypeName(site.EntityTypeName);
var clauseInfo = site.ClauseInfo;
var isOrderBy = site.Kind == InterceptorKind.OrderBy;
// Use concrete key type (arity 0) when available; otherwise fall back to arity-matching
var keyType = site.KeyTypeName != null ? GetShortTypeName(site.KeyTypeName) : null;
var thisType = site.BuilderTypeName;
var concreteType = ToConcreteTypeName(thisType);
// Check if this is on QueryBuilder<T> or QueryBuilder<T, TResult>
if (site.ResultTypeName != null)
{
var resultType = SanitizeTupleResultType(GetShortTypeName(site.ResultTypeName));
if (keyType != null)
{
// Non-generic interceptor (arity 0) — concrete key type
sb.AppendLine($" public static {thisType}<{entityType}, {resultType}> {methodName}(");
sb.AppendLine($" this {thisType}<{entityType}, {resultType}> builder,");
sb.AppendLine($" Expression<Func<{entityType}, {keyType}>> _,");
sb.AppendLine($" Direction direction = Direction.Ascending)");
}
else
{
// Arity-matching interceptor — include all type params from class + method
sb.AppendLine($" public static {thisType}<T, TResult> {methodName}<T, TResult, TKey>(");
sb.AppendLine($" this {thisType}<T, TResult> builder,");
sb.AppendLine($" Expression<Func<T, TKey>> _,");
sb.AppendLine($" Direction direction = Direction.Ascending) where T : class");
}
}
else
{
if (keyType != null)
{
// Non-generic interceptor (arity 0) — concrete key type
sb.AppendLine($" public static {thisType}<{entityType}> {methodName}(");
sb.AppendLine($" this {thisType}<{entityType}> builder,");
sb.AppendLine($" Expression<Func<{entityType}, {keyType}>> _,");
sb.AppendLine($" Direction direction = Direction.Ascending)");
}
else
{
// Arity-matching interceptor — include all type params from class + method
sb.AppendLine($" public static {thisType}<T> {methodName}<T, TKey>(");
sb.AppendLine($" this {thisType}<T> builder,");
sb.AppendLine($" Expression<Func<T, TKey>> _,");
sb.AppendLine($" Direction direction = Direction.Ascending) where T : class");
}
}
sb.AppendLine($" {{");
// Cast to concrete type (receiver is always an interface)
if (site.ResultTypeName != null)
{
var resultType = SanitizeTupleResultType(GetShortTypeName(site.ResultTypeName));
sb.AppendLine($" var __b = Unsafe.As<{concreteType}<{entityType}, {resultType}>>(builder);");
}
else if (keyType != null)
{
sb.AppendLine($" var __b = Unsafe.As<{concreteType}<{entityType}>>(builder);");
}
else
{
sb.AppendLine($" var __b = Unsafe.As<{concreteType}<T>>(builder);");
}
var builderVar = "__b";
// Simplified prebuilt chain path: passthrough (no SQL generation)
if (prebuiltChain != null)
{
if (isFirstInChain && prebuiltChain.MaxParameterCount > 0)
sb.AppendLine($" {builderVar}.AllocatePrebuiltParams({prebuiltChain.MaxParameterCount});");
if (clauseBit.HasValue)
{
sb.AppendLine($" {builderVar}.SetClauseBit({clauseBit.Value});");
sb.AppendLine($" return builder;");
}
else
{
sb.AppendLine($" return builder;");
}
sb.AppendLine($" }}");
return;
}
// When using open generic type params (arity-matching), the concrete return type
// can't be implicitly converted to the open generic interface return type.
// Cast through Unsafe.As to bridge the gap.
var needsReturnCast = keyType == null;
string returnCastOpen;
string returnCastClose;
if (needsReturnCast)
{
var returnType = site.ResultTypeName != null ? $"{thisType}<T, TResult>" : $"{thisType}<T>";
returnCastOpen = $"Unsafe.As<{returnType}>(";
returnCastClose = ")";
}
else
{
returnCastOpen = "";
returnCastClose = "";
}
var bitSuffix = ClauseBitSuffix(clauseBit);
if (clauseInfo is OrderByClauseInfo orderByInfo && orderByInfo.IsSuccess)
{
// Generate optimized interceptor with pre-computed SQL
var escapedSql = EscapeStringLiteral(orderByInfo.ColumnSql);
var directionSuffix = orderByInfo.IsDescending ? " DESC" : " ASC";
var builderMethod = isOrderBy ? "AddOrderByClause" : "AddThenByClause";
sb.AppendLine($" return {returnCastOpen}{builderVar}.{builderMethod}(@\"{escapedSql}\", direction){bitSuffix}{returnCastClose};");
}
else if (clauseInfo != null && clauseInfo.IsSuccess)
{
// Non-OrderByClauseInfo but still successful
var escapedSql = EscapeStringLiteral(clauseInfo.SqlFragment);
var builderMethod = isOrderBy ? "AddOrderByClause" : "AddThenByClause";
sb.AppendLine($" return {returnCastOpen}{builderVar}.{builderMethod}(@\"{escapedSql}\", direction){bitSuffix}{returnCastClose};");
}
else
{
// Non-translatable clause — skip interceptor entirely so the original method runs
return;
}
sb.AppendLine($" }}");
}
/// <summary>
/// Generates a GroupBy interceptor with SQL fragment.
/// </summary>
private static void GenerateGroupByInterceptor(StringBuilder sb, UsageSiteInfo site, string methodName, int? clauseBit = null,
PrebuiltChainInfo? prebuiltChain = null, bool isFirstInChain = false)
{
var entityType = GetShortTypeName(site.EntityTypeName);
var clauseInfo = site.ClauseInfo;
// Use concrete key type (arity 0) when available; otherwise fall back to arity-matching
var keyType = site.KeyTypeName != null ? GetShortTypeName(site.KeyTypeName) : null;
var thisType = site.BuilderTypeName;
var concreteType = ToConcreteTypeName(thisType);
// Check if this is on QueryBuilder<T> or QueryBuilder<T, TResult>
if (site.ResultTypeName != null)
{
var resultType = SanitizeTupleResultType(GetShortTypeName(site.ResultTypeName));
if (keyType != null)
{
sb.AppendLine($" public static {thisType}<{entityType}, {resultType}> {methodName}(");
sb.AppendLine($" this {thisType}<{entityType}, {resultType}> builder,");
sb.AppendLine($" Expression<Func<{entityType}, {keyType}>> _)");
}
else
{
sb.AppendLine($" public static {thisType}<T, TResult> {methodName}<T, TResult, TKey>(");
sb.AppendLine($" this {thisType}<T, TResult> builder,");
sb.AppendLine($" Expression<Func<T, TKey>> _) where T : class");
}
}
else
{
if (keyType != null)
{
sb.AppendLine($" public static {thisType}<{entityType}> {methodName}(");
sb.AppendLine($" this {thisType}<{entityType}> builder,");
sb.AppendLine($" Expression<Func<{entityType}, {keyType}>> _)");
}
else
{
sb.AppendLine($" public static {thisType}<T> {methodName}<T, TKey>(");
sb.AppendLine($" this {thisType}<T> builder,");
sb.AppendLine($" Expression<Func<T, TKey>> _) where T : class");
}
}
sb.AppendLine($" {{");
if (clauseInfo == null || !clauseInfo.IsSuccess)
{
// Non-translatable clause — skip interceptor entirely so the original method runs
return;
}
// Cast to concrete type (receiver is always an interface)
if (site.ResultTypeName != null)
{
var resultType = SanitizeTupleResultType(GetShortTypeName(site.ResultTypeName));
sb.AppendLine($" var __b = Unsafe.As<{concreteType}<{entityType}, {resultType}>>(builder);");
}
else if (keyType != null)
{
sb.AppendLine($" var __b = Unsafe.As<{concreteType}<{entityType}>>(builder);");
}
else
{
sb.AppendLine($" var __b = Unsafe.As<{concreteType}<T>>(builder);");
}
var builderVar = "__b";
// Simplified prebuilt chain path: passthrough (no SQL generation)
if (prebuiltChain != null)
{
if (isFirstInChain && prebuiltChain.MaxParameterCount > 0)
sb.AppendLine($" {builderVar}.AllocatePrebuiltParams({prebuiltChain.MaxParameterCount});");
if (clauseBit.HasValue)
{
sb.AppendLine($" {builderVar}.SetClauseBit({clauseBit.Value});");
sb.AppendLine($" return builder;");
}
else
{
sb.AppendLine($" return builder;");
}
sb.AppendLine($" }}");
return;
}
{
// Generate optimized interceptor with pre-computed SQL
var escapedSql = EscapeStringLiteral(clauseInfo.SqlFragment);
var bitSuffix = ClauseBitSuffix(clauseBit);
// When using open generic type params (arity-matching), cast return through Unsafe.As
var needsReturnCast = keyType == null;
string returnCastOpen = "", returnCastClose = "";
if (needsReturnCast)
{
var returnType = site.ResultTypeName != null ? $"{thisType}<T, TResult>" : $"{thisType}<T>";
returnCastOpen = $"Unsafe.As<{returnType}>(";
returnCastClose = ")";
}
sb.AppendLine($" return {returnCastOpen}{builderVar}.AddGroupByClause(@\"{escapedSql}\"){bitSuffix}{returnCastClose};");
}
sb.AppendLine($" }}");
}
/// <summary>
/// Generates a Having interceptor with SQL fragment.
/// </summary>
private static void GenerateHavingInterceptor(StringBuilder sb, UsageSiteInfo site, string methodName, int? clauseBit = null,
PrebuiltChainInfo? prebuiltChain = null, bool isFirstInChain = false)
{
var entityType = GetShortTypeName(site.EntityTypeName);
var clauseInfo = site.ClauseInfo;
var thisType = site.BuilderTypeName;
var concreteType = ToConcreteTypeName(thisType);
// Check if this is on QueryBuilder<T> or QueryBuilder<T, TResult>
if (site.ResultTypeName != null)
{
var resultType = SanitizeTupleResultType(GetShortTypeName(site.ResultTypeName));
sb.AppendLine($" public static {thisType}<{entityType}, {resultType}> {methodName}(");
sb.AppendLine($" this {thisType}<{entityType}, {resultType}> builder,");
sb.AppendLine($" Expression<Func<{entityType}, bool>> _)");
}
else
{
sb.AppendLine($" public static {thisType}<{entityType}> {methodName}(");
sb.AppendLine($" this {thisType}<{entityType}> builder,");
sb.AppendLine($" Expression<Func<{entityType}, bool>> _)");
}
sb.AppendLine($" {{");
if (clauseInfo == null || !clauseInfo.IsSuccess)
{
// Non-translatable clause — skip interceptor entirely so the original method runs
return;
}
// Cast to concrete type (receiver is always an interface)
if (site.ResultTypeName != null)
{
var resultType = SanitizeTupleResultType(GetShortTypeName(site.ResultTypeName));
sb.AppendLine($" var __b = Unsafe.As<{concreteType}<{entityType}, {resultType}>>(builder);");
}
else
{
sb.AppendLine($" var __b = Unsafe.As<{concreteType}<{entityType}>>(builder);");
}
var builderVar = "__b";
// Simplified prebuilt chain path: passthrough (no SQL generation)
if (prebuiltChain != null)
{
if (isFirstInChain && prebuiltChain.MaxParameterCount > 0)
sb.AppendLine($" {builderVar}.AllocatePrebuiltParams({prebuiltChain.MaxParameterCount});");
if (clauseBit.HasValue)
{
sb.AppendLine($" {builderVar}.SetClauseBit({clauseBit.Value});");
sb.AppendLine($" return builder;");
}
else
{
sb.AppendLine($" return builder;");
}
sb.AppendLine($" }}");
return;
}
{
// Generate optimized interceptor with pre-computed SQL
var escapedSql = EscapeStringLiteral(clauseInfo.SqlFragment);
var bitSuffix = ClauseBitSuffix(clauseBit);
sb.AppendLine($" return {builderVar}.AddHavingClause(@\"{escapedSql}\"){bitSuffix};");
}
sb.AppendLine($" }}");
}
}