forked from mgutz/dat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
upsert_test.go
90 lines (79 loc) · 1.82 KB
/
upsert_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
package dat
import (
"testing"
"gopkg.in/stretchr/testify.v1/assert"
)
func TestUpsertSQLMissingWhere(t *testing.T) {
assert.Panics(t, func() {
Upsert("tab").Columns("b", "c").Values(1, 2).ToSQL()
})
}
func TestUpsertSQLWhere(t *testing.T) {
sql, args := Upsert("tab").Columns("b", "c").Values(1, 2).Where("d=$1", 4).ToSQL()
expected := `
WITH
upd AS (
UPDATE "tab"
SET "b" = $1, "c" = $2
WHERE (d=$3)
RETURNING "b","c"
), ins AS (
INSERT INTO "tab"("b","c")
SELECT $1,$2
WHERE NOT EXISTS (SELECT 1 FROM upd)
RETURNING "b","c"
)
SELECT * FROM ins UNION ALL SELECT * FROM upd
`
assert.Equal(t, stripWS(expected), stripWS(sql))
assert.Equal(t, []interface{}{1, 2, 4}, args)
}
func TestUpsertSQLReturning(t *testing.T) {
sql, args := Upsert("tab").Columns("b", "c").Values(1, 2).Where("d=$1", 4).Returning("f", "g").ToSQL()
expected := `
WITH
upd AS (
UPDATE "tab"
SET "b" = $1, "c" = $2
WHERE (d=$3)
RETURNING "f","g"
), ins AS (
INSERT INTO "tab"("b","c")
SELECT $1,$2
WHERE NOT EXISTS (SELECT 1 FROM upd)
RETURNING "f","g"
)
SELECT * FROM ins UNION ALL SELECT * FROM upd
`
assert.Equal(t, stripWS(expected), stripWS(sql))
assert.Equal(t, []interface{}{1, 2, 4}, args)
}
func TestUpsertSQLRecord(t *testing.T) {
var rec = struct {
B int `db:"b"`
C int `db:"c"`
}{1, 2}
sql, args := Upsert("tab").
Columns("b", "c").
Record(rec).
Where("d=$1", 4).
Returning("f", "g").
ToSQL()
expected := `
WITH
upd AS (
UPDATE "tab"
SET "b" = $1, "c" = $2
WHERE (d=$3)
RETURNING "f","g"
), ins AS (
INSERT INTO "tab"("b","c")
SELECT $1,$2
WHERE NOT EXISTS (SELECT 1 FROM upd)
RETURNING "f","g"
)
SELECT * FROM ins UNION ALL SELECT * FROM upd
`
assert.Equal(t, stripWS(expected), stripWS(sql))
assert.Equal(t, []interface{}{1, 2, 4}, args)
}