I'm trying to test this function:
//OpenConnection opens a connection to a MySQL database by `connStr`
// or returns error. If `connStr` is empty, error is returned.
//
// Parameters:
// - `connStr`: the URL of the database to connect to
// - `interpolateParams` : should we interpolate parameters?
//
// Returns:
// - pointer to the database connection
// - any errors that happened during this process
func OpenConnection(connStr string, interpolateParams bool) (*sql.DB, *errors.ErrorSt) {
if connStr == "" {
return nil, errors.Database().ReplaceMessage("No database connection string.")
}
connStr = connStr + "?parseTime=true&multiStatements=true"
if interpolateParams {
connStr += "&interpolateParams=true"
}
db, err := sql.Open("mysql", connStr)
if err != nil {
return nil, errors.Database().AddDetails(err.Error(), connStr)
}
return db, nil
}
for the case of interpolateParams
. I'm sifting through the official documentation and see no simple way to get the connection string from an sql.DB
. Since this is unit testing, I am, of course, hitting the function with a fake connection URL.
Is there a way to get the connection URL from sql.DB
to check for the interpolation query string?
database/sql
is primarily focused on being an interface for doing things with SQL. Connection strings are typically driver specific, so I would look to the driver that you are using for clues how to get the connection string In your case, judging by the comment at the top, you are using MySQL, so I am assuming you would be using the go-sql-driver/mysql
. You can import it directly in your code (rather than using a blank import) and access the Config
struct, documented here: https://github.com/go-sql-driver/mysql/blob/master/dsn.go#L35 which gets populated from your dsn passed into sql.Open