1// SPDX-FileCopyrightText: Chris Waldon <christopher.waldon.dev@gmail.com>
2//
3// SPDX-License-Identifier: Apache-2.0
4
5package db
6
7import (
8 "context"
9 "database/sql"
10 _ "embed"
11 "fmt"
12)
13
14type migration struct {
15 upQuery string
16 downQuery string
17 postHook func(*sql.Tx) error
18}
19
20var (
21 //go:embed sql/1_add_project_ids.up.sql
22 migration1Up string
23 //go:embed sql/1_add_project_ids.down.sql
24 migration1Down string
25 //go:embed sql/2_swap_project_url_for_id.up.sql
26 migration2Up string
27 //go:embed sql/2_swap_project_url_for_id.down.sql
28 migration2Down string
29)
30
31var migrations = [...]migration{
32 0: {
33 upQuery: `CREATE TABLE schema_migrations (version uint64, dirty bool);
34 INSERT INTO schema_migrations (version, dirty) VALUES (0, 0);`,
35 downQuery: `DROP TABLE schema_migrations;`,
36 },
37 1: {
38 upQuery: migration1Up,
39 downQuery: migration1Down,
40 postHook: generateAndInsertProjectIDs,
41 },
42 2: {
43 upQuery: migration2Up,
44 downQuery: migration2Down,
45 },
46 3: {
47 postHook: correctProjectIDs,
48 },
49}
50
51// Migrate runs all pending migrations.
52func Migrate(db *sql.DB) error {
53 version := getSchemaVersion(db)
54 for nextMigration := version + 1; nextMigration < len(migrations); nextMigration++ {
55 if err := runMigration(db, nextMigration); err != nil {
56 return fmt.Errorf("migrations failed: %w", err)
57 }
58
59 if version := getSchemaVersion(db); version != nextMigration {
60 return fmt.Errorf("migration did not update version (expected %d, got %d)", nextMigration, version)
61 }
62 }
63
64 return nil
65}
66
67// runMigration runs a single migration inside a transaction, updates the schema
68// version and commits the transaction if successful, and rolls back the
69// transaction if unsuccessful.
70func runMigration(db *sql.DB, migrationIdx int) (err error) {
71 current := migrations[migrationIdx]
72
73 tx, err := db.BeginTx(context.Background(), &sql.TxOptions{})
74 if err != nil {
75 return fmt.Errorf("failed opening transaction for migration %d: %w", migrationIdx, err)
76 }
77
78 defer func() {
79 if err == nil {
80 err = tx.Commit()
81 }
82
83 if err != nil {
84 if rbErr := tx.Rollback(); rbErr != nil {
85 err = fmt.Errorf("failed rolling back: %w due to: %w", rbErr, err)
86 }
87 }
88 }()
89
90 if len(current.upQuery) > 0 {
91 if _, err := tx.Exec(current.upQuery); err != nil {
92 return fmt.Errorf("failed running migration %d: %w", migrationIdx, err)
93 }
94 }
95
96 if current.postHook != nil {
97 if err := current.postHook(tx); err != nil {
98 return fmt.Errorf("failed running posthook for migration %d: %w", migrationIdx, err)
99 }
100 }
101
102 return updateSchemaVersion(tx, migrationIdx)
103}
104
105// undoMigration rolls the single most recent migration back inside a
106// transaction, updates the schema version and commits the transaction if
107// successful, and rolls back the transaction if unsuccessful.
108//
109//lint:ignore U1000 Will be used when #34 is implemented (https://todo.sr.ht/~amolith/willow/34)
110func undoMigration(db *sql.DB, migrationIdx int) (err error) {
111 current := migrations[migrationIdx]
112
113 tx, err := db.BeginTx(context.Background(), &sql.TxOptions{})
114 if err != nil {
115 return fmt.Errorf("failed opening undo transaction for migration %d: %w", migrationIdx, err)
116 }
117
118 defer func() {
119 if err == nil {
120 err = tx.Commit()
121 }
122
123 if err != nil {
124 if rbErr := tx.Rollback(); rbErr != nil {
125 err = fmt.Errorf("failed rolling back: %w due to: %w", rbErr, err)
126 }
127 }
128 }()
129
130 if len(current.downQuery) > 0 {
131 if _, err := tx.Exec(current.downQuery); err != nil {
132 return fmt.Errorf("failed undoing migration %d: %w", migrationIdx, err)
133 }
134 }
135
136 return updateSchemaVersion(tx, migrationIdx-1)
137}
138
139// getSchemaVersion returns the schema version from the database.
140func getSchemaVersion(db *sql.DB) int {
141 row := db.QueryRowContext(context.Background(), `SELECT version FROM schema_migrations LIMIT 1;`)
142
143 var version int
144 if err := row.Scan(&version); err != nil {
145 version = -1
146 }
147
148 return version
149}
150
151// updateSchemaVersion sets the version to the provided int.
152func updateSchemaVersion(tx *sql.Tx, version int) error {
153 if version < 0 {
154 // Do not try to use the schema_migrations table in a schema version where it doesn't exist
155 return nil
156 }
157
158 _, err := tx.Exec(`UPDATE schema_migrations SET version = @version;`, sql.Named("version", version))
159
160 return err
161}