-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathSqlBaseGenerator.cs
More file actions
1494 lines (1340 loc) · 66.5 KB
/
SqlBaseGenerator.cs
File metadata and controls
1494 lines (1340 loc) · 66.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
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
#region License
// The PostgreSQL License
//
// Copyright (C) 2016 The Npgsql Development Team
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph and the following two paragraphs appear in all copies.
//
// IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY
// FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
// INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
// DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
// ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
#endregion
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
#if ENTITIES6
using System.Globalization;
using System.Data.Entity.Core.Common.CommandTrees;
using System.Data.Entity.Core.Metadata.Edm;
#else
using System.Data.Common.CommandTrees;
using System.Data.Metadata.Edm;
#endif
using System.Linq;
using JetBrains.Annotations;
using System.Text.RegularExpressions;
using System.Text;
namespace Npgsql.SqlGenerators
{
internal abstract class SqlBaseGenerator : DbExpressionVisitor<VisitedExpression>
{
internal NpgsqlCommand Command;
internal bool CreateParametersForConstants;
bool _useNewPrecedences;
protected Dictionary<string, PendingProjectsNode> RefToNode = new Dictionary<string, PendingProjectsNode>();
protected HashSet<InputExpression> CurrentExpressions = new HashSet<InputExpression>();
protected uint AliasCounter;
protected uint ParameterCount;
internal Version Version
{
get { return _version; }
set
{
_version = value;
_useNewPrecedences = value >= new Version(9, 5);
}
}
Version _version;
static readonly Dictionary<string, string> AggregateFunctionNames = new Dictionary<string, string>()
{
{"Avg","avg"},
{"Count","count"},
{"Min","min"},
{"Max","max"},
{"Sum","sum"},
{"BigCount","count"},
{"StDev","stddev_samp"},
{"StDevP","stddev_pop"},
{"Var","var_samp"},
{"VarP","var_pop"},
};
#if ENTITIES6
static readonly Dictionary<string, Operator> BinaryOperatorFunctionNames = new Dictionary<string, Operator>()
{
{"@@",Operator.QueryMatch},
{"operator_tsquery_and",Operator.QueryAnd},
{"operator_tsquery_or",Operator.QueryOr},
{"operator_tsquery_contains",Operator.QueryContains},
{"operator_tsquery_is_contained",Operator.QueryIsContained}
};
#endif
void EnterExpression(PendingProjectsNode n) => CurrentExpressions.Add(n.Last.Exp);
void LeaveExpression(PendingProjectsNode n) => CurrentExpressions.Remove(n.Last.Exp);
protected string NextAlias() => "Alias" + AliasCounter++;
bool IsCompatible(InputExpression child, DbExpressionKind parentKind)
{
switch (parentKind)
{
case DbExpressionKind.Filter:
return
child.Projection == null &&
child.GroupBy == null &&
child.Skip == null &&
child.Limit == null;
case DbExpressionKind.GroupBy:
return
child.Projection == null &&
child.GroupBy == null &&
child.Distinct == false &&
child.OrderBy == null &&
child.Skip == null &&
child.Limit == null;
case DbExpressionKind.Distinct:
return
child.OrderBy == null &&
child.Skip == null &&
child.Limit == null;
case DbExpressionKind.Sort:
return
child.Projection == null &&
child.GroupBy == null &&
child.Skip == null &&
child.Limit == null;
case DbExpressionKind.Skip:
return
child.Projection == null &&
child.Skip == null &&
child.Limit == null;
case DbExpressionKind.Project:
return
child.Projection == null &&
child.Distinct == false;
// Limit and NewInstance are always true
default:
throw new ArgumentException("Unexpected parent expression kind");
}
}
PendingProjectsNode GetInput(DbExpression expression, string childBindingName, string parentBindingName, DbExpressionKind parentKind)
{
var n = VisitInputWithBinding(expression, childBindingName);
if (!IsCompatible(n.Last.Exp, parentKind))
n.Selects.Add(new NameAndInputExpression(parentBindingName, new InputExpression(n.Last.Exp, n.Last.AsName)));
return n;
}
PendingProjectsNode VisitInputWithBinding(DbExpression expression, string bindingName)
{
PendingProjectsNode n;
switch (expression.ExpressionKind)
{
case DbExpressionKind.Scan:
{
var scan = (ScanExpression)expression.Accept(this);
var input = new InputExpression(scan, bindingName);
n = new PendingProjectsNode(bindingName, input);
break;
}
case DbExpressionKind.Filter:
{
var exp = (DbFilterExpression)expression;
n = GetInput(exp.Input.Expression, exp.Input.VariableName, bindingName, expression.ExpressionKind);
EnterExpression(n);
var pred = exp.Predicate.Accept(this);
if (n.Last.Exp.Where == null)
n.Last.Exp.Where = new WhereExpression(pred);
else
n.Last.Exp.Where.And(pred);
LeaveExpression(n);
break;
}
case DbExpressionKind.Sort:
{
var exp = (DbSortExpression)expression;
n = GetInput(exp.Input.Expression, exp.Input.VariableName, bindingName, expression.ExpressionKind);
EnterExpression(n);
n.Last.Exp.OrderBy = new OrderByExpression();
foreach (var order in exp.SortOrder)
n.Last.Exp.OrderBy.AppendSort(order.Expression.Accept(this), order.Ascending);
LeaveExpression(n);
break;
}
case DbExpressionKind.Skip:
{
var exp = (DbSkipExpression)expression;
n = GetInput(exp.Input.Expression, exp.Input.VariableName, bindingName, expression.ExpressionKind);
EnterExpression(n);
n.Last.Exp.OrderBy = new OrderByExpression();
foreach (var order in exp.SortOrder)
n.Last.Exp.OrderBy.AppendSort(order.Expression.Accept(this), order.Ascending);
n.Last.Exp.Skip = new SkipExpression(exp.Count.Accept(this));
LeaveExpression(n);
break;
}
case DbExpressionKind.Distinct:
{
var exp = (DbDistinctExpression)expression;
var childBindingName = NextAlias();
n = VisitInputWithBinding(exp.Argument, childBindingName);
if (!IsCompatible(n.Last.Exp, expression.ExpressionKind))
{
var prev = n.Last.Exp;
var prevName = n.Last.AsName;
var input = new InputExpression(prev, prevName);
n.Selects.Add(new NameAndInputExpression(bindingName, input));
// We need to copy all the projected columns so the DISTINCT keyword will work on the correct columns
// A parent project expression is never compatible with this new expression,
// so these are the columns that finally will be projected, as wanted
foreach (ColumnExpression col in prev.Projection.Arguments)
{
input.ColumnsToProject.Add(new StringPair(prevName, col.Name), col.Name);
input.ProjectNewNames.Add(col.Name);
}
}
n.Last.Exp.Distinct = true;
break;
}
case DbExpressionKind.Limit:
{
var exp = (DbLimitExpression)expression;
n = VisitInputWithBinding(exp.Argument, NextAlias());
if (n.Last.Exp.Limit != null)
{
var least = new FunctionExpression("LEAST");
least.AddArgument(n.Last.Exp.Limit.Arg);
least.AddArgument(exp.Limit.Accept(this));
n.Last.Exp.Limit.Arg = least;
}
else
n.Last.Exp.Limit = new LimitExpression(exp.Limit.Accept(this));
break;
}
case DbExpressionKind.NewInstance:
{
var exp = (DbNewInstanceExpression)expression;
if (exp.Arguments.Count == 1 && exp.Arguments[0].ExpressionKind == DbExpressionKind.Element)
{
n = VisitInputWithBinding(((DbElementExpression)exp.Arguments[0]).Argument, NextAlias());
if (n.Last.Exp.Limit != null)
{
var least = new FunctionExpression("LEAST");
least.AddArgument(n.Last.Exp.Limit.Arg);
least.AddArgument(new LiteralExpression("1"));
n.Last.Exp.Limit.Arg = least;
}
else
n.Last.Exp.Limit = new LimitExpression(new LiteralExpression("1"));
}
else if (exp.Arguments.Count >= 1)
{
var result = new LiteralExpression("(");
for (var i = 0; i < exp.Arguments.Count; ++i)
{
var arg = exp.Arguments[i];
var visitedColumn = arg.Accept(this);
if (!(visitedColumn is ColumnExpression))
visitedColumn = new ColumnExpression(visitedColumn, "C", arg.ResultType);
result.Append(i == 0 ? "SELECT " : " UNION ALL SELECT ");
result.Append(visitedColumn);
}
result.Append(")");
n = new PendingProjectsNode(bindingName, new InputExpression(result, bindingName));
}
else
{
var type = ((CollectionType)exp.ResultType.EdmType).TypeUsage;
var result = new LiteralExpression("(SELECT ");
result.Append(new CastExpression(new LiteralExpression("NULL"), GetDbType(type.EdmType)));
result.Append(" LIMIT 0)");
n = new PendingProjectsNode(bindingName, new InputExpression(result, bindingName));
}
break;
}
case DbExpressionKind.UnionAll:
case DbExpressionKind.Intersect:
case DbExpressionKind.Except:
{
var exp = (DbBinaryExpression)expression;
var expKind = exp.ExpressionKind;
var list = new List<VisitedExpression>();
Action<DbExpression> func = null;
func = e =>
{
if (e.ExpressionKind == expKind && e.ExpressionKind != DbExpressionKind.Except)
{
var binaryExp = (DbBinaryExpression)e;
func(binaryExp.Left);
func(binaryExp.Right);
}
else
list.Add(VisitInputWithBinding(e, bindingName + "_" + list.Count).Last.Exp);
};
func(exp.Left);
func(exp.Right);
var input = new InputExpression(new CombinedProjectionExpression(expression.ExpressionKind, list), bindingName);
n = new PendingProjectsNode(bindingName, input);
break;
}
case DbExpressionKind.Project:
{
var exp = (DbProjectExpression)expression;
var child = VisitInputWithBinding(exp.Input.Expression, exp.Input.VariableName);
var input = child.Last.Exp;
var enterScope = false;
if (!IsCompatible(input, expression.ExpressionKind))
input = new InputExpression(input, child.Last.AsName);
else
enterScope = true;
if (enterScope) EnterExpression(child);
input.Projection = new CommaSeparatedExpression();
var projection = (DbNewInstanceExpression)exp.Projection;
var rowType = (RowType)projection.ResultType.EdmType;
for (var i = 0; i < rowType.Properties.Count && i < projection.Arguments.Count; ++i)
{
var prop = rowType.Properties[i];
var argument = projection.Arguments[i].Accept(this);
var constantArgument = projection.Arguments[i] as DbConstantExpression;
if (constantArgument != null && constantArgument.Value is string)
{
argument = new CastExpression(argument, "varchar");
}
input.Projection.Arguments.Add(new ColumnExpression(argument, prop.Name, prop.TypeUsage));
}
if (enterScope) LeaveExpression(child);
n = new PendingProjectsNode(bindingName, input);
break;
}
case DbExpressionKind.GroupBy:
{
var exp = (DbGroupByExpression)expression;
var child = VisitInputWithBinding(exp.Input.Expression, exp.Input.VariableName);
// I don't know why the input for GroupBy in EF have two names
RefToNode[exp.Input.GroupVariableName] = child;
var input = child.Last.Exp;
var enterScope = false;
if (!IsCompatible(input, expression.ExpressionKind))
input = new InputExpression(input, child.Last.AsName);
else enterScope = true;
if (enterScope) EnterExpression(child);
input.Projection = new CommaSeparatedExpression();
input.GroupBy = new GroupByExpression();
var rowType = (RowType)((CollectionType)exp.ResultType.EdmType).TypeUsage.EdmType;
var columnIndex = 0;
foreach (var key in exp.Keys)
{
var keyColumnExpression = key.Accept(this);
var prop = rowType.Properties[columnIndex];
input.Projection.Arguments.Add(new ColumnExpression(keyColumnExpression, prop.Name, prop.TypeUsage));
// have no idea why EF is generating a group by with a constant expression,
// but postgresql doesn't need it.
if (!(key is DbConstantExpression))
input.GroupBy.AppendGroupingKey(keyColumnExpression);
++columnIndex;
}
foreach (var ag in exp.Aggregates)
{
var function = (DbFunctionAggregate)ag;
var functionExpression = VisitFunction(function);
var prop = rowType.Properties[columnIndex];
input.Projection.Arguments.Add(new ColumnExpression(functionExpression, prop.Name, prop.TypeUsage));
++columnIndex;
}
if (enterScope) LeaveExpression(child);
n = new PendingProjectsNode(bindingName, input);
break;
}
case DbExpressionKind.CrossJoin:
case DbExpressionKind.FullOuterJoin:
case DbExpressionKind.InnerJoin:
case DbExpressionKind.LeftOuterJoin:
case DbExpressionKind.CrossApply:
case DbExpressionKind.OuterApply:
{
var input = new InputExpression();
n = new PendingProjectsNode(bindingName, input);
var from = VisitJoinChildren(expression, input, n);
input.From = from;
break;
}
case DbExpressionKind.Function:
{
var function = (DbFunctionExpression)expression;
var input = new InputExpression(
VisitFunction(function.Function, function.Arguments, function.ResultType), bindingName);
n = new PendingProjectsNode(bindingName, input);
break;
}
default:
throw new NotImplementedException();
}
RefToNode[bindingName] = n;
return n;
}
bool IsJoin(DbExpressionKind kind)
{
switch (kind)
{
case DbExpressionKind.CrossJoin:
case DbExpressionKind.FullOuterJoin:
case DbExpressionKind.InnerJoin:
case DbExpressionKind.LeftOuterJoin:
case DbExpressionKind.CrossApply:
case DbExpressionKind.OuterApply:
return true;
}
return false;
}
JoinExpression VisitJoinChildren(DbExpression expression, InputExpression input, PendingProjectsNode n)
{
DbExpressionBinding left, right;
DbExpression condition = null;
if (expression.ExpressionKind == DbExpressionKind.CrossJoin)
{
left = ((DbCrossJoinExpression)expression).Inputs[0];
right = ((DbCrossJoinExpression)expression).Inputs[1];
if (((DbCrossJoinExpression)expression).Inputs.Count > 2)
{
// I have never seen more than 2 inputs in CrossJoin
throw new NotImplementedException();
}
}
else if (expression.ExpressionKind == DbExpressionKind.CrossApply || expression.ExpressionKind == DbExpressionKind.OuterApply)
{
left = ((DbApplyExpression)expression).Input;
right = ((DbApplyExpression)expression).Apply;
}
else
{
left = ((DbJoinExpression)expression).Left;
right = ((DbJoinExpression)expression).Right;
condition = ((DbJoinExpression)expression).JoinCondition;
}
return VisitJoinChildren(left.Expression, left.VariableName, right.Expression, right.VariableName, expression.ExpressionKind, condition, input, n);
}
JoinExpression VisitJoinChildren(DbExpression left, string leftName, DbExpression right, string rightName, DbExpressionKind joinType, [CanBeNull] DbExpression condition, InputExpression input, PendingProjectsNode n)
{
var join = new JoinExpression { JoinType = joinType };
if (IsJoin(left.ExpressionKind))
join.Left = VisitJoinChildren(left, input, n);
else
{
var l = VisitInputWithBinding(left, leftName);
l.JoinParent = n;
join.Left = new FromExpression(l.Last.Exp, l.Last.AsName);
}
if (joinType == DbExpressionKind.OuterApply || joinType == DbExpressionKind.CrossApply)
{
EnterExpression(n);
var r = VisitInputWithBinding(right, rightName);
LeaveExpression(n);
r.JoinParent = n;
join.Right = new FromExpression(r.Last.Exp, r.Last.AsName) { ForceSubquery = true };
}
else
{
if (IsJoin(right.ExpressionKind))
join.Right = VisitJoinChildren(right, input, n);
else
{
var r = VisitInputWithBinding(right, rightName);
r.JoinParent = n;
join.Right = new FromExpression(r.Last.Exp, r.Last.AsName);
}
}
if (condition != null)
{
EnterExpression(n);
join.Condition = condition.Accept(this);
LeaveExpression(n);
}
return join;
}
public override VisitedExpression Visit([NotNull] DbVariableReferenceExpression expression)
{
//return new VariableReferenceExpression(expression.VariableName, _variableSubstitution);
throw new NotImplementedException();
}
public override VisitedExpression Visit([NotNull] DbUnionAllExpression expression)
{
// Handled by VisitInputWithBinding
throw new NotImplementedException();
}
public override VisitedExpression Visit([NotNull] DbTreatExpression expression)
{
throw new NotImplementedException();
}
public override VisitedExpression Visit([NotNull] DbSkipExpression expression)
{
// Handled by VisitInputWithBinding
throw new NotImplementedException();
}
public override VisitedExpression Visit([NotNull] DbSortExpression expression)
{
// Handled by VisitInputWithBinding
throw new NotImplementedException();
}
public override VisitedExpression Visit([NotNull] DbScanExpression expression)
{
MetadataProperty metadata;
string tableName;
var overrideTable = "http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator:Name";
if (expression.Target.MetadataProperties.TryGetValue(overrideTable, false, out metadata) && metadata.Value != null)
tableName = metadata.Value.ToString();
else if (expression.Target.MetadataProperties.TryGetValue("Table", false, out metadata) && metadata.Value != null)
tableName = metadata.Value.ToString();
else
tableName = expression.Target.Name;
if (expression.Target.MetadataProperties.Contains("DefiningQuery"))
{
var definingQuery = expression.Target.MetadataProperties.GetValue("DefiningQuery", false);
if (definingQuery.Value != null)
return new ScanExpression("(" + definingQuery.Value + ")", expression.Target);
}
ScanExpression scan;
var overrideSchema = "http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator:Schema";
if (expression.Target.MetadataProperties.TryGetValue(overrideSchema, false, out metadata) && metadata.Value != null)
{
var schema = metadata.Value.ToString();
scan = string.IsNullOrEmpty(schema)
? new ScanExpression(QuoteIdentifier(tableName), expression.Target)
: new ScanExpression(QuoteIdentifier(schema) + "." + QuoteIdentifier(tableName), expression.Target);
}
else if (expression.Target.MetadataProperties.TryGetValue("Schema", false, out metadata) && metadata.Value != null)
{
var schema = metadata.Value.ToString();
scan = string.IsNullOrEmpty(schema)
? new ScanExpression(QuoteIdentifier(tableName), expression.Target)
: new ScanExpression(QuoteIdentifier(schema) + "." + QuoteIdentifier(tableName), expression.Target);
}
else
{
var schema = expression.Target.EntityContainer.Name;
scan = string.IsNullOrEmpty(schema)
? new ScanExpression(QuoteIdentifier(tableName), expression.Target)
: new ScanExpression(QuoteIdentifier(schema) + "." + QuoteIdentifier(tableName), expression.Target);
}
return scan;
}
public override VisitedExpression Visit([NotNull] DbRelationshipNavigationExpression expression)
{
throw new NotImplementedException();
}
public override VisitedExpression Visit([NotNull] DbRefExpression expression)
{
throw new NotImplementedException();
}
public override VisitedExpression Visit([NotNull] DbQuantifierExpression expression)
{
// TODO: EXISTS or NOT EXISTS depending on expression.ExpressionKind
// comes with it's built in test (subselect for EXISTS)
// This kind of expression is never even created in the EF6 code base
throw new NotImplementedException();
}
public override VisitedExpression Visit([NotNull] DbProjectExpression expression)
=> VisitInputWithBinding(expression, NextAlias()).Last.Exp;
// use parameter in sql
public override VisitedExpression Visit([NotNull] DbParameterReferenceExpression expression)
=> new LiteralExpression("@" + expression.ParameterName);
public override VisitedExpression Visit([NotNull] DbOrExpression expression)
=> OperatorExpression.Build(Operator.Or, _useNewPrecedences, expression.Left.Accept(this), expression.Right.Accept(this));
public override VisitedExpression Visit([NotNull] DbOfTypeExpression expression)
{
throw new NotImplementedException();
}
// select does something different here. But insert, update, delete, and functions can just use
// a NULL literal.
public override VisitedExpression Visit([NotNull] DbNullExpression expression)
=> new LiteralExpression("NULL");
// argument can be a "NOT EXISTS" or similar operator that can be negated.
// Convert the not if that's the case
public override VisitedExpression Visit([NotNull] DbNotExpression expression)
=> OperatorExpression.Negate(expression.Argument.Accept(this), _useNewPrecedences);
// Handled by VisitInputWithBinding
public override VisitedExpression Visit([NotNull] DbNewInstanceExpression expression)
{
throw new NotImplementedException();
}
public override VisitedExpression Visit([NotNull] DbLimitExpression expression)
{
// Normally handled by VisitInputWithBinding
// Otherwise, it is (probably) a child of a DbElementExpression,
// in which case the child of this expression might be a DbProjectExpression,
// then the correct columns will be projected since Limit is compatible with the result of a DbProjectExpression,
// which will result in having a Projection on the node after visiting it.
var node = VisitInputWithBinding(expression, NextAlias());
if (node.Last.Exp.Projection == null)
{
// This DbLimitExpression is (probably) a child of DbElementExpression
// and this expression's child is not a DbProjectExpression, but we should
// find a DbProjectExpression if we look deeper in the command tree.
// The child of this expression is (probably) a DbSortExpression or something else
// that will (probably) be an ancestor to a DbProjectExpression.
// Since this is (probably) a child of DbElementExpression, we want the first column,
// so make sure it is propagated from the nearest explicit projection.
var projection = node.Selects[0].Exp.Projection;
for (var i = 1; i < node.Selects.Count; i++)
{
var column = (ColumnExpression)projection.Arguments[0];
node.Selects[i].Exp.ColumnsToProject[new StringPair(node.Selects[i - 1].AsName, column.Name)] = column.Name;
}
}
return node.Last.Exp;
}
// LIKE keyword
public override VisitedExpression Visit([NotNull] DbLikeExpression expression)
=> OperatorExpression.Build(Operator.Like, _useNewPrecedences, expression.Argument.Accept(this), expression.Pattern.Accept(this));
public override VisitedExpression Visit([NotNull] DbJoinExpression expression)
{
// Handled by VisitInputWithBinding
throw new NotImplementedException();
}
public override VisitedExpression Visit([NotNull] DbIsOfExpression expression)
{
throw new NotImplementedException();
}
public override VisitedExpression Visit([NotNull] DbIsNullExpression expression)
=> OperatorExpression.Build(Operator.IsNull, _useNewPrecedences, expression.Argument.Accept(this));
// NOT EXISTS
public override VisitedExpression Visit([NotNull] DbIsEmptyExpression expression)
=> OperatorExpression.Negate(new ExistsExpression(expression.Argument.Accept(this)), _useNewPrecedences);
public override VisitedExpression Visit([NotNull] DbIntersectExpression expression)
{
// INTERSECT keyword
// Handled by VisitInputWithBinding
throw new NotImplementedException();
}
// Normally handled by VisitInputWithBinding
// Otherwise, it is (probably) a child of a DbElementExpression.
// Group by always projects the correct columns.
public override VisitedExpression Visit([NotNull] DbGroupByExpression expression)
=> VisitInputWithBinding(expression, NextAlias()).Last.Exp;
public override VisitedExpression Visit([NotNull] DbRefKeyExpression expression)
{
throw new NotImplementedException();
}
public override VisitedExpression Visit([NotNull] DbEntityRefExpression expression)
{
throw new NotImplementedException();
}
// a function call
// may be built in, canonical, or user defined
public override VisitedExpression Visit([NotNull] DbFunctionExpression expression)
=> VisitFunction(expression.Function, expression.Arguments, expression.ResultType);
public override VisitedExpression Visit([NotNull] DbFilterExpression expression)
{
// Handled by VisitInputWithBinding
throw new NotImplementedException();
}
public override VisitedExpression Visit([NotNull] DbExceptExpression expression)
{
// EXCEPT keyword
// Handled by VisitInputWithBinding
throw new NotImplementedException();
}
public override VisitedExpression Visit([NotNull] DbElementExpression expression)
{
// If child of DbNewInstanceExpression, this is handled in VisitInputWithBinding
// a scalar expression (ie ExecuteScalar)
// so it will likely be translated into a select
//throw new NotImplementedException();
var scalar = new LiteralExpression("(");
scalar.Append(expression.Argument.Accept(this));
scalar.Append(")");
return scalar;
}
public override VisitedExpression Visit([NotNull] DbDistinctExpression expression)
{
// Handled by VisitInputWithBinding
throw new NotImplementedException();
}
public override VisitedExpression Visit([NotNull] DbDerefExpression expression)
{
throw new NotImplementedException();
}
public override VisitedExpression Visit([NotNull] DbCrossJoinExpression expression)
{
// join without ON
// Handled by VisitInputWithBinding
throw new NotImplementedException();
}
public override VisitedExpression Visit([NotNull] DbConstantExpression expression)
{
if (CreateParametersForConstants)
{
var parameter = new NpgsqlParameter
{
ParameterName = "p_" + ParameterCount++,
NpgsqlDbType = NpgsqlProviderManifest.GetNpgsqlDbType(((PrimitiveType)expression.ResultType.EdmType).PrimitiveTypeKind),
Value = expression.Value
};
Command.Parameters.Add(parameter);
return new LiteralExpression("@" + parameter.ParameterName);
}
return new ConstantExpression(expression.Value, expression.ResultType);
}
public override VisitedExpression Visit([NotNull] DbComparisonExpression expression)
{
Operator comparisonOperator;
switch (expression.ExpressionKind)
{
case DbExpressionKind.Equals: comparisonOperator = Operator.Equals; break;
case DbExpressionKind.GreaterThan: comparisonOperator = Operator.GreaterThan; break;
case DbExpressionKind.GreaterThanOrEquals: comparisonOperator = Operator.GreaterThanOrEquals; break;
case DbExpressionKind.LessThan: comparisonOperator = Operator.LessThan; break;
case DbExpressionKind.LessThanOrEquals: comparisonOperator = Operator.LessThanOrEquals; break;
case DbExpressionKind.Like: comparisonOperator = Operator.Like; break;
case DbExpressionKind.NotEquals: comparisonOperator = Operator.NotEquals; break;
default: throw new NotSupportedException();
}
return OperatorExpression.Build(comparisonOperator, _useNewPrecedences, expression.Left.Accept(this), expression.Right.Accept(this));
}
public override VisitedExpression Visit([NotNull] DbCastExpression expression)
=> new CastExpression(expression.Argument.Accept(this), GetDbType(expression.ResultType.EdmType));
protected string GetDbType(EdmType edmType)
{
var primitiveType = edmType as PrimitiveType;
if (primitiveType == null)
throw new NotSupportedException();
switch (primitiveType.PrimitiveTypeKind)
{
case PrimitiveTypeKind.Boolean:
return "bool";
case PrimitiveTypeKind.SByte:
case PrimitiveTypeKind.Byte:
case PrimitiveTypeKind.Int16:
return "int2";
case PrimitiveTypeKind.Int32:
return "int4";
case PrimitiveTypeKind.Int64:
return "int8";
case PrimitiveTypeKind.String:
return "text";
case PrimitiveTypeKind.Decimal:
return "numeric";
case PrimitiveTypeKind.Single:
return "float4";
case PrimitiveTypeKind.Double:
return "float8";
case PrimitiveTypeKind.DateTime:
return "timestamp";
case PrimitiveTypeKind.DateTimeOffset:
return "timestamptz";
case PrimitiveTypeKind.Time:
return "interval";
case PrimitiveTypeKind.Binary:
return "bytea";
case PrimitiveTypeKind.Guid:
return "uuid";
}
throw new NotSupportedException();
}
public override VisitedExpression Visit([NotNull] DbCaseExpression expression)
{
var caseExpression = new LiteralExpression(" CASE ");
for (var i = 0; i < expression.When.Count && i < expression.Then.Count; ++i)
{
caseExpression.Append(" WHEN (");
caseExpression.Append(expression.When[i].Accept(this));
caseExpression.Append(") THEN (");
caseExpression.Append(expression.Then[i].Accept(this));
caseExpression.Append(")");
}
if (expression.Else is DbNullExpression)
caseExpression.Append(" END ");
else
{
caseExpression.Append(" ELSE (");
caseExpression.Append(expression.Else.Accept(this));
caseExpression.Append(") END ");
}
return caseExpression;
}
public override VisitedExpression Visit([NotNull] DbArithmeticExpression expression)
{
Operator arithmeticOperator;
switch (expression.ExpressionKind)
{
case DbExpressionKind.Divide:
arithmeticOperator = Operator.Div;
break;
case DbExpressionKind.Minus:
arithmeticOperator = Operator.Sub;
break;
case DbExpressionKind.Modulo:
arithmeticOperator = Operator.Mod;
break;
case DbExpressionKind.Multiply:
arithmeticOperator = Operator.Mul;
break;
case DbExpressionKind.Plus:
arithmeticOperator = Operator.Add;
break;
case DbExpressionKind.UnaryMinus:
arithmeticOperator = Operator.UnaryMinus;
break;
default:
throw new NotSupportedException();
}
if (expression.ExpressionKind == DbExpressionKind.UnaryMinus)
{
Debug.Assert(expression.Arguments.Count == 1);
return OperatorExpression.Build(arithmeticOperator, _useNewPrecedences, expression.Arguments[0].Accept(this));
}
Debug.Assert(expression.Arguments.Count == 2);
return OperatorExpression.Build(arithmeticOperator, _useNewPrecedences, expression.Arguments[0].Accept(this), expression.Arguments[1].Accept(this));
}
public override VisitedExpression Visit([NotNull] DbApplyExpression expression)
{
// like a join, but used when the right hand side (the Apply part) is a function.
// it lets you return the results of a function call given values from the
// left hand side (the Input part).
// sql standard is lateral join
// Handled by VisitInputWithBinding
throw new NotImplementedException();
}
public override VisitedExpression Visit([NotNull] DbAndExpression expression)
=> OperatorExpression.Build(Operator.And, _useNewPrecedences, expression.Left.Accept(this), expression.Right.Accept(this));
public override VisitedExpression Visit([NotNull] DbExpression expression)
{
// only concrete types visited
throw new NotSupportedException();
}
public abstract void BuildCommand(DbCommand command);
internal static string QuoteIdentifier(string identifier)
=> "\"" + identifier.Replace("\"", "\"\"") + "\"";
VisitedExpression VisitFunction(DbFunctionAggregate functionAggregate)
{
if (functionAggregate.Function.NamespaceName == "Edm")
{
FunctionExpression aggregate;
try
{
aggregate = new FunctionExpression(AggregateFunctionNames[functionAggregate.Function.Name]);
}
catch (KeyNotFoundException)
{
throw new NotSupportedException();
}
Debug.Assert(functionAggregate.Arguments.Count == 1);
VisitedExpression aggregateArg;
if (functionAggregate.Distinct)
{
aggregateArg = new LiteralExpression("DISTINCT ");
((LiteralExpression)aggregateArg).Append(functionAggregate.Arguments[0].Accept(this));
}
else
{
aggregateArg = functionAggregate.Arguments[0].Accept(this);
}
aggregate.AddArgument(aggregateArg);
return new CastExpression(aggregate, GetDbType(functionAggregate.ResultType.EdmType));
}
throw new NotSupportedException();
}
VisitedExpression VisitFunction(EdmFunction function, IList<DbExpression> args, TypeUsage resultType)
{
if (function.NamespaceName == "Edm")
{
VisitedExpression arg;
switch (function.Name)
{
// string functions
case "Concat":
Debug.Assert(args.Count == 2);
return OperatorExpression.Build(Operator.Concat, _useNewPrecedences, args[0].Accept(this), args[1].Accept(this));
case "Contains":
Debug.Assert(args.Count == 2);
var contains = new FunctionExpression("position");
arg = args[1].Accept(this);
arg.Append(" in ");
arg.Append(args[0].Accept(this));
contains.AddArgument(arg);
// if position returns zero, then contains is false
return OperatorExpression.Build(Operator.GreaterThan, _useNewPrecedences, contains, new LiteralExpression("0"));
// case "EndsWith": - depends on a reverse function to be able to implement with parameterized queries
case "IndexOf":
Debug.Assert(args.Count == 2);
var indexOf = new FunctionExpression("position");
arg = args[0].Accept(this);
arg.Append(" in ");
arg.Append(args[1].Accept(this));
indexOf.AddArgument(arg);
return indexOf;
case "Left":
Debug.Assert(args.Count == 2);
return Substring(args[0].Accept(this), new LiteralExpression(" 1 "), args[1].Accept(this));
case "Length":
var length = new FunctionExpression("char_length");
Debug.Assert(args.Count == 1);
length.AddArgument(args[0].Accept(this));
return new CastExpression(length, GetDbType(resultType.EdmType));
case "LTrim":
return StringModifier("ltrim", args);
case "Replace":
var replace = new FunctionExpression("replace");
Debug.Assert(args.Count == 3);
replace.AddArgument(args[0].Accept(this));
replace.AddArgument(args[1].Accept(this));
replace.AddArgument(args[2].Accept(this));
return replace;
// case "Reverse":
case "Right":
Debug.Assert(args.Count == 2);
{
var arg0 = args[0].Accept(this);
var arg1 = args[1].Accept(this);
var start = new FunctionExpression("char_length");
start.AddArgument(arg0);