-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
PredicateTranslator.cs
1660 lines (1464 loc) · 66.4 KB
/
PredicateTranslator.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 2015-2017 MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.RegularExpressions;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Options;
using MongoDB.Bson.Serialization.Serializers;
using MongoDB.Driver.Linq.Expressions;
using MongoDB.Driver.Linq.Expressions.ResultOperators;
using MongoDB.Driver.Linq.Processors;
using MongoDB.Driver.Support;
namespace MongoDB.Driver.Linq.Translators
{
internal sealed class PredicateTranslator
{
#region static
// private static fields
private static readonly FilterDefinitionBuilder<BsonDocument> __builder = new FilterDefinitionBuilder<BsonDocument>();
// public static methods
public static BsonDocument Translate<TDocument>(Expression<Func<TDocument, bool>> predicate, IBsonSerializer<TDocument> parameterSerializer, IBsonSerializerRegistry serializerRegistry)
{
var parameterExpression = new DocumentExpression(parameterSerializer);
var context = new PipelineBindingContext(serializerRegistry);
context.AddExpressionMapping(predicate.Parameters[0], parameterExpression);
var node = PartialEvaluator.Evaluate(predicate.Body);
node = Transformer.Transform(node);
node = context.Bind(node);
return Translate(node, serializerRegistry);
}
public static BsonDocument Translate(Expression node, IBsonSerializerRegistry serializerRegistry)
{
var translator = new PredicateTranslator(serializerRegistry);
node = FieldExpressionFlattener.FlattenFields(node);
return translator.Translate(node)
.Render(serializerRegistry.GetSerializer<BsonDocument>(), serializerRegistry);
}
#endregion
// private fields
private readonly IBsonSerializerRegistry _serializerRegistry;
// constructors
private PredicateTranslator(IBsonSerializerRegistry serializerRegistry)
{
_serializerRegistry = serializerRegistry;
}
// private methods
private FilterDefinition<BsonDocument> Translate(Expression node)
{
FilterDefinition<BsonDocument> filter = null;
switch (node.NodeType)
{
case ExpressionType.And:
filter = TranslateAnd((BinaryExpression)node);
break;
case ExpressionType.AndAlso:
filter = TranslateAndAlso((BinaryExpression)node);
break;
case ExpressionType.ArrayIndex:
filter = TranslateBoolean(node);
break;
case ExpressionType.Call:
filter = TranslateMethodCall((MethodCallExpression)node);
break;
case ExpressionType.Constant:
filter = TranslateConstant((ConstantExpression)node);
break;
case ExpressionType.Equal:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.NotEqual:
filter = TranslateComparison((BinaryExpression)node);
break;
case ExpressionType.MemberAccess:
filter = TranslateBoolean(node);
break;
case ExpressionType.Not:
filter = TranslateNot((UnaryExpression)node);
break;
case ExpressionType.Or:
filter = TranslateOr((BinaryExpression)node);
break;
case ExpressionType.OrElse:
filter = TranslateOrElse((BinaryExpression)node);
break;
case ExpressionType.TypeIs:
filter = TranslateTypeIsQuery((TypeBinaryExpression)node);
break;
case ExpressionType.Extension:
var mongoExpression = node as ExtensionExpression;
if (mongoExpression != null)
{
switch (mongoExpression.ExtensionType)
{
case ExtensionExpressionType.FieldAsDocument:
case ExtensionExpressionType.Field:
if (mongoExpression.Type == typeof(bool))
{
filter = TranslateBoolean(mongoExpression);
}
break;
case ExtensionExpressionType.InjectedFilter:
return TranslateInjectedFilter((InjectedFilterExpression)node);
case ExtensionExpressionType.Pipeline:
filter = TranslatePipeline((PipelineExpression)node);
break;
}
}
break;
}
if (filter == null)
{
var message = string.Format("Unsupported filter: {0}.", node);
throw new ArgumentException(message);
}
return filter;
}
// private methods
private FilterDefinition<BsonDocument> TranslateAndAlso(BinaryExpression node)
{
return __builder.And(Translate(node.Left), Translate(node.Right));
}
private FilterDefinition<BsonDocument> TranslateAnd(BinaryExpression node)
{
if (node.Left.Type == typeof(bool) && node.Right.Type == typeof(bool))
{
return TranslateAndAlso(node);
}
return null;
}
private bool CanAnyBeRenderedWithoutElemMatch(Expression node)
{
switch (node.NodeType)
{
// this doesn't cover all cases, but absolutely covers
// the most common ones. This is opt-in behavior, so
// when someone else discovers an Any query that shouldn't
// be rendered with $elemMatch, we'll have to add it in.
case ExpressionType.Equal:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.NotEqual:
return true;
case ExpressionType.Call:
var callNode = (MethodCallExpression)node;
switch (callNode.Method.Name)
{
case "Contains":
case "StartsWith":
case "EndsWith":
return true;
default:
return false;
}
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.Not:
var unaryExpression = (UnaryExpression)node;
return CanAnyBeRenderedWithoutElemMatch(unaryExpression.Operand);
case ExpressionType.Extension:
var pipelineExpression = node as PipelineExpression;
if (pipelineExpression != null)
{
var source = pipelineExpression.Source as ISerializationExpression;
return source == null;
}
return false;
default:
return false;
}
}
private FilterDefinition<BsonDocument> TranslateArrayLength(Expression variableNode, ExpressionType operatorType, ConstantExpression constantNode)
{
var allowedOperators = new[]
{
ExpressionType.Equal,
ExpressionType.NotEqual,
ExpressionType.GreaterThan,
ExpressionType.GreaterThanOrEqual,
ExpressionType.LessThan,
ExpressionType.LessThanOrEqual
};
if (!allowedOperators.Contains(operatorType))
{
return null;
}
if (constantNode.Type != typeof(int))
{
return null;
}
var value = ToInt32(constantNode);
IFieldExpression fieldExpression = null;
var unaryExpression = variableNode as UnaryExpression;
if (unaryExpression != null && unaryExpression.NodeType == ExpressionType.ArrayLength)
{
TryGetFieldExpression(unaryExpression.Operand, out fieldExpression);
}
var memberExpression = variableNode as MemberExpression;
if (memberExpression != null && memberExpression.Member.Name == "Count")
{
TryGetFieldExpression(memberExpression.Expression, out fieldExpression);
}
var pipelineExpression = variableNode as PipelineExpression;
if (pipelineExpression != null && pipelineExpression.ResultOperator != null && pipelineExpression.ResultOperator is CountResultOperator)
{
TryGetFieldExpression(pipelineExpression.Source, out fieldExpression);
}
if (fieldExpression != null)
{
switch (operatorType)
{
case ExpressionType.Equal:
return __builder.Size(fieldExpression.FieldName, value);
case ExpressionType.NotEqual:
return __builder.Not(__builder.Size(fieldExpression.FieldName, value));
case ExpressionType.GreaterThan:
return __builder.SizeGt(fieldExpression.FieldName, value);
case ExpressionType.GreaterThanOrEqual:
return __builder.SizeGte(fieldExpression.FieldName, value);
case ExpressionType.LessThan:
return __builder.SizeLt(fieldExpression.FieldName, value);
case ExpressionType.LessThanOrEqual:
return __builder.SizeLte(fieldExpression.FieldName, value);
}
}
return null;
}
private FilterDefinition<BsonDocument> TranslateBitwiseComparison(Expression variableExpression, ExpressionType operatorType, ConstantExpression constantExpression)
{
var binaryExpression = variableExpression as BinaryExpression;
if (binaryExpression == null ||
binaryExpression.NodeType != ExpressionType.And ||
binaryExpression.Right.NodeType != ExpressionType.Constant ||
(operatorType != ExpressionType.Equal && operatorType != ExpressionType.NotEqual))
{
return null;
}
var field = GetFieldExpression(binaryExpression.Left);
var maskExpression = (ConstantExpression)binaryExpression.Right;
var value = field.SerializeValue(maskExpression.Type, maskExpression.Value).ToInt64();
var comparison = Convert.ToInt64(constantExpression.Value);
if (value == comparison)
{
if (operatorType == ExpressionType.Equal)
{
return __builder.BitsAllSet(field.FieldName, value);
}
else
{
return __builder.BitsAnyClear(field.FieldName, value);
}
}
else if (comparison == 0)
{
if (operatorType == ExpressionType.Equal)
{
return __builder.BitsAllClear(field.FieldName, value);
}
else
{
return __builder.BitsAnySet(field.FieldName, value);
}
}
return null;
}
private FilterDefinition<BsonDocument> TranslateBoolean(bool value)
{
if (value)
{
return new BsonDocument(); // empty query matches all documents
}
else
{
return __builder.Type("_id", (BsonType)(-1)); // matches no documents (and uses _id index when used at top level)
}
}
private FilterDefinition<BsonDocument> TranslateBoolean(Expression expression)
{
if (expression.Type == typeof(bool))
{
var constantExpression = expression as ConstantExpression;
if (constantExpression != null)
{
return TranslateBoolean((bool)constantExpression.Value);
}
var fieldExpression = GetFieldExpression(expression);
return new BsonDocument(fieldExpression.FieldName, true);
}
return null;
}
private FilterDefinition<BsonDocument> TranslateComparison(BinaryExpression binaryExpression)
{
// the constant could be on either side
var variableExpression = binaryExpression.Left;
var constantExpression = binaryExpression.Right as ConstantExpression;
var operatorType = binaryExpression.NodeType;
if (constantExpression == null)
{
return null;
}
var query = TranslateArrayLength(variableExpression, operatorType, constantExpression);
if (query != null)
{
return query;
}
query = TranslateMod(variableExpression, operatorType, constantExpression);
if (query != null)
{
return query;
}
query = TranslateCompareTo(variableExpression, operatorType, constantExpression);
if (query != null)
{
return query;
}
query = TranslateStringIndexOfQuery(variableExpression, operatorType, constantExpression);
if (query != null)
{
return query;
}
query = TranslateStringIndexQuery(variableExpression, operatorType, constantExpression);
if (query != null)
{
return query;
}
query = TranslateStringLengthQuery(variableExpression, operatorType, constantExpression);
if (query != null)
{
return query;
}
query = TranslateStringCaseInsensitiveComparisonQuery(variableExpression, operatorType, constantExpression);
if (query != null)
{
return query;
}
query = TranslateTypeComparisonQuery(variableExpression, operatorType, constantExpression);
if (query != null)
{
return query;
}
query = TranslateBitwiseComparison(variableExpression, operatorType, constantExpression);
if (query != null)
{
return query;
}
return TranslateComparison(variableExpression, operatorType, constantExpression);
}
private FilterDefinition<BsonDocument> TranslateCompareTo(Expression variableExpression, ExpressionType operatorType, ConstantExpression constantExpression)
{
if (constantExpression.Type != typeof(int) || ((int)constantExpression.Value) != 0)
{
return null;
}
var call = variableExpression as MethodCallExpression;
if (call == null || call.Object == null || call.Method.Name != "CompareTo" || call.Arguments.Count != 1)
{
return null;
}
constantExpression = call.Arguments[0] as ConstantExpression;
if (constantExpression == null)
{
return null;
}
return TranslateComparison(call.Object, operatorType, constantExpression);
}
private FilterDefinition<BsonDocument> TranslateComparison(Expression variableExpression, ExpressionType operatorType, ConstantExpression constantExpression)
{
var value = constantExpression.Value;
var methodCallExpression = variableExpression as MethodCallExpression;
if (methodCallExpression != null && value is bool)
{
var boolValue = (bool)value;
var query = this.TranslateMethodCall(methodCallExpression);
var isTrueComparison = (boolValue && operatorType == ExpressionType.Equal)
|| (!boolValue && operatorType == ExpressionType.NotEqual);
return isTrueComparison ? query : __builder.Not(query);
}
var fieldExpression = GetFieldExpression(variableExpression);
var valueSerializer = FieldValueSerializerHelper.GetSerializerForValueType(fieldExpression.Serializer, _serializerRegistry, constantExpression.Type, value);
var serializedValue = valueSerializer.ToBsonValue(value);
switch (operatorType)
{
case ExpressionType.Equal: return __builder.Eq(fieldExpression.FieldName, serializedValue);
case ExpressionType.GreaterThan: return __builder.Gt(fieldExpression.FieldName, serializedValue);
case ExpressionType.GreaterThanOrEqual: return __builder.Gte(fieldExpression.FieldName, serializedValue);
case ExpressionType.LessThan: return __builder.Lt(fieldExpression.FieldName, serializedValue);
case ExpressionType.LessThanOrEqual: return __builder.Lte(fieldExpression.FieldName, serializedValue);
case ExpressionType.NotEqual: return __builder.Ne(fieldExpression.FieldName, serializedValue);
}
return null;
}
private FilterDefinition<BsonDocument> TranslateConstant(ConstantExpression constantExpression)
{
var value = constantExpression.Value;
if (value != null && value.GetType() == typeof(bool))
{
return TranslateBoolean((bool)value);
}
return null;
}
private FilterDefinition<BsonDocument> TranslateContainsKey(MethodCallExpression methodCallExpression)
{
var dictionaryType = methodCallExpression.Object.Type;
var implementedInterfaces = new List<Type>(dictionaryType.GetTypeInfo().GetInterfaces());
if (dictionaryType.GetTypeInfo().IsInterface)
{
implementedInterfaces.Add(dictionaryType);
}
Type dictionaryGenericInterface = null;
Type dictionaryInterface = null;
foreach (var implementedInterface in implementedInterfaces)
{
if (implementedInterface.GetTypeInfo().IsGenericType)
{
if (implementedInterface.GetGenericTypeDefinition() == typeof(IDictionary<,>))
{
dictionaryGenericInterface = implementedInterface;
}
}
else if (implementedInterface == typeof(IDictionary))
{
dictionaryInterface = implementedInterface;
}
}
if (dictionaryGenericInterface == null && dictionaryInterface == null)
{
return null;
}
var arguments = methodCallExpression.Arguments.ToArray();
if (arguments.Length != 1)
{
return null;
}
var constantExpression = arguments[0] as ConstantExpression;
if (constantExpression == null)
{
return null;
}
var key = constantExpression.Value;
var fieldExpression = GetFieldExpression(methodCallExpression.Object);
var serializer = fieldExpression.Serializer;
var dictionarySerializer = serializer as IBsonDictionarySerializer;
if (dictionarySerializer == null)
{
var message = string.Format(
"{0} in a LINQ query is only supported for members that are serialized using a serializer that implements IBsonDictionarySerializer.",
methodCallExpression.Method.Name); // could be Contains (for IDictionary) or ContainsKey (for IDictionary<TKey, TValue>)
throw new NotSupportedException(message);
}
var keySerializer = dictionarySerializer.KeySerializer;
var keySerializationInfo = new BsonSerializationInfo(
null, // elementName
keySerializer,
keySerializer.ValueType);
var serializedKey = keySerializationInfo.SerializeValue(key);
var dictionaryRepresentation = dictionarySerializer.DictionaryRepresentation;
switch (dictionaryRepresentation)
{
case DictionaryRepresentation.ArrayOfDocuments:
return __builder.Eq(fieldExpression.FieldName + ".k", serializedKey);
case DictionaryRepresentation.Document:
return __builder.Exists(fieldExpression.FieldName + "." + serializedKey.AsString);
default:
var message = string.Format(
"{0} in a LINQ query is only supported for DictionaryRepresentation ArrayOfDocuments or Document, not {1}.",
methodCallExpression.Method.Name, // could be Contains (for IDictionary) or ContainsKey (for IDictionary<TKey, TValue>)
dictionaryRepresentation);
throw new NotSupportedException(message);
}
}
private FilterDefinition<BsonDocument> TranslateContains(MethodCallExpression methodCallExpression)
{
// handle IDictionary Contains the same way as IDictionary<TKey, TValue> ContainsKey
if (methodCallExpression.Object != null && typeof(IDictionary).GetTypeInfo().IsAssignableFrom(methodCallExpression.Object.Type))
{
return TranslateContainsKey(methodCallExpression);
}
if (methodCallExpression.Method.DeclaringType == typeof(string))
{
return TranslateStringQuery(methodCallExpression);
}
return null;
}
private FilterDefinition<BsonDocument> TranslateEquals(MethodCallExpression methodCallExpression)
{
var arguments = methodCallExpression.Arguments.ToArray();
// assume that static and instance Equals mean the same thing for all classes (i.e. an equality test)
Expression firstExpression = null;
Expression secondExpression = null;
if (methodCallExpression.Object == null)
{
// static Equals method
if (arguments.Length == 2)
{
firstExpression = arguments[0];
secondExpression = arguments[1];
}
}
else
{
// instance Equals method
if (arguments.Length == 1)
{
firstExpression = methodCallExpression.Object;
secondExpression = arguments[0];
}
}
if (firstExpression != null && secondExpression != null)
{
// the constant could be either expression
var variableExpression = firstExpression;
var constantExpression = secondExpression as ConstantExpression;
if (constantExpression == null)
{
constantExpression = firstExpression as ConstantExpression;
variableExpression = secondExpression;
}
if (constantExpression == null)
{
return null;
}
if (variableExpression.Type == typeof(Type) && constantExpression.Type == typeof(Type))
{
return TranslateTypeComparisonQuery(variableExpression, ExpressionType.Equal, constantExpression);
}
return TranslateComparison(variableExpression, ExpressionType.Equal, constantExpression);
}
return null;
}
private FilterDefinition<BsonDocument> TranslateHasFlag(MethodCallExpression methodCallExpression)
{
if (methodCallExpression.Object == null)
{
return null;
}
var field = GetFieldExpression(methodCallExpression.Object);
var flagExpression = (ConstantExpression)methodCallExpression.Arguments[0];
var value = field.SerializeValue(flagExpression.Type, flagExpression.Value).ToInt64();
return __builder.BitsAllSet(field.FieldName, value);
}
private FilterDefinition<BsonDocument> TranslateIn(MethodCallExpression methodCallExpression)
{
var methodDeclaringType = methodCallExpression.Method.DeclaringType;
var methodDeclaringTypeInfo = methodDeclaringType.GetTypeInfo();
var arguments = methodCallExpression.Arguments.ToArray();
IFieldExpression fieldExpression = null;
ConstantExpression valuesExpression = null;
if (methodDeclaringType == typeof(Enumerable) || methodDeclaringType == typeof(Queryable))
{
if (arguments.Length == 2)
{
fieldExpression = GetFieldExpression(arguments[1]);
valuesExpression = arguments[0] as ConstantExpression;
}
}
else
{
if (methodDeclaringTypeInfo.IsGenericType)
{
methodDeclaringType = methodDeclaringType.GetGenericTypeDefinition();
methodDeclaringTypeInfo = methodDeclaringType.GetTypeInfo();
}
bool contains = methodDeclaringType == typeof(ICollection<>) || methodDeclaringTypeInfo.GetInterface("ICollection`1") != null;
if (contains && arguments.Length == 1)
{
fieldExpression = GetFieldExpression(arguments[0]);
valuesExpression = methodCallExpression.Object as ConstantExpression;
}
}
if (fieldExpression != null && valuesExpression != null)
{
var ienumerableInterfaceType = valuesExpression.Type.FindIEnumerable();
var itemType = ienumerableInterfaceType.GetTypeInfo().GetGenericArguments()[0];
var serializedValues = fieldExpression.SerializeValues(itemType, (IEnumerable)valuesExpression.Value);
return __builder.In(fieldExpression.FieldName, serializedValues);
}
return null;
}
private FilterDefinition<BsonDocument> TranslateInjectedFilter(InjectedFilterExpression node)
{
return new BsonDocumentFilterDefinition<BsonDocument>(node.Filter);
}
private FilterDefinition<BsonDocument> TranslateIsMatch(MethodCallExpression methodCallExpression)
{
if (methodCallExpression.Method.DeclaringType == typeof(Regex))
{
var arguments = methodCallExpression.Arguments.ToArray();
var obj = methodCallExpression.Object;
if (obj == null)
{
if (arguments.Length == 2 || arguments.Length == 3)
{
var fieldExpression = GetFieldExpression(arguments[0]);
var patternExpression = arguments[1] as ConstantExpression;
if (patternExpression != null)
{
var pattern = patternExpression.Value as string;
if (pattern != null)
{
var options = RegexOptions.None;
if (arguments.Length == 3)
{
var optionsExpression = arguments[2] as ConstantExpression;
if (optionsExpression == null || optionsExpression.Type != typeof(RegexOptions))
{
return null;
}
options = (RegexOptions)optionsExpression.Value;
}
var regex = new Regex(pattern, options);
return __builder.Regex(fieldExpression.FieldName, regex);
}
}
}
}
else
{
var regexExpression = obj as ConstantExpression;
if (regexExpression != null && arguments.Length == 1)
{
var serializationInfo = GetFieldExpression(arguments[0]);
var regex = regexExpression.Value as Regex;
if (regex != null)
{
return __builder.Regex(serializationInfo.FieldName, regex);
}
}
}
}
return null;
}
private FilterDefinition<BsonDocument> TranslateIsNullOrEmpty(MethodCallExpression methodCallExpression)
{
if (methodCallExpression.Method.DeclaringType == typeof(string) && methodCallExpression.Object == null)
{
var arguments = methodCallExpression.Arguments.ToArray();
var fieldExpression = GetFieldExpression(arguments[0]);
return __builder.In<string>(fieldExpression.FieldName, new string[] { null, "" });
}
return null;
}
private FilterDefinition<BsonDocument> TranslateMethodCall(MethodCallExpression methodCallExpression)
{
switch (methodCallExpression.Method.Name)
{
case "Contains": return TranslateContains(methodCallExpression);
case "ContainsKey": return TranslateContainsKey(methodCallExpression);
case "EndsWith": return TranslateStringQuery(methodCallExpression);
case "Equals": return TranslateEquals(methodCallExpression);
case "HasFlag": return TranslateHasFlag(methodCallExpression);
case "In": return TranslateIn(methodCallExpression);
case "IsMatch": return TranslateIsMatch(methodCallExpression);
case "IsNullOrEmpty": return TranslateIsNullOrEmpty(methodCallExpression);
case "StartsWith": return TranslateStringQuery(methodCallExpression);
}
return null;
}
private FilterDefinition<BsonDocument> TranslateMod(Expression variableExpression, ExpressionType operatorType, ConstantExpression constantExpression)
{
if (operatorType != ExpressionType.Equal && operatorType != ExpressionType.NotEqual)
{
return null;
}
if (constantExpression.Type != typeof(int) && constantExpression.Type != typeof(long))
{
return null;
}
var value = ToInt64(constantExpression);
var modBinaryExpression = variableExpression as BinaryExpression;
if (modBinaryExpression != null && modBinaryExpression.NodeType == ExpressionType.Modulo)
{
var fieldExpression = GetFieldExpression(modBinaryExpression.Left);
var modulusExpression = modBinaryExpression.Right as ConstantExpression;
if (modulusExpression != null)
{
var modulus = ToInt64(modulusExpression);
if (operatorType == ExpressionType.Equal)
{
return __builder.Mod(fieldExpression.FieldName, modulus, value);
}
else
{
return __builder.Not(__builder.Mod(fieldExpression.FieldName, modulus, value));
}
}
}
return null;
}
private FilterDefinition<BsonDocument> TranslateNot(UnaryExpression unaryExpression)
{
var filter = Translate(unaryExpression.Operand);
return __builder.Not(filter);
}
private FilterDefinition<BsonDocument> TranslateOrElse(BinaryExpression binaryExpression)
{
return __builder.Or(Translate(binaryExpression.Left), Translate(binaryExpression.Right));
}
private FilterDefinition<BsonDocument> TranslateOr(BinaryExpression binaryExpression)
{
if (binaryExpression.Left.Type == typeof(bool) && binaryExpression.Right.Type == typeof(bool))
{
return TranslateOrElse(binaryExpression);
}
return null;
}
private FilterDefinition<BsonDocument> TranslatePipeline(PipelineExpression node)
{
if (node.ResultOperator is AllResultOperator)
{
return TranslatePipelineAll(node);
}
if (node.ResultOperator is AnyResultOperator)
{
return TranslatePipelineAny(node);
}
if (node.ResultOperator is ContainsResultOperator)
{
return TranslatePipelineContains(node);
}
return null;
}
private FilterDefinition<BsonDocument> TranslatePipelineAll(PipelineExpression node)
{
var whereExpression = node.Source as WhereExpression;
if (whereExpression == null)
{
return null;
}
var constant = whereExpression.Source as ConstantExpression;
if (constant == null)
{
return null;
}
var embeddedPipeline = whereExpression.Predicate as PipelineExpression;
if (!(embeddedPipeline?.ResultOperator is ContainsResultOperator))
{
return null;
}
var fieldExpression = embeddedPipeline.Source as IFieldExpression;
if (fieldExpression == null)
{
return null;
}
var arraySerializer = fieldExpression.Serializer as IBsonArraySerializer;
if (arraySerializer == null)
{
return null;
}
BsonSerializationInfo itemSerializationInfo;
if (!arraySerializer.TryGetItemSerializationInfo(out itemSerializationInfo))
{
return null;
}
var serializedValues = itemSerializationInfo.SerializeValues((IEnumerable)constant.Value);
return __builder.All(fieldExpression.FieldName, serializedValues);
}
private FilterDefinition<BsonDocument> TranslatePipelineAny(PipelineExpression node)
{
var fieldExpression = node.Source as IFieldExpression;
if (fieldExpression != null)
{
return __builder.And(
__builder.Ne(fieldExpression.FieldName, BsonNull.Value),
__builder.Not(__builder.Size(fieldExpression.FieldName, 0)));
}
var whereExpression = node.Source as WhereExpression;
if (whereExpression == null)
{
return null;
}
fieldExpression = whereExpression.Source as IFieldExpression;
if (fieldExpression == null)
{
if (whereExpression.Source is ConstantExpression)
{
return TranslatePipelineAnyScalar(node);
}
return null;
}
FilterDefinition<BsonDocument> filter;
var renderWithoutElemMatch = CanAnyBeRenderedWithoutElemMatch(whereExpression.Predicate);
if (renderWithoutElemMatch)
{
var predicate = FieldNamePrefixer.Prefix(whereExpression.Predicate, fieldExpression.FieldName);
filter = Translate(predicate);
}
else
{
var predicate = DocumentToFieldConverter.Convert(whereExpression.Predicate);
filter = __builder.ElemMatch(fieldExpression.FieldName, Translate(predicate));
if (!(fieldExpression.Serializer is IBsonDocumentSerializer))
{
filter = new ScalarElementMatchFilterDefinition<BsonDocument>(filter);
}
}
return filter;
}
private FilterDefinition<BsonDocument> TranslatePipelineAnyScalar(PipelineExpression node)
{
var whereExpression = node.Source as WhereExpression;
if (whereExpression == null)
{
return null;
}
var constant = whereExpression.Source as ConstantExpression;
if (constant == null)
{
return null;
}
var embeddedPipeline = whereExpression.Predicate as PipelineExpression;
if (!(embeddedPipeline?.ResultOperator is ContainsResultOperator))
{
return null;
}
var fieldExpression = embeddedPipeline.Source as IFieldExpression;
if (fieldExpression == null)
{
return null;
}
var arraySerializer = fieldExpression.Serializer as IBsonArraySerializer;
if (arraySerializer == null)
{
return null;
}
BsonSerializationInfo itemSerializationInfo;
if (!arraySerializer.TryGetItemSerializationInfo(out itemSerializationInfo))
{
return null;
}
var serializedValues = itemSerializationInfo.SerializeValues((IEnumerable)constant.Value);
return __builder.In(fieldExpression.FieldName, serializedValues);
}
private FilterDefinition<BsonDocument> TranslatePipelineContains(PipelineExpression node)
{
var value = ((ContainsResultOperator)node.ResultOperator).Value;
var constantExpression = node.Source as ConstantExpression;
IFieldExpression field;
if (constantExpression != null)
{
field = value as IFieldExpression;
if (field != null)
{
var ienumerableInterfaceType = constantExpression.Type.FindIEnumerable();
var itemType = ienumerableInterfaceType.GetTypeInfo().GetGenericArguments()[0];
var serializedValues = field.SerializeValues(itemType, (IEnumerable)constantExpression.Value);
return __builder.In(field.FieldName, serializedValues);
}
}
else
{
constantExpression = value as ConstantExpression;
field = node.Source as IFieldExpression;
if (constantExpression != null && field != null)
{
var arraySerializer = field.Serializer as IBsonArraySerializer;