Debian Codegraph @

db/schema/schema_test.go

raw
1 package schema_test
2
3 import (
4 "database/sql"
5 "fmt"
6 "path/filepath"
7 "testing"
8
9 "github.com/stretchr/testify/require"
10 "heckel.io/ntfy/v2/db/pg"
11 "heckel.io/ntfy/v2/db/schema"
12 dbtest "heckel.io/ntfy/v2/db/test"
13
14 _ "github.com/mattn/go-sqlite3"
15 )
16
17 const testCreateQuery = `CREATE TABLE IF NOT EXISTS things (id TEXT PRIMARY KEY, name TEXT NOT NULL)`
18
19 func testCreate(tx *sql.Tx) error {
20 _, err := tx.Exec(testCreateQuery)
21 return err
22 }
23
24 func openTestPostgres(t *testing.T) *sql.DB {
25 t.Helper()
26 host, err := pg.Open(dbtest.CreateTestPostgresSchema(t))
27 require.Nil(t, err)
28 t.Cleanup(func() { host.DB.Close() })
29 return host.DB
30 }
31
32 func openTestSQLite(t *testing.T) *sql.DB {
33 t.Helper()
34 d, err := sql.Open("sqlite3", filepath.Join(t.TempDir(), "test.db"))
35 require.Nil(t, err)
36 t.Cleanup(func() { d.Close() })
37 return d
38 }
39
40 func forEachDialect(t *testing.T, f func(t *testing.T, d *sql.DB, dialect schema.Dialect)) {
41 t.Run("postgres", func(t *testing.T) {
42 f(t, openTestPostgres(t), schema.Postgres)
43 })
44 t.Run("sqlite", func(t *testing.T) {
45 f(t, openTestSQLite(t), schema.SQLite)
46 })
47 }
48
49 func TestMigrate_FreshCreate(t *testing.T) {
50 forEachDialect(t, func(t *testing.T, d *sql.DB, dialect schema.Dialect) {
51 // A fresh database jumps straight to the target version; migration steps are not consulted
52 require.Nil(t, schema.Migrate(d, dialect, "things", 3, testCreate, nil))
53 _, err := d.Exec(`INSERT INTO things (id, name) VALUES ('a', 'thing a')`)
54 require.Nil(t, err)
55 require.Equal(t, 3, storeVersion(t, d, dialect, "things"))
56 // Idempotent: a second node boots against the migrated schema
57 require.Nil(t, schema.Migrate(d, dialect, "things", 3, testCreate, nil))
58 })
59 }
60
61 func TestMigrate_AppliesMigrationSteps(t *testing.T) {
62 forEachDialect(t, func(t *testing.T, d *sql.DB, dialect schema.Dialect) {
63 require.Nil(t, schema.Migrate(d, dialect, "things", 1, testCreate, nil))
64 // A newer version of the code migrates 1 -> 3 step by step, in order
65 migrations := map[int]schema.MigrateFunc{
66 1: func(tx *sql.Tx) error {
67 _, err := tx.Exec(`ALTER TABLE things ADD COLUMN color TEXT NOT NULL DEFAULT ''`)
68 return err
69 },
70 2: func(tx *sql.Tx) error {
71 _, err := tx.Exec(`ALTER TABLE things ADD COLUMN size INT NOT NULL DEFAULT 0`)
72 return err
73 },
74 }
75 require.Nil(t, schema.Migrate(d, dialect, "things", 3, testCreate, migrations))
76 _, err := d.Exec(`INSERT INTO things (id, name, color, size) VALUES ('b', 'thing b', 'red', 2)`)
77 require.Nil(t, err)
78 require.Equal(t, 3, storeVersion(t, d, dialect, "things"))
79 })
80 }
81
82 func TestMigrate_ClosureCarriesConfig(t *testing.T) {
83 // Migrations needing config take it via closure at map-construction time; there is no
84 // params plumbing in the framework itself
85 migrationsFor := func(defaultName string) map[int]schema.MigrateFunc {
86 return map[int]schema.MigrateFunc{
87 1: schema.AsMigrateFunc(fmt.Sprintf(`ALTER TABLE things ADD COLUMN nick TEXT NOT NULL DEFAULT '%s'`, defaultName)),
88 }
89 }
90 forEachDialect(t, func(t *testing.T, d *sql.DB, dialect schema.Dialect) {
91 require.Nil(t, schema.Migrate(d, dialect, "things", 1, testCreate, nil))
92 _, err := d.Exec(`INSERT INTO things (id, name) VALUES ('a', 'thing a')`)
93 require.Nil(t, err)
94 require.Nil(t, schema.Migrate(d, dialect, "things", 2, testCreate, migrationsFor("configured-default")))
95 var nick string
96 require.Nil(t, d.QueryRow(`SELECT nick FROM things WHERE id = 'a'`).Scan(&nick))
97 require.Equal(t, "configured-default", nick)
98 })
99 }
100
101 func TestMigrate_InvalidDialect(t *testing.T) {
102 d := openTestSQLite(t)
103 err := schema.Migrate(d, schema.Dialect(99), "things", 1, testCreate, nil)
104 require.Error(t, err)
105 }
106
107 func TestMigrate_RefusesFutureVersion(t *testing.T) {
108 forEachDialect(t, func(t *testing.T, d *sql.DB, dialect schema.Dialect) {
109 require.Nil(t, schema.Migrate(d, dialect, "things", 2, testCreate, map[int]schema.MigrateFunc{}))
110 err := schema.Migrate(d, dialect, "things", 1, testCreate, nil)
111 require.Error(t, err)
112 })
113 }
114
115 func TestMigrate_MissingStepFails(t *testing.T) {
116 forEachDialect(t, func(t *testing.T, d *sql.DB, dialect schema.Dialect) {
117 require.Nil(t, schema.Migrate(d, dialect, "things", 1, testCreate, nil))
118 err := schema.Migrate(d, dialect, "things", 3, testCreate, nil) // No step 1 -> 2 registered
119 require.Error(t, err)
120 })
121 }
122
123 func TestMigrate_StoresAreIndependent(t *testing.T) {
124 // Postgres only: stores share one database, tracked as rows in schema_version. On SQLite
125 // every store has its own database file, so independence is by file.
126 d := openTestPostgres(t)
127 require.Nil(t, schema.Migrate(d, schema.Postgres, "things", 1, testCreate, nil))
128 require.Nil(t, schema.Migrate(d, schema.Postgres, "gadgets", 4, func(tx *sql.Tx) error {
129 _, err := tx.Exec(`CREATE TABLE IF NOT EXISTS gadgets (id TEXT PRIMARY KEY)`)
130 return err
131 }, nil))
132 require.Equal(t, 1, storeVersion(t, d, schema.Postgres, "things"))
133 require.Equal(t, 4, storeVersion(t, d, schema.Postgres, "gadgets"))
134 }
135
136 func TestMigrate_SQLiteReadsExistingSchemaVersionTable(t *testing.T) {
137 // Existing ntfy SQLite databases (message, user, webpush) track their version in a
138 // schemaVersion (id, version) table keyed by id = 1; the framework uses that table as-is
139 // on SQLite, so existing databases migrate without any adoption step
140 d := openTestSQLite(t)
141 _, err := d.Exec(testCreateQuery)
142 require.Nil(t, err)
143 _, err = d.Exec(`CREATE TABLE schemaVersion (id INT PRIMARY KEY, version INT NOT NULL)`)
144 require.Nil(t, err)
145 _, err = d.Exec(`INSERT INTO schemaVersion VALUES (1, 1)`)
146 require.Nil(t, err)
147 migrations := map[int]schema.MigrateFunc{
148 1: func(tx *sql.Tx) error {
149 _, err := tx.Exec(`ALTER TABLE things ADD COLUMN color TEXT NOT NULL DEFAULT ''`)
150 return err
151 },
152 }
153 require.Nil(t, schema.Migrate(d, schema.SQLite, "things", 2, testCreate, migrations))
154 _, err = d.Exec(`INSERT INTO things (id, name, color) VALUES ('a', 'thing a', 'red')`)
155 require.Nil(t, err)
156 require.Equal(t, 2, storeVersion(t, d, schema.SQLite, "things"))
157 }
158
159 func TestMigrate_ConcurrentFreshCreate(t *testing.T) {
160 // Postgres only: concurrent cold-boots must not race on DDL (CREATE TABLE IF NOT EXISTS is
161 // not atomic); Migrate serializes via an advisory lock. SQLite has a single writer.
162 schemaDSN := dbtest.CreateTestPostgresSchema(t)
163 const n = 8
164 errs := make(chan error, n)
165 for i := 0; i < n; i++ {
166 go func() {
167 host, err := pg.Open(schemaDSN)
168 if err != nil {
169 errs <- err
170 return
171 }
172 defer host.DB.Close()
173 errs <- schema.Migrate(host.DB, schema.Postgres, "things", 1, testCreate, nil)
174 }()
175 }
176 for i := 0; i < n; i++ {
177 require.Nil(t, <-errs)
178 }
179 }
180
181 func storeVersion(t *testing.T, d *sql.DB, dialect schema.Dialect, store string) int {
182 t.Helper()
183 var version int
184 if dialect == schema.Postgres {
185 require.Nil(t, d.QueryRow(`SELECT version FROM schema_version WHERE store = $1`, store).Scan(&version), fmt.Sprintf("store %s", store))
186 } else {
187 require.Nil(t, d.QueryRow(`SELECT version FROM schemaVersion WHERE id = 1`).Scan(&version), fmt.Sprintf("store %s", store))
188 }
189 return version
190 }