forked from huandu/go-sqlbuilder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
args_test.go
88 lines (70 loc) · 2.14 KB
/
args_test.go
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
// Copyright 2018 Huan Du. All rights reserved.
// Licensed under the MIT license that can be found in the LICENSE file.
package sqlbuilder
import (
"bytes"
"fmt"
"strings"
"testing"
)
func TestArgs(t *testing.T) {
cases := map[string][]interface{}{
"abc ? def\n[123]": {"abc $? def", 123},
"abc ? def\n[456]": {"abc $0 def", 456},
"abc def\n[]": {"abc $1 def", 123},
"abc ? def\n[789]": {"abc ${s} def", Named("s", 789)},
"abc def \n[]": {"abc ${unknown} def ", 123},
"abc $ def\n[]": {"abc $$ def", 123},
"abcdef$\n[]": {"abcdef$", 123},
"abc ? ? ? ? def\n[123 456 123 456]": {"abc $? $? $0 $? def", 123, 456, 789},
"abc ? raw ? raw def\n[123 123]": {"abc $? $? $0 $? def", 123, Raw("raw"), 789},
}
for expected, c := range cases {
args := new(Args)
for i := 1; i < len(c); i++ {
args.Add(c[i])
}
sql, values := args.Compile(c[0].(string))
actual := fmt.Sprintf("%v\n%v", sql, values)
if actual != expected {
t.Fatalf("invalid compile result. [expected:%v] [actual:%v]", expected, actual)
}
}
old := DefaultFlavor
DefaultFlavor = PostgreSQL
defer func() {
DefaultFlavor = old
}()
// PostgreSQL flavor compiled sql.
for expected, c := range cases {
args := new(Args)
for i := 1; i < len(c); i++ {
args.Add(c[i])
}
sql, values := args.Compile(c[0].(string))
actual := fmt.Sprintf("%v\n%v", sql, values)
expected = toPostgreSQL(expected)
if actual != expected {
t.Fatalf("invalid compile result. [expected:%v] [actual:%v]", expected, actual)
}
}
}
func toPostgreSQL(sql string) string {
parts := strings.Split(sql, "?")
buf := &bytes.Buffer{}
buf.WriteString(parts[0])
for i, p := range parts[1:] {
fmt.Fprintf(buf, "$%v", i+1)
buf.WriteString(p)
}
return buf.String()
}
func TestArgsAdd(t *testing.T) {
args := &Args{}
for i := 0; i < maxPredefinedArgs*2; i++ {
expected := fmt.Sprintf("$%v", i)
if actual := args.Add(i); actual != expected {
t.Fatalf("invalid args placeholder. [expected:%v] [actual:%v]", expected, actual)
}
}
}