Repository navigation
Expand file tree
/
Copy pathpeer_test.go
More file actions
289 lines (272 loc) · 7.52 KB
/
Copy pathpeer_test.go
File metadata and controls
289 lines (272 loc) · 7.52 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// Copyright (c) 2026 The liustack/sqlite Authors.
// SPDX-License-Identifier: MIT
// Use of this source code is governed by the MIT license in LICENSE at the
// root of this repository.
//go:build ((linux || darwin) && (amd64 || arm64)) || (windows && (amd64 || arm64))
package sqlite
import (
"bufio"
"context"
"database/sql"
"fmt"
"io"
"os"
"os/exec"
"strings"
"syscall"
"testing"
"time"
)
// The peer helper runs the statements it reads from its standard input, one
// per line, on one connection to the database named in its environment. For
// each it prints the rows, the columns of a row joined by "|", or the
// error, and then peerDone.
//
// The line peerCheckpoints is not a statement: the first one has the helper
// watch the checkpoints the driver runs in its process (watchCheckpoints),
// and each prints how many it saw and the longest, in nanoseconds, joined
// by "|".
const (
peerEnv = "SQLITE_TEST_PEER_DB"
peerDone = "--done--"
peerCheckpoints = "--checkpoints--"
)
// PeerEnv and PeerHelper are for TestMain, which is in the other test package.
const PeerEnv = peerEnv
var PeerHelper = peerHelper
func peerHelper(dsn string) int {
ctx := context.Background()
db, err := sql.Open("sqlite", dsn)
if err != nil {
fmt.Println(err)
return 1
}
var conn *sql.Conn
var watch *checkpointWatch
in := bufio.NewScanner(os.Stdin)
for in.Scan() {
if in.Text() == peerCheckpoints {
if watch == nil {
watch = watchCheckpoints("")
}
c := watch.now()
fmt.Printf("%d|%d\n%s\n", c.n, int64(c.longest), peerDone)
continue
}
// A connection that failed is dropped by database/sql: the next
// statement takes a new one.
if conn == nil {
if conn, err = db.Conn(ctx); err != nil {
fmt.Printf("error: %v\n%s\n", err, peerDone)
conn = nil
continue
}
}
if err := peerRun(ctx, conn, in.Text()); err != nil {
fmt.Printf("error: %v\n", err)
conn.Close()
conn = nil
}
fmt.Println(peerDone)
}
return 0
}
func peerRun(ctx context.Context, conn *sql.Conn, q string) error {
rows, err := conn.QueryContext(ctx, q)
if err != nil {
return err
}
defer rows.Close()
cols, err := rows.Columns()
if err != nil {
return err
}
vals := make([]any, len(cols))
for i := range vals {
vals[i] = new(sql.NullString)
}
for rows.Next() {
if err := rows.Scan(vals...); err != nil {
return err
}
out := make([]string, len(vals))
for i, v := range vals {
out[i] = v.(*sql.NullString).String
}
fmt.Println(strings.Join(out, "|"))
}
return rows.Err()
}
// A peer is another process with the database open: this driver in the
// test binary run again, or the sqlite3 shell, which is SQLite's own VFS.
type peer struct {
t *testing.T
cmd *exec.Cmd
in io.WriteCloser
out *bufio.Reader
stopped bool
}
// peerKinds are the peers the machine has.
func peerKinds() []string {
kinds := []string{"driver"}
if _, err := exec.LookPath("sqlite3"); err == nil {
kinds = append(kinds, "sqlite3")
}
return kinds
}
func startPeer(t *testing.T, kind, path string) *peer {
t.Helper()
// It leaves the journal mode of the file as the test made it.
return startPeerDSN(t, kind, path, "file:"+path+"?_pragma=journal_mode")
}
// startPeerDSN starts a peer that opens path, the driver with dsn.
func startPeerDSN(t *testing.T, kind, path, dsn string) *peer {
t.Helper()
var cmd *exec.Cmd
if kind == "sqlite3" {
// It waits for a lock as long as this driver does by default (5 s):
// the shell alone waits for none, and gives "database is locked" as
// soon as it meets one, as while a connection here closes and locks
// the database to checkpoint.
cmd = exec.Command("sqlite3", "-batch", "-cmd", ".timeout 5000", path)
} else {
exe, err := os.Executable()
if err != nil {
t.Fatal(err)
}
cmd = exec.Command(exe)
// Every goroutine in the dump of a peer that hangs (stop).
cmd.Env = append(os.Environ(), peerEnv+"="+dsn, "GOTRACEBACK=all")
}
in, err := cmd.StdinPipe()
if err != nil {
t.Fatal(err)
}
out, err := cmd.StdoutPipe()
if err != nil {
t.Fatal(err)
}
cmd.Stderr = cmd.Stdout
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
p := &peer{t: t, cmd: cmd, in: in, out: bufio.NewReader(out)}
t.Cleanup(p.stop)
return p
}
// do runs one statement in the peer and returns what it printed.
func (p *peer) do(q string) string {
p.t.Helper()
end := ""
if p.cmd.Args[0] == "sqlite3" {
end = ";\n.print " + peerDone
}
if _, err := io.WriteString(p.in, q+end+"\n"); err != nil {
p.t.Fatalf("peer: %s: %v", q, err)
}
var b strings.Builder
for {
line, err := p.out.ReadString('\n')
if err != nil {
p.t.Fatalf("peer: %s: %v after %q", q, err, b.String())
}
if line == peerDone+"\n" {
break
}
b.WriteString(line)
}
return strings.TrimSpace(b.String())
}
// many runs q n times in the peer with no pause in between: they are sent
// without waiting for what the peer prints. It returns what the peer
// printed for each that printed something, an error or rows, and the
// longest time between the ends of two statements, or from the call to the
// end of the first: as the peer always has the next statement to run, that
// is about how long its slowest statement took.
func (p *peer) many(q string, n int) (printed []string, slowest time.Duration) {
p.t.Helper()
end := ""
if p.cmd.Args[0] == "sqlite3" {
end = ";\n.print " + peerDone
}
go func() {
// A write that fails leaves the peer short of statements: the
// reads below fail then.
w := bufio.NewWriter(p.in)
for range n {
w.WriteString(q + end + "\n")
}
w.Flush()
}()
last := time.Now()
for i := range n {
var b strings.Builder
for {
line, err := p.out.ReadString('\n')
if err != nil {
p.t.Fatalf("peer: %s, %d of %d: %v after %q", q, i, n, err, b.String())
}
if line == peerDone+"\n" {
break
}
b.WriteString(line)
}
now := time.Now()
slowest = max(slowest, now.Sub(last))
last = now
if s := strings.TrimSpace(b.String()); s != "" {
printed = append(printed, s)
}
}
return printed, slowest
}
// up waits until the shell runs, before it reads the database: a newer
// shell reads it at its first statement, also one like SELECT 1.
func (p *peer) up() {
p.t.Helper()
if _, err := io.WriteString(p.in, ".print "+peerDone+"\n"); err != nil {
p.t.Fatalf("peer: %v", err)
}
if line, err := p.out.ReadString('\n'); err != nil || line != peerDone+"\n" {
p.t.Fatalf("peer: %q %v", line, err)
}
}
// want runs one statement in the peer, which must print want.
func (p *peer) want(q, want string) {
p.t.Helper()
if got := p.do(q); got != want {
p.t.Fatalf("peer: %s: %q, want %q", q, got, want)
}
}
// stop ends the peer, which closes its connection. A peer still running
// 10 s after its input closed fails the test: it gets SIGQUIT where there
// is one, so that the test shows where its goroutines were, and is killed
// where there is none.
func (p *peer) stop() {
if p.stopped {
return
}
p.stopped = true
p.in.Close()
exited := make(chan struct{})
go func() {
p.cmd.Process.Wait()
close(exited)
}()
select {
case <-exited:
case <-time.After(10 * time.Second):
if err := p.cmd.Process.Signal(syscall.SIGQUIT); err != nil {
p.cmd.Process.Kill()
}
// One that SIGQUIT does not end is killed. The output ends as the
// peer exits.
kill := time.AfterFunc(10*time.Second, func() { p.cmd.Process.Kill() })
rest, _ := io.ReadAll(p.out)
kill.Stop()
<-exited
p.cmd.Wait() // closes the pipes
p.t.Fatalf("peer %d did not exit 10 s after its input closed:\n%s", p.cmd.Process.Pid, rest)
}
p.cmd.Wait() // closes the pipes
}