-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsquibble_test.go
More file actions
409 lines (367 loc) · 11.9 KB
/
squibble_test.go
File metadata and controls
409 lines (367 loc) · 11.9 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package squibble_test
import (
"context"
"database/sql"
"errors"
"fmt"
"path/filepath"
"strings"
"testing"
"time"
"github.com/tailscale/squibble"
_ "modernc.org/sqlite"
)
func mustOpenDB(t *testing.T) *sql.DB {
t.Helper()
path := filepath.Join(t.TempDir(), "test.db")
db, err := sql.Open("sqlite", "file://"+path)
if err != nil {
t.Fatalf("Open database: %v", err)
}
t.Cleanup(func() { db.Close() })
return db
}
func mustTableSchema(t *testing.T, db *sql.DB, table string) string {
t.Helper()
var schema string
err := db.QueryRow(
`SELECT sql FROM sqlite_schema WHERE name = ? AND type = 'table'`, table,
).Scan(&schema)
if err != nil {
t.Fatalf("Read schema for table %q: %v", table, err)
}
return schema
}
func checkTableSchema(t *testing.T, db *sql.DB, table, want string) {
t.Helper()
if got := mustTableSchema(t, db, table); !strings.EqualFold(got, want) {
t.Fatalf("Schema for table %q: got %q, want %q", table, got, want)
}
}
func mustHash(t *testing.T, text string) string {
t.Helper()
h, err := squibble.SQLDigest(text)
if err != nil {
t.Fatalf("SchemaHash failed: %v", err)
}
return h
}
func TestEmptySchema(t *testing.T) {
db := mustOpenDB(t)
invalid := new(squibble.Schema)
if err := invalid.Apply(t.Context(), db); err == nil {
t.Error("Apply should have failed, but did not")
}
}
func TestInitSchema(t *testing.T) {
db := mustOpenDB(t)
const schema = `create table foo (x text)`
s := &squibble.Schema{Current: schema, Logf: t.Logf}
if err := s.Apply(t.Context(), db); err != nil {
t.Fatalf("Apply failed: %v", err)
}
checkTableSchema(t, db, "foo", schema)
}
func TestUpgrade(t *testing.T) {
db := mustOpenDB(t)
// N.B.: The subtests in this test are intended to execute in order.
const v1 = `create table foo (x text)`
const v2 = `create table foo (x text, y text)`
const v3 = `create table foo (x text, y text); create table bar (z integer not null)`
const v4 = `create table foo (x text, z integer)`
t.Run("InitV1", func(t *testing.T) {
s := &squibble.Schema{Current: v1, Logf: t.Logf}
if err := s.Apply(t.Context(), db); err != nil {
t.Fatalf("Apply v1: unexpected error: %v", err)
}
checkTableSchema(t, db, "foo", v1)
})
t.Run("V1toV2", func(t *testing.T) {
s := &squibble.Schema{
Current: v2,
Updates: []squibble.UpdateRule{
{mustHash(t, v1), mustHash(t, v2),
squibble.Exec(`ALTER TABLE foo ADD COLUMN y text`)},
},
Logf: t.Logf,
}
if err := s.Apply(t.Context(), db); err != nil {
t.Fatalf("Apply v2: unexpected error: %v", err)
}
checkTableSchema(t, db, "foo", v2)
})
t.Run("V2toV3", func(t *testing.T) {
s := &squibble.Schema{
Current: v3,
Updates: []squibble.UpdateRule{
{mustHash(t, v1), mustHash(t, v2),
squibble.Exec(`ALTER TABLE foo ADD COLUMN y text`)},
{mustHash(t, v2), mustHash(t, v3),
squibble.Exec(`CREATE TABLE bar (z integer not null)`)},
},
Logf: t.Logf,
}
if err := s.Apply(t.Context(), db); err != nil {
t.Fatalf("Apply v3: unexpected error: %v", err)
}
checkTableSchema(t, db, "foo", v2)
checkTableSchema(t, db, "bar", `create table bar (z integer not null)`)
})
// Add the new "__ignored__" table to the schema, representing a table that
// should be disregarded when comparing schema versions.
//
// The tests after this expect this table and index to be present so they
// can exercise the filtering by columns. Note that we specifically chose an
// index name that doesn't match the table, to verify that the filter is
// considering the affiliated table name and not the index name alone.
const vX = `create table __ignored__ (z integer) ; create index blahblah on __ignored__(z)`
if _, err := db.ExecContext(t.Context(), vX); err != nil {
t.Fatalf("Exec vX: %v", err)
}
checkTableSchema(t, db, "__ignored__", `create table __ignored__ (z integer)`)
t.Run("V3toVX/Filtered", func(t *testing.T) {
// With a table filter in place, we should be able to claim v3 is
// current, i.e., we will not be distracted by __ignored__ or its index.
s := &squibble.Schema{
Current: v3,
Logf: t.Logf,
IgnoreTables: []string{"__ignored__"}, // filter me
}
if err := s.Apply(t.Context(), db); err != nil {
t.Fatalf("Apply v3: unexpected error: %v", err)
}
})
t.Run("V3toVX/Unfiltered", func(t *testing.T) {
// However, in contrast with the above, we should get an error on v3
// without the filter, because __ignored__ and its index are included.
s := &squibble.Schema{
Current: v3,
Logf: t.Logf,
IgnoreTables: nil, // no filter
}
if err := s.Apply(t.Context(), db); err == nil {
t.Fatal("Apply v3: unexpectedly succeeded")
}
})
t.Run("V3toV4/Filtered", func(t *testing.T) {
// Upgrading to another version (v4) should work with a filter.
s := &squibble.Schema{
Current: v4,
Updates: []squibble.UpdateRule{
{mustHash(t, v3), mustHash(t, v4),
squibble.Exec(
`DROP TABLE bar`,
`ALTER TABLE foo DROP COLUMN y`,
`ALTER TABLE foo ADD COLUMN z integer`,
),
},
},
IgnoreTables: []string{"__ignored__"}, // filter me
Logf: t.Logf,
}
if err := s.Apply(t.Context(), db); err != nil {
t.Fatalf("Apply v4: unexpected error: %v", err)
}
})
t.Run("History", func(t *testing.T) {
hr, err := squibble.History(t.Context(), db)
if err != nil {
t.Fatalf("History: unexpected error: %v", err)
}
t.Log("History of upgrades (chronological):")
for i, h := range hr {
t.Logf("[%d] %s %s %q", i+1, h.Timestamp.Format(time.RFC3339Nano), h.Digest, h.Schema)
}
})
}
func TestMultiUpgrade(t *testing.T) {
db := mustOpenDB(t)
const v1 = `-- initial schema
create table foo (x text)`
const v2 = `-- add a column
create table foo (x text, y text)`
const v3 = `-- add a table
create table foo (x text, y text);
create table bar (z integer not null)`
const v4 = `-- don't change anything but the comments
create table foo (x text, y text);
create table bar (z integer not null)`
const v5 = `-- drop a table
create table bar (z integer not null)`
const v6 = `-- restore the table
create table foo (x text, y text);
create table bar (z integer not null)`
const v7 = `-- same, same
create table foo (x text, y text);
create table bar (z integer not null)`
t.Run("InitV1", func(t *testing.T) {
s := &squibble.Schema{Current: v1, Logf: t.Logf}
if err := s.Apply(t.Context(), db); err != nil {
t.Fatalf("Apply v1: unexpected error: %v", err)
}
checkTableSchema(t, db, "foo", `create table foo (x text)`)
})
t.Run("V2toV7", func(t *testing.T) {
s := &squibble.Schema{
Current: v7,
Updates: []squibble.UpdateRule{
// History: v1 → v2 → v3 → (v4 = v3) → v5 → (v6 = v3) → (v7 = v3)
// The cycle exercises the correct handling of repeats.
{mustHash(t, v1), mustHash(t, v2),
squibble.Exec(`ALTER TABLE foo ADD COLUMN y text`)},
{mustHash(t, v2), mustHash(t, v3),
squibble.Exec(`CREATE TABLE bar (z integer not null)`)},
{mustHash(t, v3), mustHash(t, v4),
squibble.NoAction},
{mustHash(t, v4), mustHash(t, v5),
squibble.Exec(`DROP TABLE foo`)},
{mustHash(t, v5), mustHash(t, v6),
squibble.Exec(`CREATE TABLE foo (x text, y text)`)},
{mustHash(t, v6), mustHash(t, v7),
squibble.NoAction},
},
Logf: t.Logf,
}
if err := s.Apply(t.Context(), db); err != nil {
t.Fatalf("Apply v3: unexpected error: %v", err)
}
checkTableSchema(t, db, "bar", `create table bar (z integer not null)`)
})
t.Run("History", func(t *testing.T) {
hr, err := squibble.History(t.Context(), db)
if err != nil {
t.Fatalf("History: unexpected error: %v", err)
}
t.Log("History of upgrades (chronological):")
for i, h := range hr {
t.Logf("[%d] %s %s %q", i+1, h.Timestamp.Format(time.RFC3339Nano), h.Digest, h.Schema)
}
})
t.Run("Validate", func(t *testing.T) {
if err := squibble.Validate(t.Context(), db, v7, nil); err != nil {
t.Fatal(err)
}
})
t.Run("Invalidate", func(t *testing.T) {
err := squibble.Validate(t.Context(), db, v1, nil)
var ve squibble.ValidationError
if !errors.As(err, &ve) {
t.Fatalf("Validate: got %v, want %T", err, ve)
}
t.Logf("OK, validation diff:\n%s", ve.Diff)
})
}
func TestBadUpgrade(t *testing.T) {
db := mustOpenDB(t)
const v1 = `create table foo (x text not null)`
const v2 = `create table foo (x text not null, y integer not null default 0)`
// Initialize the database with schema v1.
s := &squibble.Schema{Current: v1, Logf: t.Logf}
if err := s.Apply(t.Context(), db); err != nil {
t.Fatalf("Apply initial schema: %v", err)
}
// Now target an upgrade to schema v2, but in which the upgrade rule does
// not produce a result equivalent to v2.
s.Current = v2
s.Updates = append(s.Updates, squibble.UpdateRule{
Source: mustHash(t, v1),
Target: mustHash(t, v2),
Apply: squibble.Exec(`
ALTER TABLE foo ADD COLUMN y INTEGER NOT NULL DEFAULT 0; -- OK
ALTER TABLE foo ADD COLUMN z BLOB; -- not expected
`),
})
if err := s.Apply(t.Context(), db); err == nil {
t.Error("Apply should have failed, but did not")
} else {
t.Logf("Apply: got expected error: %v", err)
}
}
func TestUnmanaged(t *testing.T) {
db := mustOpenDB(t)
// If the database already has a schema that isn't managed by the Schema,
// Apply should report an error.
if _, err := db.Exec(`create table t (a string)`); err != nil {
t.Fatalf("Initialize schema: %v", err)
}
s := &squibble.Schema{Current: `create table u (b integer)`, Logf: t.Logf}
if err := s.Apply(t.Context(), db); err == nil {
t.Error("Apply should have failed but did not")
} else if !strings.Contains(err.Error(), "unmanaged schema") {
t.Errorf("Apply: got %v, want unmanaged schema", err)
}
}
func TestInconsistent(t *testing.T) {
tmp := func(context.Context, squibble.DBConn) error { panic("notused") }
bad1 := &squibble.Schema{
Current: "create table ok (a text)",
Updates: []squibble.UpdateRule{
{"", "def", tmp}, // missing source
{"abc", "", tmp}, // missing target
{"abc", "def", nil}, // missing func
},
Logf: t.Logf,
}
bad2 := &squibble.Schema{
Current: "create table ok (a text)",
Updates: []squibble.UpdateRule{
{"abc", "def", tmp},
{"ghi", "jkl", tmp}, // missing link from def to ghi
{"jkl", "mno", tmp}, // missing link to current
},
Logf: t.Logf,
}
tests := []struct {
name string
input *squibble.Schema
want string
}{
{"NoCurrent", &squibble.Schema{}, "no current schema"},
{"NoSource", bad1, "1: missing source"},
{"NoTarget", bad1, "2: missing target"},
{"NoFunc", bad1, "3: missing Apply function"},
{"BadStitch", bad2, "2: want source def, got ghi"},
{"NoTail", bad2, fmt.Sprintf("missing upgrade from %s to target %s", "mno",
mustHash(t, bad2.Current))},
}
db := mustOpenDB(t)
ctx := t.Context()
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
err := tc.input.Apply(ctx, db)
if err == nil {
t.Fatal("Apply should have failed but did not")
} else if !strings.Contains(err.Error(), tc.want) {
t.Errorf("Got error %v, want %q", err, tc.want)
}
})
}
}
func TestCompatible(t *testing.T) {
const schema = `create table t (a text); create table u (b integer)`
t.Run("Empty", func(t *testing.T) {
db := mustOpenDB(t)
s := &squibble.Schema{Current: schema, Logf: t.Logf}
if err := s.Apply(t.Context(), db); err != nil {
t.Errorf("Apply: unexpected error: %v", err)
}
if err := squibble.Validate(t.Context(), db, schema, nil); err != nil {
t.Errorf("Validate: unexpected error: %v", err)
}
})
t.Run("NonEmpty", func(t *testing.T) {
db := mustOpenDB(t)
if _, err := db.Exec(schema); err != nil {
t.Fatalf("Initializing schema: %v", err)
}
s := &squibble.Schema{Current: "-- compatible schema\n" + schema, Logf: t.Logf}
if err := s.Apply(t.Context(), db); err != nil {
t.Errorf("Apply: unexpected error: %v", err)
}
if err := squibble.Validate(t.Context(), db, schema, nil); err != nil {
t.Errorf("Validate: unexpected error: %v", err)
}
})
}