tangled
alpha
login
or
join now
tjh.dev
/
core
forked from
tangled.org/core
0
fork
atom
this repo has no description
0
fork
atom
overview
issues
pulls
pipelines
add migration handler
oppi.li
1 year ago
52eb59c8
480521bc
+55
1 changed file
expand all
collapse all
unified
split
appview
db
db.go
+55
appview/db/db.go
···
3
3
import (
4
4
"context"
5
5
"database/sql"
6
6
+
"log"
6
7
7
8
_ "github.com/mattn/go-sqlite3"
8
9
)
···
122
123
unique(starred_by_did, repo_at)
123
124
);
124
125
126
126
+
create table if not exists migrations (
127
127
+
id integer primary key autoincrement,
128
128
+
name text unique
129
129
+
)
125
130
`)
126
131
if err != nil {
127
132
return nil, err
128
133
}
134
134
+
135
135
+
// run migrations
136
136
+
runMigration(db, "add-description-to-repos", func(tx *sql.Tx) error {
137
137
+
tx.Exec(`
138
138
+
alter table repos add column description text check (length(description) <= 200);
139
139
+
`)
140
140
+
return nil
141
141
+
})
142
142
+
129
143
return &DB{db}, nil
130
144
}
145
145
+
146
146
+
type migrationFn = func(*sql.Tx) error
147
147
+
148
148
+
func runMigration(d *sql.DB, name string, migrationFn migrationFn) error {
149
149
+
tx, err := d.Begin()
150
150
+
if err != nil {
151
151
+
return err
152
152
+
}
153
153
+
defer tx.Rollback()
154
154
+
155
155
+
var exists bool
156
156
+
err = tx.QueryRow("select exists (select 1 from migrations where name = ?)", name).Scan(&exists)
157
157
+
if err != nil {
158
158
+
return err
159
159
+
}
160
160
+
161
161
+
if !exists {
162
162
+
// run migration
163
163
+
err = migrationFn(tx)
164
164
+
if err != nil {
165
165
+
log.Printf("Failed to run migration %s: %v", name, err)
166
166
+
return err
167
167
+
}
168
168
+
169
169
+
// mark migration as complete
170
170
+
_, err = tx.Exec("insert into migrations (name) values (?)", name)
171
171
+
if err != nil {
172
172
+
log.Printf("Failed to mark migration %s as complete: %v", name, err)
173
173
+
return err
174
174
+
}
175
175
+
176
176
+
// commit the transaction
177
177
+
if err := tx.Commit(); err != nil {
178
178
+
return err
179
179
+
}
180
180
+
} else {
181
181
+
log.Printf("skipped migration %s, already applied", name)
182
182
+
}
183
183
+
184
184
+
return nil
185
185
+
}