-
-
Notifications
You must be signed in to change notification settings - Fork 524
Expand file tree
/
Copy pathMySqlCompiler.cs
More file actions
112 lines (82 loc) · 3.31 KB
/
MySqlCompiler.cs
File metadata and controls
112 lines (82 loc) · 3.31 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
using System.Linq;
namespace SqlKata.Compilers
{
public class MySqlCompiler : Compiler
{
public MySqlCompiler()
{
OpeningIdentifier = ClosingIdentifier = "`";
LastId = "SELECT last_insert_id() as Id";
}
public override string EngineCode { get; } = EngineCodes.MySql;
public override 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);
if (!string.IsNullOrWhiteSpace(fromQuery.IndexHint))
{
subCtx.RawSql += $" USE INDEX({fromQuery.IndexHint})";
}
return "(" + subCtx.RawSql + ")" + alias;
}
if (from is FromClause fromClause)
{
var fromStatment = Wrap(fromClause.Table);
if (!string.IsNullOrWhiteSpace(fromClause.IndexHint))
{
fromStatment += $" USE INDEX({fromClause.IndexHint})";
}
return fromStatment;
}
throw InvalidClauseException("TableExpression", from);
}
public override 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}" : "";
var indexHint = "";
if (!string.IsNullOrWhiteSpace(join.IndexHint))
{
indexHint = $" USE INDEX({join.IndexHint})";
}
return $"{join.Type} {joinTable}{indexHint}{onClause}";
}
public override string CompileLimit(SqlResult ctx)
{
var limit = ctx.Query.GetLimit(EngineCode);
var offset = ctx.Query.GetOffset(EngineCode);
if (offset == 0 && limit == 0)
{
return null;
}
if (offset == 0)
{
ctx.Bindings.Add(limit);
return $"LIMIT {parameterPlaceholder}";
}
if (limit == 0)
{
// MySql will not accept offset without limit, so we will put a large number
// to avoid this error.
ctx.Bindings.Add(offset);
return $"LIMIT 18446744073709551615 OFFSET {parameterPlaceholder}";
}
// We have both values
ctx.Bindings.Add(limit);
ctx.Bindings.Add(offset);
return $"LIMIT {parameterPlaceholder} OFFSET {parameterPlaceholder}";
}
}
}