【问题标题】:Getting connection string of db connection获取数据库连接的连接字符串
【发布时间】:2019-01-27 20:51:51
【问题描述】:

我正在尝试测试这个功能:

//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
}

对于interpolateParams 的情况。我正在筛选the official documentation,并没有看到从sql.DB 获取连接字符串的简单方法。由于这是单元测试,我当然会使用虚假的连接 URL 来访问该功能。

有没有办法从 sql.DB 获取连接 URL 以检查插值查询字符串?

【问题讨论】:

  • 只需将该逻辑移动到构建连接字符串的函数中,然后对其进行单元测试。
  • 我必须得到老板的许可才能这样做。 (我只负责单元测试和记录。)
  • 如果你负责编写测试而不是代码,那是一个非常不幸的情况(这是一种客观上很糟糕的操作方式),但我想你可以为连接字符串编写一个测试- 不存在的构建函数,并让该测试失败,直到开发人员更改代码。
  • @Adrian 好消息:老板告诉我不要担心

标签: unit-testing go


【解决方案1】:

database/sql 主要专注于成为使用 SQL 执行操作的接口。连接字符串通常是特定于驱动程序的,因此我会查看您正在使用的驱动程序以获取如何获取连接字符串的线索在您的情况下,根据顶部的注释判断,您使用的是 MySQL,所以我假设您会使用go-sql-driver/mysql。您可以直接在您的代码中导入它(而不是使用空白导入)并访问Config 结构,记录在此:https://github.com/go-sql-driver/mysql/blob/master/dsn.go#L35,它从您的 dsn 填充到 sql.Open

【讨论】:

    猜你喜欢
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多