-
-
Notifications
You must be signed in to change notification settings - Fork 523
Expand file tree
/
Copy pathCompiler.cs
More file actions
1082 lines (840 loc) · 34 KB
/
Compiler.cs
File metadata and controls
1082 lines (840 loc) · 34 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace SqlKata.Compilers
{
public partial class Compiler
{
private readonly ConditionsCompilerProvider _compileConditionMethodsProvider;
protected virtual string parameterPlaceholder { get; set; } = "?";
protected virtual string parameterPrefix { get; set; } = "@p";
protected virtual string OpeningIdentifier { get; set; } = "\"";
protected virtual string ClosingIdentifier { get; set; } = "\"";
protected virtual string ColumnAsKeyword { get; set; } = "AS ";
protected virtual string TableAsKeyword { get; set; } = "AS ";
protected virtual string LastId { get; set; } = "";
protected virtual string EscapeCharacter { get; set; } = "\\";
protected virtual string SingleInsertStartClause { get; set; } = "INSERT INTO";
protected virtual string MultiInsertStartClause { get; set; } = "INSERT INTO";
protected Compiler()
{
_compileConditionMethodsProvider = new ConditionsCompilerProvider(this);
}
public virtual string EngineCode { get; }
/// <summary>
/// Whether the compiler supports the `SELECT ... FILTER` syntax
/// </summary>
/// <value></value>
public virtual bool SupportsFilterClause { get; set; } = false;
/// <summary>
/// If true the compiler will remove the SELECT clause for the query used inside WHERE EXISTS
/// </summary>
/// <value></value>
public virtual bool OmitSelectInsideExists { get; set; } = true;
protected virtual string SingleRowDummyTableName { get => null; }
/// <summary>
/// A list of white-listed operators
/// </summary>
/// <value></value>
protected readonly HashSet<string> operators = new HashSet<string>
{
"=", "<", ">", "<=", ">=", "<>", "!=", "<=>",
"like", "not like",
"ilike", "not ilike",
"like binary", "not like binary",
"rlike", "not rlike",
"regexp", "not regexp",
"similar to", "not similar to"
};
protected HashSet<string> userOperators = new HashSet<string>
{
};
protected (string Name,object Variable)[] generateNamedBindingsArray(object[] bindings)
{
return Helper.Flatten(bindings).Select((v, i) =>
{
if (v is NamedParameterVariable param)
{
return (param.Variable, param.Value);
}
return (parameterPrefix + i, v);
}).ToArray();
}
protected Dictionary<string, object> generateNamedBindings((string, object)[] bindings)
{
var dictionary = new Dictionary<string, object>();
foreach (var (name, variable) in bindings)
{
dictionary.TryAdd(name, variable);
}
return dictionary;
}
protected SqlResult PrepareResult(SqlResult ctx)
{
var bindings = generateNamedBindingsArray(ctx.Bindings.ToArray());
ctx.NamedBindings = generateNamedBindings(bindings);
ctx.Sql = Helper.ReplaceAll(ctx.RawSql, parameterPlaceholder, EscapeCharacter, i => bindings[i].Name);
return ctx;
}
private Query TransformAggregateQuery(Query query)
{
var clause = query.GetOneComponent<AggregateClause>("aggregate", EngineCode);
if (clause.Columns.Count == 1 && !query.IsDistinct) return query;
if (query.IsDistinct)
{
query.ClearComponent("aggregate", EngineCode);
query.ClearComponent("select", EngineCode);
query.Select(clause.Columns.ToArray());
}
else
{
foreach (var column in clause.Columns)
{
query.WhereNotNull(column);
}
}
var outerClause = new AggregateClause()
{
Columns = new List<string> { "*" },
Type = clause.Type
};
return new Query()
.AddComponent("aggregate", outerClause)
.From(query, $"{clause.Type}Query");
}
protected virtual SqlResult CompileRaw(Query query)
{
SqlResult ctx;
if (query.Method == "insert")
{
ctx = CompileInsertQuery(query);
}
else if (query.Method == "update")
{
ctx = CompileUpdateQuery(query);
}
else if (query.Method == "delete")
{
ctx = CompileDeleteQuery(query);
}
else
{
if (query.Method == "aggregate")
{
query.ClearComponent("limit")
.ClearComponent("order")
.ClearComponent("group");
query = TransformAggregateQuery(query);
}
ctx = CompileSelectQuery(query);
}
// handle CTEs
if (query.HasComponent("cte", EngineCode))
{
ctx = CompileCteQuery(ctx, query);
}
ctx.RawSql = Helper.ExpandParameters(ctx.RawSql, parameterPlaceholder, EscapeCharacter, ctx.Bindings.ToArray());
return ctx;
}
/// <summary>
/// Add the passed operator(s) to the white list so they can be used with
/// the Where/Having methods, this prevent passing arbitrary operators
/// that opens the door for SQL injections.
/// </summary>
/// <param name="operators"></param>
/// <returns></returns>
public Compiler Whitelist(params string[] operators)
{
foreach (var op in operators)
{
this.userOperators.Add(op);
}
return this;
}
public virtual SqlResult Compile(Query query)
{
var ctx = CompileRaw(query);
ctx = PrepareResult(ctx);
return ctx;
}
public virtual SqlResult Compile(IEnumerable<Query> queries)
{
var compiled = queries.Select(CompileRaw).ToArray();
var bindings = compiled.Select(r => r.Bindings).ToArray();
var totalBindingsCount = bindings.Select(b => b.Count).Aggregate((a, b) => a + b);
var combinedBindings = new List<object>(totalBindingsCount);
foreach (var cb in bindings)
{
combinedBindings.AddRange(cb);
}
var ctx = new SqlResult(parameterPlaceholder, EscapeCharacter)
{
RawSql = compiled.Select(r => r.RawSql).Aggregate((a, b) => a + ";\n" + b),
Bindings = combinedBindings,
};
ctx = PrepareResult(ctx);
return ctx;
}
protected virtual SqlResult CompileSelectQuery(Query query)
{
var ctx = new SqlResult(parameterPlaceholder, EscapeCharacter)
{
Query = query.Clone(),
};
var results = new[] {
this.CompileColumns(ctx),
this.CompileFrom(ctx),
this.CompileJoins(ctx),
this.CompileWheres(ctx),
this.CompileGroups(ctx),
this.CompileHaving(ctx),
this.CompileOrders(ctx),
this.CompileLimit(ctx),
this.CompileUnion(ctx),
}
.Where(x => x != null)
.Where(x => !string.IsNullOrEmpty(x))
.ToList();
string sql = string.Join(" ", results);
ctx.RawSql = sql;
return ctx;
}
protected virtual SqlResult CompileAdHocQuery(AdHocTableFromClause adHoc)
{
var ctx = new SqlResult(parameterPlaceholder, EscapeCharacter);
var row = "SELECT " + string.Join(", ", adHoc.Columns.Select(col => $"{parameterPlaceholder} AS {Wrap(col)}"));
var fromTable = SingleRowDummyTableName;
if (fromTable != null)
{
row += $" FROM {fromTable}";
}
var rows = string.Join(" UNION ALL ", Enumerable.Repeat(row, adHoc.Values.Count / adHoc.Columns.Count));
ctx.RawSql = rows;
ctx.Bindings = adHoc.Values;
return ctx;
}
protected virtual SqlResult CompileDeleteQuery(Query query)
{
var ctx = new SqlResult(parameterPlaceholder, EscapeCharacter)
{
Query = query
};
if (!ctx.Query.HasComponent("from", EngineCode))
{
throw new InvalidOperationException("No table set to delete");
}
var fromClause = ctx.Query.GetOneComponent<AbstractFrom>("from", EngineCode);
string table = null;
if (fromClause is FromClause fromClauseCast)
{
table = Wrap(fromClauseCast.Table);
}
if (fromClause is RawFromClause rawFromClause)
{
table = WrapIdentifiers(rawFromClause.Expression);
ctx.Bindings.AddRange(rawFromClause.Bindings);
}
if (table is null)
{
throw new InvalidOperationException("Invalid table expression");
}
var joins = CompileJoins(ctx);
var where = CompileWheres(ctx);
if (!string.IsNullOrEmpty(where))
{
where = " " + where;
}
if (string.IsNullOrEmpty(joins))
{
ctx.RawSql = $"DELETE FROM {table}{where}";
}
else
{
// check if we have alias
if (fromClause is FromClause && !string.IsNullOrEmpty(fromClause.Alias))
{
ctx.RawSql = $"DELETE {Wrap(fromClause.Alias)} FROM {table} {joins}{where}";
}
else
{
ctx.RawSql = $"DELETE {table} FROM {table} {joins}{where}";
}
}
return ctx;
}
protected virtual SqlResult CompileUpdateQuery(Query query)
{
var ctx = new SqlResult(parameterPlaceholder, EscapeCharacter)
{
Query = query
};
if (!ctx.Query.HasComponent("from", EngineCode))
{
throw new InvalidOperationException("No table set to update");
}
var fromClause = ctx.Query.GetOneComponent<AbstractFrom>("from", EngineCode);
string table = null;
if (fromClause is FromClause fromClauseCast)
{
table = Wrap(fromClauseCast.Table);
}
if (fromClause is RawFromClause rawFromClause)
{
table = WrapIdentifiers(rawFromClause.Expression);
ctx.Bindings.AddRange(rawFromClause.Bindings);
}
if (table is null)
{
throw new InvalidOperationException("Invalid table expression");
}
// check for increment statements
var clause = ctx.Query.GetOneComponent("update", EngineCode);
string wheres;
if (clause != null && clause is IncrementClause increment)
{
var column = Wrap(increment.Column);
var value = Parameter(ctx, Math.Abs(increment.Value));
var sign = increment.Value >= 0 ? "+" : "-";
wheres = CompileWheres(ctx);
if (!string.IsNullOrEmpty(wheres))
{
wheres = " " + wheres;
}
ctx.RawSql = $"UPDATE {table} SET {column} = {column} {sign} {value}{wheres}";
return ctx;
}
var toUpdate = ctx.Query.GetOneComponent<InsertClause>("update", EngineCode);
var parts = new List<string>();
for (var i = 0; i < toUpdate.Columns.Count; i++)
{
parts.Add(Wrap(toUpdate.Columns[i]) + " = " + Parameter(ctx, toUpdate.Values[i]));
}
var sets = string.Join(", ", parts);
wheres = CompileWheres(ctx);
if (!string.IsNullOrEmpty(wheres))
{
wheres = " " + wheres;
}
ctx.RawSql = $"UPDATE {table} SET {sets}{wheres}";
return ctx;
}
protected virtual SqlResult CompileInsertQuery(Query query)
{
var ctx = new SqlResult(parameterPlaceholder, EscapeCharacter)
{
Query = query
};
if (!ctx.Query.HasComponent("from", EngineCode))
throw new InvalidOperationException("No table set to insert");
var fromClause = ctx.Query.GetOneComponent<AbstractFrom>("from", EngineCode);
if (fromClause is null)
throw new InvalidOperationException("Invalid table expression");
string table = null;
if (fromClause is FromClause fromClauseCast)
table = Wrap(fromClauseCast.Table);
if (fromClause is RawFromClause rawFromClause)
{
table = WrapIdentifiers(rawFromClause.Expression);
ctx.Bindings.AddRange(rawFromClause.Bindings);
}
if (table is null)
throw new InvalidOperationException("Invalid table expression");
var inserts = ctx.Query.GetComponents<AbstractInsertClause>("insert", EngineCode);
if (inserts[0] is InsertQueryClause insertQueryClause)
return CompileInsertQueryClause(ctx, table, insertQueryClause);
else
return CompileValueInsertClauses(ctx, table, inserts.Cast<InsertClause>());
}
protected virtual SqlResult CompileInsertQueryClause(
SqlResult ctx, string table, InsertQueryClause clause)
{
string columns = GetInsertColumnsList(clause.Columns);
var subCtx = CompileSelectQuery(clause.Query);
ctx.Bindings.AddRange(subCtx.Bindings);
ctx.RawSql = $"{SingleInsertStartClause} {table}{columns} {subCtx.RawSql}";
return ctx;
}
protected virtual SqlResult CompileValueInsertClauses(
SqlResult ctx, string table, IEnumerable<InsertClause> insertClauses)
{
bool isMultiValueInsert = insertClauses.Skip(1).Any();
var insertInto = (isMultiValueInsert) ? MultiInsertStartClause : SingleInsertStartClause;
var firstInsert = insertClauses.First();
string columns = GetInsertColumnsList(firstInsert.Columns);
var values = string.Join(", ", Parameterize(ctx, firstInsert.Values));
ctx.RawSql = $"{insertInto} {table}{columns} VALUES ({values})";
if (isMultiValueInsert)
return CompileRemainingInsertClauses(ctx, table, insertClauses);
if (firstInsert.ReturnId && !string.IsNullOrEmpty(LastId))
ctx.RawSql += ";" + LastId;
return ctx;
}
protected virtual SqlResult CompileRemainingInsertClauses(SqlResult ctx, string table, IEnumerable<InsertClause> inserts)
{
foreach (var insert in inserts.Skip(1))
{
string values = string.Join(", ", Parameterize(ctx, insert.Values));
ctx.RawSql += $", ({values})";
}
return ctx;
}
protected string GetInsertColumnsList(List<string> columnList)
{
var columns = "";
if (columnList.Any())
columns = $" ({string.Join(", ", WrapArray(columnList))})";
return columns;
}
protected virtual SqlResult CompileCteQuery(SqlResult ctx, Query query)
{
var cteFinder = new CteFinder(query, EngineCode);
var cteSearchResult = cteFinder.Find();
var rawSql = new StringBuilder("WITH ");
var cteBindings = new List<object>();
foreach (var cte in cteSearchResult)
{
var cteCtx = CompileCte(cte);
cteBindings.AddRange(cteCtx.Bindings);
rawSql.Append(cteCtx.RawSql.Trim());
rawSql.Append(",\n");
}
rawSql.Length -= 2; // remove last comma
rawSql.Append('\n');
rawSql.Append(ctx.RawSql);
ctx.Bindings.InsertRange(0, cteBindings);
ctx.RawSql = rawSql.ToString();
return ctx;
}
/// <summary>
/// Compile a single column clause
/// </summary>
/// <param name="ctx"></param>
/// <param name="column"></param>
/// <returns></returns>
public virtual string CompileColumn(SqlResult ctx, AbstractColumn column)
{
if (column is RawColumn raw)
{
ctx.Bindings.AddRange(raw.Bindings);
return WrapIdentifiers(raw.Expression);
}
if (column is QueryColumn queryColumn)
{
var alias = "";
if (!string.IsNullOrWhiteSpace(queryColumn.Query.QueryAlias))
{
alias = $" {ColumnAsKeyword}{WrapValue(queryColumn.Query.QueryAlias)}";
}
var subCtx = CompileSelectQuery(queryColumn.Query);
ctx.Bindings.AddRange(subCtx.Bindings);
return "(" + subCtx.RawSql + $"){alias}";
}
if (column is AggregatedColumn aggregatedColumn)
{
string agg = aggregatedColumn.Aggregate.ToUpperInvariant();
var (col, alias) = SplitAlias(CompileColumn(ctx, aggregatedColumn.Column));
alias = string.IsNullOrEmpty(alias) ? "" : $" {ColumnAsKeyword}{alias}";
string filterCondition = CompileFilterConditions(ctx, aggregatedColumn);
if (string.IsNullOrEmpty(filterCondition))
{
return $"{agg}({col}){alias}";
}
if (SupportsFilterClause)
{
return $"{agg}({col}) FILTER (WHERE {filterCondition}){alias}";
}
return $"{agg}(CASE WHEN {filterCondition} THEN {col} END){alias}";
}
return Wrap((column as Column).Name);
}
protected virtual string CompileFilterConditions(SqlResult ctx, AggregatedColumn aggregatedColumn)
{
if (aggregatedColumn.Filter == null)
{
return null;
}
var wheres = aggregatedColumn.Filter.GetComponents<AbstractCondition>("where");
return CompileConditions(ctx, wheres);
}
public virtual SqlResult CompileCte(AbstractFrom cte)
{
var ctx = new SqlResult(parameterPlaceholder, EscapeCharacter);
if (null == cte)
{
return ctx;
}
if (cte is RawFromClause raw)
{
ctx.Bindings.AddRange(raw.Bindings);
ctx.RawSql = $"{WrapValue(raw.Alias)} AS ({WrapIdentifiers(raw.Expression)})";
}
else if (cte is QueryFromClause queryFromClause)
{
var subCtx = CompileSelectQuery(queryFromClause.Query);
ctx.Bindings.AddRange(subCtx.Bindings);
ctx.RawSql = $"{WrapValue(queryFromClause.Alias)} AS ({subCtx.RawSql})";
}
else if (cte is AdHocTableFromClause adHoc)
{
var subCtx = CompileAdHocQuery(adHoc);
ctx.Bindings.AddRange(subCtx.Bindings);
ctx.RawSql = $"{WrapValue(adHoc.Alias)} AS ({subCtx.RawSql})";
}
return ctx;
}
protected virtual SqlResult OnBeforeSelect(SqlResult ctx)
{
return ctx;
}
protected virtual string CompileColumns(SqlResult ctx)
{
if (ctx.Query.HasComponent("aggregate", EngineCode))
{
var aggregate = ctx.Query.GetOneComponent<AggregateClause>("aggregate", EngineCode);
var aggregateColumns = aggregate.Columns
.Select(x => CompileColumn(ctx, new Column { Name = x }))
.ToList();
string sql = string.Empty;
if (aggregateColumns.Count == 1)
{
sql = string.Join(", ", aggregateColumns);
if (ctx.Query.IsDistinct)
{
sql = "DISTINCT " + sql;
}
return "SELECT " + aggregate.Type.ToUpperInvariant() + "(" + sql + $") {ColumnAsKeyword}" + WrapValue(aggregate.Type);
}
return "SELECT 1";
}
var columns = ctx.Query
.GetComponents<AbstractColumn>("select", EngineCode)
.Select(x => CompileColumn(ctx, x))
.ToList();
var distinct = ctx.Query.IsDistinct ? "DISTINCT " : "";
var select = columns.Any() ? string.Join(", ", columns) : "*";
return $"SELECT {distinct}{select}";
}
public virtual string CompileUnion(SqlResult ctx)
{
// Handle UNION, EXCEPT and INTERSECT
if (!ctx.Query.GetComponents("combine", EngineCode).Any())
{
return null;
}
var combinedQueries = new List<string>();
var clauses = ctx.Query.GetComponents<AbstractCombine>("combine", EngineCode);
foreach (var clause in clauses)
{
if (clause is Combine combineClause)
{
var combineOperator = combineClause.Operation.ToUpperInvariant() + " " + (combineClause.All ? "ALL " : "");
var subCtx = CompileSelectQuery(combineClause.Query);
ctx.Bindings.AddRange(subCtx.Bindings);
combinedQueries.Add($"{combineOperator}{subCtx.RawSql}");
}
else
{
var combineRawClause = clause as RawCombine;
ctx.Bindings.AddRange(combineRawClause.Bindings);
combinedQueries.Add(WrapIdentifiers(combineRawClause.Expression));
}
}
return string.Join(" ", combinedQueries);
}
public virtual string CompileTableExpression(SqlResult ctx, AbstractFrom from)
{
if (from is RawFromClause raw)
{
ctx.Bindings.AddRange(raw.Bindings);
return WrapIdentifiers(raw.Expression);
}
if (from is QueryFromClause queryFromClause)
{
var fromQuery = queryFromClause.Query;
var alias = string.IsNullOrEmpty(fromQuery.QueryAlias) ? "" : $" {TableAsKeyword}" + WrapValue(fromQuery.QueryAlias);
var subCtx = CompileSelectQuery(fromQuery);
ctx.Bindings.AddRange(subCtx.Bindings);
return "(" + subCtx.RawSql + ")" + alias;
}
if (from is FromClause fromClause)
{
return Wrap(fromClause.Table);
}
throw InvalidClauseException("TableExpression", from);
}
public virtual string CompileFrom(SqlResult ctx)
{
if (ctx.Query.HasComponent("from", EngineCode))
{
var from = ctx.Query.GetOneComponent<AbstractFrom>("from", EngineCode);
return "FROM " + CompileTableExpression(ctx, from);
}
return string.Empty;
}
public virtual string CompileJoins(SqlResult ctx)
{
if (!ctx.Query.HasComponent("join", EngineCode))
{
return null;
}
var joins = ctx.Query
.GetComponents<BaseJoin>("join", EngineCode)
.Select(x => CompileJoin(ctx, x.Join));
return "\n" + string.Join("\n", joins);
}
public virtual string CompileJoin(SqlResult ctx, Join join, bool isNested = false)
{
var from = join.GetOneComponent<AbstractFrom>("from", EngineCode);
var conditions = join.GetComponents<AbstractCondition>("where", EngineCode);
var joinTable = CompileTableExpression(ctx, from);
var constraints = CompileConditions(ctx, conditions);
var onClause = conditions.Any() ? $" ON {constraints}" : "";
return $"{join.Type} {joinTable}{onClause}";
}
public virtual string CompileWheres(SqlResult ctx)
{
if (!ctx.Query.HasComponent("where", EngineCode))
{
return null;
}
var conditions = ctx.Query.GetComponents<AbstractCondition>("where", EngineCode);
var sql = CompileConditions(ctx, conditions).Trim();
return string.IsNullOrEmpty(sql) ? null : $"WHERE {sql}";
}
public virtual string CompileGroups(SqlResult ctx)
{
if (!ctx.Query.HasComponent("group", EngineCode))
{
return null;
}
var columns = ctx.Query
.GetComponents<AbstractColumn>("group", EngineCode)
.Select(x => CompileColumn(ctx, x));
return "GROUP BY " + string.Join(", ", columns);
}
public virtual string CompileOrders(SqlResult ctx)
{
if (!ctx.Query.HasComponent("order", EngineCode))
{
return null;
}
var columns = ctx.Query
.GetComponents<AbstractOrderBy>("order", EngineCode)
.Select(x =>
{
if (x is RawOrderBy raw)
{
ctx.Bindings.AddRange(raw.Bindings);
return WrapIdentifiers(raw.Expression);
}
var direction = (x as OrderBy).Ascending ? "" : " DESC";
return Wrap((x as OrderBy).Column) + direction;
});
return "ORDER BY " + string.Join(", ", columns);
}
public virtual string CompileHaving(SqlResult ctx)
{
if (!ctx.Query.HasComponent("having", EngineCode))
{
return null;
}
var sql = new List<string>();
string boolOperator;
var having = ctx.Query.GetComponents("having", EngineCode)
.Cast<AbstractCondition>()
.ToList();
for (var i = 0; i < having.Count; i++)
{
var compiled = CompileCondition(ctx, having[i]);
if (!string.IsNullOrEmpty(compiled))
{
boolOperator = i > 0 ? having[i].IsOr ? "OR " : "AND " : "";
sql.Add(boolOperator + compiled);
}
}
return $"HAVING {string.Join(" ", sql)}";
}
public virtual string CompileLimit(SqlResult ctx)
{
var limit = ctx.Query.GetLimit(EngineCode);
var offset = ctx.Query.GetOffset(EngineCode);
if (limit == 0 && offset == 0)
{
return null;
}
if (offset == 0)
{
ctx.Bindings.Add(limit);
return $"LIMIT {parameterPlaceholder}";
}
if (limit == 0)
{
ctx.Bindings.Add(offset);
return $"OFFSET {parameterPlaceholder}";
}
ctx.Bindings.Add(limit);
ctx.Bindings.Add(offset);
return $"LIMIT {parameterPlaceholder} OFFSET {parameterPlaceholder}";
}
/// <summary>
/// Compile the random statement into SQL.
/// </summary>
/// <param name="seed"></param>
/// <returns></returns>
public virtual string CompileRandom(string seed)
{
return "RANDOM()";
}
public virtual string CompileLower(string value)
{
return $"LOWER({value})";
}
public virtual string CompileUpper(string value)
{
return $"UPPER({value})";
}
public virtual string CompileTrue()
{
return "true";
}
public virtual string CompileFalse()
{
return "false";
}
private InvalidCastException InvalidClauseException(string section, AbstractClause clause)
{
return new InvalidCastException($"Invalid type \"{clause.GetType().Name}\" provided for the \"{section}\" clause.");
}
protected string checkOperator(string op)
{
op = op.ToLowerInvariant();
var valid = operators.Contains(op) || userOperators.Contains(op);
if (!valid)
{
throw new InvalidOperationException($"The operator '{op}' cannot be used. Please consider white listing it before using it.");
}
return op;
}
/// <summary>
/// Wrap a single string in a column identifier.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual string Wrap(string value)
{
if (value.ToLowerInvariant().Contains(" as "))
{
var (before, after) = SplitAlias(value);
return Wrap(before) + $" {ColumnAsKeyword}" + WrapValue(after);
}
if (value.Contains("."))
{
return string.Join(".", value.Split('.').Select((x, index) =>
{
return WrapValue(x);
}));
}
// If we reach here then the value does not contain an "AS" alias
// nor dot "." expression, so wrap it as regular value.
return WrapValue(value);
}
public virtual (string, string) SplitAlias(string value)
{
var index = value.LastIndexOf(" as ", StringComparison.OrdinalIgnoreCase);
if (index > 0)
{
var before = value.Substring(0, index);
var after = value.Substring(index + 4);
return (before, after);
}
return (value, null);
}
/// <summary>
/// Wrap a single string in keyword identifiers.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual string WrapValue(string value)
{
if (value == "*") return value;
var opening = this.OpeningIdentifier;
var closing = this.ClosingIdentifier;
if (string.IsNullOrWhiteSpace(opening) && string.IsNullOrWhiteSpace(closing)) return value;
return opening + value.Replace(closing, closing + closing) + closing;
}
/// <summary>
/// Resolve a parameter
/// </summary>