-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathCosmosQuerySqlGenerator.cs
More file actions
875 lines (739 loc) · 36.2 KB
/
CosmosQuerySqlGenerator.cs
File metadata and controls
875 lines (739 loc) · 36.2 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
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.EntityFrameworkCore.Cosmos.Internal;
using Microsoft.EntityFrameworkCore.Cosmos.Storage.Internal;
namespace Microsoft.EntityFrameworkCore.Cosmos.Query.Internal;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class CosmosQuerySqlGenerator(ITypeMappingSource typeMappingSource) : SqlExpressionVisitor
{
private static readonly bool UseOldBehavior35476 =
AppContext.TryGetSwitch("Microsoft.EntityFrameworkCore.Issue35476", out var enabled35476) && enabled35476;
private readonly IndentedStringBuilder _sqlBuilder = new();
private IReadOnlyDictionary<string, object> _parameterValues = null!;
private List<SqlParameter> _sqlParameters = null!;
private ParameterNameGenerator _parameterNameGenerator = null!;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual CosmosSqlQuery GetSqlQuery(
SelectExpression selectExpression,
IReadOnlyDictionary<string, object> parameterValues)
{
_sqlBuilder.Clear();
_parameterValues = parameterValues;
_sqlParameters = [];
_parameterNameGenerator = new ParameterNameGenerator();
Visit(selectExpression);
return new CosmosSqlQuery(_sqlBuilder.ToString(), _sqlParameters);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitEntityProjection(EntityProjectionExpression entityProjectionExpression)
{
Visit(entityProjectionExpression.Object);
return entityProjectionExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitExists(ExistsExpression existsExpression)
{
_sqlBuilder.AppendLine("EXISTS (");
using (_sqlBuilder.Indent())
{
Visit(existsExpression.Subquery);
}
_sqlBuilder.Append(")");
return existsExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitObjectArray(ObjectArrayExpression objectArrayExpression)
{
GenerateArray(objectArrayExpression.Subquery);
return objectArrayExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitScalarArray(ScalarArrayExpression scalarArrayExpression)
{
GenerateArray(scalarArrayExpression.Subquery);
return scalarArrayExpression;
}
private void GenerateArray(SelectExpression subquery)
{
_sqlBuilder.AppendLine("ARRAY(");
using (_sqlBuilder.Indent())
{
Visit(subquery);
}
_sqlBuilder.Append(")");
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitObjectArrayAccess(ObjectArrayAccessExpression objectArrayAccessExpression)
{
Visit(objectArrayAccessExpression.Object);
_sqlBuilder
.Append("[\"")
.Append(objectArrayAccessExpression.PropertyName)
.Append("\"]");
return objectArrayAccessExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitObjectArrayIndex(ObjectArrayIndexExpression objectArrayIndexExpression)
{
Visit(objectArrayIndexExpression.Array);
_sqlBuilder.Append("[");
Visit(objectArrayIndexExpression.Index);
_sqlBuilder.Append("]");
return objectArrayIndexExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitScalarAccess(ScalarAccessExpression scalarAccessExpression)
{
Visit(scalarAccessExpression.Object);
// TODO: Remove check once __jObject is translated to the access root in a better fashion.
// See issue #17670 and related issue #14121.
if (scalarAccessExpression.PropertyName.Length > 0)
{
_sqlBuilder
.Append("[\"")
.Append(scalarAccessExpression.PropertyName)
.Append("\"]");
}
return scalarAccessExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitObjectAccess(ObjectAccessExpression objectAccessExpression)
{
Visit(objectAccessExpression.Object);
_sqlBuilder
.Append("[\"")
.Append(objectAccessExpression.PropertyName)
.Append("\"]");
return objectAccessExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitScalarSubquery(ScalarSubqueryExpression scalarSubqueryExpression)
{
_sqlBuilder.AppendLine("(");
using (_sqlBuilder.Indent())
{
Visit(scalarSubqueryExpression.Subquery);
}
_sqlBuilder.Append(")");
return scalarSubqueryExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitProjection(ProjectionExpression projectionExpression)
{
GenerateProjection(projectionExpression, objectProjectionStyle: false);
return projectionExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
private void GenerateProjection(ProjectionExpression projectionExpression, bool objectProjectionStyle)
{
// If the SELECT has a single projection with IsValueProjection, prepend the VALUE keyword (without VALUE, Cosmos projects a JSON
// object containing the value).
if (projectionExpression.IsValueProjection)
{
_sqlBuilder.Append("VALUE ");
Visit(projectionExpression.Expression);
return;
}
if (objectProjectionStyle)
{
_sqlBuilder.Append('"').Append(projectionExpression.Alias).Append("\" : ");
}
Visit(projectionExpression.Expression);
if (!objectProjectionStyle
&& !string.IsNullOrEmpty(projectionExpression.Alias)
&& projectionExpression.Alias != projectionExpression.Name)
{
_sqlBuilder.Append(" AS " + projectionExpression.Alias);
}
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitObjectReference(ObjectReferenceExpression objectReferenceExpression)
{
_sqlBuilder.Append(objectReferenceExpression.Name);
return objectReferenceExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitValueReference(ScalarReferenceExpression scalarReferenceExpression)
{
_sqlBuilder.Append(scalarReferenceExpression.Name);
return scalarReferenceExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitSelect(SelectExpression selectExpression)
{
_sqlBuilder.Append("SELECT ");
if (selectExpression.IsDistinct)
{
_sqlBuilder.Append("DISTINCT ");
}
if (selectExpression.Projection is { Count: > 0 } projections)
{
Check.DebugAssert(
projections.Count == 1 || !projections.Any(p => p.IsValueProjection),
"Multiple projections with IsValueProjection");
// If there's only one projection, we simply project it directly (SELECT VALUE c["Id"]); this happens in GenerateProjection().
// Otherwise, we'll project a JSON object wrapping the multiple projections. Cosmos has two syntaxes for doing so:
// 1. Project out a JSON object as a value (SELECT VALUE { 'a': a, 'b': b }), or
// 2. Project a set of properties with optional AS+aliases (SELECT 'a' AS a, 'b' AS b)
// Both methods produce the exact same results; we usually prefer the 1st, but in some cases we use the 2nd.
if (projections.Count > 1
&& projections.Any(p => !string.IsNullOrEmpty(p.Alias) && p.Alias != p.Name)
&& !projections.Any(p => p.Expression is SqlFunctionExpression)) // Aggregates are not allowed
{
_sqlBuilder.AppendLine("VALUE").AppendLine("{").IncrementIndent();
GenerateList(projections, e => GenerateProjection(e, objectProjectionStyle: true), joinAction: sql => sql.AppendLine(","));
_sqlBuilder.AppendLine().DecrementIndent().Append("}");
}
else
{
GenerateList(projections, e => Visit(e));
}
}
else
{
_sqlBuilder.Append('1');
}
var sources = selectExpression.Sources;
if (sources.Count > 0)
{
_sqlBuilder.AppendLine().Append("FROM ");
Visit(sources[0]);
for (var i = 1; i < sources.Count; i++)
{
_sqlBuilder.AppendLine().Append("JOIN ");
Visit(sources[i]);
}
}
if (selectExpression.Predicate != null)
{
_sqlBuilder.AppendLine().Append("WHERE ");
Visit(selectExpression.Predicate);
}
if (selectExpression.Orderings.Any())
{
_sqlBuilder.AppendLine().Append("ORDER BY ");
var orderByScoringFunction = selectExpression.Orderings is [{ Expression: SqlFunctionExpression { IsScoringFunction: true } }];
if (!UseOldBehavior35476 && orderByScoringFunction)
{
_sqlBuilder.Append("RANK ");
}
Check.DebugAssert(UseOldBehavior35476 || orderByScoringFunction || selectExpression.Orderings.All(x => x.Expression is not SqlFunctionExpression { IsScoringFunction: true }),
"Scoring function can only appear as first (and only) ordering, or not at all.");
GenerateList(selectExpression.Orderings, e => Visit(e));
}
if (selectExpression.Offset != null
|| selectExpression.Limit != null)
{
_sqlBuilder.AppendLine().Append("OFFSET ");
if (selectExpression.Offset != null)
{
Visit(selectExpression.Offset);
}
else
{
_sqlBuilder.Append('0');
}
_sqlBuilder.Append(" LIMIT ");
if (selectExpression.Limit != null)
{
Visit(selectExpression.Limit);
}
else
{
// TODO: See Issue#18923
throw new InvalidOperationException(CosmosStrings.OffsetRequiresLimit);
}
}
return selectExpression;
}
/// <inheritdoc />
protected override Expression VisitFromSql(FromSqlExpression fromSqlExpression)
{
var sql = fromSqlExpression.Sql;
string[] substitutions;
switch (fromSqlExpression.Arguments)
{
case ParameterExpression { Name: not null } parameterExpression
when _parameterValues.TryGetValue(parameterExpression.Name, out var parameterValue)
&& parameterValue is object[] parameterValues:
{
substitutions = new string[parameterValues.Length];
for (var i = 0; i < parameterValues.Length; i++)
{
var parameterName = _parameterNameGenerator.GenerateNext();
_sqlParameters.Add(new SqlParameter(parameterName, parameterValues[i]));
substitutions[i] = parameterName;
}
break;
}
case ConstantExpression { Value: object[] constantValues }:
{
substitutions = new string[constantValues.Length];
for (var i = 0; i < constantValues.Length; i++)
{
var value = constantValues[i];
var typeMapping = typeMappingSource.FindMapping(value.GetType());
Check.DebugAssert(typeMapping is not null, "Could not find type mapping for FromSql parameter");
substitutions[i] = ((CosmosTypeMapping)typeMapping).GenerateConstant(value);
}
break;
}
default:
throw new ArgumentOutOfRangeException(
nameof(fromSqlExpression),
fromSqlExpression.Arguments,
CosmosStrings.InvalidFromSqlArguments(
fromSqlExpression.Arguments.GetType(),
fromSqlExpression.Arguments is ConstantExpression constantExpression
? constantExpression.Value?.GetType()
: null));
}
// ReSharper disable once CoVariantArrayConversion
// InvariantCulture not needed since substitutions are all strings
sql = string.Format(sql, substitutions);
_sqlBuilder.AppendLine("(");
using (_sqlBuilder.Indent())
{
_sqlBuilder.AppendLines(sql);
}
_sqlBuilder.Append(")");
return fromSqlExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitOrdering(OrderingExpression orderingExpression)
{
Visit(orderingExpression.Expression);
if (!orderingExpression.IsAscending)
{
_sqlBuilder.Append(" DESC");
}
return orderingExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitSqlBinary(SqlBinaryExpression sqlBinaryExpression)
{
if (sqlBinaryExpression.OperatorType is ExpressionType.ArrayIndex)
{
Visit(sqlBinaryExpression.Left);
_sqlBuilder.Append('[');
Visit(sqlBinaryExpression.Right);
_sqlBuilder.Append(']');
return sqlBinaryExpression;
}
var op = sqlBinaryExpression.OperatorType switch
{
// Arithmetic
ExpressionType.Add => " + ",
ExpressionType.Subtract => " - ",
ExpressionType.Multiply => " * ",
ExpressionType.Divide => " / ",
ExpressionType.Modulo => " % ",
// Bitwise >>> (zero-fill right shift) not available in C#
ExpressionType.Or => " | ",
ExpressionType.And => " & ",
ExpressionType.ExclusiveOr => " ^ ",
ExpressionType.LeftShift => " << ",
ExpressionType.RightShift => " >> ",
// Logical
ExpressionType.AndAlso => " AND ",
ExpressionType.OrElse => " OR ",
// Comparison
ExpressionType.Equal => " = ",
ExpressionType.NotEqual => " != ",
ExpressionType.GreaterThan => " > ",
ExpressionType.GreaterThanOrEqual => " >= ",
ExpressionType.LessThan => " < ",
ExpressionType.LessThanOrEqual => " <= ",
// Other
ExpressionType.Coalesce => " ?? ",
_ => throw new UnreachableException($"Unsupported unary OperatorType: {sqlBinaryExpression.OperatorType}")
};
_sqlBuilder.Append('(');
Visit(sqlBinaryExpression.Left);
if (sqlBinaryExpression.OperatorType == ExpressionType.Add
&& sqlBinaryExpression.Left.Type == typeof(string))
{
op = " || ";
}
else if (sqlBinaryExpression.OperatorType == ExpressionType.ExclusiveOr
&& sqlBinaryExpression.Type == typeof(bool))
{
op = " != ";
}
_sqlBuilder.Append(op);
Visit(sqlBinaryExpression.Right);
_sqlBuilder.Append(')');
return sqlBinaryExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitObjectBinary(ObjectBinaryExpression objectBinaryExpression)
{
var op = objectBinaryExpression.OperatorType switch
{
ExpressionType.Coalesce => " ?? ",
_ => throw new UnreachableException($"Unsupported unary OperatorType: {objectBinaryExpression.OperatorType}")
};
_sqlBuilder.Append('(');
Visit(objectBinaryExpression.Left);
_sqlBuilder.Append(op);
Visit(objectBinaryExpression.Right);
_sqlBuilder.Append(')');
return objectBinaryExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitSqlUnary(SqlUnaryExpression sqlUnaryExpression)
{
var op = sqlUnaryExpression.OperatorType switch
{
ExpressionType.UnaryPlus => "+",
ExpressionType.Negate => "-",
ExpressionType.Not => "~",
_ => throw new UnreachableException($"Unsupported unary OperatorType: {sqlUnaryExpression.OperatorType}")
};
if (sqlUnaryExpression.OperatorType == ExpressionType.Not
&& sqlUnaryExpression.Operand.Type == typeof(bool))
{
if (sqlUnaryExpression.Operand is InExpression inExpression)
{
GenerateIn(inExpression, negated: true);
return sqlUnaryExpression;
}
op = "NOT";
}
_sqlBuilder.Append(op);
_sqlBuilder.Append('(');
Visit(sqlUnaryExpression.Operand);
_sqlBuilder.Append(')');
return sqlUnaryExpression;
}
private void GenerateList<T>(
IReadOnlyList<T> items,
Action<T> generationAction,
Action<IndentedStringBuilder>? joinAction = null)
{
joinAction ??= (isb => isb.Append(", "));
for (var i = 0; i < items.Count; i++)
{
if (i > 0)
{
joinAction(_sqlBuilder);
}
generationAction(items[i]);
}
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitSqlConstant(SqlConstantExpression sqlConstantExpression)
{
Check.DebugAssert(sqlConstantExpression.TypeMapping is not null, "SqlConstantExpression without a type mapping");
_sqlBuilder.Append(((CosmosTypeMapping)sqlConstantExpression.TypeMapping).GenerateConstant(sqlConstantExpression.Value));
return sqlConstantExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitFragment(FragmentExpression fragmentExpression)
{
_sqlBuilder.Append(fragmentExpression.Fragment);
return fragmentExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitSqlConditional(SqlConditionalExpression sqlConditionalExpression)
{
_sqlBuilder.Append('(');
Visit(sqlConditionalExpression.Test);
_sqlBuilder.Append(" ? ");
Visit(sqlConditionalExpression.IfTrue);
_sqlBuilder.Append(" : ");
Visit(sqlConditionalExpression.IfFalse);
_sqlBuilder.Append(')');
return sqlConditionalExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitSqlParameter(SqlParameterExpression sqlParameterExpression)
{
var parameterName = $"@{sqlParameterExpression.Name}";
if (_sqlParameters.All(sp => sp.Name != parameterName))
{
Check.DebugAssert(sqlParameterExpression.TypeMapping is not null, "SqlParameterExpression without a type mapping.");
_sqlParameters.Add(
new SqlParameter(
parameterName,
((CosmosTypeMapping)sqlParameterExpression.TypeMapping)
.GenerateJToken(_parameterValues[sqlParameterExpression.Name])));
}
_sqlBuilder.Append(parameterName);
return sqlParameterExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected sealed override Expression VisitIn(InExpression inExpression)
{
GenerateIn(inExpression, negated: false);
return inExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitArrayConstant(ArrayConstantExpression arrayConstantExpression)
{
_sqlBuilder.Append("[");
var items = arrayConstantExpression.Items;
for (var i = 0; i < items.Count; i++)
{
if (i > 0)
{
_sqlBuilder.Append(", ");
}
Visit(items[i]);
}
_sqlBuilder.Append("]");
return arrayConstantExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected sealed override Expression VisitSource(SourceExpression sourceExpression)
{
// https://learn.microsoft.com/azure/cosmos-db/nosql/query/from
if (sourceExpression.WithIn)
{
if (sourceExpression.Alias is null)
{
throw new UnreachableException("Alias cannot be null when WithIn is true");
}
_sqlBuilder
.Append(sourceExpression.Alias)
.Append(" IN ");
VisitContainerExpression(sourceExpression.Expression);
}
else
{
VisitContainerExpression(sourceExpression.Expression);
if (sourceExpression.Alias is not null)
{
_sqlBuilder
.Append(" ")
.Append(sourceExpression.Alias);
}
}
return sourceExpression;
void VisitContainerExpression(Expression containerExpression)
{
var subquery = containerExpression is SelectExpression;
var simpleValueProjectionSubquery = containerExpression is SelectExpression
{
Sources: [],
Predicate: null,
Offset: null,
Limit: null,
Orderings: [],
IsDistinct: false,
Projection.Count: 1
};
if (subquery)
{
if (simpleValueProjectionSubquery)
{
_sqlBuilder.Append("(");
}
else
{
_sqlBuilder.AppendLine("(").IncrementIndent();
}
}
Visit(sourceExpression.Expression);
if (subquery)
{
if (simpleValueProjectionSubquery)
{
_sqlBuilder.Append(")");
}
else
{
_sqlBuilder.DecrementIndent().Append(")");
}
}
}
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual void GenerateIn(InExpression inExpression, bool negated)
{
Check.DebugAssert(
inExpression.ValuesParameter is null,
"InExpression.ValuesParameter must have been expanded to constants before SQL generation (in "
+ "InExpressionValuesExpandingExpressionVisitor)");
Check.DebugAssert(inExpression.Values is not null, "Missing Values on InExpression");
Visit(inExpression.Item);
_sqlBuilder.Append(negated ? " NOT IN (" : " IN (");
GenerateList(inExpression.Values, e => Visit(e));
_sqlBuilder.Append(')');
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitObjectFunction(ObjectFunctionExpression objectFunctionExpression)
{
GenerateFunction(objectFunctionExpression.Name, objectFunctionExpression.Arguments);
return objectFunctionExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitSqlFunction(SqlFunctionExpression sqlFunctionExpression)
{
GenerateFunction(sqlFunctionExpression.Name, sqlFunctionExpression.Arguments);
return sqlFunctionExpression;
}
private void GenerateFunction(string name, IReadOnlyList<Expression> arguments)
{
_sqlBuilder.Append(name);
_sqlBuilder.Append('(');
GenerateList(arguments, e => Visit(e));
_sqlBuilder.Append(')');
}
private sealed class ParameterNameGenerator
{
private int _count;
public string GenerateNext()
=> "@p" + _count++;
}
}