-
Notifications
You must be signed in to change notification settings - Fork 0
/
update_test.go
81 lines (67 loc) · 2.24 KB
/
update_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
package sq
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestUpdateBuilderToSql(t *testing.T) {
b := Update("").
Prefix("WITH prefix AS ?", 0).
Table("a").
Set("b", Expr("? + 1", 1)).
SetMap(Eq{"c": 2}).
Set("c1", Case("status").When("1", "2").When("2", "1")).
Set("c2", Case().When("a = 2", Expr("?", "foo")).When("a = 3", Expr("?", "bar"))).
Set("c3", Select("a").From("b")).
Where("d = ?", 3).
OrderBy("e").
Limit(4).
Offset(5).
Suffix("RETURNING ?", 6)
sql, args, err := b.ToSql()
require.NoError(t, err)
expectedSql :=
"WITH prefix AS ? " +
"UPDATE a SET b = ? + 1, c = ?, " +
"c1 = CASE status WHEN 1 THEN 2 WHEN 2 THEN 1 END, " +
"c2 = CASE WHEN a = 2 THEN ? WHEN a = 3 THEN ? END, " +
"c3 = (SELECT a FROM b) " +
"WHERE d = ? " +
"ORDER BY e LIMIT 4 OFFSET 5 " +
"RETURNING ?"
require.Equal(t, expectedSql, sql)
expectedArgs := []any{0, 1, 2, "foo", "bar", 3, 6}
require.Equal(t, expectedArgs, args)
}
func TestUpdateBuilderToSqlErr(t *testing.T) {
_, _, err := Update("").Set("x", 1).ToSql()
require.Error(t, err)
_, _, err = Update("x").ToSql()
require.Error(t, err)
}
func TestUpdateBuilderPlaceholders(t *testing.T) {
b := Update("test").SetMap(Eq{"x": 1, "y": 2})
sql, _, _ := b.PlaceholderFormat(Question).ToSql()
require.Equal(t, "UPDATE test SET x = ?, y = ?", sql)
sql, _, _ = b.PlaceholderFormat(Dollar).ToSql()
require.Equal(t, "UPDATE test SET x = $1, y = $2", sql)
}
func TestUpdateBuilderFrom(t *testing.T) {
sql, _, err := Update("employees").Set("sales_count", 100).From("accounts").Where("accounts.name = ?", "ACME").ToSql()
require.NoError(t, err)
require.Equal(t, "UPDATE employees SET sales_count = ? FROM accounts WHERE accounts.name = ?", sql)
}
func TestUpdateBuilderFromSelect(t *testing.T) {
sql, _, err := Update("employees").
Set("sales_count", 100).
FromSelect(Select("id").
From("accounts").
Where("accounts.name = ?", "ACME"), "subquery").
Where("employees.account_id = subquery.id").ToSql()
require.NoError(t, err)
expectedSql :=
"UPDATE employees " +
"SET sales_count = ? " +
"FROM (SELECT id FROM accounts WHERE accounts.name = ?) AS subquery " +
"WHERE employees.account_id = subquery.id"
require.Equal(t, expectedSql, sql)
}