-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackup_factory_test.go
More file actions
224 lines (206 loc) · 6.34 KB
/
Copy pathbackup_factory_test.go
File metadata and controls
224 lines (206 loc) · 6.34 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
package sqlite
import (
"context"
"database/sql"
"errors"
"path/filepath"
"testing"
)
// TestBackup_LiveDBToFile copies an in-memory database into a freshly created
// on-disk file and verifies the rows survive after reopening the file.
func TestBackup_LiveDBToFile(t *testing.T) {
ctx := context.Background()
// Populate a source in-memory database.
srcDB, srcSC, srcConn := withSQLite3Conn(t, ":memory:")
if _, err := srcSC.ExecContext(ctx, `CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO t (id, name) VALUES (1, 'alpha'), (2, 'beta'), (3, 'gamma');`); err != nil {
t.Fatal(err)
}
_ = srcDB
// Open a destination on-disk database.
dstPath := filepath.Join(t.TempDir(), "backup.db")
dstDB, err := sql.Open(DriverNameSQLite3, dstPath)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { dstDB.Close() })
dstSC, err := dstDB.Conn(ctx)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { dstSC.Close() })
var dstConn *Conn
if err := dstSC.Raw(func(dc any) error {
dstConn = dc.(*Conn)
return nil
}); err != nil {
t.Fatal(err)
}
bk, err := dstConn.Backup("main", srcConn, "main")
if err != nil {
t.Fatalf("Backup: %v", err)
}
// Step until the source is fully copied.
totalSteps := 0
for {
more, err := bk.Step(2)
if err != nil {
t.Fatalf("Step: %v", err)
}
totalSteps++
if !more {
break
}
if totalSteps > 1000 {
t.Fatal("backup did not converge after 1000 steps")
}
}
if remaining := bk.Remaining(); remaining != 0 {
t.Errorf("Remaining()=%d after Step returned done, want 0", remaining)
}
if pages := bk.PageCount(); pages == 0 {
t.Errorf("PageCount() = 0 after copy, want > 0")
}
if err := bk.Finish(); err != nil {
t.Fatalf("Finish: %v", err)
}
// Verify the destination contains the source rows.
rows, err := dstSC.QueryContext(ctx, "SELECT id, name FROM t ORDER BY id")
if err != nil {
t.Fatal(err)
}
defer rows.Close()
type entry struct {
id int
name string
}
var got []entry
for rows.Next() {
var e entry
if err := rows.Scan(&e.id, &e.name); err != nil {
t.Fatal(err)
}
got = append(got, e)
}
want := []entry{{1, "alpha"}, {2, "beta"}, {3, "gamma"}}
if len(got) != len(want) {
t.Fatalf("got %d rows, want %d: %+v", len(got), len(want), got)
}
for i, w := range want {
if got[i] != w {
t.Errorf("[%d] got %+v, want %+v", i, got[i], w)
}
}
}
// TestBackup_NilSourceConn ensures Backup rejects a nil source rather than
// segfaulting.
func TestBackup_NilSourceConn(t *testing.T) {
_, _, c := withSQLite3Conn(t, ":memory:")
_, err := c.Backup("main", nil, "main")
if err == nil {
t.Fatal("expected error from nil src conn")
}
}
// TestSerializeDeserialize_RoundTrip dumps an in-memory database to bytes and
// reloads it into a fresh in-memory database, checking row preservation.
func TestSerializeDeserialize_RoundTrip(t *testing.T) {
ctx := context.Background()
src, err := sql.Open(DriverNameSQLite3, ":memory:")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { src.Close() })
src.SetMaxOpenConns(1)
if _, err := src.ExecContext(ctx, `CREATE TABLE m (k INTEGER PRIMARY KEY, v TEXT);
INSERT INTO m (k, v) VALUES (1, 'one'), (2, 'two');`); err != nil {
t.Fatal(err)
}
data, err := Serialize(ctx, src)
if err != nil {
t.Fatalf("Serialize: %v", err)
}
if len(data) == 0 {
t.Fatal("Serialize returned empty bytes")
}
dst, err := sql.Open(DriverNameSQLite3, ":memory:")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { dst.Close() })
dst.SetMaxOpenConns(1)
// Force the destination's only conn to be the one we Deserialize into.
dstConn, err := dst.Conn(ctx)
if err != nil {
t.Fatal(err)
}
defer dstConn.Close()
if err := dstConn.Raw(func(dc any) error {
return dc.(*Conn).Deserialize(data)
}); err != nil {
t.Fatalf("Deserialize: %v", err)
}
var k int
var v string
if err := dstConn.QueryRowContext(ctx, "SELECT k, v FROM m ORDER BY k LIMIT 1").Scan(&k, &v); err != nil {
t.Fatal(err)
}
if k != 1 || v != "one" {
t.Errorf("got k=%d v=%q, want k=1 v=\"one\"", k, v)
}
}
// TestLoadExtension_Disabled returns a descriptive error when EnableLoadExtension
// hasn't been called, since SQLite refuses load_extension by default.
//
// Skipped under -race: modernc's _sqlite3LoadExtension does pointer arithmetic
// that trips Go's checkptr analyzer (enabled by -race), aborting the test
// binary with "fatal error: checkptr: pointer arithmetic result points to
// invalid allocation". The underlying C code is correct; this is a known
// modernc / Go-checkptr interaction.
//
// Also skipped on darwin and windows: modernc.org/libc's Xdlopen (darwin)
// and XLoadLibraryW (windows) shims abort the test binary with TODOTODO
// before our error-return path has a chance to fire. The test still
// covers the disabled-extensions error contract on linux, where it runs
// unconditionally.
func TestLoadExtension_Disabled(t *testing.T) {
if raceEnabled {
t.Skip("modernc.org/sqlite's _sqlite3LoadExtension trips Go's checkptr under -race")
}
if loadExtensionUnsupported {
t.Skip("modernc.org/libc dlopen/LoadLibraryW shim unimplemented on this OS")
}
_, _, c := withSQLite3Conn(t, ":memory:")
err := c.LoadExtension("/nonexistent/path/foo", "")
if err == nil {
t.Fatal("expected error loading a disabled/missing extension")
}
// We don't assert the exact text — different platforms phrase it
// differently — but we ensure an *Error came back.
var se *Error
if !errors.As(err, &se) {
t.Errorf("error not *sqlite.Error: %T (%v)", err, err)
}
}
// TestLoadExtension_EnabledBadPath enables loading and confirms a bad path
// surfaces as an error rather than crashing.
//
// Skipped on platforms where modernc.org/libc's dynamic-loader shim is
// incomplete: darwin's Xdlopen prints "Xdlopen: TODOTODO" and aborts;
// windows's XLoadLibraryW does the same. Also skipped under -race for the
// checkptr reason TestLoadExtension_Disabled is skipped.
func TestLoadExtension_EnabledBadPath(t *testing.T) {
if loadExtensionUnsupported {
t.Skip("modernc.org/libc dlopen/LoadLibraryW shim unimplemented on this OS")
}
if raceEnabled {
t.Skip("modernc.org/sqlite's _sqlite3LoadExtension trips Go's checkptr under -race")
}
_, _, c := withSQLite3Conn(t, ":memory:")
if err := c.EnableLoadExtension(true); err != nil {
t.Fatal(err)
}
err := c.LoadExtension("/definitely/not/an/extension", "")
if err == nil {
t.Fatal("expected error from missing path")
}
}