-
-
Save clairew/7a03f07800f2e45201cbe33ef47f266e to your computer and use it in GitHub Desktop.
DB Connection Helper Function Example
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
//GetTestDBConnection returns DB pointer to be used in test suite | |
func GetTestDBConnection() *sql.DB, error { | |
testDbName, sqlDriver := GenerateTestDB() // wrapped logic that generates test db and tables | |
dbUser, dbPass, dbHost, dbPort := GetDBCredsFromConfig() // get necessary db credentials | |
log.Info("Initializing test database connection") | |
connectionString := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", dbUser, dbPass, dbHost, dbPort, testDbName) | |
db, err := sql.Open(sqlDriver, connectionString) | |
if err != nil { | |
log.WithFields(log.Fields{ // use logrus logging package to specify error and scenario | |
"err": err, | |
"dbName": testDbName, | |
}).Warn("Unable to establish test database connection") | |
return nil, err | |
} | |
return db, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment