Last active
July 28, 2019 00:56
-
-
Save jfeng45/88dd35b15b4898693caf00a86d05cb3d to your computer and use it in GitHub Desktop.
database factory for Mysql database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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