/
RavenQueryProviderProcessor.cs
3945 lines (3365 loc) · 160 KB
/
RavenQueryProviderProcessor.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 file="RavenQueryProviderProcessor.cs" company="Hibernating Rhinos LTD">
// Copyright (c) Hibernating Rhinos LTD. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using Lambda2Js;
using Raven.Client.Documents.Conventions;
using Raven.Client.Documents.Indexes;
using Raven.Client.Documents.Queries;
using Raven.Client.Documents.Queries.Facets;
using Raven.Client.Documents.Queries.Highlighting;
using Raven.Client.Documents.Queries.MoreLikeThis;
using Raven.Client.Documents.Queries.Spatial;
using Raven.Client.Documents.Queries.Suggestions;
using Raven.Client.Documents.Queries.TimeSeries;
using Raven.Client.Documents.Session;
using Raven.Client.Documents.Session.Loaders;
using Raven.Client.Documents.Session.Tokens;
using Raven.Client.Exceptions;
using Raven.Client.Extensions;
using Raven.Client.Util;
using MethodCallExpression = System.Linq.Expressions.MethodCallExpression;
namespace Raven.Client.Documents.Linq
{
/// <summary>
/// Process a Linq expression to a Lucene query
/// </summary>
internal class RavenQueryProviderProcessor<T>
{
private readonly Action<IDocumentQueryCustomization> _customizeQuery;
/// <summary>
/// The query generator
/// </summary>
protected readonly IDocumentQueryGenerator QueryGenerator;
internal const string WholeDocumentComparisonExceptionMessage =
"You cannot compare the whole document in Where closure. Please write a conditional statement using fields from the document. A query such as session.Query<User>().Where(u => u == null) is not meaningful, you are asserting that the document itself is not null, which it can never be. Did you intend to assert that a property isn't set to null?";
internal IAbstractDocumentQuery<T> DocumentQuery;
internal string FromAlias;
internal readonly LinqPathProvider LinqPathProvider;
private readonly Action<QueryResult> _afterQueryExecuted;
private readonly LinqQueryHighlightings _highlightings;
private bool _chainedWhere;
private int _insideWhere;
private int _insideFilter;
private bool _insideNegate;
private bool _insideExact;
private SpecialQueryType _queryType = SpecialQueryType.None;
private Type _newExpressionType;
private string _currentPath = string.Empty;
private int _subClauseDepth;
private Expression _groupByElementSelector;
private string _jsSelectBody;
private List<string> _jsProjectionNames;
private StringBuilder _declareBuilder;
private List<DeclareToken> _declareTokens;
private List<LoadToken> _loadTokens;
private HashSet<string> _loadAliases;
private readonly HashSet<string> _loadAliasesMovedToOutputFunction;
private int _insideLet = 0;
private string _loadAlias;
private bool _selectLoad;
private const string DefaultLoadAlias = "__load";
private const string DefaultAliasPrefix = "__alias";
private bool _addedDefaultAlias;
private Type _ofType;
private bool _isSelectArg;
private (bool IsSet, string Name) _manualLet;
private JavascriptConversionExtensions.TypedParameterSupport _typedParameterSupport;
private readonly HashSet<string> _aliasKeywords = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"AS",
"SELECT",
"WHERE",
"GROUP",
"ORDER",
"INCLUDE",
"UPDATE",
"LIMIT",
"OFFSET"
};
private List<string> _projectionParameters;
private int _aliasesCount;
/// <summary>
/// The index name
/// </summary>
protected readonly string IndexName;
private readonly string _collectionName;
/// <summary>
/// Gets the current path in the case of expressions within collections
/// </summary>
public string CurrentPath => _currentPath;
/// <summary>
/// Initializes a new instance of the <see cref="RavenQueryProviderProcessor{T}"/> class.
/// </summary>
/// <param name="queryGenerator">The document query generator.</param>
/// <param name="customizeQuery">The customize query.</param>
/// <param name="afterQueryExecuted">Executed after the query run, allow access to the query results</param>
/// <param name="indexName">The name of the index the query is executed against.</param>
/// <param name="collectionName">The name of the collection the query is executed against.</param>
/// <param name="fieldsToFetch">The fields to fetch in this query</param>
/// <param name="isMapReduce"></param>
/// /// <param name ="originalType" >the original type of the query if TransformWith is called otherwise null</param>
public RavenQueryProviderProcessor(
IDocumentQueryGenerator queryGenerator,
Action<IDocumentQueryCustomization> customizeQuery,
Action<QueryResult> afterQueryExecuted,
LinqQueryHighlightings highlightings,
string indexName,
string collectionName,
HashSet<FieldToFetch> fieldsToFetch,
bool isMapReduce,
Type originalType,
DocumentConventions conventions,
bool isProjectInto)
{
FieldsToFetch = fieldsToFetch;
_newExpressionType = typeof(T);
QueryGenerator = queryGenerator;
IndexName = indexName;
_collectionName = collectionName;
_isMapReduce = isMapReduce;
_afterQueryExecuted = afterQueryExecuted;
_highlightings = highlightings;
_customizeQuery = customizeQuery;
_originalQueryType = originalType ?? throw new ArgumentNullException(nameof(originalType));
_conventions = conventions;
_isProjectInto = isProjectInto;
LinqPathProvider = new LinqPathProvider(queryGenerator.Conventions);
_jsProjectionNames = new List<string>();
_loadAliasesMovedToOutputFunction = new HashSet<string>();
}
/// <summary>
/// Gets or sets the fields to fetch.
/// </summary>
/// <value>The fields to fetch.</value>
public HashSet<FieldToFetch> FieldsToFetch { get; set; }
/// <summary>
/// Visits the expression and generate the lucene query
/// </summary>
/// <param name="expression">The expression.</param>
protected void VisitExpression(Expression expression)
{
if (expression is BinaryExpression)
{
VisitBinaryExpression((BinaryExpression)expression);
}
else
{
switch (expression.NodeType)
{
case ExpressionType.MemberAccess:
VisitMemberAccess((MemberExpression)expression, true);
break;
case ExpressionType.Not:
var unaryExpressionOp = ((UnaryExpression)expression).Operand;
switch (unaryExpressionOp.NodeType)
{
case ExpressionType.MemberAccess:
VisitMemberAccess((MemberExpression)unaryExpressionOp, false);
break;
case ExpressionType.Call:
// probably a call to !In() or !string.IsNullOrEmpty()
DocumentQuery.OpenSubclause();
DocumentQuery.WhereTrue();
DocumentQuery.AndAlso();
DocumentQuery.NegateNext();
VisitMethodCall((MethodCallExpression)unaryExpressionOp);
DocumentQuery.CloseSubclause();
break;
default:
//probably the case of !(complex condition)
DocumentQuery.OpenSubclause();
DocumentQuery.WhereTrue();
DocumentQuery.AndAlso();
DocumentQuery.NegateNext();
_insideNegate = true;
VisitExpression(unaryExpressionOp);
_insideNegate = false;
DocumentQuery.CloseSubclause();
break;
}
break;
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
VisitExpression(((UnaryExpression)expression).Operand);
break;
default:
if (expression is MethodCallExpression)
{
VisitMethodCall((MethodCallExpression)expression);
}
else if (expression is LambdaExpression lambdaExpression)
{
var body = lambdaExpression.Body;
if (body.NodeType == ExpressionType.Constant && ((ConstantExpression)body).Value is bool)
{
throw new ArgumentException("Constants expressions such as Where(x => true) are not allowed in the RavenDB queries");
}
if (body.NodeType == ExpressionType.Invoke && body.Type == typeof(bool))
{
throw new NotSupportedException("Invocation expressions such as Where(x => SomeFunction(x)) are not supported in RavenDB queries");
}
VisitExpression(body);
}
break;
}
}
}
private void VisitBinaryExpression(BinaryExpression expression)
{
if (_insideWhere > 0)
{
VerifyLegalBinaryExpression(expression);
}
var subclause = false;
if (_insideNegate)
{
_insideNegate = false;
subclause = true;
DocumentQuery.OpenSubclause();
}
switch (expression.NodeType)
{
case ExpressionType.OrElse:
VisitOrElse(expression);
break;
case ExpressionType.AndAlso:
VisitAndAlso(expression);
break;
case ExpressionType.NotEqual:
VisitNotEquals(expression);
break;
case ExpressionType.Equal:
VisitEquals(expression);
break;
case ExpressionType.GreaterThan:
VisitGreaterThan(expression);
break;
case ExpressionType.GreaterThanOrEqual:
VisitGreaterThanOrEqual(expression);
break;
case ExpressionType.LessThan:
VisitLessThan(expression);
break;
case ExpressionType.LessThanOrEqual:
VisitLessThanOrEqual(expression);
break;
}
if (subclause)
DocumentQuery.CloseSubclause();
}
private void VerifyLegalBinaryExpression(BinaryExpression expression)
{
if (expression.Left is BinaryExpression left)
{
VerifyLegalBinaryExpression(left);
}
if (expression.Right is BinaryExpression right)
{
VerifyLegalBinaryExpression(right);
}
switch (expression.NodeType)
{
case ExpressionType.OrElse:
case ExpressionType.AndAlso:
return;
}
if (IsMemberAccessForQuerySource(expression.Left) &&
IsMemberAccessForQuerySource(expression.Right))
{
// x.Foo < x.Bar
throw new NotSupportedException("Where clauses containing a Binary Expression between two fields are not supported. " +
"All Binary Expressions inside a Where clause should be between a field and a constant value. " +
$"`{expression.Left}` and `{expression.Right}` are both fields, so cannot convert {expression} to a proper query.");
}
}
private void VisitAndAlso(BinaryExpression andAlso)
{
if (TryHandleBetween(andAlso))
return;
if (_subClauseDepth > 0)
DocumentQuery.OpenSubclause();
_subClauseDepth++;
// negate optimization : (RavenDB-3973). in order to disable you may just set isNotEqualCheckBoundsToAndAlsoLeft & Right to "false"
bool isNotEqualCheckBoundsToAndAlsoLeft = (andAlso.Left.NodeType == ExpressionType.NotEqual);
bool isNotEqualCheckBoundsToAndAlsoRight = (andAlso.Right.NodeType == ExpressionType.NotEqual);
if (isNotEqualCheckBoundsToAndAlsoRight && isNotEqualCheckBoundsToAndAlsoLeft)
// avoid empty group (i.e. : "a != 1 && a != 2" should generate "((-a:1 AND a:*) AND -a:2)"
isNotEqualCheckBoundsToAndAlsoLeft = false;
if (isNotEqualCheckBoundsToAndAlsoLeft || isNotEqualCheckBoundsToAndAlsoRight)
{
_subClauseDepth++;
DocumentQuery.OpenSubclause();
}
VisitExpression(andAlso.Left);
DocumentQuery.AndAlso();
VisitExpression(andAlso.Right);
if (isNotEqualCheckBoundsToAndAlsoLeft || isNotEqualCheckBoundsToAndAlsoRight)
{
_subClauseDepth--;
DocumentQuery.CloseSubclause();
}
_subClauseDepth--;
if (_subClauseDepth > 0)
DocumentQuery.CloseSubclause();
}
private bool TryHandleBetween(BinaryExpression andAlso)
{
// x.Foo > 100 && x.Foo < 200
// x.Foo < 200 && x.Foo > 100
// 100 < x.Foo && 200 > x.Foo
// 200 > x.Foo && 100 < x.Foo
// x.Foo >= 100 && x.Foo <= 200
// x.Foo <= 200 && x.Foo >= 100
// 100 <= x.Foo && 200 >= x.Foo
// 200 >= x.Foo && 100 <= x.Foo
var isPossibleBetween =
(andAlso.Left.NodeType == ExpressionType.GreaterThan && andAlso.Right.NodeType == ExpressionType.LessThan) ||
(andAlso.Left.NodeType == ExpressionType.GreaterThanOrEqual && andAlso.Right.NodeType == ExpressionType.LessThanOrEqual) ||
(andAlso.Left.NodeType == ExpressionType.LessThan && andAlso.Right.NodeType == ExpressionType.GreaterThan) ||
(andAlso.Left.NodeType == ExpressionType.LessThanOrEqual && andAlso.Right.NodeType == ExpressionType.GreaterThanOrEqual);
if (isPossibleBetween == false || IsFilterModeActive())
return false;
var leftMember = GetMemberForBetween((BinaryExpression)andAlso.Left);
var rightMember = GetMemberForBetween((BinaryExpression)andAlso.Right);
if (leftMember == null || rightMember == null)
return false;
// both must be on the same property
if (leftMember.Item1.Path != rightMember.Item1.Path)
return false;
var min = (andAlso.Left.NodeType == ExpressionType.LessThan ||
andAlso.Left.NodeType == ExpressionType.LessThanOrEqual)
? rightMember.Item2
: leftMember.Item2;
var max = (andAlso.Left.NodeType == ExpressionType.LessThan ||
andAlso.Left.NodeType == ExpressionType.LessThanOrEqual)
? leftMember.Item2
: rightMember.Item2;
if (andAlso.Left.NodeType == ExpressionType.GreaterThanOrEqual || andAlso.Left.NodeType == ExpressionType.LessThanOrEqual)
DocumentQuery.WhereBetween(leftMember.Item1.Path, min, max, _insideExact);
else
{
DocumentQuery.WhereGreaterThan(leftMember.Item1.Path, min, _insideExact);
DocumentQuery.AndAlso();
DocumentQuery.WhereLessThan(leftMember.Item1.Path, max, _insideExact);
}
return true;
}
private Tuple<ExpressionInfo, object> GetMemberForBetween(BinaryExpression binaryExpression)
{
if (IsMemberAccessForQuerySource(binaryExpression.Left))
{
var expressionInfo = GetMember(binaryExpression.Left);
return Tuple.Create(expressionInfo, GetValueFromExpression(binaryExpression.Right, expressionInfo.Type));
}
if (IsMemberAccessForQuerySource(binaryExpression.Right))
{
var expressionInfo = GetMember(binaryExpression.Right);
return Tuple.Create(expressionInfo, GetValueFromExpression(binaryExpression.Left, expressionInfo.Type));
}
return null;
}
private object GetValueFromExpression(Expression expression, Type type)
{
return LinqPathProvider.GetValueFromExpression(expression, type);
}
private void VisitOrElse(BinaryExpression orElse)
{
if (_subClauseDepth > 0)
DocumentQuery.OpenSubclause();
_subClauseDepth++;
VisitExpression(orElse.Left);
DocumentQuery.OrElse();
VisitExpression(orElse.Right);
_subClauseDepth--;
if (_subClauseDepth > 0)
DocumentQuery.CloseSubclause();
}
private void VisitEquals(BinaryExpression expression)
{
var constantExpression = expression.Right as ConstantExpression;
if (constantExpression != null && true.Equals(constantExpression.Value))
{
VisitExpression(expression.Left);
return;
}
if (constantExpression != null && false.Equals(constantExpression.Value) &&
expression.Left.NodeType != ExpressionType.MemberAccess)
{
DocumentQuery.OpenSubclause();
DocumentQuery.WhereTrue();
DocumentQuery.AndAlso();
DocumentQuery.NegateNext();
_insideNegate = true;
VisitExpression(expression.Left);
_insideNegate = false;
DocumentQuery.CloseSubclause();
return;
}
var methodCallExpression = expression.Left as MethodCallExpression;
// checking for VB.NET string equality
if (methodCallExpression != null && methodCallExpression.Method.Name == "CompareString" &&
expression.Right.NodeType == ExpressionType.Constant &&
Equals(((ConstantExpression)expression.Right).Value, 0))
{
var expressionMemberInfo = GetMember(methodCallExpression.Arguments[0]);
DocumentQuery.WhereEquals(
new WhereParams
{
FieldName = expressionMemberInfo.Path,
Value = GetValueFromExpression(methodCallExpression.Arguments[1], GetMemberType(expressionMemberInfo)),
AllowWildcards = false,
Exact = _insideExact
});
return;
}
if (IsMemberAccessForQuerySource(expression.Left) == false && IsMemberAccessForQuerySource(expression.Right))
{
VisitEquals(Expression.Equal(expression.Right, expression.Left));
return;
}
var memberInfo = GetMember(expression.Left);
if (memberInfo.Path == string.Empty)
{
throw new InvalidQueryException(WholeDocumentComparisonExceptionMessage);
}
DocumentQuery.WhereEquals(new WhereParams
{
FieldName = memberInfo.Path,
Value = GetValueFromExpression(expression.Right, GetMemberType(memberInfo)),
AllowWildcards = false,
IsNestedPath = memberInfo.IsNestedPath,
Exact = _insideExact
});
}
private bool IsMemberAccessForQuerySource(Expression node)
{
while (node.NodeType == ExpressionType.Convert || node.NodeType == ExpressionType.ConvertChecked)
{
node = ((UnaryExpression)node).Operand;
}
if (node.NodeType == ExpressionType.Parameter)
return true;
if (node.NodeType == ExpressionType.Call && node is MethodCallExpression callExpressionNode && callExpressionNode.Method.Name == "get_Item" && callExpressionNode.Object?.NodeType == ExpressionType.Parameter)
return true;
if (node.NodeType != ExpressionType.MemberAccess)
return false;
var memberExpression = ((MemberExpression)node);
if (memberExpression.Expression == null) // static call
return false;
if (memberExpression.Expression.NodeType == ExpressionType.Constant)
return false;
return IsMemberAccessForQuerySource(memberExpression.Expression);
}
private void VisitNotEquals(BinaryExpression expression)
{
var methodCallExpression = expression.Left as MethodCallExpression;
// checking for VB.NET string equality
if (methodCallExpression != null && methodCallExpression.Method.Name == "CompareString" &&
expression.Right.NodeType == ExpressionType.Constant &&
Equals(((ConstantExpression)expression.Right).Value, 0))
{
var expressionMemberInfo = GetMember(methodCallExpression.Arguments[0]);
DocumentQuery.WhereNotEquals(new WhereParams
{
FieldName = expressionMemberInfo.Path,
Value = GetValueFromExpression(methodCallExpression.Arguments[0], GetMemberType(expressionMemberInfo)),
AllowWildcards = false,
Exact = _insideExact
});
return;
}
if (IsMemberAccessForQuerySource(expression.Left) == false && IsMemberAccessForQuerySource(expression.Right))
{
VisitNotEquals(Expression.NotEqual(expression.Right, expression.Left));
return;
}
var memberInfo = GetMember(expression.Left);
if (memberInfo.Path == string.Empty)
{
throw new InvalidQueryException(WholeDocumentComparisonExceptionMessage);
}
DocumentQuery.WhereNotEquals(new WhereParams
{
FieldName = memberInfo.Path,
Value = GetValueFromExpression(expression.Right, GetMemberType(memberInfo)),
AllowWildcards = false,
Exact = _insideExact
});
}
private static Type GetMemberType(ExpressionInfo info)
{
return info.Type;
}
private static readonly Regex CastingRemover = new Regex(@"(?<!\\)[\(\)]", RegexOptions.Compiled);
private static readonly Regex ConvertRemover = new Regex(@"^(Convert\((.+)\,.*\))", RegexOptions.Compiled);
/// <summary>
/// Gets member info for the specified expression and the path to that expression
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
protected virtual ExpressionInfo GetMember(Expression expression)
{
var parameterExpression = GetParameterExpressionIncludingConversions(expression);
if (parameterExpression != null)
{
if (_currentPath.EndsWith("[]."))
_currentPath = _currentPath.Substring(0, _currentPath.Length - 3);
return new ExpressionInfo(_currentPath, parameterExpression.Type, false);
}
return GetMemberDirect(expression);
}
private ExpressionInfo GetMemberDirect(Expression expression)
{
var result = LinqPathProvider.GetPath(expression, IsFilterModeActive());
//for standard queries, we take just the last part. But for dynamic queries, we take the whole part
var convertMatch = ConvertRemover.Match(result.Path);
if (convertMatch.Success)
result.Path = result.Path.Replace(convertMatch.Groups[1].Value, convertMatch.Groups[2].Value);
var propertyName = GetPropertyName(result.Path, expression.NodeType);
return new ExpressionInfo(propertyName, result.MemberType, result.IsNestedPath, result.Args)
{
MaybeProperty = result.MaybeProperty
};
}
private string GetPropertyName(string selectPath, ExpressionType type)
{
selectPath = LinqPathProvider.RemoveTransparentIdentifiersIfNeeded(selectPath);
var indexOf = selectPath.IndexOf('.');
string alias = null;
if (indexOf != -1)
{
alias = selectPath.Substring(0, indexOf);
selectPath = selectPath.Substring(indexOf + 1);
}
selectPath = CastingRemover.Replace(selectPath, string.Empty); // removing cast remains
if (type == ExpressionType.ArrayLength)
{
selectPath += ".Length";
}
string propertyName = null;
if (IndexName == null && _collectionName != null)
{
propertyName = QueryGenerator.Conventions.FindPropertyNameForDynamicIndex(typeof(T), IndexName, CurrentPath,
selectPath);
}
else
{
if (_insideSelect > 0 && QueryGenerator.Conventions.FindProjectedPropertyNameForIndex != null)
{
propertyName = QueryGenerator.Conventions.FindProjectedPropertyNameForIndex(typeof(T), IndexName, CurrentPath,
selectPath);
}
if (propertyName == null)
{
propertyName = QueryGenerator.Conventions.FindPropertyNameForIndex(typeof(T), IndexName, CurrentPath,
selectPath);
}
}
return AddAliasToPathIfNeeded(alias, propertyName);
}
private string AddAliasToPathIfNeeded(string alias, string prop)
{
if (alias != null &&
(alias == FromAlias ||
_loadAliases != null &&
_loadAliases.Contains(alias)))
return $"{alias}.{prop}";
return prop;
}
private static ParameterExpression GetParameterExpressionIncludingConversions(Expression expression)
{
var paramExpr = expression as ParameterExpression;
if (paramExpr != null)
return paramExpr;
switch (expression.NodeType)
{
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
return GetParameterExpressionIncludingConversions(((UnaryExpression)expression).Operand);
}
return null;
}
private void VisitEquals(MethodCallExpression expression)
{
GetEqualsArgumentsFromExpression(expression, out var firstArg, out var secondArg, out var comparisonArg);
ExpressionInfo fieldInfo;
Expression constant;
if (IsMemberAccessForQuerySource(firstArg))
{
if (IsMemberAccessForQuerySource(secondArg))
throw new NotSupportedException("Where clauses containing an Equals Expression between two fields are not supported. " +
"The equalization should be between a field and a constant value. " +
$"`{firstArg}` and `{secondArg}` are both fields, so cannot convert {expression} to a proper query.");
fieldInfo = GetMember(firstArg);
constant = secondArg;
}
else if (IsMemberAccessForQuerySource(secondArg))
{
fieldInfo = GetMember(secondArg);
constant = firstArg;
}
else
{
throw new NotSupportedException("Where clauses containing an Expression between two constants are not supported. " +
"The equalization should be between a field and a constant value. " +
$"`{firstArg}` and `{secondArg}` are both constants, so cannot convert {expression} to a proper query.");
}
if (comparisonArg != null
&& comparisonArg.NodeType == ExpressionType.Constant
&& comparisonArg.Type == typeof(StringComparison))
{
var comparisonType = ((ConstantExpression)comparisonArg).Value;
switch ((StringComparison)comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.Ordinal:
throw new NotSupportedException(
"RavenDB queries case sensitivity is dependent on the index, not the query. If you need case sensitive queries, use a static index and an NotAnalyzed field for that.");
case StringComparison.CurrentCultureIgnoreCase:
case StringComparison.OrdinalIgnoreCase:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
DocumentQuery.WhereEquals(new WhereParams
{
FieldName = fieldInfo.Path,
Value = GetValueFromExpression(constant, GetMemberType(fieldInfo)),
AllowWildcards = false,
Exact = _insideExact
});
}
private static void GetEqualsArgumentsFromExpression(MethodCallExpression expression, out Expression firstArg, out Expression secondArg, out Expression comparisonArg)
{
comparisonArg = null;
if (expression.Object == null)
{
firstArg = expression.Arguments[0];
secondArg = expression.Arguments[1];
if (expression.Arguments.Count == 3)
comparisonArg = expression.Arguments[2];
}
else
{
firstArg = expression.Object;
secondArg = expression.Arguments[0];
if (expression.Arguments.Count == 2)
comparisonArg = expression.Arguments[1];
}
}
private void VisitStringContains(MethodCallExpression _)
{
throw new NotSupportedException(@"Contains is not supported, doing a substring match over a text field is a very slow operation, and is not allowed using the Linq API.
The recommended method is to use full text search (mark the field as Analyzed and use the Search() method to query it.");
}
private void VisitStartsWith(MethodCallExpression expression)
{
var memberInfo = GetMember(expression.Object);
DocumentQuery.WhereStartsWith(
memberInfo.Path,
GetValueFromExpression(expression.Arguments[0], GetMemberType(memberInfo)), _insideExact);
}
private void VisitEndsWith(MethodCallExpression expression)
{
var memberInfo = GetMember(expression.Object);
DocumentQuery.WhereEndsWith(
memberInfo.Path,
GetValueFromExpression(expression.Arguments[0], GetMemberType(memberInfo)), _insideExact);
}
private void VisitIsNullOrEmpty(MethodCallExpression expression, bool notEquals)
{
var memberInfo = GetMember(expression.Arguments[0]);
DocumentQuery.OpenSubclause();
if (notEquals)
DocumentQuery.WhereNotEquals(memberInfo.Path, null, _insideExact);
else
DocumentQuery.WhereEquals(memberInfo.Path, null, _insideExact);
if (notEquals)
DocumentQuery.AndAlso();
else
DocumentQuery.OrElse();
if (notEquals)
DocumentQuery.WhereNotEquals(memberInfo.Path, string.Empty, _insideExact);
else
DocumentQuery.WhereEquals(memberInfo.Path, string.Empty, _insideExact);
DocumentQuery.CloseSubclause();
}
private void VisitGreaterThan(BinaryExpression expression)
{
bool isStringCompare = false;
if (IsStringCompareTo(expression))
{
if (expression.Left is ConstantExpression)
{
VisitLessThan(Expression.LessThan(expression.Right, expression.Left));
return;
}
expression = NormalizeStringCompareExpression(expression);
isStringCompare = true;
}
else if (IsMemberAccessForQuerySource(expression.Left) == false && IsMemberAccessForQuerySource(expression.Right))
{
VisitLessThan(Expression.LessThan(expression.Right, expression.Left));
return;
}
var memberInfo = GetMember(expression.Left);
var memberType = GetMemberType(memberInfo);
object value;
if (isStringCompare)
value = ((expression.Left as MethodCallExpression).Arguments[0] as ConstantExpression).Value;
else
value = GetValueFromExpression(expression.Right, memberType);
var fieldName = GetFieldNameForRangeQuery(memberInfo, value);
if (ShouldExcludeNullTypes(memberType))
{
DocumentQuery.OpenSubclause();
}
DocumentQuery.WhereGreaterThan(
fieldName,
value,
_insideExact);
if (ShouldExcludeNullTypes(memberType))
{
DocumentQuery.AndAlso();
DocumentQuery.WhereNotEquals(fieldName, null, _insideExact);
DocumentQuery.CloseSubclause();
}
}
private void VisitGreaterThanOrEqual(BinaryExpression expression)
{
bool isStringCompare = false;
if (IsStringCompareTo(expression))
{
if (expression.Left is ConstantExpression)
{
VisitLessThanOrEqual(Expression.LessThanOrEqual(expression.Right, expression.Left));
return;
}
expression = NormalizeStringCompareExpression(expression);
isStringCompare = true;
}
else if (IsMemberAccessForQuerySource(expression.Left) == false && IsMemberAccessForQuerySource(expression.Right))
{
VisitLessThanOrEqual(Expression.LessThanOrEqual(expression.Right, expression.Left));
return;
}
var memberInfo = GetMember(expression.Left);
var memberType = GetMemberType(memberInfo);
object value;
if (isStringCompare)
value = ((expression.Left as MethodCallExpression).Arguments[0] as ConstantExpression).Value;
else
value = GetValueFromExpression(expression.Right, memberType);
var fieldName = GetFieldNameForRangeQuery(memberInfo, value);
if (ShouldExcludeNullTypes(memberType))
{
DocumentQuery.OpenSubclause();
}
DocumentQuery.WhereGreaterThanOrEqual(
fieldName,
value,
_insideExact);
if (ShouldExcludeNullTypes(memberType))
{
DocumentQuery.AndAlso();
DocumentQuery.WhereNotEquals(fieldName, null, _insideExact);
DocumentQuery.CloseSubclause();
}
}
private static bool ShouldExcludeNullTypes(Type memberType)
{
return memberType.IsValueType && Nullable.GetUnderlyingType(memberType) != null;
}
private void VisitLessThan(BinaryExpression expression)
{
bool isStringCompare = false;
if (IsStringCompareTo(expression))
{
if (expression.Left is ConstantExpression)
{
VisitGreaterThan(Expression.GreaterThan(expression.Right, expression.Left));
return;
}
expression = NormalizeStringCompareExpression(expression);
isStringCompare = true;
}
else if (IsMemberAccessForQuerySource(expression.Left) == false && IsMemberAccessForQuerySource(expression.Right))
{
VisitGreaterThan(Expression.GreaterThan(expression.Right, expression.Left));
return;
}
var memberInfo = GetMember(expression.Left);
var memberType = GetMemberType(memberInfo);
object value;
if (isStringCompare)
value = ((expression.Left as MethodCallExpression).Arguments[0] as ConstantExpression).Value;
else
value = GetValueFromExpression(expression.Right, memberType);
var fieldName = GetFieldNameForRangeQuery(memberInfo, value);
if (ShouldExcludeNullTypes(memberType))
{
DocumentQuery.OpenSubclause();
}
DocumentQuery.WhereLessThan(
fieldName,
value,
_insideExact);
if (ShouldExcludeNullTypes(memberType))
{
DocumentQuery.AndAlso();
DocumentQuery.WhereNotEquals(fieldName, null, _insideExact);
DocumentQuery.CloseSubclause();
}
}
private void VisitLessThanOrEqual(BinaryExpression expression)
{
bool isStringCompare = false;
if (IsStringCompareTo(expression))
{
if (expression.Left is ConstantExpression)
{
VisitGreaterThanOrEqual(Expression.GreaterThanOrEqual(expression.Right, expression.Left));
return;
}
expression = NormalizeStringCompareExpression(expression);
isStringCompare = true;
}
else if(IsMemberAccessForQuerySource(expression.Left) == false && IsMemberAccessForQuerySource(expression.Right))
{
VisitGreaterThanOrEqual(Expression.GreaterThanOrEqual(expression.Right, expression.Left));
return;
}
var memberInfo = GetMember(expression.Left);
var memberType = GetMemberType(memberInfo);
object value;
if (isStringCompare)
value = ((expression.Left as MethodCallExpression).Arguments[0] as ConstantExpression).Value;
else
value = GetValueFromExpression(expression.Right, memberType);
var fieldName = GetFieldNameForRangeQuery(memberInfo, value);
if (ShouldExcludeNullTypes(memberType))
{
DocumentQuery.OpenSubclause();
}
DocumentQuery.WhereLessThanOrEqual(
fieldName,
value,
_insideExact);
if (ShouldExcludeNullTypes(memberType))