-
Notifications
You must be signed in to change notification settings - Fork 22
/
setup.go
65 lines (58 loc) · 1.43 KB
/
setup.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
package migrations
import (
"fmt"
"github.com/go-pg/pg/v10/orm"
)
func (m *migrator) ensureMigrationTables() error {
exists, err := m.checkIfTableExists(m.opts.MigrationsTableName)
if err != nil {
return err
}
if !exists {
_, err = m.db.Exec(fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %q ("id" SERIAL PRIMARY KEY, "name" TEXT NOT NULL, "batch" INTEGER NOT NULL, "completed_at" TIMESTAMPTZ NOT NULL)`, escapeTableName(m.opts.MigrationsTableName)))
if err != nil {
return err
}
}
exists, err = m.checkIfTableExists(m.opts.MigrationLockTableName)
if err != nil {
return err
}
if !exists {
_, err = m.db.Exec(fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %q ("id" TEXT PRIMARY KEY, "is_locked" BOOLEAN NOT NULL)`, escapeTableName(m.opts.MigrationLockTableName)))
if err != nil {
return err
}
}
count, err := orm.NewQuery(m.db).
Table(m.opts.MigrationLockTableName).
Count()
if err != nil {
return err
}
if count == 0 {
l := map[string]interface{}{
"id": lockID,
"is_locked": false,
}
_, err = m.db.
Model(&l).
Table(m.opts.MigrationLockTableName).
Insert()
if err != nil {
return err
}
}
return nil
}
func (m *migrator) checkIfTableExists(name string) (bool, error) {
count, err := orm.NewQuery(m.db).
Table("information_schema.tables").
Where("table_name = ?", name).
Where("table_schema = current_schema").
Count()
if err != nil {
return false, err
}
return count > 0, nil
}