Newer
Older
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
// initBoltDB initializes db with persistent state like the password salt and checks whether an already initialized database has the expected version number.
func initBoltDB(db *bolt.DB) error {
// Initialize persistent state like password salt
err := db.Update(func(tx *bolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists([]byte("meta"))
// Check database version
storedVersion := bucket.Get([]byte("version"))
if storedVersion != nil && string(storedVersion) != expectDBVersion {
return fmt.Errorf("Unexpected database version: have %q, want %q", storedVersion, expectDBVersion)
// Make sure the db version is stored
err = bucket.Put([]byte("version"), []byte(expectDBVersion))
// Create new PW salt if it doesn't already exist
pwSalt := bucket.Get([]byte("pwsalt"))
if pwSalt == nil {
pwSalt = make([]byte, 16)
_, err := rand.Read(pwSalt)
if err != nil {
return err
}
err = bucket.Put([]byte("pwsalt"), pwSalt)
if err != nil {
return err
}
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
//go:embed migrations/*.sql
var migrationFS embed.FS
func initSQLdb(ctx context.Context, db *sqlx.DB) error {
// Make sure that we have a table for the migrations
tx, err := db.BeginTxx(ctx, nil)
if err != nil {
return fmt.Errorf("creating tx: %w", err)
}
defer func() {
if err != nil {
tx.Rollback()
return
}
tx.Commit()
}()
_, err = tx.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS migrations (name string)`)
if err != nil {
return fmt.Errorf("creating migrations table: %w", err)
}
_, err = tx.ExecContext(ctx, `CREATE UNIQUE INDEX IF NOT EXISTS migrations_name ON migrations (name)`)
if err != nil {
return fmt.Errorf("creating migrations index: %w", err)
}
entries, err := migrationFS.ReadDir("migrations")
if err != nil {
return fmt.Errorf("reading embedded migration FS: %w", err)
}
sort.Slice(entries, func(i, j int) bool {
return entries[i].Name() < entries[j].Name()
})
for _, e := range entries {
// Check if we need to apply that migration
var count int
err = tx.GetContext(ctx, &count, `SELECT count(*) FROM migrations WHERE name = ?1`, e.Name())
if err != nil {
return fmt.Errorf("checking for migration %q: %w", e.Name(), err)
}
if count > 1 {
return fmt.Errorf("migration %q applied more than once", e.Name())
}
if count == 1 {
continue
}
content, err := fs.ReadFile(migrationFS, "migrations/"+e.Name())
if err != nil {
return fmt.Errorf("reading migration %q: %w", e.Name(), err)
}
_, err = tx.ExecContext(ctx, string(content))
if err != nil {
return fmt.Errorf("applying migration %q: %w", e.Name(), err)
}
// Mark migration as applied
_, err = tx.ExecContext(ctx, `INSERT INTO migrations (name) VALUES (?1)`, e.Name())
if err != nil {
return fmt.Errorf("marking migration %q as applied: %w", e.Name(), err)
}
}
return nil
}
func migrateBoltToQL(ctx context.Context, b *bolt.DB, ql *sqlx.DB) error {
// Check if the ql DB has already been the target of a migration
var count int
err := ql.GetContext(ctx, &count, `SELECT count(*) FROM state WHERE key = "migrated-from-bolt" AND val = "true"`)
if err != nil {
return err
}
if count == 1 {
log.Println("migration already done")
return nil // Nothing to do here
}
tx, err := ql.Beginx()
defer func() {
if err != nil {
log.Println("rolling back transaction")
tx.Rollback()
return
}
tx.Commit()
}()
// Migrate users
err = migrateUsers(ctx, b, tx)
if err != nil {
return fmt.Errorf("migrating users: %w", err)
}
// Migrate wines
err = migrateWines(ctx, b, tx)
if err != nil {
return fmt.Errorf("migrating wines: %w", err)
}
// Migrate state
err = migrateState(ctx, b, tx)
if err != nil {
return fmt.Errorf("migrating state: %w", err)
}
// Mark migration complete
_, err = tx.ExecContext(ctx, `INSERT INTO state (key, val) VALUES (?1, ?2)`, "migrated-from-bolt", "true")
if err != nil {
return fmt.Errorf("marking migration complete: %w", err)
}
log.Println("migration complete")
return nil
}
func migrateUsers(ctx context.Context, b *bolt.DB, sqlTx *sqlx.Tx) error {
err := b.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte("users"))
if bucket == nil || bucket.Stats().KeyN == 0 {
return nil // No users, nothing to migrate
}
err := bucket.ForEach(func(k, v []byte) error {
name := string(k)
pwhash := string(v)
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
_, err := sqlTx.ExecContext(ctx, `INSERT INTO users (name, password) VALUES (?1, ?2)`, name, pwhash)
return err
})
return err
})
return err
}
func migrateWines(ctx context.Context, b *bolt.DB, sqlTx *sqlx.Tx) error {
err := b.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte("wines"))
if bucket == nil || bucket.Stats().KeyN == 0 {
return nil
}
err := bucket.ForEach(func(k, d []byte) error {
if d != nil {
return fmt.Errorf("%q not a bucket", k)
}
u, err := uuid.ParseBytes(k)
if err != nil {
return err
}
if err != nil {
return err
}
log.WithFields(log.Fields{
"uuid": u.String(),
"name": v.Name,
}).Info("migrating wine")
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
data := bucket.Bucket(k)
if data == nil {
return fmt.Errorf("no data for %q", k)
}
rawPicture := data.Get([]byte("picture"))
res, err := sqlTx.ExecContext(ctx, `INSERT INTO wines (name, rating, picture, country) VALUES (?1, ?2, ?3, ?4)`,
v.Name, v.Rating, rawPicture, string(v.Country[:]))
if err != nil {
return err
}
id, err := res.LastInsertId()
if err != nil {
return err
}
// Insert comments
for _, c := range v.Comments {
_, err := sqlTx.ExecContext(ctx, `INSERT INTO comments (wine, content) VALUES (?1, ?2)`, id, c.Content)
if err != nil {
return err
}
}
return nil
})
return err
})
return err
}
func migrateState(ctx context.Context, b *bolt.DB, sqlTx *sqlx.Tx) error {
err := b.View(func(tx *bolt.Tx) error {
for _, name := range []string{"state", "meta"} {
bucket := tx.Bucket([]byte(name))
if bucket == nil || bucket.Stats().KeyN == 0 {
continue
}
log.WithFields(log.Fields{
"name": name,
"keys": bucket.Stats().KeyN,
}).Info("migrating metadata bucket")
err := bucket.ForEach(func(k, v []byte) error {
key := string(k)
val := string(v)
_, err := sqlTx.ExecContext(ctx, `INSERT INTO state (key, val) VALUES (?1, ?2)`, key, val)
return err
})
if err != nil {
return err
}
}
return nil
})
return err
}