-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuilder_test.go
More file actions
99 lines (82 loc) · 2.24 KB
/
builder_test.go
File metadata and controls
99 lines (82 loc) · 2.24 KB
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
package squildx
import (
"testing"
)
func TestFullAPIExample(t *testing.T) {
q, params, err := New().
Select("u.name", "o.total").
From("users u").
InnerJoin("orders o ON o.user_id = u.id").
Where("age > :min_age", Params{"min_age": 18}).
Where("active = :active", Params{"active": true}).
OrderBy("u.name ASC").
Limit(10).
Offset(20).
Build()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
expected := "SELECT u.name, o.total FROM users u INNER JOIN orders o ON o.user_id = u.id WHERE age > :min_age AND active = :active ORDER BY u.name ASC LIMIT 10 OFFSET 20"
if q != expected {
t.Errorf("SQL mismatch\n got: %s\nwant: %s", q, expected)
}
assertParam(t, params, "min_age", 18)
assertParam(t, params, "active", true)
if len(params) != 2 {
t.Errorf("expected 2 params, got %d", len(params))
}
}
func TestImmutability(t *testing.T) {
base := New().Select("*").From("users")
q1, _, err := base.Where("active = :active", Params{"active": true}).Build()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
q2, _, err := base.Where("role = :role", Params{"role": "admin"}).Build()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if q1 != "SELECT * FROM users WHERE active = :active" {
t.Errorf("q1 mismatch: %s", q1)
}
if q2 != "SELECT * FROM users WHERE role = :role" {
t.Errorf("q2 mismatch: %s", q2)
}
}
func TestConditionalFiltering(t *testing.T) {
type filter struct {
Age int
Name string
}
f := filter{Age: 25}
q := New().Select("*").From("users")
if f.Age != 0 {
q = q.Where("age = :age", Params{"age": f.Age})
}
if f.Name != "" {
q = q.Where("name = :name", Params{"name": f.Name})
}
sql, params, err := q.Build()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
expected := "SELECT * FROM users WHERE age = :age"
if sql != expected {
t.Errorf("SQL mismatch\n got: %s\nwant: %s", sql, expected)
}
assertParam(t, params, "age", 25)
if len(params) != 1 {
t.Errorf("expected 1 param, got %d", len(params))
}
}
func assertParam(t *testing.T, params Params, key string, expected any) {
t.Helper()
val, ok := params[key]
if !ok {
t.Errorf("missing param %q", key)
return
}
if val != expected {
t.Errorf("param %q = %v, want %v", key, val, expected)
}
}