-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathMySqlDialectTests.cs
More file actions
1374 lines (1130 loc) · 54.8 KB
/
MySqlDialectTests.cs
File metadata and controls
1374 lines (1130 loc) · 54.8 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 SqlParser.Ast;
using SqlParser.Dialects;
using SqlParser.Tokens;
using static SqlParser.Ast.Expression;
using DataType = SqlParser.Ast.DataType;
// ReSharper disable StringLiteralTypo
namespace SqlParser.Tests.Dialects;
public class MySqlDialectTests : ParserTestBase
{
public MySqlDialectTests()
{
DefaultDialects = [new MySqlDialect()];
}
[Fact]
public void Parse_Identifier()
{
VerifiedStatement("SELECT $a$, àà");
}
[Fact]
public void Parse_Literal_String()
{
var select = VerifiedOnlySelect("SELECT 'single', \"double\"");
Assert.Equal(2, select.Projection.Count);
Assert.Equal(new LiteralValue(new Value.SingleQuotedString("single")), select.Projection.First().AsExpr());
Assert.Equal(new LiteralValue(new Value.DoubleQuotedString("double")), select.Projection.Last().AsExpr());
}
[Fact]
public void Parse_Show_Columns()
{
DefaultDialects = [new MySqlDialect(), new GenericDialect()];
var tableName = new ObjectName("mytable");
Assert.Equal(new Statement.ShowColumns(false, false, tableName),
VerifiedStatement("SHOW COLUMNS FROM mytable"));
tableName = new ObjectName(["mydb", "mytable"]);
Assert.Equal(new Statement.ShowColumns(false, false, tableName),
VerifiedStatement("SHOW COLUMNS FROM mydb.mytable"));
tableName = new ObjectName("mytable");
Assert.Equal(new Statement.ShowColumns(true, false, tableName),
VerifiedStatement("SHOW EXTENDED COLUMNS FROM mytable"));
Assert.Equal(new Statement.ShowColumns(false, true, tableName),
VerifiedStatement("SHOW FULL COLUMNS FROM mytable"));
var filter = new ShowStatementFilter.Like("pattern");
Assert.Equal(new Statement.ShowColumns(false, false, tableName, filter),
VerifiedStatement("SHOW COLUMNS FROM mytable LIKE 'pattern'"));
var where = new ShowStatementFilter.Where(VerifiedExpr("1 = 2"));
Assert.Equal(new Statement.ShowColumns(false, false, tableName, where),
VerifiedStatement("SHOW COLUMNS FROM mytable WHERE 1 = 2"));
OneStatementParsesTo("SHOW FIELDS FROM mytable", "SHOW COLUMNS FROM mytable");
OneStatementParsesTo("SHOW COLUMNS IN mytable", "SHOW COLUMNS FROM mytable");
OneStatementParsesTo("SHOW FIELDS IN mytable", "SHOW COLUMNS FROM mytable");
OneStatementParsesTo("SHOW COLUMNS FROM mytable FROM mydb", "SHOW COLUMNS FROM mydb.mytable");
}
[Fact]
public void Parse_Show_Tables()
{
DefaultDialects = [new MySqlDialect(), new GenericDialect()];
var show = VerifiedStatement<Statement.ShowTables>("SHOW TABLES");
Assert.Equal(new Statement.ShowTables(false, false), show);
show = VerifiedStatement<Statement.ShowTables>("SHOW TABLES FROM mydb");
Assert.Equal(new Statement.ShowTables(false, false, ShowClause.From, "mydb"), show);
show = VerifiedStatement<Statement.ShowTables>("SHOW EXTENDED TABLES");
Assert.Equal(new Statement.ShowTables(true, false), show);
show = VerifiedStatement<Statement.ShowTables>("SHOW FULL TABLES");
Assert.Equal(new Statement.ShowTables(false, true), show);
show = VerifiedStatement<Statement.ShowTables>("SHOW TABLES LIKE 'pattern'");
Assert.Equal(new Statement.ShowTables(false, false, null, null, new ShowStatementFilter.Like("pattern")), show);
VerifiedStatement("SHOW TABLES IN mydb");
VerifiedStatement("SHOW TABLES FROM mydb");
}
[Fact]
public void Parse_Show_Extended_Full()
{
DefaultDialects = [new MySqlDialect(), new GenericDialect()];
ParseSqlStatements("SHOW EXTENDED FULL TABLES");
ParseSqlStatements("SHOW EXTENDED FULL COLUMNS FROM mytable");
Assert.Throws<ParserException>(() => ParseSqlStatements("SHOW EXTENDED FULL CREATE TABLE mytable"));
Assert.Throws<ParserException>(() => ParseSqlStatements("SHOW EXTENDED FULL COLLATION"));
Assert.Throws<ParserException>(() => ParseSqlStatements("SHOW EXTENDED FULL VARIABLES"));
}
[Fact]
public void Parse_Show_Create()
{
DefaultDialects = [new MySqlDialect(), new GenericDialect()];
var name = new ObjectName("myident");
foreach (var type in new[]
{
ShowCreateObject.Table,
ShowCreateObject.Trigger,
ShowCreateObject.Event,
ShowCreateObject.Function,
ShowCreateObject.Procedure,
ShowCreateObject.View
})
{
var statement = VerifiedStatement($"SHOW CREATE {type} myident");
Assert.Equal(new Statement.ShowCreate(type, name), statement);
}
}
[Fact]
public void Parse_Show_Collation()
{
DefaultDialects = [new MySqlDialect(), new GenericDialect()];
Assert.Equal(new Statement.ShowCollation(), VerifiedStatement("SHOW COLLATION"));
Assert.Equal(new Statement.ShowCollation(new ShowStatementFilter.Like("pattern")),
VerifiedStatement("SHOW COLLATION LIKE 'pattern'"));
Assert.Equal(new Statement.ShowCollation(new ShowStatementFilter.Where(VerifiedExpr("1 = 2"))),
VerifiedStatement("SHOW COLLATION WHERE 1 = 2"));
}
[Fact]
public void Parse_Use()
{
List<string> validObjectNames = ["mydb", "SCHEMA", "DATABASE", "CATALOG", "WAREHOUSE", "DEFAULT"];
List<char> quoteStyles = [Symbols.SingleQuote, Symbols.DoubleQuote];
foreach (var objectName in validObjectNames)
{
var useStatement = VerifiedStatement<Statement.Use>($"USE {objectName}");
var expected = new Use.Object(new ObjectName(new Ident(objectName)));
Assert.Equal(expected, useStatement.Name);
foreach (var quote in quoteStyles)
{
useStatement = VerifiedStatement<Statement.Use>($"USE {quote}{objectName}{quote}");
expected = new Use.Object(new ObjectName(new Ident(objectName, quote)));
Assert.Equal(expected, useStatement.Name);
}
}
}
[Fact]
public void Parse_Set_Variables()
{
DefaultDialects = [new MySqlDialect(), new GenericDialect()];
VerifiedStatement("SET sql_mode = CONCAT(@@sql_mode, ',STRICT_TRANS_TABLES')");
var expected = new Statement.SetVariable(true, false, new OneOrManyWithParens<ObjectName>.One("autocommit"), new[]
{
new LiteralValue(Number("1"))
});
Assert.Equal(expected, VerifiedStatement("SET LOCAL autocommit = 1"));
}
[Fact]
public void Parse_Create_Table_Auto_Increment()
{
var create =
VerifiedStatement<Statement.CreateTable>("CREATE TABLE foo (bar INT PRIMARY KEY AUTO_INCREMENT)");
Assert.Equal("foo", create.Element.Name);
Assert.Equal(new ColumnDef[]
{
new("bar", new DataType.Int(),
Options: new ColumnOptionDef[]
{
new(new ColumnOption.Unique(true)),
new(new ColumnOption.DialectSpecific(new[] {new Word("AUTO_INCREMENT")}))
})
}, create.Element.Columns);
}
[Fact]
public void Parse_Create_Table_Set_Enum()
{
var create =
VerifiedStatement<Statement.CreateTable>("CREATE TABLE foo (bar SET('a', 'b'), baz ENUM('a', 'b'))");
Assert.Equal("foo", create.Element.Name);
Assert.Equal(new ColumnDef[]
{
new("bar", new DataType.Set(new[] {"a", "b"})),
new("baz", new DataType.Enum(new[] {"a", "b"}))
}, create.Element.Columns);
}
[Fact]
public void Parse_Create_Table_Engine_Default_Charset()
{
var create =
VerifiedStatement<Statement.CreateTable>(
"CREATE TABLE foo (id INT(11)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3");
Assert.Equal("foo", create.Element.Name);
Assert.Equal(new TableEngine("InnoDB"), create.Element.Engine);
Assert.Equal("utf8mb3", create.Element.DefaultCharset);
Assert.Equal(new ColumnDef[]
{
new("id", new DataType.Int(11))
}, create.Element.Columns);
}
[Fact]
public void Parse_Create_Table_Collate()
{
var create =
VerifiedStatement<Statement.CreateTable>("CREATE TABLE foo (id INT(11)) COLLATE=utf8mb4_0900_ai_ci");
Assert.Equal("foo", create.Element.Name);
Assert.Equal("utf8mb4_0900_ai_ci", create.Element.Collation);
Assert.Equal(new ColumnDef[] { new("id", new DataType.Int(11)) }, create.Element.Columns);
}
[Fact]
public void Parse_Create_Table_Comment_Character_Set()
{
var create =
VerifiedStatement<Statement.CreateTable>(
"CREATE TABLE foo (s TEXT CHARACTER SET utf8mb4 COMMENT 'comment')");
Assert.Equal("foo", create.Element.Name);
Assert.Equal(new ColumnDef[]
{
new("s", new DataType.Text(),
Options: new ColumnOptionDef[]
{
new(new ColumnOption.CharacterSet("utf8mb4")),
new(new ColumnOption.Comment("comment"))
})
}, create.Element.Columns);
}
[Fact]
public void Parse_Quote_Identifiers()
{
var create = VerifiedStatement<Statement.CreateTable>("CREATE TABLE `PRIMARY` (`BEGIN` INT PRIMARY KEY)");
Assert.Equal("`PRIMARY`", create.Element.Name);
Assert.Equal(new ColumnDef[]
{
new(new Ident("BEGIN", Symbols.Backtick), new DataType.Int(), Options: new ColumnOptionDef[]
{
new(new ColumnOption.Unique(true))
})
}, create.Element.Columns);
}
[Fact]
public void Parse_Escaped_Quote_Identifiers_With_Escape()
{
var query = VerifiedStatement<Statement.Select>("SELECT `quoted `` identifier`", unescape: true);
var body = new SetExpression.SelectExpression(new Select(new[]
{
new SelectItem.UnnamedExpression(new Identifier(new Ident("quoted ` identifier", Symbols.Backtick)))
}));
var expected = new Statement.Select(new Query(body));
Assert.Equal(expected, query);
}
[Fact]
public void Parse_Escaped_Quote_Identifiers_No_Escape()
{
var query = VerifiedStatement<Statement.Select>("SELECT `quoted `` identifier`");
var body = new SetExpression.SelectExpression(new Select(new[]
{
new SelectItem.UnnamedExpression(new Identifier(new Ident("quoted `` identifier", Symbols.Backtick)))
}));
var expected = new Statement.Select(new Query(body));
Assert.Equal(expected, query);
}
[Fact]
public void Parse_Escaped_Backticks_With_No_Escape()
{
const string sql = "SELECT ```quoted identifier```";
var statement = VerifiedStatement(sql, [new MySqlDialect()]);
var body = new SetExpression.SelectExpression(new Select([
new SelectItem.UnnamedExpression(new Identifier(new Ident("``quoted identifier``", '`')))
]));
var expected = new Query(body);
Assert.Equal(expected, statement);
}
[Fact]
public void Parse_Unterminated_Escape()
{
var ex = Assert.Throws<TokenizeException>(() => OneStatementParsesTo("SELECT 'I\'m not fine\'", ""));
Assert.Equal("Unterminated string literal. Expected ' after Line: 1, Col: 21", ex.Message);
ex = Assert.Throws<TokenizeException>(() => OneStatementParsesTo("SELECT 'I\\\\'m not fine'", ""));
Assert.Equal("Unterminated string literal. Expected ' after Line: 1, Col: 23", ex.Message);
}
[Fact]
public void Parse_Escaped_String_With_Escape()
{
AssertMySqlQuotedString("SELECT 'I\\'m fine'", "I'm fine");
AssertMySqlQuotedString("SELECT 'I''m fine'", "I'm fine");
AssertMySqlQuotedString("SELECT 'I\"m fine'", "I\"m fine");
void AssertMySqlQuotedString(string sql, string quoted)
{
var statement = OneStatementParsesTo(sql, "", unescape: true);
var query = (Statement.Select)statement;
var body = (SetExpression.SelectExpression)query.Query.Body;
Assert.Equal(new LiteralValue(new Value.SingleQuotedString(quoted)),
body.Select.Projection.Single().AsExpr());
}
}
[Fact]
public void Parse_Create_Table_With_Minimum_Display_Width()
{
const string sql =
"CREATE TABLE foo (bar_tinyint TINYINT(3), bar_smallint SMALLINT(5), bar_mediumint MEDIUMINT(6), bar_int INT(11), bar_bigint BIGINT(20))";
var create = VerifiedStatement<Statement.CreateTable>(sql);
var expected = new ColumnDef[]
{
new("bar_tinyint", new DataType.TinyInt(3)),
new("bar_smallint", new DataType.SmallInt(5)),
new("bar_mediumint", new DataType.MediumInt(6)),
new("bar_int", new DataType.Int(11)),
new("bar_bigint", new DataType.BigInt(20)),
};
Assert.Equal("foo", create.Element.Name.Values[0]);
Assert.Equal(expected, create.Element.Columns);
}
[Fact]
public void Parse_Create_Table_Unsigned()
{
const string sql =
"CREATE TABLE foo (bar_tinyint TINYINT(3) UNSIGNED, bar_smallint SMALLINT(5) UNSIGNED, bar_mediumint MEDIUMINT(13) UNSIGNED, bar_int INT(11) UNSIGNED, bar_bigint BIGINT(20) UNSIGNED)";
var create = VerifiedStatement<Statement.CreateTable>(sql);
var expected = new ColumnDef[]
{
new("bar_tinyint", new DataType.UnsignedTinyInt(3)),
new("bar_smallint", new DataType.UnsignedSmallInt(5)),
new("bar_mediumint", new DataType.UnsignedMediumInt(13)),
new("bar_int", new DataType.UnsignedInt(11)),
new("bar_bigint", new DataType.UnsignedBigInt(20)),
};
Assert.Equal("foo", create.Element.Name.Values[0]);
Assert.Equal(expected, create.Element.Columns);
}
[Fact]
public void Parse_Simple_Insert()
{
const string sql =
"INSERT INTO tasks (title, priority) VALUES ('Test Some Inserts', 1), ('Test Entry 2', 2), ('Test Entry 3', 3)";
var insert = VerifiedStatement<Statement.Insert>(sql);
var body = new SetExpression.ValuesExpression(new Values(new Sequence<Expression>[]
{
[
new LiteralValue(new Value.SingleQuotedString("Test Some Inserts")),
new LiteralValue(Number("1"))
],
[
new LiteralValue(new Value.SingleQuotedString("Test Entry 2")),
new LiteralValue(Number("2"))
],
[
new LiteralValue(new Value.SingleQuotedString("Test Entry 3")),
new LiteralValue(Number("3"))
]
}));
var expected = new Query(body);
Assert.Equal("tasks", insert.InsertOperation.Name);
Assert.Equal(new Ident[] { "title", "priority" }, insert.InsertOperation.Columns!);
Assert.Equal(expected, insert.InsertOperation.Source!.Query);
}
[Fact]
public void Parse_Empty_Row_Insert()
{
ParseSqlStatements("INSERT INTO tb () VALUES (), ()");
ParseSqlStatements("INSERT INTO tb VALUES (), ()");
var insert = OneStatementParsesTo<Statement.Insert>(
"INSERT INTO tb () VALUES (), ()",
"INSERT INTO tb VALUES (), ()");
Assert.Equal("tb", insert.InsertOperation.Name);
Assert.Equal(new Statement.Select(
new Query(new SetExpression.ValuesExpression(new Values(new Sequence<Expression>[]
{
[],
[]
}))))
, insert.InsertOperation.Source);
}
[Fact]
public void Parse_Insert_With_On_Duplicate_Update()
{
const string sql =
"INSERT INTO permission_groups (name, description, perm_create, perm_read, perm_update, perm_delete) VALUES ('accounting_manager', 'Some description about the group', true, true, true, true) ON DUPLICATE KEY UPDATE description = VALUES(description), perm_create = VALUES(perm_create), perm_read = VALUES(perm_read), perm_update = VALUES(perm_update), perm_delete = VALUES(perm_delete)";
var insert = VerifiedStatement<Statement.Insert>(sql);
Assert.Equal("permission_groups", insert.InsertOperation.Name);
Assert.Equal(new Ident[] { "name", "description", "perm_create", "perm_read", "perm_update", "perm_delete" },
insert.InsertOperation.Columns!);
var rows = new Sequence<Expression>[]
{
[
new LiteralValue(new Value.SingleQuotedString("accounting_manager")),
new LiteralValue(new Value.SingleQuotedString("Some description about the group")),
new LiteralValue(new Value.Boolean(true)),
new LiteralValue(new Value.Boolean(true)),
new LiteralValue(new Value.Boolean(true)),
new LiteralValue(new Value.Boolean(true))
]
};
Assert.Equal(new Query(new SetExpression.ValuesExpression(new Values(rows))), (Query)insert.InsertOperation.Source!);
var update = new OnInsert.DuplicateKeyUpdate(new Statement.Assignment[]
{
new(new AssignmentTarget.ColumnName("description") , new Function("VALUES")
{
Args = new FunctionArguments.List(new FunctionArgumentList([
new FunctionArg.Unnamed(new FunctionArgExpression.FunctionExpression(new Identifier("description")))
]))
}),
new(new AssignmentTarget.ColumnName("perm_create"), new Function("VALUES")
{
Args = new FunctionArguments.List(new FunctionArgumentList([
new FunctionArg.Unnamed(new FunctionArgExpression.FunctionExpression(new Identifier("perm_create")))
]))
}),
new(new AssignmentTarget.ColumnName("perm_read"), new Function("VALUES")
{
Args = new FunctionArguments.List(new FunctionArgumentList([
new FunctionArg.Unnamed(new FunctionArgExpression.FunctionExpression(new Identifier("perm_read")))
]))
}),
new(new AssignmentTarget.ColumnName("perm_update"), new Function("VALUES")
{
Args = new FunctionArguments.List(new FunctionArgumentList([
new FunctionArg.Unnamed(new FunctionArgExpression.FunctionExpression(new Identifier("perm_update")))
]))
}),
new(new AssignmentTarget.ColumnName("perm_delete"), new Function("VALUES")
{
Args = new FunctionArguments.List(new FunctionArgumentList([
new FunctionArg.Unnamed(new FunctionArgExpression.FunctionExpression(new Identifier("perm_delete")))
]))
})
});
Assert.Equal(update, insert.InsertOperation.On);
}
[Fact]
public void Parse_Update_With_Joins()
{
const string sql =
"UPDATE orders AS o JOIN customers AS c ON o.customer_id = c.id SET o.completed = true WHERE c.firstname = 'Peter'";
var update = VerifiedStatement<Statement.Update>(sql);
var table = new TableWithJoins(new TableFactor.Table("orders")
{
Alias = new TableAlias("o", true)
})
{
Joins = new Join[]
{
new(new TableFactor.Table("customers")
{
Alias = new TableAlias("c", true)
})
{
JoinOperator = new JoinOperator.Inner(new JoinConstraint.On(new BinaryOp(
new CompoundIdentifier(new Ident[] {"o", "customer_id"}),
BinaryOperator.Eq,
new CompoundIdentifier(new Ident[] {"c", "id"})
)))
}
}
};
var assignments = new Statement.Assignment[]
{
new(new AssignmentTarget.ColumnName(new ObjectName(["o", "completed"])), new LiteralValue(new Value.Boolean(true)))
};
var op = new BinaryOp(
new CompoundIdentifier(new Ident[] { "c", "firstname" }),
BinaryOperator.Eq,
new LiteralValue(new Value.SingleQuotedString("Peter"))
);
Assert.Equal(table, update.Table);
Assert.Equal(assignments, update.Assignments);
Assert.Equal(op, update.Selection);
}
[Fact]
public void Parse_Alter_Table_Drop_Primary_Key()
{
DefaultDialects = [new MySqlDialect(), new GenericDialect()];
var alter = VerifiedStatement<Statement.AlterTable>("ALTER TABLE tab DROP PRIMARY KEY");
Assert.Equal("tab", alter.Name);
}
[Fact]
public void Parse_Alter_Table_Change_Column()
{
var alter = VerifiedStatement<Statement.AlterTable>(
"ALTER TABLE orders CHANGE COLUMN description desc TEXT NOT NULL");
var operation = new AlterTableOperation.ChangeColumn("description", "desc", new DataType.Text(),
new[]
{
new ColumnOption.NotNull()
});
Assert.Equal("orders", alter.Name);
Assert.Equal(operation, alter.Operations.First());
alter = VerifiedStatement<Statement.AlterTable>(
"ALTER TABLE orders CHANGE COLUMN description desc TEXT NOT NULL");
Assert.Equal("orders", alter.Name);
Assert.Equal(operation, alter.Operations.First());
var expectedOperation = new AlterTableOperation.ChangeColumn(
"description", "desc", new DataType.Text(), [new ColumnOption.NotNull()],
new MySqlColumnPosition.First());
var alterTable = VerifiedStatement<Statement.AlterTable>("ALTER TABLE orders CHANGE COLUMN description desc TEXT NOT NULL FIRST");
Assert.Equal(expectedOperation, alterTable.Operations.First());
alterTable = VerifiedStatement<Statement.AlterTable>("ALTER TABLE orders CHANGE COLUMN description desc TEXT NOT NULL AFTER foo");
expectedOperation = new AlterTableOperation.ChangeColumn(
"description", "desc", new DataType.Text(), [new ColumnOption.NotNull()],
new MySqlColumnPosition.After("foo"));
Assert.Equal(expectedOperation, alterTable.Operations.First());
}
[Fact]
public void Parse_Alter_Table_Change_Column_With_Column_Position()
{
AlterTableOperation expectedOperation = new AlterTableOperation.ChangeColumn("description", "desc",
new DataType.Text(),
[new ColumnOption.NotNull()], new MySqlColumnPosition.First());
var sql1 = "ALTER TABLE orders CHANGE COLUMN description desc TEXT NOT NULL FIRST";
var operation = VerifiedStatement<Statement.AlterTable>(sql1).Operations.First();
Assert.Equal(expectedOperation, operation);
expectedOperation = new AlterTableOperation.ChangeColumn("description", "desc", new DataType.Text(),
[new ColumnOption.NotNull()], new MySqlColumnPosition.First());
var sql2 = "ALTER TABLE orders CHANGE description desc TEXT NOT NULL FIRST";
operation = OneStatementParsesTo<Statement.AlterTable>(sql2, sql1).Operations.First();
Assert.Equal(expectedOperation, operation);
expectedOperation = new AlterTableOperation.ChangeColumn("description", "desc", new DataType.Text(),
[new ColumnOption.NotNull()], new MySqlColumnPosition.After("total_count"));
sql1 = "ALTER TABLE orders CHANGE COLUMN description desc TEXT NOT NULL AFTER total_count";
operation = VerifiedStatement<Statement.AlterTable>(sql1).Operations.First();
Assert.Equal(expectedOperation, operation);
sql2 = "ALTER TABLE orders CHANGE description desc TEXT NOT NULL AFTER total_count";
operation = OneStatementParsesTo<Statement.AlterTable>(sql2, sql1).Operations.First();
Assert.Equal(expectedOperation, operation);
}
[Fact]
public void Parse_Substring_In_Select()
{
var query = OneStatementParsesTo<Statement.Select>(
"SELECT DISTINCT SUBSTRING(description, 0, 1) FROM test",
"SELECT DISTINCT SUBSTRING(description FROM 0 FOR 1) FROM test");
var body = new SetExpression.SelectExpression(new Select(new[]
{
new SelectItem.UnnamedExpression(new Substring(
new Identifier("description"),
new LiteralValue(Number("0")),
new LiteralValue(Number("1"))
))
})
{
Distinct = new DistinctFilter.Distinct(),
From = new TableWithJoins[]
{
new(new TableFactor.Table("test"))
}
});
var expected = new Statement.Select(new Query(body));
Assert.Equal(expected, query);
}
[Fact]
public void Parse_Show_Variables()
{
DefaultDialects = [new MySqlDialect(), new GenericDialect()];
VerifiedStatement("SHOW VARIABLES");
VerifiedStatement("SHOW VARIABLES LIKE 'admin%'");
VerifiedStatement("SHOW VARIABLES WHERE value = '3306'");
VerifiedStatement("SHOW GLOBAL VARIABLES");
VerifiedStatement("SHOW GLOBAL VARIABLES LIKE 'admin%'");
VerifiedStatement("SHOW GLOBAL VARIABLES WHERE value = '3306'");
VerifiedStatement("SHOW SESSION VARIABLES");
VerifiedStatement("SHOW SESSION VARIABLES LIKE 'admin%'");
VerifiedStatement("SHOW GLOBAL VARIABLES WHERE value = '3306'");
}
[Fact]
public void Parse_Kill()
{
DefaultDialects = [new MySqlDialect(), new GenericDialect()];
var kill = VerifiedStatement<Statement.Kill>("KILL CONNECTION 5");
Assert.Equal(new Statement.Kill(KillType.Connection, 5), kill);
kill = VerifiedStatement<Statement.Kill>("KILL QUERY 5");
Assert.Equal(new Statement.Kill(KillType.Query, 5), kill);
kill = VerifiedStatement<Statement.Kill>("KILL 5");
Assert.Equal(new Statement.Kill(KillType.None, 5), kill);
}
[Fact]
public void Public_Table_Column_Option_On_Update()
{
var create =
VerifiedStatement<Statement.CreateTable>(
"CREATE TABLE foo (`modification_time` DATETIME ON UPDATE CURRENT_TIMESTAMP())");
Assert.Equal("foo", create.Element.Name);
Assert.Equal([
new(new Ident("modification_time", Symbols.Backtick), new DataType.Datetime(),
Options: new ColumnOptionDef[]
{
new(Option: new ColumnOption.OnUpdate(new Function("CURRENT_TIMESTAMP")
{
Args = new FunctionArguments.List(FunctionArgumentList.Empty())
}))
})
], create.Element.Columns);
}
[Fact]
public void Parse_Set_Names()
{
DefaultDialects = [new MySqlDialect(), new GenericDialect()];
var set = VerifiedStatement<Statement.SetNames>("SET NAMES utf8mb4");
Assert.Equal("utf8mb4", set.CharsetName);
set = VerifiedStatement<Statement.SetNames>("SET NAMES utf8mb4 COLLATE bogus");
Assert.Equal("utf8mb4", set.CharsetName);
Assert.Equal("bogus", set.CollationName);
set = VerifiedStatement<Statement.SetNames>("set names utf8mb4 collate bogus");
Assert.Equal("utf8mb4", set.CharsetName);
var def = VerifiedStatement<Statement.SetNamesDefault>("SET NAMES DEFAULT");
Assert.Equal(new Statement.SetNamesDefault(), def);
}
[Fact]
public void Parse_Limit_MySql_Syntax()
{
DefaultDialects = [new MySqlDialect(), new GenericDialect()];
OneStatementParsesTo(
"SELECT id, fname, lname FROM customer LIMIT 5, 10",
"SELECT id, fname, lname FROM customer LIMIT 10 OFFSET 5");
}
[Fact]
public void Parse_Create_Table_With_Index_Definition()
{
DefaultDialects = [new MySqlDialect(), new GenericDialect()];
OneStatementParsesTo(
"CREATE TABLE tb (id INT, INDEX (id))",
"CREATE TABLE tb (id INT, INDEX (id))");
OneStatementParsesTo(
"CREATE TABLE tb (id INT, index USING BTREE (id))",
"CREATE TABLE tb (id INT, INDEX USING BTREE (id))");
OneStatementParsesTo(
"CREATE TABLE tb (id INT, KEY USING HASH (id))",
"CREATE TABLE tb (id INT, KEY USING HASH (id))");
OneStatementParsesTo(
"CREATE TABLE tb (id INT, key index (id))",
"CREATE TABLE tb (id INT, KEY index (id))");
OneStatementParsesTo(
"CREATE TABLE tb (id INT, INDEX 'index' (id))",
"CREATE TABLE tb (id INT, INDEX 'index' (id))");
OneStatementParsesTo(
"CREATE TABLE tb (id INT, INDEX index USING BTREE (id))",
"CREATE TABLE tb (id INT, INDEX index USING BTREE (id))");
OneStatementParsesTo(
"CREATE TABLE tb (id INT, INDEX index USING HASH (id))",
"CREATE TABLE tb (id INT, INDEX index USING HASH (id))");
OneStatementParsesTo(
"CREATE TABLE tb (id INT, INDEX (c1, c2, c3, c4,c5))",
"CREATE TABLE tb (id INT, INDEX (c1, c2, c3, c4, c5))");
}
[Fact]
public void Parse_Create_Table_With_Fulltext_Definition()
{
DefaultDialects = [new MySqlDialect(), new GenericDialect()];
VerifiedStatement("CREATE TABLE tb (id INT, FULLTEXT (id))");
VerifiedStatement("CREATE TABLE tb (id INT, FULLTEXT INDEX (id))");
VerifiedStatement("CREATE TABLE tb (id INT, FULLTEXT KEY (id))");
VerifiedStatement("CREATE TABLE tb (id INT, FULLTEXT potato (id))");
VerifiedStatement("CREATE TABLE tb (id INT, FULLTEXT INDEX potato (id))");
VerifiedStatement("CREATE TABLE tb (id INT, FULLTEXT KEY potato (id))");
VerifiedStatement("CREATE TABLE tb (c1 INT, c2 INT, FULLTEXT KEY potato (c1, c2))");
}
[Fact]
public void Parse_Create_Table_With_Special_Definition()
{
DefaultDialects = [new MySqlDialect(), new GenericDialect()];
VerifiedStatement("CREATE TABLE tb (id INT, SPATIAL (id))");
VerifiedStatement("CREATE TABLE tb (id INT, SPATIAL INDEX (id))");
VerifiedStatement("CREATE TABLE tb (id INT, SPATIAL KEY (id))");
VerifiedStatement("CREATE TABLE tb (id INT, SPATIAL potato (id))");
VerifiedStatement("CREATE TABLE tb (id INT, SPATIAL INDEX potato (id))");
VerifiedStatement("CREATE TABLE tb (id INT, SPATIAL KEY potato (id))");
VerifiedStatement("CREATE TABLE tb (c1 INT, c2 INT, SPATIAL KEY potato (c1, c2))");
}
[Fact]
public void Parse_Fulltext_Expression()
{
DefaultDialects = [new MySqlDialect(), new GenericDialect()];
VerifiedStatement("SELECT * FROM tb WHERE MATCH (c1) AGAINST ('string')");
VerifiedStatement("SELECT * FROM tb WHERE MATCH (c1) AGAINST ('string' IN NATURAL LANGUAGE MODE)");
VerifiedStatement(
"SELECT * FROM tb WHERE MATCH (c1) AGAINST ('string' IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION)");
VerifiedStatement("SELECT * FROM tb WHERE MATCH (c1) AGAINST ('string' IN BOOLEAN MODE)");
VerifiedStatement("SELECT * FROM tb WHERE MATCH (c1) AGAINST ('string' WITH QUERY EXPANSION)");
VerifiedStatement("SELECT * FROM tb WHERE MATCH (c1, c2, c3) AGAINST ('string')");
VerifiedStatement("SELECT * FROM tb WHERE MATCH (c1) AGAINST (123)");
VerifiedStatement("SELECT * FROM tb WHERE MATCH (c1) AGAINST (NULL)");
VerifiedStatement(
"SELECT COUNT(IF(MATCH (title, body) AGAINST ('database' IN NATURAL LANGUAGE MODE), 1, NULL)) AS count FROM articles");
}
[Fact]
public void Parse_Create_Table_With_Fulltext_Definition_Should_Not_Accept_Constraint_Name()
{
DefaultDialects = [new MySqlDialect(), new GenericDialect()];
Assert.Throws<ParserException>(() =>
VerifiedStatement("CREATE TABLE tb (c1 INT, CONSTRAINT cons FULLTEXT (c1))"));
}
[Fact]
public void Parse_Values()
{
VerifiedStatement("VALUES ROW(1, true, 'a')");
VerifiedStatement(
"SELECT a, c FROM (VALUES ROW(1, true, 'a'), ROW(2, false, 'b'), ROW(3, false, 'c')) AS t (a, b, c)");
}
[Fact]
public void Parse_Hex_String_Introducer()
{
var query = VerifiedStatement<Statement.Select>("SELECT _latin1 X'4D7953514C'");
var projection = new SelectItem[]
{
new SelectItem.UnnamedExpression(new IntroducedString("_latin1",
new Value.HexStringLiteral("4D7953514C")))
};
Assert.Equal(projection, ((SetExpression.SelectExpression)query.Query.Body).Select.Projection);
}
[Fact]
// ReSharper disable once IdentifierTypo
public void Parse_String_Introducers()
{
VerifiedStatement("SELECT _binary 'abc'");
OneStatementParsesTo("SELECT _utf8'abc'", "SELECT _utf8 'abc'");
OneStatementParsesTo("SELECT _utf8mb4'abc'", "SELECT _utf8mb4 'abc'");
VerifiedStatement("SELECT _binary 'abc', _utf8mb4 'abc'");
}
[Fact]
public void Parse_Select_With_Numeric_Prefix_Column_Name()
{
const string sql = "SELECT 123col_$@123abc FROM \"table\"";
var select = VerifiedOnlySelect(sql);
Assert.Equal(new Identifier(new Ident("123col_$@123abc")), select.Projection.First().AsExpr());
}
[Fact]
public void Parse_Div_Infix()
{
const string sql = "SELECT 5 DIV 2";
VerifiedOnlySelect(sql);
}
[Fact]
public void Parse_Drop_Table()
{
var drop = VerifiedStatement<Statement.Drop>("DROP TEMPORARY TABLE foo");
Assert.True(drop.Temporary);
}
[Fact]
public void Parse_Create_Table_Unique_Key()
{
const string sql =
"CREATE TABLE foo (id INT PRIMARY KEY AUTO_INCREMENT, bar INT NOT NULL, UNIQUE KEY bar_key (bar))";
const string canonical =
"CREATE TABLE foo (id INT PRIMARY KEY AUTO_INCREMENT, bar INT NOT NULL, CONSTRAINT bar_key UNIQUE (bar))";
var create = (Statement.CreateTable)OneStatementParsesTo(sql, canonical, [new MySqlDialect()]);
var constraints = new Sequence<TableConstraint>
{
new TableConstraint.Unique(["bar"]){ Name = "bar_key" }
};
Assert.Equal("foo", create.Element.Name);
Assert.Equal(constraints, create.Element.Constraints);
var columns = new Sequence<ColumnDef>
{
new("id", new DataType.Int(), Options:
[
new(new ColumnOption.Unique(true)),
new(new ColumnOption.DialectSpecific([new Word("AUTO_INCREMENT")]))
]),
new("bar", new DataType.Int(), Options: [new(new ColumnOption.NotNull())])
};
Assert.Equal(columns, create.Element.Columns);
}
[Fact]
public void Parse_Create_Table_Comment()
{
const string withoutEqual = "CREATE TABLE foo (bar INT) COMMENT 'baz'";
const string withEqual = "CREATE TABLE foo (bar INT) COMMENT = 'baz'";
foreach (var sql in new[] { withoutEqual, withEqual })
{
var create = VerifiedStatement<Statement.CreateTable>(sql, [new MySqlDialect()]);
Assert.Equal("foo", create.Element.Name);
Assert.Equal("baz", create.Element.Comment!.Comment);
}
}
[Fact]
public void Parse_Alter_Role()
{
var sql = "ALTER ROLE old_name WITH NAME = new_name";
var dialect = new[] { new MsSqlDialect() };
var alter = ParseSqlStatements(sql, dialect);
var expected = new Statement.AlterRole("old_name", new AlterRoleOperation.RenameRole("new_name"));
Assert.Equal(expected, alter.First());
sql = "ALTER ROLE role_name ADD MEMBER new_member";
var statement = VerifiedStatement(sql, dialect);
expected = new Statement.AlterRole("role_name", new AlterRoleOperation.AddMember("new_member"));
Assert.Equal(expected, statement);
sql = "ALTER ROLE role_name DROP MEMBER old_member";
statement = VerifiedStatement(sql, dialect);
expected = new Statement.AlterRole("role_name", new AlterRoleOperation.DropMember("old_member"));
Assert.Equal(expected, statement);
}
[Fact]
public void Parse_Create_Table_Auto_Increment_Offset()
{
const string canonical = "CREATE TABLE foo (bar INT NOT NULL AUTO_INCREMENT) ENGINE=InnoDB AUTO_INCREMENT 123";
const string withEqual = "CREATE TABLE foo(bar INT NOT NULL AUTO_INCREMENT) ENGINE = InnoDB AUTO_INCREMENT = 123";
foreach (var sql in new[] { canonical, withEqual })
{
var create = (Statement.CreateTable)OneStatementParsesTo(sql, canonical);
Assert.Equal(123, create.Element.AutoIncrementOffset!.Value);
}
}
[Fact]
public void Parse_Attach_Database()
{
const string sql = "ATTACH DATABASE 'test.db' AS test";
var statement = VerifiedStatement(sql);
Assert.Equal(sql, statement.ToSql());
var expected = new Statement.AttachDatabase("test", new LiteralValue(new Value.SingleQuotedString("test.db")), true);
Assert.Equal(expected, statement);
}
[Fact]
public void Parse_Delete_With_Order_By()
{
const string sql = "DELETE FROM customers ORDER BY id DESC";
var delete = VerifiedStatement(sql);
var from = new FromTable.WithFromKeyword([new(new TableFactor.Table("customers"))]);
var expected = new Statement.Delete(new DeleteOperation(null, from,
OrderBy: [new(new Identifier("id"), Asc: false)]));
Assert.Equal(expected, delete);
}
[Fact]
public void Parse_Delete_With_Limit()
{
const string sql = "DELETE FROM customers LIMIT 100";
var delete = VerifiedStatement(sql);
var from = new FromTable.WithFromKeyword([new(new TableFactor.Table("customers"))]);
var expected = new Statement.Delete(new DeleteOperation(null, from,
Limit: new LiteralValue(new Value.Number("100"))
));
Assert.Equal(expected, delete);
}
[Fact]
public void Parse_Rlike_And_Regexp()
{
var queries = new[]{
"SELECT 1 WHERE 'a' RLIKE '^a$'",
"SELECT 1 WHERE 'a' REGEXP '^a$'",
"SELECT 1 WHERE 'a' NOT RLIKE '^a$'",
"SELECT 1 WHERE 'a' NOT REGEXP '^a$'",
};
var dialects = new Dialect[] { new MySqlDialect(), new GenericDialect() };
foreach (var sql in queries)
{
VerifiedOnlySelect(sql, dialects);
}
}
[Fact]
public void Parse_Ignore_Insert()
{
const string sql = "INSERT IGNORE INTO tasks (title, priority) VALUES ('Test Some Inserts', 1)";