0

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?

4
  • 1
    Just move that logic to a function that builds the connection string, and unit test that. Commented Aug 21, 2018 at 15:56
  • I'd have to get the boss's permission to do that. (I'm responsible only for unit-testing and documenting.) Commented Aug 21, 2018 at 15:58
  • 2
    If you're responsible for writing the tests but not the code, that's a highly unfortunate situation (that's an objectively terrible way to operate), but I suppose you could write a test for the connection-string-building function which does not exist, and let that test fail until a dev changes the code. Commented Aug 21, 2018 at 16:00
  • @Adrian good news: boss told me not to worry about it Commented Aug 21, 2018 at 17:02

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.