-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathCompiler.cs
More file actions
451 lines (396 loc) · 17.9 KB
/
Compiler.cs
File metadata and controls
451 lines (396 loc) · 17.9 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
// Copyright (C) 2011-2023 Xtensive LLC.
// This code is distributed under MIT license terms.
// See the License.txt file in the project root for more information.
// Created by: Malisa Ncube
// Created: 2011.02.25
using System;
using Xtensive.Sql.Compiler;
using Xtensive.Sql.Ddl;
using Xtensive.Sql.Dml;
using Xtensive.Sql.Model;
using Xtensive.Core;
using System.Collections.Generic;
namespace Xtensive.Sql.Drivers.MySql.v5_0
{
internal class Compiler : SqlCompiler
{
protected const long NanosecondsPerDay = 86400000000000;
protected const long NanosecondsPerHour = 3600000000000;
protected const long NanosecondsPerMinute = 60000000000;
protected const long NanosecondsPerSecond = 1000000000;
protected const long NanosecondsPerMillisecond = 1000000;
protected const long NanosecondsPerMicrosecond = 1000;
protected const long MillisecondsPerDay = 86400000;
/// <inheritdoc/>
public override void Visit(SqlSelect node)
{
using (context.EnterScope(node)) {
var comment = node.Comment;
VisitCommentIfBefore(comment);
AppendTranslatedEntry(node);
VisitCommentIfWithin(comment);
VisitSelectColumns(node);
VisitSelectFrom(node);
VisitSelectHints(node);
VisitSelectWhere(node);
VisitSelectGroupBy(node);
VisitSelectOrderBy(node);
VisitSelectLimitOffset(node);
VisitSelectLock(node);
AppendTranslatedExit(node);
VisitCommentIfAfter(comment);
}
}
/// <inheritdoc/>
public override void Visit(SqlAlterTable node)
{
if (node.Action is SqlRenameColumn renameColumnAction)
((Translator) translator).Translate(context, renameColumnAction);
else if (node.Action is SqlDropConstraint) {
using (context.EnterScope(node)) {
AppendTranslatedEntry(node);
var action = node.Action as SqlDropConstraint;
var constraint = action.Constraint as TableConstraint;
AppendTranslated(node, AlterTableSection.DropConstraint);
if (constraint is ForeignKey) {
_ = context.Output.Append("FOREIGN KEY ");
translator.TranslateIdentifier(context.Output, constraint.DbName);
}
else if (constraint is PrimaryKey)
_ = context.Output.Append("PRIMARY KEY ");
else {
AppendTranslated(constraint, ConstraintSection.Entry);
}
AppendTranslated(node, AlterTableSection.DropBehavior);
AppendTranslatedExit(node);
}
}
else {
base.Visit(node);
}
}
/// <inheritdoc/>
public override void Visit(SqlFreeTextTable node)
{
//See Readme.txt point 6.
throw SqlHelper.NotSupported("FreeText");
}
/// <inheritdoc/>
public override void Visit(SqlBinary node)
{
switch (node.NodeType) {
case SqlNodeType.DateTimePlusInterval:
DateTimeAddInterval(node.Left, node.Right).AcceptVisitor(this);
return;
case SqlNodeType.DateTimeMinusDateTime:
DateTimeSubtractDateTime(node.Left, node.Right).AcceptVisitor(this);
return;
case SqlNodeType.DateTimeMinusInterval:
DateTimeAddInterval(node.Left, -node.Right).AcceptVisitor(this);
return;
case SqlNodeType.TimePlusInterval:
TimeAddInterval(node.Left, node.Right).AcceptVisitor(this);
return;
case SqlNodeType.TimeMinusTime:
TimeSubtractTime(node.Left, node.Right).AcceptVisitor(this);
return;
default:
base.Visit(node);
return;
}
}
/// <inheritdoc/>
public override void Visit(SqlUnary node)
{
if (node.NodeType == SqlNodeType.BitNot) {
Visit(BitNot(node.Operand));
return;
}
base.Visit(node);
}
/// <inheritdoc/>
/// //Thanks to Csaba Beer.
public override void Visit(SqlQueryExpression node)
{
using (context.EnterScope(node)) {
//bool needOpeningParenthesis = false;
//bool needClosingParenthesis = false;
AppendTranslatedEntry(node);
//if (needOpeningParenthesis)
// context.Output.Append("(");
node.Left.AcceptVisitor(this);
//if (needClosingParenthesis)
// context.Output.Append(")");
AppendTranslated(node.NodeType);
AppendTranslated(node, QueryExpressionSection.All);
//if (needOpeningParenthesis)
// context.Output.Append("(");
node.Right.AcceptVisitor(this);
//if (needClosingParenthesis)
// context.Output.Append(")");
AppendTranslatedExit(node);
}
}
/// <inheritdoc/>
public override void Visit(SqlFunctionCall node)
{
var arguments = node.Arguments;
switch (node.FunctionType) {
case SqlFunctionType.Truncate:
SqlDml.FunctionCall("TRUNCATE", arguments[0], SqlDml.Literal(0)).AcceptVisitor(this);
return;
case SqlFunctionType.Concat:
Visit(SqlDml.Concat(arguments.ToArray(node.Arguments.Count)));
return;
case SqlFunctionType.CharLength:
SqlDml.FunctionCall(translator.TranslateToString(SqlFunctionType.CharLength), node.Arguments[0]).AcceptVisitor(this);
// SqlDml.CharLength(node.Arguments[0]).AcceptVisitor(this);
return;
case SqlFunctionType.PadLeft:
case SqlFunctionType.PadRight:
SqlHelper.GenericPad(node).AcceptVisitor(this);
return;
case SqlFunctionType.Rand:
SqlDml.FunctionCall(translator.TranslateToString(SqlFunctionType.Rand)).AcceptVisitor(this);
return;
case SqlFunctionType.Square:
SqlDml.Power(arguments[0], 2).AcceptVisitor(this);
return;
case SqlFunctionType.IntervalToMilliseconds:
Visit(CastToLong(arguments[0]) / NanosecondsPerMillisecond);
return;
case SqlFunctionType.IntervalConstruct:
case SqlFunctionType.IntervalToNanoseconds:
Visit(CastToLong(arguments[0]));
return;
case SqlFunctionType.DateTimeAddMonths:
Visit(DateTimeAddMonth(arguments[0], arguments[1]));
return;
case SqlFunctionType.DateTimeAddYears:
Visit(DateTimeAddYear(arguments[0], arguments[1]));
return;
case SqlFunctionType.DateTimeConstruct:
ConstructDateTime(arguments).AcceptVisitor(this);
return;
case SqlFunctionType.DateAddYears:
Visit(DateAddYear(arguments[0], arguments[1]));
return;
case SqlFunctionType.DateAddMonths:
Visit(DateAddMonth(arguments[0], arguments[1]));
return;
case SqlFunctionType.DateAddDays:
Visit(DateAddDay(arguments[0], arguments[1]));
return;
case SqlFunctionType.DateConstruct:
ConstructDate(arguments).AcceptVisitor(this);
return;
case SqlFunctionType.TimeAddHours:
Visit(SqlDml.FunctionCall("TIME", SqlDml.FunctionCall(
"DATE_ADD",
SqlDml.Literal(new DateTime(2001, 1, 1)),
SqlDml.RawConcat(
SqlDml.RawConcat(SqlDml.Native("INTERVAL "), SqlDml.FunctionCall("TIME_TO_SEC", arguments[0]) + arguments[1] * 3600),
SqlDml.Native("SECOND")))));
return;
case SqlFunctionType.TimeAddMinutes:
Visit(SqlDml.FunctionCall("TIME",
SqlDml.FunctionCall("DATE_ADD",
SqlDml.Literal(new DateTime(2001, 1, 1)),
SqlDml.RawConcat(
SqlDml.RawConcat(SqlDml.Native("INTERVAL "), SqlDml.FunctionCall("TIME_TO_SEC", arguments[0]) + arguments[1] * 60),
SqlDml.Native("SECOND")))));
return;
case SqlFunctionType.TimeToNanoseconds:
TimeToNanoseconds(arguments[0]).AcceptVisitor(this);
return;
case SqlFunctionType.DateToString:
Visit(DateToString(arguments[0]));
return;
case SqlFunctionType.TimeToString:
Visit(TimeToString(arguments[0]));
return;
case SqlFunctionType.DateTimeToDate:
DateTimeToDate(node.Arguments[0]).AcceptVisitor(this);
return;
case SqlFunctionType.DateToDateTime:
DateToDateTime(node.Arguments[0]).AcceptVisitor(this);
return;
case SqlFunctionType.DateTimeToTime:
DateTimeToTime(node.Arguments[0]).AcceptVisitor(this);
return;
case SqlFunctionType.TimeToDateTime:
TimeToDateTime(node.Arguments[0]).AcceptVisitor(this);
return;
case SqlFunctionType.DateTimeToStringIso:
Visit(DateTimeToStringIso(arguments[0]));
return;
}
base.Visit(node);
}
public override void Visit(SqlPlaceholder node)
{
if (node.Id is Orm.Providers.ParameterBinding qpb
&& qpb.TypeMapping?.Type == typeof(TimeOnly)) {
_ = context.Output.Append("TIME(");
base.Visit(node);
_ = context.Output.Append(")");
}
else {
base.Visit(node);
}
}
/// <inheritdoc/>
protected override void VisitSelectLimitOffset(SqlSelect node)
{
if (node.Limit is not null) {
translator.SelectLimit(context, node);
node.Limit.AcceptVisitor(this);
}
if (node.Offset is not null) {
if (node.Limit is null) {
translator.SelectLimit(context, node);
_ = context.Output.Append(" 18446744073709551615 "); // magic number from http://dev.mysql.com/doc/refman/5.0/en/select.html
}
translator.SelectOffset(context, node);
node.Offset.AcceptVisitor(this);
}
}
/// <inheritdoc/>
public override void Visit(SqlExtract node)
{
if (node.DateTimePart == SqlDateTimePart.DayOfWeek || node.DateTimePart == SqlDateTimePart.DayOfYear) {
Visit(SqlDml.FunctionCall(node.DateTimePart.ToString(), node.Operand));
return;
}
if (node.DatePart == SqlDatePart.DayOfWeek || node.DatePart == SqlDatePart.DayOfYear) {
Visit(SqlDml.FunctionCall(node.DatePart.ToString(), node.Operand));
return;
}
base.Visit(node);
}
protected virtual SqlExpression ConstructDateTime(IReadOnlyList<SqlExpression> arguments)
{
return DateTimeAddDay(
DateTimeAddMonth(
DateTimeAddYear(
SqlDml.Literal(new DateTime(2001, 1, 1)),
arguments[0] - 2001),
arguments[1] - 1),
arguments[2] - 1);
}
protected virtual SqlExpression DateTimeSubtractDateTime(SqlExpression date1, SqlExpression date2)
{
return (CastToDecimal(DateDiffDay(date1, date2), 18, 0) * NanosecondsPerDay)
+
(CastToDecimal(DateTimeDiffMicrosecond(DateTimeAddDay(date2, DateDiffDay(date1, date2)), date1), 18, 0) * NanosecondsPerMicrosecond);
}
protected virtual SqlExpression DateTimeAddInterval(SqlExpression date, SqlExpression interval)
{
return DateTimeAddMicrosecond(
DateTimeAddDay(date, ((interval - (interval % NanosecondsPerDay)) + ((interval % NanosecondsPerDay) > (NanosecondsPerDay / 2) ? 0 : 1)) / NanosecondsPerDay),
(interval / NanosecondsPerMillisecond * NanosecondsPerMicrosecond) % (MillisecondsPerDay * NanosecondsPerMicrosecond));
}
protected virtual SqlExpression ConstructDate(IReadOnlyList<SqlExpression> arguments)
{
return DateAddDay(
DateAddMonth(
DateAddYear(
SqlDml.Literal(new DateOnly(2001, 1, 1)),
arguments[0] - 2001),
arguments[1] - 1),
arguments[2] - 1);
}
protected virtual SqlExpression TimeToNanoseconds(SqlExpression time)
{
var nPerHour = SqlDml.Extract(SqlTimePart.Hour, time) * NanosecondsPerHour;
var nPerMinute = SqlDml.Extract(SqlTimePart.Minute, time) * NanosecondsPerMinute;
var nPerSecond = SqlDml.Extract(SqlTimePart.Second, time) * NanosecondsPerSecond;
var nPerMillisecond = SqlDml.Extract(SqlTimePart.Millisecond, time) * NanosecondsPerMillisecond;
return nPerHour + nPerMinute + nPerSecond + nPerMillisecond;
}
protected virtual SqlExpression TimeSubtractTime(SqlExpression time1, SqlExpression time2) =>
SqlDml.Modulo(
NanosecondsPerDay + CastToDecimal(SqlDml.FunctionCall("TIME_TO_SEC", time1) - SqlDml.FunctionCall("TIME_TO_SEC", time2), 18, 0) * NanosecondsPerSecond,
NanosecondsPerDay);
protected virtual SqlExpression TimeAddInterval(SqlExpression time, SqlExpression interval) =>
SqlDml.FunctionCall("TIME",
SqlDml.FunctionCall(
"DATE_ADD",
SqlDml.Literal(new DateTime(2001, 1, 1)),
SqlDml.RawConcat(
SqlDml.RawConcat(SqlDml.Native("INTERVAL "),
SqlDml.FunctionCall("TIME_TO_SEC", time) + interval / NanosecondsPerSecond),
SqlDml.Native("SECOND"))));
#region Static helpers
protected static SqlCast CastToLong(SqlExpression arg) => SqlDml.Cast(arg, SqlType.Int64);
protected static SqlCast CastToDecimal(SqlExpression arg, short precision, short scale) =>
SqlDml.Cast(arg, SqlType.Decimal, precision, scale);
protected static SqlUserFunctionCall DateDiffDay(SqlExpression date1, SqlExpression date2) =>
SqlDml.FunctionCall("DATEDIFF", date1, date2);
protected static SqlUserFunctionCall DateTimeDiffMicrosecond(SqlExpression datetime1, SqlExpression datetime2) =>
SqlDml.FunctionCall("TIMESTAMPDIFF", SqlDml.Native("MICROSECOND"), datetime1, datetime2);
protected static SqlUserFunctionCall DateTimeDiffSecond(SqlExpression datetime1, SqlExpression datetime2) =>
SqlDml.FunctionCall("TIMESTAMPDIFF", SqlDml.Native("SECOND"), datetime1, datetime2);
protected static SqlUserFunctionCall DateTimeAddYear(SqlExpression datetime, SqlExpression years) =>
SqlDml.FunctionCall("TIMESTAMPADD", SqlDml.Native("YEAR"), years, datetime);
protected static SqlUserFunctionCall DateTimeAddMonth(SqlExpression datetime, SqlExpression months) =>
SqlDml.FunctionCall("TIMESTAMPADD", SqlDml.Native("MONTH"), months, datetime);
protected static SqlUserFunctionCall DateTimeAddDay(SqlExpression datetime, SqlExpression days) =>
SqlDml.FunctionCall("TIMESTAMPADD", SqlDml.Native("DAY"), days, datetime);
protected static SqlUserFunctionCall DateTimeAddHour(SqlExpression datetime, SqlExpression days) =>
SqlDml.FunctionCall("TIMESTAMPADD", SqlDml.Native("HOUR"), days, datetime);
protected static SqlUserFunctionCall DateTimeAddMicrosecond(SqlExpression datetime, SqlExpression microseconds) =>
SqlDml.FunctionCall("TIMESTAMPADD", SqlDml.Native("MICROSECOND"), microseconds, datetime);
protected static SqlUserFunctionCall DateAddYear(SqlExpression date, SqlExpression years) =>
SqlDml.FunctionCall("DATE_ADD", date, SqlDml.RawConcat(SqlDml.Native("INTERVAL "), SqlDml.RawConcat(years, SqlDml.Native("YEAR"))));
protected static SqlUserFunctionCall DateAddMonth(SqlExpression date, SqlExpression months) =>
SqlDml.FunctionCall("DATE_ADD", date, SqlDml.RawConcat(SqlDml.Native("INTERVAL "), SqlDml.RawConcat(months, SqlDml.Native("MONTH"))));
protected static SqlUserFunctionCall DateAddDay(SqlExpression date, SqlExpression days) =>
SqlDml.FunctionCall("DATE_ADD", date, SqlDml.RawConcat(SqlDml.Native("INTERVAL "), SqlDml.RawConcat(days, SqlDml.Native("DAY"))));
protected static SqlUserFunctionCall TimeAddHour(SqlExpression time, SqlExpression hours) =>
SqlDml.FunctionCall("DATE_ADD", time, SqlDml.RawConcat(SqlDml.Native("INTERVAL "), SqlDml.RawConcat(hours, SqlDml.Native("HOUR"))));
protected static SqlUserFunctionCall TimeAddMinute(SqlExpression time, SqlExpression minutes) =>
SqlDml.FunctionCall("DATE_ADD", time, SqlDml.RawConcat(SqlDml.Native("INTERVAL "), SqlDml.RawConcat(minutes, SqlDml.Native("MINUTE"))));
protected static SqlUserFunctionCall TimeAddSecond(SqlExpression time, SqlExpression seconds) =>
SqlDml.FunctionCall("DATE_ADD", time, SqlDml.RawConcat(SqlDml.Native("INTERVAL "), SqlDml.RawConcat(seconds, SqlDml.Native("SECOND"))));
protected static SqlUserFunctionCall TimeAddMillisecond(SqlExpression time, SqlExpression millisecond) =>
SqlDml.FunctionCall("DATE_ADD", time, SqlDml.RawConcat(SqlDml.Native("INTERVAL "), SqlDml.RawConcat(millisecond * 1000, SqlDml.Native("MICROSECOND"))));
protected static SqlUserFunctionCall DateToString(SqlExpression dateTime) =>
SqlDml.FunctionCall("DATE_FORMAT", dateTime, "%Y-%m-%d");
protected static SqlUserFunctionCall TimeToString(SqlExpression dateTime) =>
SqlDml.FunctionCall("DATE_FORMAT", dateTime, "%H:%i:%s.%f0");
private static SqlExpression DateTimeToDate(SqlExpression dateTime) =>
SqlDml.Cast(dateTime, SqlType.Date);
private static SqlExpression DateToDateTime(SqlExpression date) =>
SqlDml.Cast(date, SqlType.DateTime);
private static SqlExpression DateTimeToTime(SqlExpression dateTime) =>
SqlDml.Cast(dateTime, SqlType.Time);
// can't convert via cast, because mysql shots to its head and creates
// value that it can't read later. This mimics conversion that occurs
// in newer versions (5.6+) and use current date as a source of year,
// month and day values :-)
private static SqlExpression TimeToDateTime(SqlExpression time) =>
SqlDml.FunctionCall("DATE_ADD",
SqlDml.Literal(DateTime.Now.Date),
SqlDml.RawConcat(
SqlDml.RawConcat(SqlDml.Native("INTERVAL "),
SqlDml.FunctionCall("TIME_TO_SEC", time)),
SqlDml.Native("SECOND")));
protected static SqlUserFunctionCall DateTimeToStringIso(SqlExpression dateTime) =>
SqlDml.FunctionCall("DATE_FORMAT", dateTime, "%Y-%m-%dT%T");
protected static SqlUserFunctionCall BitNot(SqlExpression operand) =>
SqlDml.FunctionCall(
"CAST",
SqlDml.RawConcat(
SqlDml.Native("~"),
SqlDml.RawConcat(
operand,
SqlDml.Native("AS SIGNED"))));
#endregion
// Constructors
protected internal Compiler(SqlDriver driver)
: base(driver)
{
}
}
}