forked from mgutz/dat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
insect_test.go
109 lines (96 loc) · 2.29 KB
/
insect_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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package dat
import (
"regexp"
"testing"
"gopkg.in/stretchr/testify.v1/assert"
)
var regexpWS = regexp.MustCompile(`\s`)
func stripWS(s string) string {
return regexpWS.ReplaceAllLiteralString(s, "")
}
func TestInsectSqlSimple(t *testing.T) {
sql, args := Insect("tab").Columns("b", "c").Values(1, 2).ToSQL()
expected := `
WITH
sel AS (SELECT b, c FROM tab WHERE (b = $1) AND (c = $2)),
ins AS (
INSERT INTO "tab"("b","c")
SELECT $1, $2
WHERE NOT EXISTS (SELECT 1 FROM sel)
RETURNING "b","c"
)
SELECT * FROM ins UNION ALL SELECT * FROM sel
`
assert.Equal(t, stripWS(expected), stripWS(sql))
assert.Equal(t, args, []interface{}{1, 2})
}
func TestInsectSqlWhere(t *testing.T) {
sql, args := Insect("tab").
Columns("b", "c").
Values(1, 2).
Where("d = $1", 3).
ToSQL()
expected := `
WITH
sel AS (SELECT b, c FROM tab WHERE (d = $1)),
ins AS (
INSERT INTO "tab"("b","c")
SELECT $2, $3
WHERE NOT EXISTS (SELECT 1 FROM sel)
RETURNING "b", "c"
)
SELECT * FROM ins UNION ALL SELECT * FROM sel
`
assert.Equal(t, stripWS(expected), stripWS(sql))
assert.Equal(t, args, []interface{}{3, 1, 2})
}
func TestInsectSqlReturning(t *testing.T) {
sql, args := Insect("tab").
Columns("b", "c").
Values(1, 2).
Where("d = $1", 3).
Returning("id", "f", "g").
ToSQL()
expected := `
WITH
sel AS (SELECT id, f, g FROM tab WHERE (d = $1)),
ins AS (
INSERT INTO "tab"("b","c")
SELECT $2,$3
WHERE NOT EXISTS (SELECT 1 FROM sel)
RETURNING "id","f","g"
)
SELECT * FROM ins UNION ALL SELECT * FROM sel
`
assert.Equal(t, stripWS(expected), stripWS(sql))
assert.Equal(t, args, []interface{}{3, 1, 2})
}
func TestInsectSqlRecord(t *testing.T) {
type Embedded struct {
D int `db:"d"`
}
var rec = struct {
B int `db:"b"`
C int `db:"c"`
Embedded
}{1, 2, Embedded{4}}
sql, args := Insect("tab").
Columns("b", "c", "d").
Record(rec).
Where("d = $1", 3).
Returning("id", "f", "g").
ToSQL()
expected := `
WITH
sel AS (SELECT id, f, g FROM tab WHERE (d = $1)),
ins AS (
INSERT INTO "tab"("b","c","d")
SELECT $2, $3, $4
WHERE NOT EXISTS (SELECT 1 FROM sel)
RETURNING "id","f","g"
)
SELECT * FROM ins UNION ALL SELECT * FROM sel
`
assert.Equal(t, stripWS(expected), stripWS(sql))
assert.Equal(t, args, []interface{}{3, 1, 2, 4})
}