forked from harness/harness
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
63 lines (53 loc) · 1.23 KB
/
database.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
package database
import (
"database/sql"
"fmt"
"github.com/drone/drone/pkg/database/migrate"
_ "github.com/go-sql-driver/mysql"
_ "github.com/mattn/go-sqlite3"
"github.com/russross/meddler"
)
// global instance of our database connection.
var db *sql.DB
// Init connects to database and performs migration if necessary.
//
// Database driver name and data source information is provided by user
// from within command line, and error checking is deferred to sql.Open.
//
// Init will just bail out and returns error if driver name
// is not listed, no fallback nor default driver sets here.
func Init(name, datasource string) error {
var err error
driver := map[string]struct {
Md *meddler.Database
Mg migrate.DriverBuilder
}{
"sqlite3": {
meddler.SQLite,
migrate.SQLite,
},
"mysql": {
meddler.MySQL,
migrate.MySQL,
},
}
if drv, ok := driver[name]; ok {
meddler.Default = drv.Md
migrate.Driver = drv.Mg
} else {
return fmt.Errorf("%s driver not found", name)
}
db, err = sql.Open(name, datasource)
if err != nil {
return err
}
migration := migrate.New(db)
if err := migration.All().Migrate(); err != nil {
return err
}
return nil
}
// Close database connection.
func Close() {
db.Close()
}