Skip to content

Instantly share code, notes, and snippets.

@jfeng45
Last active July 28, 2019 00:56
Show Gist options
  • Save jfeng45/88dd35b15b4898693caf00a86d05cb3d to your computer and use it in GitHub Desktop.
Save jfeng45/88dd35b15b4898693caf00a86d05cb3d to your computer and use it in GitHub Desktop.
database factory for Mysql database
// sqlFactory is receiver for Build method
type sqlFactory struct{}
// implement Build method for SQL database
func (sf *sqlFactory) Build(c container.Container, dsc *config.DataStoreConfig) (DataStoreInterface, error) {
key := dsc.Code
//if it is already in container, return
if value, found := c.Get(key); found {
sdb := value.(*sql.DB)
sdt := databasehandler.SqlDBTx{DB: sdb}
logger.Log.Debug("found db in container for key:", key)
return &sdt, nil
}
db, err := sql.Open(dsc.DriverName, dsc.UrlAddress)
if err != nil {
return nil, errors.Wrap(err, "")
}
// check the connection
err = db.Ping()
if err != nil {
return nil, errors.Wrap(err, "")
}
dt := databasehandler.SqlDBTx{DB: db}
c.Put(key, db)
return &dt, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment