-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstmt_test.go
102 lines (88 loc) · 2.56 KB
/
stmt_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
package mysqlx
import (
"context"
"database/sql"
"fmt"
"math"
"testing"
)
func prepare1(cnn *sql.Conn, in any) (out any, err error) {
stmt, err := cnn.PrepareContext(context.Background(), "SELECT ?")
if err != nil {
return nil, err
}
defer stmt.Close()
rows, err := stmt.Query(in)
if err != nil {
return nil, err
}
defer rows.Close()
if !rows.Next() {
return nil, sql.ErrNoRows
}
err = rows.Scan(&out)
return
}
// value constraint, comparable without string as strings are returned as byte slices.
type value interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
~float32 | ~float64 | ~bool
}
func testPrepareValue[T value, S value](t *testing.T, cnn *sql.Conn, in T, expected S) {
t.Helper()
t.Run(fmt.Sprintf("%T(%v)", in, in), func(t *testing.T) {
actual, err := prepare1(cnn, in)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if a, ok := actual.(S); !ok {
t.Fatalf("expected type %T got %T", expected, actual)
} else if a != expected {
t.Fatalf("expected value %T(%v) got %T(%v)", expected, expected, actual, actual)
}
})
}
func testPrepareString(t *testing.T, cnn *sql.Conn, in any) {
t.Helper()
t.Run(fmt.Sprintf("%T(%q)", in, in), func(t *testing.T) {
actual, err := prepare1(cnn, in)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if a, ok := actual.([]byte); !ok {
t.Fatalf("expected type []byte got %T", actual)
} else if ss, ok := in.(string); ok {
if string(a) != string(ss) {
t.Fatalf("expected %q got %q", in, actual)
}
}
})
}
func TestPrepare(t *testing.T) {
connector := NewConnector(t)
db := sql.OpenDB(connector)
defer db.Close()
// Grab single connection
cnn, err := db.Conn(context.Background())
assertNoError(t, err)
defer cnn.Close()
// testPrepare(t, cnn, nil)
testPrepareValue(t, cnn, 0, int64(0))
testPrepareValue(t, cnn, 1, int64(1))
testPrepareValue(t, cnn, math.MinInt64, int64(math.MinInt64))
testPrepareValue(t, cnn, math.MaxInt64, int64(math.MaxInt64))
testPrepareValue(t, cnn, float64(1.5), float64(1.5))
testPrepareValue(t, cnn, float32(1.5), float64(1.5))
testPrepareValue(t, cnn, int64(42), int64(42))
testPrepareValue(t, cnn, true, int64(1))
testPrepareValue(t, cnn, false, int64(0))
testPrepareString(t, cnn, "")
testPrepareString(t, cnn, "abc")
testPrepareString(t, cnn, JSON("{}"))
testPrepareString(t, cnn, XML("<foo />"))
testPrepareString(t, cnn, []byte{})
testPrepareString(t, cnn, []byte("abc"))
testPrepareString(t, cnn, JSON([]byte("{}")))
testPrepareString(t, cnn, XML([]byte("<foo />")))
}