2014-02-07 13:10:01 +03:00
|
|
|
package database
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
2014-03-08 14:12:43 +03:00
|
|
|
"fmt"
|
2014-02-07 13:10:01 +03:00
|
|
|
"log"
|
|
|
|
|
2014-03-08 08:19:28 +03:00
|
|
|
"github.com/drone/drone/pkg/database/migrate"
|
2014-02-07 13:10:01 +03:00
|
|
|
"github.com/drone/drone/pkg/database/schema"
|
2014-03-08 08:19:28 +03:00
|
|
|
|
|
|
|
_ "github.com/go-sql-driver/mysql"
|
|
|
|
_ "github.com/mattn/go-sqlite3"
|
|
|
|
|
|
|
|
"github.com/russross/meddler"
|
2014-02-07 13:10:01 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
// global instance of our database connection.
|
|
|
|
var db *sql.DB
|
|
|
|
|
2014-03-08 14:12:43 +03:00
|
|
|
// 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.
|
2014-03-08 08:19:28 +03:00
|
|
|
func Init(name, datasource string) error {
|
|
|
|
driver := map[string]struct {
|
|
|
|
Md *meddler.Database
|
2014-03-10 03:08:58 +03:00
|
|
|
Mg migrate.DriverBuilder
|
2014-03-08 08:19:28 +03:00
|
|
|
}{
|
|
|
|
"sqlite3": {
|
|
|
|
meddler.SQLite,
|
|
|
|
migrate.SQLite,
|
|
|
|
},
|
|
|
|
"mysql": {
|
|
|
|
meddler.MySQL,
|
|
|
|
migrate.MySQL,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2014-03-08 14:12:43 +03:00
|
|
|
if drv, ok := driver[name]; ok {
|
|
|
|
meddler.Default = drv.Md
|
|
|
|
migrate.Driver = drv.Mg
|
|
|
|
} else {
|
|
|
|
return fmt.Errorf("%s driver not found", name)
|
|
|
|
}
|
2014-03-08 08:19:28 +03:00
|
|
|
|
|
|
|
db, err := sql.Open(name, datasource)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
Set(db)
|
|
|
|
|
|
|
|
migration := migrate.New(db)
|
|
|
|
migration.All().Migrate()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-02-07 13:10:01 +03:00
|
|
|
// Set sets the default database.
|
|
|
|
func Set(database *sql.DB) {
|
|
|
|
// set the global database
|
|
|
|
db = database
|
|
|
|
|
|
|
|
// load the database schema. If this is
|
|
|
|
// a new database all the tables and
|
|
|
|
// indexes will be created.
|
|
|
|
if err := schema.Load(db); err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
}
|