-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathQuerySupport.cs
1792 lines (1624 loc) · 67 KB
/
QuerySupport.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
namespace Ceen.Database
{
/// <summary>
/// Helper class for constructing a where clause programatically.
/// This class should be used with:
/// using static Ceen.Database.QueryUtil
/// </summary>
public static class QueryUtil
{
/// <summary>
/// Returns an empty query
/// </summary>
/// <returns>The empty query</returns>
public static Empty Empty => new Empty();
/// <summary>
/// Creates a new query order (ascending)
/// </summary>
/// <param name="name">The property to order by</param>
/// <param name="next">The next order property</param>
/// <returns>The query order</returns>
public static QueryOrder Order(string name, QueryOrder next = null) => new QueryOrder(name, false, next);
/// <summary>
/// Creates a new ascending query order
/// </summary>
/// <param name="name">The property to order by</param>
/// <param name="next">The next order property</param>
/// <returns>The query order</returns>
public static QueryOrder OrderAsc(string name, QueryOrder next = null) => new QueryOrder(name, false, next);
/// <summary>
/// Creates a new descending query order
/// </summary>
/// <param name="name">The property to order by</param>
/// <param name="next">The next order property</param>
/// <returns>The query order</returns>
public static QueryOrder OrderDesc(string name, QueryOrder next = null) => new QueryOrder(name, true, next);
/// <summary>
/// Constructs an And sequence
/// </summary>
/// <param name="args">The arguments to and together</param>
/// <returns>A query element</returns>
public static QueryElement And(params QueryElement[] args) => new And(args);
/// <summary>
/// Constructs an And sequence
/// </summary>
/// <param name="args">The arguments to and together</param>
/// <returns>A query element</returns>
public static QueryElement And(IEnumerable<QueryElement> args) => new And(args);
/// <summary>
/// Constructs an or sequence
/// </summary>
/// <param name="args">The arguments to or together</param>
/// <returns>A query element</returns>
public static QueryElement Or(params QueryElement[] args) => new Or(args);
/// <summary>
/// Constructs an or sequence
/// </summary>
/// <param name="args">The arguments to or together</param>
/// <returns>A query element</returns>
public static QueryElement Or(IEnumerable<QueryElement> args) => new Or(args);
/// <summary>
/// Constructs a property access
/// </summary>
/// <param name="name">The name of the property to query</param>
/// <returns>A query element</returns>
public static QueryElement Property(string name) => new Property(name);
/// <summary>
/// Compares two items for equality
/// </summary>
/// <param name="lhs">Either a property or a value</param>
/// <param name="rhs">Either a property or a value</param>
/// <returns>A query element</returns>
public static QueryElement Equal(object lhs, object rhs) => new Compare(lhs, "=", rhs);
/// <summary>
/// Compares two items for equality
/// </summary>
/// <param name="lhs">Either a property or a value</param>
/// <param name="rhs">Either a property or a value</param>
/// <returns>A query element</returns>
public static QueryElement Like(object lhs, object rhs) => new Compare(lhs, "LIKE", rhs);
/// <summary>
/// Compares two items with the given operator
/// </summary>
/// <param name="lhs">Either a property or a value</param>
/// <param name="operator">The operator to use</param>
/// <param name="rhs">Either a property or a value</param>
/// <returns>A query element</returns>
public static QueryElement Compare(object lhs, string @operator, object rhs) => new Compare(lhs, @operator, rhs);
/// <summary>
/// Applies an arithmetic operator to two operands
/// </summary>
/// <param name="lhs">Either a property or a value</param>
/// <param name="operator">The operator to use</param>
/// <param name="rhs">Either a property or a value</param>
/// <returns>A query element</returns>
public static QueryElement Arithmetic(object lhs, string @operator, object rhs)
{
// Check if we can reduce this to a single value
if ((lhs is Value || !(lhs is QueryElement)) && (rhs is Value || !(rhs is QueryElement)))
{
var lh = (lhs is Value lval) ? lval.Item : lhs;
var rh = (rhs is Value rval) ? rval.Item : rhs;
if (IsNumericType(lh) && IsNumericType(rh))
{
if (lh is double || rh is double)
{
var dbl = (double)Convert.ChangeType(lh, typeof(double));
var dbr = (double)Convert.ChangeType(rh, typeof(double));
switch (@operator)
{
case "+": return new Value(dbl + dbr);
case "-": return new Value(dbl - dbr);
case "*": return new Value(dbl * dbr);
case "/": return new Value(dbl / dbr);
case "%": return new Value(dbl % dbr);
}
}
else if (lh is float || rh is float)
{
var dbl = (float)Convert.ChangeType(lh, typeof(float));
var dbr = (float)Convert.ChangeType(rh, typeof(float));
switch (@operator)
{
case "+": return new Value(dbl + dbr);
case "-": return new Value(dbl - dbr);
case "*": return new Value(dbl * dbr);
case "/": return new Value(dbl / dbr);
case "%": return new Value(dbl % dbr);
}
}
else if (lh is ulong || rh is ulong)
{
var dbl = (ulong)Convert.ChangeType(lh, typeof(ulong));
var dbr = (ulong)Convert.ChangeType(rh, typeof(ulong));
switch (@operator)
{
case "+": return new Value(dbl + dbr);
case "-": return new Value(dbl - dbr);
case "*": return new Value(dbl * dbr);
case "/": return new Value(dbl / dbr);
case "%": return new Value(dbl % dbr);
}
}
else
{
var dbl = (long)Convert.ChangeType(lh, typeof(long));
var dbr = (long)Convert.ChangeType(rh, typeof(long));
switch (@operator)
{
case "+": return new Value(dbl + dbr);
case "-": return new Value(dbl - dbr);
case "*": return new Value(dbl * dbr);
case "/": return new Value(dbl / dbr);
case "%": return new Value(dbl % dbr);
}
}
}
else if ((lh is DateTime || lh is TimeSpan) && (rh is DateTime || rh is TimeSpan))
{
if (lh is DateTime && rh is DateTime)
{
switch (@operator)
{
case "-": return new Value((DateTime)lh - (DateTime)rh);
}
}
else if (lh is TimeSpan && rh is TimeSpan)
{
switch (@operator)
{
case "+": return new Value((TimeSpan)lh + (TimeSpan)rh);
case "-": return new Value((TimeSpan)lh - (TimeSpan)rh);
}
}
else if (lh is DateTime && rh is TimeSpan)
{
switch (@operator)
{
case "+": return new Value((DateTime)lh + (TimeSpan)rh);
case "-": return new Value((DateTime)lh - (TimeSpan)rh);
}
}
}
}
// Unable to shorten, just return "as-is"
return new Arithmetic(lhs, @operator, rhs);
}
/// <summary>
/// Checks if the item is a numeric type
/// </summary>
/// <param name="o">The item to check</param>
/// <returns><c>true</c> if the item is numeric, <c>false</c> otherwise</returns>
private static bool IsNumericType(object o)
{
if (o == null)
return false;
switch (Type.GetTypeCode(o.GetType()))
{
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
//case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Single:
return true;
default:
return false;
}
}
/// <summary>
/// Adds two operands
/// </summary>
/// <param name="lhs">Either a property or a value</param>
/// <param name="rhs">Either a property or a value</param>
/// <returns>A query element</returns>
public static QueryElement Add(object lhs, object rhs) => Arithmetic(lhs, "+", rhs);
/// <summary>
/// Subtracts two operands
/// </summary>
/// <param name="lhs">Either a property or a value</param>
/// <param name="rhs">Either a property or a value</param>
/// <returns>A query element</returns>
public static QueryElement Subtract(object lhs, object rhs) => Arithmetic(lhs, "-", rhs);
/// <summary>
/// Multiplies two operands
/// </summary>
/// <param name="lhs">Either a property or a value</param>
/// <param name="rhs">Either a property or a value</param>
/// <returns>A query element</returns>
public static QueryElement Multiply(object lhs, object rhs) => Arithmetic(lhs, "*", rhs);
/// <summary>
/// Divides two operands
/// </summary>
/// <param name="lhs">Either a property or a value</param>
/// <param name="rhs">Either a property or a value</param>
/// <returns>A query element</returns>
public static QueryElement Divide(object lhs, object rhs) => Arithmetic(lhs, "/", rhs);
/// <summary>
/// Computes the modulo two operands
/// </summary>
/// <param name="lhs">Either a property or a value</param>
/// <param name="rhs">Either a property or a value</param>
/// <returns>A query element</returns>
public static QueryElement Modulo(object lhs, object rhs) => Arithmetic(lhs, "%", rhs);
/// <summary>
/// Checks if an element is in a list
/// </summary>
/// <param name="lhs">The item to examine</param>
/// <param name="args">The list of options</param>
/// <returns>A query element</returns>
public static QueryElement In(object lhs, IEnumerable<object> args) => new Compare(lhs, "IN", args);
/// <summary>
/// Checks if an element is not in a list
/// </summary>
/// <param name="lhs">The item to examine</param>
/// <param name="args">The list of options</param>
/// <returns>A query element</returns>
public static QueryElement NotIn(object lhs, IEnumerable<object> args) => new Compare(lhs, "NOT IN", args);
/// <summary>
/// Checks if an element is in a list
/// </summary>
/// <param name="lhs">The item to examine</param>
/// <param name="other">The query to check if the value is in</param>
/// <returns>A query element</returns>
public static QueryElement In(object lhs, Query other) => new Compare(lhs, "IN", other);
/// <summary>
/// Checks if an element is in a list
/// </summary>
/// <param name="lhs">The item to examine</param>
/// <param name="other">The query to check if the value is not in</param>
/// <returns>A query element</returns>
public static QueryElement NotIn(object lhs, Query other) => new Compare(lhs, "NOT IN", other);
/// <summary>
/// Negates an expression
/// </summary>
/// <param name="expr">The expression to negate</param>
/// <returns>A query element</returns>
public static QueryElement Not(object expr) => new UnaryOperator("not", expr);
/// <summary>
/// Accepts a anonymous object where the properties are column names,
/// and the values are the values to compare the properties to.
/// Produces an and query for all items
/// </summary>
/// <param name="arg">The anonymous object to inspect</param>
/// <returns>A query element</returns>
public static QueryElement Equal(object arg)
{
var props = arg.GetType().GetProperties();
if (props.Length == 1)
return Compare(
Property(props.First().Name),
"=",
props.First().GetValue(arg)
);
return MultipleAnd(arg);
}
/// <summary>
/// Accepts a anonymous object where the properties are column names,
/// and the values are the values to compare the properties to.
/// Produces an and query for all items
/// </summary>
/// <param name="arg">The anonymous object to inspect</param>
/// <param name="@operator">The compare operator to use</param>
/// <returns>A query element</returns>
public static QueryElement MultipleAnd(object args, string @operator = "=")
{
return And(
args
.GetType()
.GetProperties()
.Select(x =>
Compare(
Property(x.Name),
@operator,
x.GetValue(args)
)
)
);
}
/// <summary>
/// Accepts a anonymous object where the properties are column names,
/// and the values are the values to compare the properties to.
/// Produces an or query for all items
/// </summary>
/// <param name="arg">The anonymous object to inspect</param>
/// <param name="@operator">The compare operator to use</param>
/// <returns>A query element</returns>
public static QueryElement MultipleOr(object args, string @operator = "=")
{
return Or(
args
.GetType()
.GetProperties()
.Select(x =>
Compare(
Property(x.Name),
@operator,
x.GetValue(args)
)
)
);
}
/// <summary>
/// Parses a lambda expression and returns a query
/// </summary>
/// <param name="expr">The expression to parse</param>
/// <typeparam name="T">The target type</typeparam>
/// <returns>A query element</returns>
public static QueryElement FromLambda<T>(Expression<Func<T, bool>> expr)
{
return FromLambda(expr.Body, expr.Parameters.First());
}
/// <summary>
/// Handles parsing a lambda fragment with an enum compare, and unwraps the type casts
/// </summary>
/// <param name="bx"></param>
/// <param name="@operator"></param>
/// <param name="methodtarget"></param>
/// <returns></returns>
private static QueryElement UnwrapCompare(BinaryExpression bx, string @operator, ParameterExpression methodtarget)
{
var lhs = bx.Left;
var rhs = bx.Right;
if (lhs is UnaryExpression luex && lhs.NodeType == ExpressionType.Convert)
lhs = luex.Operand;
if (rhs is UnaryExpression ruex && rhs.NodeType == ExpressionType.Convert)
rhs = ruex.Operand;
var lhsmtype = GetMemberType(lhs);
var rhsmtype = GetMemberType(rhs);
var lqp = FromLambda(lhs, methodtarget);
var rqp = FromLambda(rhs, methodtarget);
// If we unwrapped the left-hand side due to enum conversion, fix the right-hand side
if (lhs != bx.Left && lhsmtype != null && lhsmtype.IsEnum && rqp is Value rqpv && rqpv.Item != null)
{
if (rqpv.Item is string vs)
rqp = new Value(Enum.Parse(lhsmtype, vs));
else
rqp = new Value(Enum.ToObject(lhsmtype, rqpv.Item));
}
// If we unwrapped the right-hand side due to enum conversion, fix the left-hand side
if (rhs != bx.Left && rhsmtype != null && rhsmtype.IsEnum && lqp is Value lqpv && lqpv.Item != null)
{
if (lqpv.Item is string vs)
lqp = new Value(Enum.Parse(rhsmtype, vs));
else
lqp = new Value(Enum.ToObject(rhsmtype, lqpv.Item));
}
return Compare(lqp, @operator, rqp);
}
private static Type GetMemberType(Expression e)
{
if (e is MemberExpression me)
{
if (me.Member is System.Reflection.PropertyInfo pi)
return pi.PropertyType;
else if (me.Member is System.Reflection.FieldInfo fi)
return fi.FieldType;
}
return null;
}
/// <summary>
/// Parses an expression as a query element
/// </summary>
/// <param name="expr">The expression to parse</param>
/// <param name="methodtarget">The parameter used as input for the lambda</param>
/// <returns>A query element</returns>
private static QueryElement FromLambda(Expression expr, ParameterExpression methodtarget)
{
if (expr is BinaryExpression bexpr)
{
switch (bexpr.NodeType)
{
case ExpressionType.Equal:
return UnwrapCompare(bexpr, "=", methodtarget);
case ExpressionType.NotEqual:
return UnwrapCompare(bexpr, "!=", methodtarget);
case ExpressionType.GreaterThan:
return UnwrapCompare(bexpr, ">", methodtarget);
case ExpressionType.LessThan:
return UnwrapCompare(bexpr, "<", methodtarget);
case ExpressionType.LessThanOrEqual:
return UnwrapCompare(bexpr, "<=", methodtarget);
case ExpressionType.GreaterThanOrEqual:
return UnwrapCompare(bexpr, ">=", methodtarget);
case ExpressionType.AndAlso:
case ExpressionType.And:
return And(FromLambda(bexpr.Left, methodtarget), FromLambda(bexpr.Right, methodtarget));
case ExpressionType.OrElse:
case ExpressionType.Or:
return Or(FromLambda(bexpr.Left, methodtarget), FromLambda(bexpr.Right, methodtarget));
case ExpressionType.Add:
return Add(FromLambda(bexpr.Left, methodtarget), FromLambda(bexpr.Right, methodtarget));
case ExpressionType.Subtract:
return Subtract(FromLambda(bexpr.Left, methodtarget), FromLambda(bexpr.Right, methodtarget));
case ExpressionType.Multiply:
return Multiply(FromLambda(bexpr.Left, methodtarget), FromLambda(bexpr.Right, methodtarget));
case ExpressionType.Divide:
return Divide(FromLambda(bexpr.Left, methodtarget), FromLambda(bexpr.Right, methodtarget));
case ExpressionType.Modulo:
return Modulo(FromLambda(bexpr.Left, methodtarget), FromLambda(bexpr.Right, methodtarget));
}
}
else if (expr is ConstantExpression cexpr)
{
return new Value(cexpr.Value);
}
else if (expr is MemberExpression mexpr)
{
if (mexpr.Expression == methodtarget)
return Property(mexpr.Member.Name);
return new Value(GetValue(mexpr));
}
else if (expr is MethodCallExpression callexpr)
{
if (callexpr.Method.DeclaringType == typeof(string) && callexpr.Method.Name == nameof(string.Equals))
{
var useLike = false;
if (callexpr.Method.GetParameters().Length == 3)
useLike = new StringComparison[] {
StringComparison.CurrentCultureIgnoreCase,
StringComparison.InvariantCultureIgnoreCase,
StringComparison.OrdinalIgnoreCase
}.Contains((StringComparison)GetValue(callexpr.Arguments.Last()));
if (useLike)
return Like(FromLambda(callexpr.Arguments.First(), methodtarget), FromLambda(callexpr.Arguments.Skip(1).First(), methodtarget));
else
return Equal(FromLambda(callexpr.Arguments.First(), methodtarget), FromLambda(callexpr.Arguments.Last(), methodtarget));
}
else if (callexpr.Method.DeclaringType == typeof(TimeSpan) && callexpr.Method.IsStatic && callexpr.Method.GetParameters().Length == 1)
{
var arg = FromLambda(callexpr.Arguments.First(), methodtarget);
if (arg is Value argv)
{
if (callexpr.Method.Name == nameof(TimeSpan.FromTicks))
return new Value(TimeSpan.FromTicks((long)Convert.ChangeType(argv.Item, typeof(long))));
if (callexpr.Method.Name == nameof(TimeSpan.FromMilliseconds))
return new Value(TimeSpan.FromMilliseconds((double)Convert.ChangeType(argv.Item, typeof(double))));
if (callexpr.Method.Name == nameof(TimeSpan.FromSeconds))
return new Value(TimeSpan.FromSeconds((double)Convert.ChangeType(argv.Item, typeof(double))));
if (callexpr.Method.Name == nameof(TimeSpan.FromMinutes))
return new Value(TimeSpan.FromMinutes((double)Convert.ChangeType(argv.Item, typeof(double))));
if (callexpr.Method.Name == nameof(TimeSpan.FromHours))
return new Value(TimeSpan.FromHours((double)Convert.ChangeType(argv.Item, typeof(double))));
if (callexpr.Method.Name == nameof(TimeSpan.FromDays))
return new Value(TimeSpan.FromDays((double)Convert.ChangeType(argv.Item, typeof(double))));
}
}
else if (callexpr.Method.DeclaringType.IsGenericType && callexpr.Method.DeclaringType.GetGenericTypeDefinition() == typeof(Dictionary<,>) && callexpr.Method.Name == nameof(Dictionary<int,int>.ContainsKey) && callexpr.Arguments.Count == 1)
{
var collection = GetValue(callexpr.Object);
if (collection is IEnumerable cenm && !(collection is string))
{
var seqex =
callexpr.Method.DeclaringType
.GetProperty(nameof(Dictionary<int,int>.Keys))
.GetValue(collection, null) as IEnumerable;
var arg = FromLambda(callexpr.Arguments.First(), methodtarget);
return In(arg, seqex.Cast<object>());
}
}
else if (callexpr.Method.IsStatic && callexpr.Method.DeclaringType == typeof(System.Linq.Enumerable) && callexpr.Method.Name == nameof(System.Linq.Enumerable.Contains))
{
var collection = GetValue(callexpr.Arguments.First());
if (collection is IEnumerable cenm && !(collection is string))
{
var arg = FromLambda(callexpr.Arguments.Last(), methodtarget);
return In(arg, cenm.Cast<object>());
}
}
throw new Exception($"Method is not supported: {callexpr.Method}");
}
else if (expr is UnaryExpression uexp)
{
if (uexp.NodeType == ExpressionType.Not)
return Not(FromLambda(uexp.Operand, methodtarget));
}
throw new Exception($"Expression is not supported: {expr.NodeType}");
}
/// <summary>
/// Extracts the value from an expression
/// </summary>
/// <param name="expr">The expression to get the value for</param>
/// <returns>The value</returns>
private static object GetValue(Expression expr)
{
if (expr is ConstantExpression cexpr)
return cexpr.Value;
else if (expr is MemberExpression mexpr)
return GetValue(mexpr);
else
throw new Exception($"Expression is not supported: {expr.NodeType}");
}
/// <summary>
/// Extracts the value from a member
/// </summary>
/// <param name="member">The member to get the value for</param>
/// <returns>The value</returns>
private static object GetValue(MemberExpression member)
{
return
Expression.Lambda<Func<object>>(
Expression.Convert(member, typeof(object))
)
.Compile()
.Invoke();
}
}
/// <summary>
/// The query types supported
/// </summary>
public enum QueryType
{
/// <summary>Undetermined statement type, defaults to SELECT</summary>
Default,
/// <summary>A SELECT statement</summary>
Select,
/// <summary>An UPDATE statement</summary>
Update,
/// <summary>A DELETE statement</summary>
Delete,
/// <summary>An INSERT statement</summary>
Insert
}
/// <summary>
/// Represents a full SQL query statement
/// </summary>
public class ParsedQuery
{
/// <summary>
/// The query type
/// </summary>
private QueryType m_type;
/// <summary>
/// The columns to return
/// </summary>
private List<string> m_columns;
/// <summary>
/// The where clause to use
/// </summary>
private QueryElement m_where;
/// <summary>
/// The limit to use
/// </summary>
private Tuple<long, long> m_limit;
/// <summary>
/// The order to use
/// </summary>
private List<QueryOrder> m_orders;
/// <summary>
/// The values used for an update
/// </summary>
private Dictionary<string, object> m_updatevalues;
/// <summary>
/// Flag indicating if the instance is finalized
/// </summary>
private bool m_isCompleted = false;
/// <summary>
/// The type this instance is for
/// </summary>
public Type DataType { get => m_map.Type; }
/// <summary>
/// The table mapping for the data type
/// </summary>
private readonly TableMapping m_map;
/// <summary>
/// A flag indicating if insert issues are ignored
/// </summary>
private bool m_ignoreInsert;
/// <summary>
/// The object being inserted, used for back-setting generated values
/// </summary>
private object m_insertItem;
/// <summary>
/// Default constructor
/// </summary>
public ParsedQuery(TableMapping map)
{
m_map = map ?? throw new ArgumentNullException(nameof(map));
}
/// <summary>
/// Gets the query type this instance represents
/// </summary>
public QueryType Type => m_type == QueryType.Default ? QueryType.Select : m_type;
/// <summary>
/// The columns to select, null means all
/// </summary>
public IEnumerable<string> SelectColumns { get => m_columns?.Distinct(); }
/// <summary>
/// The where clause
/// </summary>
/// <returns></returns>
public QueryElement WhereQuery { get => m_where ?? new Empty(); }
/// <summary>
/// The limit to apply, or null for unlimited
/// </summary>
public Tuple<long, long> LimitParams { get => m_limit; }
/// <summary>
/// Gets the update values
/// </summary>
public Dictionary<string, object> UpdateValues => m_updatevalues;
/// <summary>
/// Gets a value indicating if inserts are ignored
/// </summary>
public bool IgnoresInsert => m_ignoreInsert;
/// <summary>
/// The item being inserted
/// </summary>
public object InsertItem => m_insertItem;
/// <summary>
/// The order clause
/// </summary>
/// <value></value>
public QueryOrder OrderClause
{
get
{
QueryOrder prev = null;
if (m_orders != null)
for (int i = m_orders.Count - 1; i >= 0 ; i--)
prev = new QueryOrder(m_orders[i], prev);
return prev;
}
}
/// <summary>
/// Marks the query as a select opration and optionally restricts the select part of the query
/// </summary>
/// <param name="columns">The columns to return</param>
/// <returns>The query instance</returns>
public ParsedQuery Select(params string[] columns)
{
if (m_isCompleted)
throw new InvalidOperationException("Cannot change the query after it is finalized");
if (m_type == QueryType.Default || m_type == QueryType.Select)
m_type = QueryType.Select;
else
throw new ArgumentException($"Cannot change the query type from {m_type} to SELECT");
if (columns != null && columns.Length != 0)
{
if (m_columns == null)
m_columns = new List<string>();
foreach (var c in columns)
{
if (!m_map.AllColumnsByMemberName.ContainsKey(c))
throw new ArgumentException($"The type {DataType} has no member named {c}");
m_columns.AddRange(columns);
}
}
return this;
}
/// <summary>
/// Marks the query as a delete operation
/// </summary>
/// <returns>The query instance</returns>
public ParsedQuery Delete()
{
if (m_isCompleted)
throw new InvalidOperationException("Cannot change the query after it is finalized");
if (m_type == QueryType.Default || m_type == QueryType.Delete)
m_type = QueryType.Delete;
else
throw new ArgumentException($"Cannot change the query type from {m_type} to DELETE");
return this;
}
/// <summary>
/// Marks the query as an insert and sets the values
/// </summary>
/// <param name="item">The item to insert</param>
/// <returns>The query instance</returns>
public ParsedQuery Insert(object item)
{
if (m_isCompleted)
throw new InvalidOperationException("Cannot change the query after it is finalized");
if (item == null)
throw new ArgumentNullException(nameof(item));
if (item.GetType() != DataType)
throw new ArgumentException("The type to insert must be the same as the query is for");
if (m_insertItem != null)
throw new InvalidOperationException("Cannot call insert twice");
if (m_type == QueryType.Default || m_type == QueryType.Insert)
m_type = QueryType.Insert;
else
throw new ArgumentException($"Cannot change the query type from {m_type} to INSERT");
m_insertItem = item;
if (m_updatevalues == null)
m_updatevalues = new Dictionary<string, object>();
foreach (var col in m_map.InsertColumns)
m_updatevalues.Add(col.MemberName, col.GetValueForDb(item));
return this;
}
/// <summary>
/// Marks the query as an update and sets the values to update
/// </summary>
/// <param name="values">An anonymous object with parameters to update</param>
/// <returns>The query instance</returns>
public ParsedQuery Update(object values)
{
if (values == null)
throw new ArgumentNullException(nameof(values));
Dictionary<string, object> props;
if (values.GetType() == DataType)
{
props = m_map
.UpdateColumns
.ToDictionary(
x => x.MemberName,
x => x.GetValueForDb(values)
);
}
else
{
props = values
.GetType()
.GetProperties()
.ToDictionary(
x => x.Name,
x => {
var v = x.GetValue(values);
if (x.PropertyType.IsEnum)
v = (v ?? string.Empty).ToString();
return v;
}
);
}
return Update(props);
}
/// <summary>
/// Marks the query as an update and sets the values to update
/// </summary>
/// <param name="values">The values to update</param>
/// <returns>The query instance</returns>
public ParsedQuery Update(Dictionary<string, object> values)
{
if (m_isCompleted)
throw new InvalidOperationException("Cannot change the query after it is finalized");
if (m_type == QueryType.Default || m_type == QueryType.Update)
m_type = QueryType.Update;
else
throw new ArgumentException($"Cannot change the query type from {m_type} to UPDATE");
if (m_updatevalues == null)
m_updatevalues = new Dictionary<string, object>();
foreach (var item in values)
{
if (!m_map.UpdateColumns.Any(x => x.MemberName == item.Key))
{
if (m_map.AllColumnsByMemberName.ContainsKey(item.Key))
throw new ArgumentException($"The type {DataType} cannot update {item.Key}");
else
throw new ArgumentException($"The type {DataType} has no member named {item.Key}");
}
m_updatevalues.Add(item.Key, item.Value);
}
return this;
}
/// <summary>
/// Computes the where filter from a string
/// </summary>
/// <param name="filter">The filter string</param>
/// <returns>The query instance</returns>
public ParsedQuery Where(string filter)
{
return Where(FilterParser.ParseFilter(m_map, filter));
}
/// <summary>
/// Adds a additional where clause to the query
/// </summary>
/// <param name="query">The query to add</param>
/// <returns>The query instance</returns>
public ParsedQuery Where(QueryElement query)
{
if (m_isCompleted)
throw new InvalidOperationException("Cannot change the query after it is finalized");
if (m_type == QueryType.Default)
throw new InvalidOperationException($"Cannot use {nameof(Where)} before the query type has been set");
if (m_type == QueryType.Insert)
throw new InvalidOperationException($"Cannot have a where statement on an INSERT");
if (query != null)
{
if (m_where == null)
m_where = query;
else
m_where = new And(m_where, query);
}
return this;
}
/// <summary>
/// Prepends a match for the primary key to the where clause
/// </summary>
/// <param name="item">The item with the primary key values</param>
/// <returns>The query instance</returns>
public ParsedQuery MatchPrimaryKeys(object item)
{
return MatchPrimaryKeys(m_map.PrimaryKeys
.Select(x => {
var prop = item.GetType().GetProperty(x.MemberName);
if (prop != null)
return prop.GetValue(item);
var field = item.GetType().GetField(x.MemberName);
if (field != null)
return field.GetValue(item);
throw new ArgumentException($"The data item does not have the primary key property {x.MemberName}");
})
.ToArray()
);
}
/// <summary>
/// Prepends a match for the primary key to the where clause
/// </summary>
/// <param name="values">The primary key values</param>
/// <returns>The query instance</returns>
public ParsedQuery MatchPrimaryKeys(object[] values)
{
if (m_isCompleted)
throw new InvalidOperationException("Cannot change the query after it is finalized");
if (m_type == QueryType.Default)
throw new InvalidOperationException($"Cannot use {nameof(MatchPrimaryKeys)} before the query type has been set");
if (m_type == QueryType.Insert)
throw new InvalidOperationException($"Cannot have a where statement on an INSERT");
if (m_map.PrimaryKeys.Length == 0)
throw new ArgumentException($"The type {DataType} does not have a primary key");
if (values == null || values.Length != m_map.PrimaryKeys.Length)
throw new ArgumentException($"Expected {m_map.PrimaryKeys.Length} keys but got {values?.Length}");
var els = values
.Select((x, i) => new Compare(
new Property(m_map.PrimaryKeys[i].MemberName),
"=",
new Value(x)
))
.ToArray();
var q = els.Length == 1 ? (QueryElement)els[0] : new And(els);
if (m_where == null || m_where is Empty)
m_where = q;
else
m_where = new And(q, m_where);
return this;
}
/// <summary>
/// Adds order clauses to the query
/// </summary>
/// <param name="orders">The order to use</param>
/// <returns>The query instance</returns>
public ParsedQuery OrderBy(params QueryOrder[] orders)
{
return OrderBy(orders.AsEnumerable());
}
/// <summary>
/// Adds order clauses to the query
/// </summary>
/// <param name="orders">The order to use</param>
/// <returns>The query instance</returns>
public ParsedQuery OrderBy(IEnumerable<QueryOrder> orders)
{
if (m_isCompleted)
throw new InvalidOperationException("Cannot change the query after it is finalized");
if (m_type == QueryType.Default)
throw new InvalidOperationException($"Cannot use {nameof(OrderBy)} before the query type has been set");
if (m_type == QueryType.Insert)
throw new InvalidOperationException($"Cannot have an order-by statement on an INSERT");
if (m_orders == null)
m_orders = new List<QueryOrder>();
m_orders.AddRange(orders);
return this;