-
Notifications
You must be signed in to change notification settings - Fork 491
/
ExpressionToSQL.cs
2017 lines (1775 loc) · 95.8 KB
/
ExpressionToSQL.cs
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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos.Linq
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.Azure.Cosmos.CosmosElements;
using Microsoft.Azure.Cosmos.CosmosElements.Numbers;
using Microsoft.Azure.Cosmos.Spatial;
using Microsoft.Azure.Cosmos.SqlObjects;
using Microsoft.Azure.Documents;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using static Microsoft.Azure.Cosmos.Linq.FromParameterBindings;
// ReSharper disable UnusedParameter.Local
//////////////////////////////////////////////////////////////////////
//
// data.SelectMany(x => x.fields.SelectMany(y => y.fields.Select(z => f(x,y,z)))
// expression tree:
// SelectMany - lambda - Selectmany - lambda - Select - lambda - f(x,y,z)
// | | | | | |
// data x .- fields y .- fields z
// | |
// x y
// parameter bound_to
// x data
// y x.fields
// z y.fields
//
// data.Where(x => f(x)).Select(y => g(y))
// expression tree:
// Select - lambda - g(y)
// | |
// | y
// Where - lambda - f(x)
// | |
// data x
//
// parameter bound_to
// x data
// y Where
/// <summary>
/// Core Linq to DocDBSQL translator.
/// </summary>
internal static class ExpressionToSql
{
public static class LinqMethods
{
public const string Any = "Any";
public const string Average = "Average";
public const string Count = "Count";
public const string Max = "Max";
public const string Min = "Min";
public const string OrderBy = "OrderBy";
public const string ThenBy = "ThenBy";
public const string OrderByDescending = "OrderByDescending";
public const string ThenByDescending = "ThenByDescending";
public const string Select = "Select";
public const string SelectMany = "SelectMany";
public const string Sum = "Sum";
public const string Skip = "Skip";
public const string Take = "Take";
public const string Distinct = "Distinct";
public const string Where = "Where";
}
private static string SqlRoot = "root";
private static string DefaultParameterName = "v";
private static bool usePropertyRef = false;
private static SqlIdentifier RootIdentifier = SqlIdentifier.Create(SqlRoot);
/// <summary>
/// Toplevel entry point.
/// </summary>
/// <param name="inputExpression">An Expression representing a Query on a IDocumentQuery object.</param>
/// <param name="parameters">Optional dictionary for parameter name and value</param>
/// <param name="serializationOptions">Optional serializer options.</param>
/// <returns>The corresponding SQL query.</returns>
public static SqlQuery TranslateQuery(
Expression inputExpression,
IDictionary<object, string> parameters,
CosmosSerializationOptions serializationOptions)
{
TranslationContext context = new TranslationContext(serializationOptions, parameters);
ExpressionToSql.Translate(inputExpression, context); // ignore result here
QueryUnderConstruction query = context.currentQuery;
query = query.FlattenAsPossible();
SqlQuery result = query.GetSqlQuery();
return result;
}
/// <summary>
/// Translate an expression into a query.
/// Query is constructed as a side-effect in context.currentQuery.
/// </summary>
/// <param name="inputExpression">Expression to translate.</param>
/// <param name="context">Context for translation.</param>
public static Collection Translate(Expression inputExpression, TranslationContext context)
{
if (inputExpression == null)
{
throw new ArgumentNullException("inputExpression");
}
Collection collection;
switch (inputExpression.NodeType)
{
case ExpressionType.Call:
MethodCallExpression methodCallExpression = (MethodCallExpression)inputExpression;
bool shouldConvertToScalarAnyCollection = (context.PeekMethod() == null) && methodCallExpression.Method.Name.Equals(LinqMethods.Any);
collection = ExpressionToSql.VisitMethodCall(methodCallExpression, context);
if (shouldConvertToScalarAnyCollection) collection = ExpressionToSql.ConvertToScalarAnyCollection(context);
break;
case ExpressionType.Constant:
collection = ExpressionToSql.TranslateInput((ConstantExpression)inputExpression, context);
break;
case ExpressionType.MemberAccess:
collection = ExpressionToSql.VisitMemberAccessCollectionExpression(inputExpression, context, ExpressionToSql.GetBindingParameterName(context));
break;
case ExpressionType.Parameter:
SqlScalarExpression scalar = ExpressionToSql.VisitNonSubqueryScalarExpression(inputExpression, context);
collection = ExpressionToSql.ConvertToCollection(scalar);
break;
default:
throw new DocumentQueryException(string.Format(CultureInfo.CurrentCulture, ClientResources.ExpressionTypeIsNotSupported, inputExpression.NodeType));
}
return collection;
}
private static Collection TranslateInput(ConstantExpression inputExpression, TranslationContext context)
{
if (!typeof(IDocumentQuery).IsAssignableFrom(inputExpression.Type))
{
throw new DocumentQueryException(ClientResources.InputIsNotIDocumentQuery);
}
// ExpressionToSql is the query input value: a IDocumentQuery
if (!(inputExpression.Value is IDocumentQuery input))
{
throw new DocumentQueryException(ClientResources.InputIsNotIDocumentQuery);
}
context.currentQuery = new QueryUnderConstruction(context.GetGenFreshParameterFunc());
Type elemType = TypeSystem.GetElementType(inputExpression.Type);
context.SetInputParameter(elemType, ParameterSubstitution.InputParameterName); // ignore result
// First outer collection
Collection result = new Collection(ExpressionToSql.SqlRoot);
return result;
}
/// <summary>
/// Get a paramter name to be binded to the a collection from the next lambda.
/// It's merely for readability purpose. If that is not possible, use a default
/// parameter name.
/// </summary>
/// <param name="context">The translation context</param>
/// <returns>A parameter name</returns>
private static string GetBindingParameterName(TranslationContext context)
{
MethodCallExpression peekMethod = context.PeekMethod();
// The parameter name is the top method's parameter if applicable
string parameterName = null;
if (peekMethod.Arguments.Count > 1)
{
if (peekMethod.Arguments[1] is LambdaExpression lambda && lambda.Parameters.Count > 0)
{
parameterName = lambda.Parameters[0].Name;
}
}
if (parameterName == null) parameterName = ExpressionToSql.DefaultParameterName;
return parameterName;
}
#region VISITOR
/// <summary>
/// Visitor which produces a SqlScalarExpression.
/// </summary>
/// <param name="inputExpression">Expression to visit.</param>
/// <param name="context">Context information.</param>
/// <returns>The translation as a ScalarExpression.</returns>
internal static SqlScalarExpression VisitNonSubqueryScalarExpression(Expression inputExpression, TranslationContext context)
{
if (inputExpression == null)
{
return null;
}
switch (inputExpression.NodeType)
{
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.Not:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.ArrayLength:
case ExpressionType.Quote:
case ExpressionType.TypeAs:
return ExpressionToSql.VisitUnary((UnaryExpression)inputExpression, context);
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.And:
case ExpressionType.AndAlso:
case ExpressionType.Or:
case ExpressionType.OrElse:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.Equal:
case ExpressionType.NotEqual:
case ExpressionType.Coalesce:
case ExpressionType.ArrayIndex:
case ExpressionType.RightShift:
case ExpressionType.LeftShift:
case ExpressionType.ExclusiveOr:
return ExpressionToSql.VisitBinary((BinaryExpression)inputExpression, context);
case ExpressionType.TypeIs:
return ExpressionToSql.VisitTypeIs((TypeBinaryExpression)inputExpression, context);
case ExpressionType.Conditional:
return ExpressionToSql.VisitConditional((ConditionalExpression)inputExpression, context);
case ExpressionType.Constant:
return ExpressionToSql.VisitConstant((ConstantExpression)inputExpression, context);
case ExpressionType.Parameter:
return ExpressionToSql.VisitParameter((ParameterExpression)inputExpression, context);
case ExpressionType.MemberAccess:
return ExpressionToSql.VisitMemberAccess((MemberExpression)inputExpression, context);
case ExpressionType.New:
return ExpressionToSql.VisitNew((NewExpression)inputExpression, context);
case ExpressionType.NewArrayInit:
case ExpressionType.NewArrayBounds:
return ExpressionToSql.VisitNewArray((NewArrayExpression)inputExpression, context);
case ExpressionType.Invoke:
return ExpressionToSql.VisitInvocation((InvocationExpression)inputExpression, context);
case ExpressionType.MemberInit:
return ExpressionToSql.VisitMemberInit((MemberInitExpression)inputExpression, context);
case ExpressionType.ListInit:
return ExpressionToSql.VisitListInit((ListInitExpression)inputExpression, context);
case ExpressionType.Call:
return ExpressionToSql.VisitMethodCallScalar((MethodCallExpression)inputExpression, context);
default:
throw new DocumentQueryException(string.Format(CultureInfo.CurrentCulture, ClientResources.ExpressionTypeIsNotSupported, inputExpression.NodeType));
}
}
private static SqlScalarExpression VisitMethodCallScalar(MethodCallExpression methodCallExpression, TranslationContext context)
{
// Check if it is a UDF method call
if (methodCallExpression.Method.Equals(typeof(CosmosLinq).GetMethod("InvokeUserDefinedFunction")))
{
string udfName = ((ConstantExpression)methodCallExpression.Arguments[0]).Value as string;
if (string.IsNullOrEmpty(udfName))
{
throw new DocumentQueryException(string.Format(CultureInfo.CurrentCulture, ClientResources.UdfNameIsNullOrEmpty));
}
SqlIdentifier methodName = SqlIdentifier.Create(udfName);
List<SqlScalarExpression> arguments = new List<SqlScalarExpression>();
if (methodCallExpression.Arguments.Count == 2)
{
// We have two cases here, if the udf was expecting only one parameter and this parameter is an array
// then the second argument will be an expression of this array.
// else we will have a NewArrayExpression of the udf arguments
if (methodCallExpression.Arguments[1] is NewArrayExpression newArrayExpression)
{
ReadOnlyCollection<Expression> argumentsExpressions = newArrayExpression.Expressions;
foreach (Expression argument in argumentsExpressions)
{
arguments.Add(ExpressionToSql.VisitScalarExpression(argument, context));
}
}
else if (methodCallExpression.Arguments[1].NodeType == ExpressionType.Constant &&
methodCallExpression.Arguments[1].Type == typeof(object[]))
{
object[] argumentsExpressions = (object[])((ConstantExpression)methodCallExpression.Arguments[1]).Value;
foreach (object argument in argumentsExpressions)
{
arguments.Add(ExpressionToSql.VisitConstant(Expression.Constant(argument), context));
}
}
else
{
arguments.Add(ExpressionToSql.VisitScalarExpression(methodCallExpression.Arguments[1], context));
}
}
return SqlFunctionCallScalarExpression.Create(methodName, true, arguments.ToImmutableArray());
}
else
{
return BuiltinFunctionVisitor.VisitBuiltinFunctionCall(methodCallExpression, context);
}
}
private static SqlObjectProperty VisitBinding(MemberBinding binding, TranslationContext context)
{
switch (binding.BindingType)
{
case MemberBindingType.Assignment:
return ExpressionToSql.VisitMemberAssignment((MemberAssignment)binding, context);
case MemberBindingType.MemberBinding:
return ExpressionToSql.VisitMemberMemberBinding((MemberMemberBinding)binding, context);
case MemberBindingType.ListBinding:
default:
return ExpressionToSql.VisitMemberListBinding((MemberListBinding)binding, context);
}
}
private static SqlUnaryScalarOperatorKind GetUnaryOperatorKind(ExpressionType type)
{
switch (type)
{
case ExpressionType.UnaryPlus:
return SqlUnaryScalarOperatorKind.Plus;
case ExpressionType.Negate:
return SqlUnaryScalarOperatorKind.Minus;
case ExpressionType.OnesComplement:
return SqlUnaryScalarOperatorKind.BitwiseNot;
case ExpressionType.Not:
return SqlUnaryScalarOperatorKind.Not;
default:
throw new DocumentQueryException(string.Format(CultureInfo.CurrentCulture, ClientResources.UnaryOperatorNotSupported, type));
}
}
private static SqlScalarExpression VisitUnary(UnaryExpression inputExpression, TranslationContext context)
{
SqlScalarExpression operand = ExpressionToSql.VisitScalarExpression(inputExpression.Operand, context);
// handle NOT IN
if (operand is SqlInScalarExpression sqlInScalarExpression && inputExpression.NodeType == ExpressionType.Not)
{
SqlInScalarExpression inExpression = sqlInScalarExpression;
return SqlInScalarExpression.Create(inExpression.Needle, true, inExpression.Haystack);
}
if (inputExpression.NodeType == ExpressionType.Quote)
{
return operand;
}
if (inputExpression.NodeType == ExpressionType.Convert)
{
return operand;
}
SqlUnaryScalarOperatorKind op = GetUnaryOperatorKind(inputExpression.NodeType);
return SqlUnaryScalarExpression.Create(op, operand);
}
private static SqlBinaryScalarOperatorKind GetBinaryOperatorKind(ExpressionType expressionType, Type resultType)
{
switch (expressionType)
{
case ExpressionType.Add:
{
if (resultType == typeof(string))
{
return SqlBinaryScalarOperatorKind.StringConcat;
}
return SqlBinaryScalarOperatorKind.Add;
}
case ExpressionType.AndAlso:
return SqlBinaryScalarOperatorKind.And;
case ExpressionType.And:
return SqlBinaryScalarOperatorKind.BitwiseAnd;
case ExpressionType.Or:
return SqlBinaryScalarOperatorKind.BitwiseOr;
case ExpressionType.ExclusiveOr:
return SqlBinaryScalarOperatorKind.BitwiseXor;
case ExpressionType.Divide:
return SqlBinaryScalarOperatorKind.Divide;
case ExpressionType.Equal:
return SqlBinaryScalarOperatorKind.Equal;
case ExpressionType.GreaterThan:
return SqlBinaryScalarOperatorKind.GreaterThan;
case ExpressionType.GreaterThanOrEqual:
return SqlBinaryScalarOperatorKind.GreaterThanOrEqual;
case ExpressionType.LessThan:
return SqlBinaryScalarOperatorKind.LessThan;
case ExpressionType.LessThanOrEqual:
return SqlBinaryScalarOperatorKind.LessThanOrEqual;
case ExpressionType.Modulo:
return SqlBinaryScalarOperatorKind.Modulo;
case ExpressionType.Multiply:
return SqlBinaryScalarOperatorKind.Multiply;
case ExpressionType.NotEqual:
return SqlBinaryScalarOperatorKind.NotEqual;
case ExpressionType.OrElse:
return SqlBinaryScalarOperatorKind.Or;
case ExpressionType.Subtract:
return SqlBinaryScalarOperatorKind.Subtract;
case ExpressionType.Coalesce:
return SqlBinaryScalarOperatorKind.Coalesce;
default:
throw new DocumentQueryException(string.Format(CultureInfo.CurrentCulture, ClientResources.BinaryOperatorNotSupported, expressionType));
}
}
private static SqlScalarExpression VisitBinary(BinaryExpression inputExpression, TranslationContext context)
{
// Speical case for string.CompareTo
// if any of the left or right expression is MethodCallExpression
// the other expression should only be constant (integer)
MethodCallExpression methodCallExpression = null;
ConstantExpression constantExpression = null;
bool reverseNodeType = false;
if (inputExpression.Left.NodeType == ExpressionType.Call && inputExpression.Right.NodeType == ExpressionType.Constant)
{
methodCallExpression = (MethodCallExpression)inputExpression.Left;
constantExpression = (ConstantExpression)inputExpression.Right;
}
else if (inputExpression.Right.NodeType == ExpressionType.Call && inputExpression.Left.NodeType == ExpressionType.Constant)
{
methodCallExpression = (MethodCallExpression)inputExpression.Right;
constantExpression = (ConstantExpression)inputExpression.Left;
reverseNodeType = true;
}
if (methodCallExpression != null && constantExpression != null)
{
if (TryMatchStringCompareTo(methodCallExpression, constantExpression, inputExpression.NodeType))
{
return ExpressionToSql.VisitStringCompareTo(methodCallExpression, constantExpression, inputExpression.NodeType, reverseNodeType, context);
}
}
SqlScalarExpression left = ExpressionToSql.VisitScalarExpression(inputExpression.Left, context);
SqlScalarExpression right = ExpressionToSql.VisitScalarExpression(inputExpression.Right, context);
if (inputExpression.NodeType == ExpressionType.ArrayIndex)
{
SqlMemberIndexerScalarExpression result = SqlMemberIndexerScalarExpression.Create(left, right);
return result;
}
SqlBinaryScalarOperatorKind op = GetBinaryOperatorKind(inputExpression.NodeType, inputExpression.Type);
if (left is SqlMemberIndexerScalarExpression && right is SqlLiteralScalarExpression literalScalarExpression)
{
right = ExpressionToSql.ApplyCustomConverters(inputExpression.Left, literalScalarExpression);
}
else if (right is SqlMemberIndexerScalarExpression && left is SqlLiteralScalarExpression sqlLiteralScalarExpression)
{
left = ExpressionToSql.ApplyCustomConverters(inputExpression.Right, sqlLiteralScalarExpression);
}
return SqlBinaryScalarExpression.Create(op, left, right);
}
private static SqlScalarExpression ApplyCustomConverters(Expression left, SqlLiteralScalarExpression right)
{
MemberExpression memberExpression;
if (left is UnaryExpression unaryExpression)
{
memberExpression = unaryExpression.Operand as MemberExpression;
}
else
{
memberExpression = left as MemberExpression;
}
if (memberExpression != null)
{
Type memberType = memberExpression.Type;
if (memberType.IsNullable())
{
memberType = memberType.NullableUnderlyingType();
}
// There are two ways to specify a custom attribute
// 1- by specifying the JsonConverterAttribute on a Class/Enum
// [JsonConverter(typeof(StringEnumConverter))]
// Enum MyEnum
// {
// ...
// }
//
// 2- by specifying the JsonConverterAttribute on a property
// class MyClass
// {
// [JsonConverter(typeof(StringEnumConverter))]
// public MyEnum MyEnum;
// }
//
// Newtonsoft gives high precedence to the attribute specified
// on a property over on a type (class/enum)
// so we check both attributes and apply the same precedence rules
// JsonConverterAttribute doesn't allow duplicates so it's safe to
// use FirstOrDefault()
CustomAttributeData memberAttribute = memberExpression.Member.CustomAttributes.Where(ca => ca.AttributeType == typeof(JsonConverterAttribute)).FirstOrDefault();
CustomAttributeData typeAttribute = memberType.GetsCustomAttributes().Where(ca => ca.AttributeType == typeof(JsonConverterAttribute)).FirstOrDefault();
CustomAttributeData converterAttribute = memberAttribute ?? typeAttribute;
if (converterAttribute != null)
{
Debug.Assert(converterAttribute.ConstructorArguments.Count > 0);
Type converterType = (Type)converterAttribute.ConstructorArguments[0].Value;
object value = default(object);
// Enum
if (memberType.IsEnum())
{
Number64 number64 = ((SqlNumberLiteral)right.Literal).Value;
if (number64.IsDouble)
{
value = Enum.ToObject(memberType, Number64.ToDouble(number64));
}
else
{
value = Enum.ToObject(memberType, Number64.ToLong(number64));
}
}
// DateTime
else if (memberType == typeof(DateTime))
{
SqlStringLiteral serializedDateTime = (SqlStringLiteral)right.Literal;
value = DateTime.Parse(serializedDateTime.Value);
}
if (value != default(object))
{
string serializedValue;
if (converterType.GetConstructor(Type.EmptyTypes) != null)
{
serializedValue = JsonConvert.SerializeObject(value, (JsonConverter)Activator.CreateInstance(converterType));
}
else
{
serializedValue = JsonConvert.SerializeObject(value);
}
return CosmosElement.Parse(serializedValue).Accept(CosmosElementToSqlScalarExpressionVisitor.Singleton);
}
}
}
return right;
}
private static bool TryMatchStringCompareTo(MethodCallExpression left, ConstantExpression right, ExpressionType compareOperator)
{
if (left.Method.Equals(typeof(string).GetMethod("CompareTo", new Type[] { typeof(string) })) && left.Arguments.Count == 1)
{
// operator can only be =, >, >=, <, <=
switch (compareOperator)
{
case ExpressionType.Equal:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
break;
default:
throw new DocumentQueryException(string.Format(CultureInfo.CurrentCulture, ClientResources.StringCompareToInvalidOperator));
}
// the constant value should be zero, otherwise we can't determine how to translate the expression
// it could be either integer or nullable integer
if (!(right.Type == typeof(int) && (int)right.Value == 0) &&
!(right.Type == typeof(int?) && ((int?)right.Value).HasValue && ((int?)right.Value).Value == 0))
{
throw new DocumentQueryException(string.Format(CultureInfo.CurrentCulture, ClientResources.StringCompareToInvalidConstant));
}
return true;
}
return false;
}
private static SqlScalarExpression VisitStringCompareTo(
MethodCallExpression left,
ConstantExpression right,
ExpressionType compareOperator,
bool reverseNodeType,
TranslationContext context)
{
if (reverseNodeType)
{
switch (compareOperator)
{
case ExpressionType.Equal:
// do nothing
break;
case ExpressionType.GreaterThan:
compareOperator = ExpressionType.LessThan;
break;
case ExpressionType.GreaterThanOrEqual:
compareOperator = ExpressionType.LessThanOrEqual;
break;
case ExpressionType.LessThan:
compareOperator = ExpressionType.GreaterThan;
break;
case ExpressionType.LessThanOrEqual:
compareOperator = ExpressionType.GreaterThanOrEqual;
break;
default:
throw new DocumentQueryException(string.Format(CultureInfo.CurrentCulture, ClientResources.StringCompareToInvalidOperator));
}
}
SqlBinaryScalarOperatorKind op = GetBinaryOperatorKind(compareOperator, null);
SqlScalarExpression leftExpression = ExpressionToSql.VisitNonSubqueryScalarExpression(left.Object, context);
SqlScalarExpression rightExpression = ExpressionToSql.VisitNonSubqueryScalarExpression(left.Arguments[0], context);
return SqlBinaryScalarExpression.Create(op, leftExpression, rightExpression);
}
private static SqlScalarExpression VisitTypeIs(TypeBinaryExpression inputExpression, TranslationContext context)
{
throw new DocumentQueryException(string.Format(CultureInfo.CurrentCulture, ClientResources.ExpressionTypeIsNotSupported, inputExpression.NodeType));
}
public static SqlScalarExpression VisitConstant(ConstantExpression inputExpression, TranslationContext context)
{
if (inputExpression.Value == null)
{
return SqlLiteralScalarExpression.SqlNullLiteralScalarExpression;
}
if (inputExpression.Type.IsNullable())
{
return ExpressionToSql.VisitConstant(Expression.Constant(inputExpression.Value, Nullable.GetUnderlyingType(inputExpression.Type)), context);
}
if (context.parameters != null && context.parameters.TryGetValue(inputExpression.Value, out string paramName))
{
SqlParameter sqlParameter = SqlParameter.Create(paramName);
return SqlParameterRefScalarExpression.Create(sqlParameter);
}
Type constantType = inputExpression.Value.GetType();
if (constantType.IsValueType())
{
if (inputExpression.Value is bool boolValue)
{
SqlBooleanLiteral literal = SqlBooleanLiteral.Create(boolValue);
return SqlLiteralScalarExpression.Create(literal);
}
if (ExpressionToSql.TryGetSqlNumberLiteral(inputExpression.Value, out SqlNumberLiteral numberLiteral))
{
return SqlLiteralScalarExpression.Create(numberLiteral);
}
if (inputExpression.Value is Guid guidValue)
{
SqlStringLiteral literal = SqlStringLiteral.Create(guidValue.ToString());
return SqlLiteralScalarExpression.Create(literal);
}
}
if (inputExpression.Value is string stringValue)
{
SqlStringLiteral literal = SqlStringLiteral.Create(stringValue);
return SqlLiteralScalarExpression.Create(literal);
}
if (typeof(Geometry).IsAssignableFrom(constantType))
{
return GeometrySqlExpressionFactory.Construct(inputExpression);
}
if (inputExpression.Value is IEnumerable enumerable)
{
List<SqlScalarExpression> arrayItems = new List<SqlScalarExpression>();
foreach (object item in enumerable)
{
arrayItems.Add(ExpressionToSql.VisitConstant(Expression.Constant(item), context));
}
return SqlArrayCreateScalarExpression.Create(arrayItems.ToImmutableArray());
}
return CosmosElement.Parse(JsonConvert.SerializeObject(inputExpression.Value)).Accept(CosmosElementToSqlScalarExpressionVisitor.Singleton);
}
private static SqlScalarExpression VisitConditional(ConditionalExpression inputExpression, TranslationContext context)
{
SqlScalarExpression conditionExpression = ExpressionToSql.VisitScalarExpression(inputExpression.Test, context);
SqlScalarExpression firstExpression = ExpressionToSql.VisitScalarExpression(inputExpression.IfTrue, context);
SqlScalarExpression secondExpression = ExpressionToSql.VisitScalarExpression(inputExpression.IfFalse, context);
return SqlConditionalScalarExpression.Create(conditionExpression, firstExpression, secondExpression);
}
private static SqlScalarExpression VisitParameter(ParameterExpression inputExpression, TranslationContext context)
{
Expression subst = context.LookupSubstitution(inputExpression);
if (subst != null)
{
return ExpressionToSql.VisitNonSubqueryScalarExpression(subst, context);
}
string name = inputExpression.Name;
SqlIdentifier id = SqlIdentifier.Create(name);
return SqlPropertyRefScalarExpression.Create(null, id);
}
private static SqlScalarExpression VisitMemberAccess(MemberExpression inputExpression, TranslationContext context)
{
SqlScalarExpression memberExpression = ExpressionToSql.VisitScalarExpression(inputExpression.Expression, context);
string memberName = inputExpression.Member.GetMemberName(context?.serializationOptions);
// if expression is nullable
if (inputExpression.Expression.Type.IsNullable())
{
// ignore .Value
if (memberName == "Value")
{
return memberExpression;
}
// convert .HasValue to IS_DEFINED expression
if (memberName == "HasValue")
{
return SqlFunctionCallScalarExpression.CreateBuiltin("IS_DEFINED", memberExpression);
}
}
if (usePropertyRef)
{
SqlIdentifier propertyIdnetifier = SqlIdentifier.Create(memberName);
SqlPropertyRefScalarExpression propertyRefExpression = SqlPropertyRefScalarExpression.Create(memberExpression, propertyIdnetifier);
return propertyRefExpression;
}
else
{
SqlScalarExpression indexExpression = SqlLiteralScalarExpression.Create(SqlStringLiteral.Create(memberName));
SqlMemberIndexerScalarExpression memberIndexerExpression = SqlMemberIndexerScalarExpression.Create(memberExpression, indexExpression);
return memberIndexerExpression;
}
}
private static SqlScalarExpression[] VisitExpressionList(ReadOnlyCollection<Expression> inputExpressionList, TranslationContext context)
{
SqlScalarExpression[] result = new SqlScalarExpression[inputExpressionList.Count];
for (int i = 0; i < inputExpressionList.Count; i++)
{
SqlScalarExpression p = ExpressionToSql.VisitScalarExpression(inputExpressionList[i], context);
result[i] = p;
}
return result;
}
private static SqlObjectProperty VisitMemberAssignment(MemberAssignment inputExpression, TranslationContext context)
{
SqlScalarExpression assign = ExpressionToSql.VisitScalarExpression(inputExpression.Expression, context);
string memberName = inputExpression.Member.GetMemberName(context?.serializationOptions);
SqlPropertyName propName = SqlPropertyName.Create(memberName);
SqlObjectProperty prop = SqlObjectProperty.Create(propName, assign);
return prop;
}
private static SqlObjectProperty VisitMemberMemberBinding(MemberMemberBinding inputExpression, TranslationContext context)
{
throw new DocumentQueryException(ClientResources.MemberBindingNotSupported);
}
private static SqlObjectProperty VisitMemberListBinding(MemberListBinding inputExpression, TranslationContext context)
{
throw new DocumentQueryException(ClientResources.MemberBindingNotSupported);
}
private static SqlObjectProperty[] VisitBindingList(ReadOnlyCollection<MemberBinding> inputExpressionList, TranslationContext context)
{
SqlObjectProperty[] list = new SqlObjectProperty[inputExpressionList.Count];
for (int i = 0; i < inputExpressionList.Count; i++)
{
SqlObjectProperty b = ExpressionToSql.VisitBinding(inputExpressionList[i], context);
list[i] = b;
}
return list;
}
private static SqlObjectProperty[] CreateInitializers(ReadOnlyCollection<Expression> arguments, ReadOnlyCollection<MemberInfo> members, TranslationContext context)
{
if (arguments.Count != members.Count)
{
throw new InvalidOperationException("Expected same number of arguments as members");
}
SqlObjectProperty[] result = new SqlObjectProperty[arguments.Count];
for (int i = 0; i < arguments.Count; i++)
{
Expression arg = arguments[i];
MemberInfo member = members[i];
SqlScalarExpression value = ExpressionToSql.VisitScalarExpression(arg, context);
string memberName = member.GetMemberName(context?.serializationOptions);
SqlPropertyName propName = SqlPropertyName.Create(memberName);
SqlObjectProperty prop = SqlObjectProperty.Create(propName, value);
result[i] = prop;
}
return result;
}
private static SqlScalarExpression VisitNew(NewExpression inputExpression, TranslationContext context)
{
if (typeof(Geometry).IsAssignableFrom(inputExpression.Type))
{
return GeometrySqlExpressionFactory.Construct(inputExpression);
}
if (inputExpression.Arguments.Count > 0)
{
if (inputExpression.Members == null)
{
throw new DocumentQueryException(ClientResources.ConstructorInvocationNotSupported);
}
SqlObjectProperty[] propertyBindings = ExpressionToSql.CreateInitializers(inputExpression.Arguments, inputExpression.Members, context);
SqlObjectCreateScalarExpression create = SqlObjectCreateScalarExpression.Create(propertyBindings);
return create;
}
else
{
// no need to return anything; the initializer will generate the complete code
return null;
}
}
private static SqlScalarExpression VisitMemberInit(MemberInitExpression inputExpression, TranslationContext context)
{
ExpressionToSql.VisitNew(inputExpression.NewExpression, context); // Return value is ignored
SqlObjectProperty[] propertyBindings = ExpressionToSql.VisitBindingList(inputExpression.Bindings, context);
SqlObjectCreateScalarExpression create = SqlObjectCreateScalarExpression.Create(propertyBindings);
return create;
}
private static SqlScalarExpression VisitListInit(ListInitExpression inputExpression, TranslationContext context)
{
throw new DocumentQueryException(string.Format(CultureInfo.CurrentCulture, ClientResources.ExpressionTypeIsNotSupported, inputExpression.NodeType));
}
private static SqlScalarExpression VisitNewArray(NewArrayExpression inputExpression, TranslationContext context)
{
SqlScalarExpression[] exprs = ExpressionToSql.VisitExpressionList(inputExpression.Expressions, context);
if (inputExpression.NodeType == ExpressionType.NewArrayInit)
{
SqlArrayCreateScalarExpression array = SqlArrayCreateScalarExpression.Create(exprs);
return array;
}
else
{
throw new DocumentQueryException(string.Format(CultureInfo.CurrentCulture, ClientResources.ExpressionTypeIsNotSupported, inputExpression.NodeType));
}
}
private static SqlScalarExpression VisitInvocation(InvocationExpression inputExpression, TranslationContext context)
{
throw new DocumentQueryException(string.Format(CultureInfo.CurrentCulture, ClientResources.ExpressionTypeIsNotSupported, inputExpression.NodeType));
}
#endregion VISITOR
#region Scalar and CollectionScalar Visitors
private static Collection ConvertToCollection(SqlScalarExpression scalar)
{
if (usePropertyRef)
{
SqlPropertyRefScalarExpression propertyRefExpression = scalar as SqlPropertyRefScalarExpression;
if (propertyRefExpression == null)
{
throw new DocumentQueryException(ClientResources.PathExpressionsOnly);
}
SqlInputPathCollection path = ConvertPropertyRefToPath(propertyRefExpression);
Collection result = new Collection(path);
return result;
}
else
{
SqlMemberIndexerScalarExpression memberIndexerExpression = scalar as SqlMemberIndexerScalarExpression;
if (memberIndexerExpression == null)
{
SqlPropertyRefScalarExpression propertyRefExpression = scalar as SqlPropertyRefScalarExpression;
if (propertyRefExpression == null)
{
throw new DocumentQueryException(ClientResources.PathExpressionsOnly);
}
SqlInputPathCollection path = ConvertPropertyRefToPath(propertyRefExpression);
Collection result = new Collection(path);
return result;
}
else
{
SqlInputPathCollection path = ConvertMemberIndexerToPath(memberIndexerExpression);
Collection result = new Collection(path);
return result;
}
}
}
/// <summary>
/// Convert the context's current query to a scalar Any collection
/// by wrapping it as following: SELECT VALUE COUNT(v0) > 0 FROM (current query) AS v0.
/// This is used in cases where LINQ expression ends with Any() which is a boolean scalar.
/// Normally Any would translate to SELECT VALUE EXISTS() subquery. However that wouldn't work
/// for these cases because it would result in a boolean value for each row instead of
/// one single "aggregated" boolean value.
/// </summary>
/// <param name="context">The translation context</param>
/// <returns>The scalar Any collection</returns>
private static Collection ConvertToScalarAnyCollection(TranslationContext context)
{
SqlQuery query = context.currentQuery.FlattenAsPossible().GetSqlQuery();
SqlCollection subqueryCollection = SqlSubqueryCollection.Create(query);
ParameterExpression parameterExpression = context.GenFreshParameter(typeof(object), ExpressionToSql.DefaultParameterName);
Binding binding = new Binding(parameterExpression, subqueryCollection, isInCollection: false, isInputParameter: true);
context.currentQuery = new QueryUnderConstruction(context.GetGenFreshParameterFunc());
context.currentQuery.AddBinding(binding);
SqlSelectSpec selectSpec = SqlSelectValueSpec.Create(
SqlBinaryScalarExpression.Create(
SqlBinaryScalarOperatorKind.GreaterThan,
SqlFunctionCallScalarExpression.CreateBuiltin(
SqlFunctionCallScalarExpression.Names.Count,
SqlPropertyRefScalarExpression.Create(null, SqlIdentifier.Create(parameterExpression.Name))),
SqlLiteralScalarExpression.Create(SqlNumberLiteral.Create(0))));
SqlSelectClause selectClause = SqlSelectClause.Create(selectSpec);
context.currentQuery.AddSelectClause(selectClause);
return new Collection(LinqMethods.Any);
}
private static SqlScalarExpression VisitNonSubqueryScalarExpression(Expression expression, ReadOnlyCollection<ParameterExpression> parameters, TranslationContext context)
{
foreach (ParameterExpression par in parameters)
{
context.PushParameter(par, context.CurrentSubqueryBinding.ShouldBeOnNewQuery);
}
SqlScalarExpression scalarExpression = ExpressionToSql.VisitNonSubqueryScalarExpression(expression, context);
foreach (ParameterExpression par in parameters)
{
context.PopParameter();
}
return scalarExpression;
}
private static SqlScalarExpression VisitNonSubqueryScalarLambda(LambdaExpression lambdaExpression, TranslationContext context)
{
ReadOnlyCollection<ParameterExpression> parameters = lambdaExpression.Parameters;
if (parameters.Count != 1)
{
throw new DocumentQueryException(string.Format(CultureInfo.CurrentCulture, ClientResources.InvalidArgumentsCount, lambdaExpression.Body, 1, parameters.Count));
}
return ExpressionToSql.VisitNonSubqueryScalarExpression(lambdaExpression.Body, parameters, context);
}
private static Collection VisitCollectionExpression(Expression expression, ReadOnlyCollection<ParameterExpression> parameters, TranslationContext context)
{