Debian Codegraph @

ast_test.go

raw symbols SCIP
1 /*
2 Copyright 2017 Google Inc.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package sqlparser
18
19 import (
20 "bytes"
21 "encoding/json"
22 "reflect"
23 "strings"
24 "testing"
25 "unsafe"
26
27 "github.com/xwb1989/sqlparser/dependency/sqltypes"
28 )
29
30 func TestAppend(t *testing.T) {
31 query := "select * from t where a = 1"
32 tree, err := Parse(query)
33 if err != nil {
34 t.Error(err)
35 }
36 var b bytes.Buffer
37 Append(&b, tree)
38 got := b.String()
39 want := query
40 if got != want {
41 t.Errorf("Append: %s, want %s", got, want)
42 }
43 Append(&b, tree)
44 got = b.String()
45 want = query + query
46 if got != want {
47 t.Errorf("Append: %s, want %s", got, want)
48 }
49 }
50
51 func TestSelect(t *testing.T) {
52 tree, err := Parse("select * from t where a = 1")
53 if err != nil {
54 t.Error(err)
55 }
56 expr := tree.(*Select).Where.Expr
57
58 sel := &Select{}
59 sel.AddWhere(expr)
60 buf := NewTrackedBuffer(nil)
61 sel.Where.Format(buf)
62 want := " where a = 1"
63 if buf.String() != want {
64 t.Errorf("where: %q, want %s", buf.String(), want)
65 }
66 sel.AddWhere(expr)
67 buf = NewTrackedBuffer(nil)
68 sel.Where.Format(buf)
69 want = " where a = 1 and a = 1"
70 if buf.String() != want {
71 t.Errorf("where: %q, want %s", buf.String(), want)
72 }
73 sel = &Select{}
74 sel.AddHaving(expr)
75 buf = NewTrackedBuffer(nil)
76 sel.Having.Format(buf)
77 want = " having a = 1"
78 if buf.String() != want {
79 t.Errorf("having: %q, want %s", buf.String(), want)
80 }
81 sel.AddHaving(expr)
82 buf = NewTrackedBuffer(nil)
83 sel.Having.Format(buf)
84 want = " having a = 1 and a = 1"
85 if buf.String() != want {
86 t.Errorf("having: %q, want %s", buf.String(), want)
87 }
88
89 // OR clauses must be parenthesized.
90 tree, err = Parse("select * from t where a = 1 or b = 1")
91 if err != nil {
92 t.Error(err)
93 }
94 expr = tree.(*Select).Where.Expr
95 sel = &Select{}
96 sel.AddWhere(expr)
97 buf = NewTrackedBuffer(nil)
98 sel.Where.Format(buf)
99 want = " where (a = 1 or b = 1)"
100 if buf.String() != want {
101 t.Errorf("where: %q, want %s", buf.String(), want)
102 }
103 sel = &Select{}
104 sel.AddHaving(expr)
105 buf = NewTrackedBuffer(nil)
106 sel.Having.Format(buf)
107 want = " having (a = 1 or b = 1)"
108 if buf.String() != want {
109 t.Errorf("having: %q, want %s", buf.String(), want)
110 }
111 }
112
113 func TestRemoveHints(t *testing.T) {
114 for _, query := range []string{
115 "select * from t use index (i)",
116 "select * from t force index (i)",
117 } {
118 tree, err := Parse(query)
119 if err != nil {
120 t.Fatal(err)
121 }
122 sel := tree.(*Select)
123 sel.From = TableExprs{
124 sel.From[0].(*AliasedTableExpr).RemoveHints(),
125 }
126 buf := NewTrackedBuffer(nil)
127 sel.Format(buf)
128 if got, want := buf.String(), "select * from t"; got != want {
129 t.Errorf("stripped query: %s, want %s", got, want)
130 }
131 }
132 }
133
134 func TestAddOrder(t *testing.T) {
135 src, err := Parse("select foo, bar from baz order by foo")
136 if err != nil {
137 t.Error(err)
138 }
139 order := src.(*Select).OrderBy[0]
140 dst, err := Parse("select * from t")
141 if err != nil {
142 t.Error(err)
143 }
144 dst.(*Select).AddOrder(order)
145 buf := NewTrackedBuffer(nil)
146 dst.Format(buf)
147 want := "select * from t order by foo asc"
148 if buf.String() != want {
149 t.Errorf("order: %q, want %s", buf.String(), want)
150 }
151 dst, err = Parse("select * from t union select * from s")
152 if err != nil {
153 t.Error(err)
154 }
155 dst.(*Union).AddOrder(order)
156 buf = NewTrackedBuffer(nil)
157 dst.Format(buf)
158 want = "select * from t union select * from s order by foo asc"
159 if buf.String() != want {
160 t.Errorf("order: %q, want %s", buf.String(), want)
161 }
162 }
163
164 func TestSetLimit(t *testing.T) {
165 src, err := Parse("select foo, bar from baz limit 4")
166 if err != nil {
167 t.Error(err)
168 }
169 limit := src.(*Select).Limit
170 dst, err := Parse("select * from t")
171 if err != nil {
172 t.Error(err)
173 }
174 dst.(*Select).SetLimit(limit)
175 buf := NewTrackedBuffer(nil)
176 dst.Format(buf)
177 want := "select * from t limit 4"
178 if buf.String() != want {
179 t.Errorf("limit: %q, want %s", buf.String(), want)
180 }
181 dst, err = Parse("select * from t union select * from s")
182 if err != nil {
183 t.Error(err)
184 }
185 dst.(*Union).SetLimit(limit)
186 buf = NewTrackedBuffer(nil)
187 dst.Format(buf)
188 want = "select * from t union select * from s limit 4"
189 if buf.String() != want {
190 t.Errorf("order: %q, want %s", buf.String(), want)
191 }
192 }
193
194 func TestWhere(t *testing.T) {
195 var w *Where
196 buf := NewTrackedBuffer(nil)
197 w.Format(buf)
198 if buf.String() != "" {
199 t.Errorf("w.Format(nil): %q, want \"\"", buf.String())
200 }
201 w = NewWhere(WhereStr, nil)
202 buf = NewTrackedBuffer(nil)
203 w.Format(buf)
204 if buf.String() != "" {
205 t.Errorf("w.Format(&Where{nil}: %q, want \"\"", buf.String())
206 }
207 }
208
209 func TestIsAggregate(t *testing.T) {
210 f := FuncExpr{Name: NewColIdent("avg")}
211 if !f.IsAggregate() {
212 t.Error("IsAggregate: false, want true")
213 }
214
215 f = FuncExpr{Name: NewColIdent("Avg")}
216 if !f.IsAggregate() {
217 t.Error("IsAggregate: false, want true")
218 }
219
220 f = FuncExpr{Name: NewColIdent("foo")}
221 if f.IsAggregate() {
222 t.Error("IsAggregate: true, want false")
223 }
224 }
225
226 func TestReplaceExpr(t *testing.T) {
227 tcases := []struct {
228 in, out string
229 }{{
230 in: "select * from t where (select a from b)",
231 out: ":a",
232 }, {
233 in: "select * from t where (select a from b) and b",
234 out: ":a and b",
235 }, {
236 in: "select * from t where a and (select a from b)",
237 out: "a and :a",
238 }, {
239 in: "select * from t where (select a from b) or b",
240 out: ":a or b",
241 }, {
242 in: "select * from t where a or (select a from b)",
243 out: "a or :a",
244 }, {
245 in: "select * from t where not (select a from b)",
246 out: "not :a",
247 }, {
248 in: "select * from t where ((select a from b))",
249 out: "(:a)",
250 }, {
251 in: "select * from t where (select a from b) = 1",
252 out: ":a = 1",
253 }, {
254 in: "select * from t where a = (select a from b)",
255 out: "a = :a",
256 }, {
257 in: "select * from t where a like b escape (select a from b)",
258 out: "a like b escape :a",
259 }, {
260 in: "select * from t where (select a from b) between a and b",
261 out: ":a between a and b",
262 }, {
263 in: "select * from t where a between (select a from b) and b",
264 out: "a between :a and b",
265 }, {
266 in: "select * from t where a between b and (select a from b)",
267 out: "a between b and :a",
268 }, {
269 in: "select * from t where (select a from b) is null",
270 out: ":a is null",
271 }, {
272 // exists should not replace.
273 in: "select * from t where exists (select a from b)",
274 out: "exists (select a from b)",
275 }, {
276 in: "select * from t where a in ((select a from b), 1)",
277 out: "a in (:a, 1)",
278 }, {
279 in: "select * from t where a in (0, (select a from b), 1)",
280 out: "a in (0, :a, 1)",
281 }, {
282 in: "select * from t where (select a from b) + 1",
283 out: ":a + 1",
284 }, {
285 in: "select * from t where 1+(select a from b)",
286 out: "1 + :a",
287 }, {
288 in: "select * from t where -(select a from b)",
289 out: "-:a",
290 }, {
291 in: "select * from t where interval (select a from b) aa",
292 out: "interval :a aa",
293 }, {
294 in: "select * from t where (select a from b) collate utf8",
295 out: ":a collate utf8",
296 }, {
297 in: "select * from t where func((select a from b), 1)",
298 out: "func(:a, 1)",
299 }, {
300 in: "select * from t where func(1, (select a from b), 1)",
301 out: "func(1, :a, 1)",
302 }, {
303 in: "select * from t where group_concat((select a from b), 1 order by a)",
304 out: "group_concat(:a, 1 order by a asc)",
305 }, {
306 in: "select * from t where group_concat(1 order by (select a from b), a)",
307 out: "group_concat(1 order by :a asc, a asc)",
308 }, {
309 in: "select * from t where group_concat(1 order by a, (select a from b))",
310 out: "group_concat(1 order by a asc, :a asc)",
311 }, {
312 in: "select * from t where substr(a, (select a from b), b)",
313 out: "substr(a, :a, b)",
314 }, {
315 in: "select * from t where substr(a, b, (select a from b))",
316 out: "substr(a, b, :a)",
317 }, {
318 in: "select * from t where convert((select a from b), json)",
319 out: "convert(:a, json)",
320 }, {
321 in: "select * from t where convert((select a from b) using utf8)",
322 out: "convert(:a using utf8)",
323 }, {
324 in: "select * from t where match((select a from b), 1) against (a)",
325 out: "match(:a, 1) against (a)",
326 }, {
327 in: "select * from t where match(1, (select a from b), 1) against (a)",
328 out: "match(1, :a, 1) against (a)",
329 }, {
330 in: "select * from t where match(1, a, 1) against ((select a from b))",
331 out: "match(1, a, 1) against (:a)",
332 }, {
333 in: "select * from t where case (select a from b) when a then b when b then c else d end",
334 out: "case :a when a then b when b then c else d end",
335 }, {
336 in: "select * from t where case a when (select a from b) then b when b then c else d end",
337 out: "case a when :a then b when b then c else d end",
338 }, {
339 in: "select * from t where case a when b then (select a from b) when b then c else d end",
340 out: "case a when b then :a when b then c else d end",
341 }, {
342 in: "select * from t where case a when b then c when (select a from b) then c else d end",
343 out: "case a when b then c when :a then c else d end",
344 }, {
345 in: "select * from t where case a when b then c when d then c else (select a from b) end",
346 out: "case a when b then c when d then c else :a end",
347 }}
348 to := NewValArg([]byte(":a"))
349 for _, tcase := range tcases {
350 tree, err := Parse(tcase.in)
351 if err != nil {
352 t.Fatal(err)
353 }
354 var from *Subquery
355 _ = Walk(func(node SQLNode) (kontinue bool, err error) {
356 if sq, ok := node.(*Subquery); ok {
357 from = sq
358 return false, nil
359 }
360 return true, nil
361 }, tree)
362 if from == nil {
363 t.Fatalf("from is nil for %s", tcase.in)
364 }
365 expr := ReplaceExpr(tree.(*Select).Where.Expr, from, to)
366 got := String(expr)
367 if tcase.out != got {
368 t.Errorf("ReplaceExpr(%s): %s, want %s", tcase.in, got, tcase.out)
369 }
370 }
371 }
372
373 func TestExprFromValue(t *testing.T) {
374 tcases := []struct {
375 in sqltypes.Value
376 out SQLNode
377 err string
378 }{{
379 in: sqltypes.NULL,
380 out: &NullVal{},
381 }, {
382 in: sqltypes.NewInt64(1),
383 out: NewIntVal([]byte("1")),
384 }, {
385 in: sqltypes.NewFloat64(1.1),
386 out: NewFloatVal([]byte("1.1")),
387 }, {
388 in: sqltypes.MakeTrusted(sqltypes.Decimal, []byte("1.1")),
389 out: NewFloatVal([]byte("1.1")),
390 }, {
391 in: sqltypes.NewVarChar("aa"),
392 out: NewStrVal([]byte("aa")),
393 }, {
394 in: sqltypes.MakeTrusted(sqltypes.Expression, []byte("rand()")),
395 err: "cannot convert value EXPRESSION(rand()) to AST",
396 }}
397 for _, tcase := range tcases {
398 got, err := ExprFromValue(tcase.in)
399 if tcase.err != "" {
400 if err == nil || err.Error() != tcase.err {
401 t.Errorf("ExprFromValue(%v) err: %v, want %s", tcase.in, err, tcase.err)
402 }
403 continue
404 }
405 if err != nil {
406 t.Error(err)
407 }
408 if got, want := got, tcase.out; !reflect.DeepEqual(got, want) {
409 t.Errorf("ExprFromValue(%v): %v, want %s", tcase.in, got, want)
410 }
411 }
412 }
413
414 func TestColNameEqual(t *testing.T) {
415 var c1, c2 *ColName
416 if c1.Equal(c2) {
417 t.Error("nil columns equal, want unequal")
418 }
419 c1 = &ColName{
420 Name: NewColIdent("aa"),
421 }
422 c2 = &ColName{
423 Name: NewColIdent("bb"),
424 }
425 if c1.Equal(c2) {
426 t.Error("columns equal, want unequal")
427 }
428 c2.Name = NewColIdent("aa")
429 if !c1.Equal(c2) {
430 t.Error("columns unequal, want equal")
431 }
432 }
433
434 func TestColIdent(t *testing.T) {
435 str := NewColIdent("Ab")
436 if str.String() != "Ab" {
437 t.Errorf("String=%s, want Ab", str.String())
438 }
439 if str.String() != "Ab" {
440 t.Errorf("Val=%s, want Ab", str.String())
441 }
442 if str.Lowered() != "ab" {
443 t.Errorf("Val=%s, want ab", str.Lowered())
444 }
445 if !str.Equal(NewColIdent("aB")) {
446 t.Error("str.Equal(NewColIdent(aB))=false, want true")
447 }
448 if !str.EqualString("ab") {
449 t.Error("str.EqualString(ab)=false, want true")
450 }
451 str = NewColIdent("")
452 if str.Lowered() != "" {
453 t.Errorf("Val=%s, want \"\"", str.Lowered())
454 }
455 }
456
457 func TestColIdentMarshal(t *testing.T) {
458 str := NewColIdent("Ab")
459 b, err := json.Marshal(str)
460 if err != nil {
461 t.Fatal(err)
462 }
463 got := string(b)
464 want := `"Ab"`
465 if got != want {
466 t.Errorf("json.Marshal()= %s, want %s", got, want)
467 }
468 var out ColIdent
469 if err := json.Unmarshal(b, &out); err != nil {
470 t.Errorf("Unmarshal err: %v, want nil", err)
471 }
472 if !reflect.DeepEqual(out, str) {
473 t.Errorf("Unmarshal: %v, want %v", out, str)
474 }
475 }
476
477 func TestColIdentSize(t *testing.T) {
478 size := unsafe.Sizeof(NewColIdent(""))
479 want := 2 * unsafe.Sizeof("")
480 if size != want {
481 t.Errorf("Size of ColIdent: %d, want 32", want)
482 }
483 }
484
485 func TestTableIdentMarshal(t *testing.T) {
486 str := NewTableIdent("Ab")
487 b, err := json.Marshal(str)
488 if err != nil {
489 t.Fatal(err)
490 }
491 got := string(b)
492 want := `"Ab"`
493 if got != want {
494 t.Errorf("json.Marshal()= %s, want %s", got, want)
495 }
496 var out TableIdent
497 if err := json.Unmarshal(b, &out); err != nil {
498 t.Errorf("Unmarshal err: %v, want nil", err)
499 }
500 if !reflect.DeepEqual(out, str) {
501 t.Errorf("Unmarshal: %v, want %v", out, str)
502 }
503 }
504
505 func TestHexDecode(t *testing.T) {
506 testcase := []struct {
507 in, out string
508 }{{
509 in: "313233",
510 out: "123",
511 }, {
512 in: "ag",
513 out: "encoding/hex: invalid byte: U+0067 'g'",
514 }, {
515 in: "777",
516 out: "encoding/hex: odd length hex string",
517 }}
518 for _, tc := range testcase {
519 out, err := newHexVal(tc.in).HexDecode()
520 if err != nil {
521 if err.Error() != tc.out {
522 t.Errorf("Decode(%q): %v, want %s", tc.in, err, tc.out)
523 }
524 continue
525 }
526 if !bytes.Equal(out, []byte(tc.out)) {
527 t.Errorf("Decode(%q): %s, want %s", tc.in, out, tc.out)
528 }
529 }
530 }
531
532 func TestCompliantName(t *testing.T) {
533 testcases := []struct {
534 in, out string
535 }{{
536 in: "aa",
537 out: "aa",
538 }, {
539 in: "1a",
540 out: "_a",
541 }, {
542 in: "a1",
543 out: "a1",
544 }, {
545 in: "a.b",
546 out: "a_b",
547 }, {
548 in: ".ab",
549 out: "_ab",
550 }}
551 for _, tc := range testcases {
552 out := NewColIdent(tc.in).CompliantName()
553 if out != tc.out {
554 t.Errorf("ColIdent(%s).CompliantNamt: %s, want %s", tc.in, out, tc.out)
555 }
556 out = NewTableIdent(tc.in).CompliantName()
557 if out != tc.out {
558 t.Errorf("TableIdent(%s).CompliantNamt: %s, want %s", tc.in, out, tc.out)
559 }
560 }
561 }
562
563 func TestColumns_FindColumn(t *testing.T) {
564 cols := Columns{NewColIdent("a"), NewColIdent("c"), NewColIdent("b"), NewColIdent("0")}
565
566 testcases := []struct {
567 in string
568 out int
569 }{{
570 in: "a",
571 out: 0,
572 }, {
573 in: "b",
574 out: 2,
575 },
576 {
577 in: "0",
578 out: 3,
579 },
580 {
581 in: "f",
582 out: -1,
583 }}
584
585 for _, tc := range testcases {
586 val := cols.FindColumn(NewColIdent(tc.in))
587 if val != tc.out {
588 t.Errorf("FindColumn(%s): %d, want %d", tc.in, val, tc.out)
589 }
590 }
591 }
592
593 func TestSplitStatementToPieces(t *testing.T) {
594 testcases := []struct {
595 input string
596 output string
597 }{{
598 input: "select * from table",
599 }, {
600 input: "select * from table1; select * from table2;",
601 output: "select * from table1; select * from table2",
602 }, {
603 input: "select * from /* comment ; */ table;",
604 output: "select * from /* comment ; */ table",
605 }, {
606 input: "select * from table where semi = ';';",
607 output: "select * from table where semi = ';'",
608 }, {
609 input: "select * from table1;--comment;\nselect * from table2;",
610 output: "select * from table1;--comment;\nselect * from table2",
611 }, {
612 input: "CREATE TABLE `total_data` (`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id', " +
613 "`region` varchar(32) NOT NULL COMMENT 'region name, like zh; th; kepler'," +
614 "`data_size` bigint NOT NULL DEFAULT '0' COMMENT 'data size;'," +
615 "`createtime` datetime NOT NULL DEFAULT NOW() COMMENT 'create time;'," +
616 "`comment` varchar(100) NOT NULL DEFAULT '' COMMENT 'comment'," +
617 "PRIMARY KEY (`id`))",
618 }}
619
620 for _, tcase := range testcases {
621 if tcase.output == "" {
622 tcase.output = tcase.input
623 }
624
625 stmtPieces, err := SplitStatementToPieces(tcase.input)
626 if err != nil {
627 t.Errorf("input: %s, err: %v", tcase.input, err)
628 continue
629 }
630
631 out := strings.Join(stmtPieces, ";")
632 if out != tcase.output {
633 t.Errorf("out: %s, want %s", out, tcase.output)
634 }
635 }
636 }