github.com/marinho/drone@v0.2.1-0.20140504195434-d3ba962e89a7/pkg/database/database.go (about) 1 package database 2 3 import ( 4 "database/sql" 5 "fmt" 6 7 "github.com/drone/drone/pkg/database/migrate" 8 9 _ "github.com/go-sql-driver/mysql" 10 _ "github.com/mattn/go-sqlite3" 11 12 "github.com/russross/meddler" 13 ) 14 15 // global instance of our database connection. 16 var db *sql.DB 17 18 // Init connects to database and performs migration if necessary. 19 // 20 // Database driver name and data source information is provided by user 21 // from within command line, and error checking is deferred to sql.Open. 22 // 23 // Init will just bail out and returns error if driver name 24 // is not listed, no fallback nor default driver sets here. 25 func Init(name, datasource string) error { 26 var err error 27 driver := map[string]struct { 28 Md *meddler.Database 29 Mg migrate.DriverBuilder 30 }{ 31 "sqlite3": { 32 meddler.SQLite, 33 migrate.SQLite, 34 }, 35 "mysql": { 36 meddler.MySQL, 37 migrate.MySQL, 38 }, 39 } 40 41 if drv, ok := driver[name]; ok { 42 meddler.Default = drv.Md 43 migrate.Driver = drv.Mg 44 } else { 45 return fmt.Errorf("%s driver not found", name) 46 } 47 48 db, err = sql.Open(name, datasource) 49 if err != nil { 50 return err 51 } 52 53 migration := migrate.New(db) 54 if err := migration.All().Migrate(); err != nil { 55 return err 56 } 57 return nil 58 } 59 60 // Close database connection. 61 func Close() { 62 db.Close() 63 }