forked from brocaar/chirpstack-application-server
/
code_migration.go
52 lines (44 loc) · 975 Bytes
/
code_migration.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
package storage
import (
"time"
"github.com/jmoiron/sqlx"
"github.com/lib/pq"
)
// CodeMigration checks if the given function code has been applied and if not
// it will execute the given function.
func CodeMigration(name string, f func(db sqlx.Ext) error) error {
return Transaction(func(tx sqlx.Ext) error {
_, err := tx.Exec("lock table code_migration")
if err != nil {
// The table might not exist when the code migration is executed
// before the schema migrations.
return ErrTransactionRollback
}
res, err := tx.Exec(`
insert into code_migration (
id,
applied_at
) values ($1, $2)
on conflict
do nothing
`, name, time.Now())
if err != nil {
switch err := err.(type) {
case *pq.Error:
switch err.Code.Name() {
case "unique_violation":
return nil
}
}
return err
}
ra, err := res.RowsAffected()
if err != nil {
return err
}
if ra == 0 {
return nil
}
return f(tx)
})
}