/
controller.go
67 lines (59 loc) · 1.28 KB
/
controller.go
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
package generic
import (
"database/sql"
"log"
"strconv"
)
type MigrationFn func(*sql.Tx)
type MigrationFnTx func(*sql.DB)
type MigrationsWrapper struct {
SchemaFn func(*sql.DB) int
}
func (m *MigrationsWrapper) Migrate(migrationFn MigrationFn, thisVersion int) MigrationFnTx {
return func(db *sql.DB) {
if m.SchemaFn(db) >= thisVersion {
return
}
log.Printf("Performing schema upgrade to version %d", thisVersion)
tx, err := db.Begin()
if err != nil {
log.Fatalf("Could not start transaction: %v", err)
}
migrationFn(tx)
SetSchemaVersion(tx, thisVersion)
err = tx.Commit()
if err != nil {
log.Fatalf("Could not commit migration transaction to version %d: %s", thisVersion, err.Error())
}
}
}
func Schema(db *sql.DB) int {
// Check schema version
q := `
SELECT value
FROM "app::setting"
WHERE key = 'schemaVersion';
`
// Version value in settings table should not be null.
version := "0"
err := db.QueryRow(q).Scan(&version)
if err != nil {
log.Fatal(err)
}
i, err := strconv.Atoi(version)
if err != nil {
log.Fatal(err)
}
return i
}
func SetSchemaVersion(db *sql.Tx, v int) {
sqlStatement := `
UPDATE "app::setting"
SET value = $1
WHERE key = 'schemaVersion';
`
_, err := db.Exec(sqlStatement, v)
if err != nil {
log.Fatal(err)
}
}