-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathdb.go
More file actions
59 lines (46 loc) · 1.38 KB
/
db.go
File metadata and controls
59 lines (46 loc) · 1.38 KB
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
package cli
import (
"database/sql"
"fmt"
"github.com/src-d/lookout/store"
"github.com/golang-migrate/migrate"
_ "github.com/lib/pq"
log "gopkg.in/src-d/go-log.v1"
)
// DBOptions contains common flags for commands using the DB
type DBOptions struct {
DB string `long:"db" default:"postgres://postgres:postgres@localhost:5432/lookout?sslmode=disable" env:"LOOKOUT_DB" description:"connection string to postgres database"`
}
func (c *DBOptions) InitDB() (*sql.DB, error) {
db, err := sql.Open("postgres", c.DB)
if err != nil {
return nil, err
}
if err = db.Ping(); err != nil {
return nil, err
}
m, err := store.NewMigrateInstance(db)
if err != nil {
return nil, err
}
dbVersion, _, err := m.Version()
// The DB is not initialized
if err == migrate.ErrNilVersion {
return nil, fmt.Errorf("the DB is empty, it needs to be initialized with the 'migrate' subcommand")
}
if err != nil {
return nil, err
}
maxVersion, err := store.MaxMigrateVersion()
if err != nil {
return nil, err
}
if dbVersion != maxVersion {
return nil, fmt.Errorf(
"database version mismatch. Current version is %v, but this binary needs version %v. "+
"Use the 'migrate' subcommand to upgrade your database", dbVersion, maxVersion)
}
log.With(log.Fields{"db-version": dbVersion}).Debugf("the DB version is up to date")
log.Infof("connection with the DB established")
return db, nil
}