Search code examples
sql-servergotestcontainerssqlx

SQLx does not see AtP placeholder


I get this error every time I try to run integration tests

sql: expected 0 arguments, got 1

However, when I run everything on the dev environment, everything works. Most likely the problem is in using @ as a placeholder, but I can't fix it for a few days now.

here is the code I use

    query := sq.StatementBuilder.
        PlaceholderFormat(sq.AtP).
        Select(
            "id",
            "username",
            "hashed_password",
        ).
        From("users").
        Where(sq.Eq{
            "username": username,
        })

    db := r.getQuerier(ctx)
    sqlQuery, args, err := query.ToSql()
    if err != nil {
        return entities.User{}, err
    }

    zlog.Debug().Msg(sqlQuery)
    zlog.Debug().Any("args", args).Send()

    var u user
    err = db.GetContext(ctx, &u, sqlQuery, args...)
    if err != nil {
        if errors.Is(err, sql.ErrNoRows) {
            return entities.User{}, auth.ErrUserNotFound
        }

        return entities.User{}, err
    }

and the logs

{"level":"debug","time":"2024-11-28T10:52:33+03:00","message":"SELECT id, username, hashed_password FROM users WHERE username = @p1"}
{"level":"debug","args":["testuser_with_refresh_token"],"time":"2024-11-28T10:52:33+03:00"}

my testcontainers setup

func CreateMSSQLServerContainer(t *testing.T) (string, func(), error) {
    containerReq := testcontainers.ContainerRequest{
        Image:        "mcr.microsoft.com/mssql/server",
        ExposedPorts: []string{"1433/tcp"},
        Env: map[string]string{
            "ACCEPT_EULA": "Y",
            "SA_PASSWORD": "YourStrong!Passw0rd",
            "MSSQL_PID":   "Developer",
        },
        WaitingFor: wait.ForSQL("1433/tcp", "sqlserver", func(host string, port nat.Port) string {
            return fmt.Sprintf("sqlserver://sa:YourStrong!Passw0rd@%s:%s?connection+timeout=30", host, port.Port())
        }).WithStartupTimeout(StartupTimeout),
    }

    _, host, ports, cleanup, err := createContainer(t, containerReq)
    if err != nil {
        return "", cleanup, err
    }

    sqlConnectionString := fmt.Sprintf("sqlserver://sa:YourStrong!Passw0rd@%s:%s?connection+timeout=30", host, ports["1433/tcp"][0].HostPort)

    return sqlConnectionString, cleanup, nil
}


Solution

  • I forgot to initialize mssql driver in my testing package :(

    import (
        "time"
    
        "github.com/jmoiron/sqlx"
    
        _ "github.com/microsoft/go-mssqldb" // mssql driver      <-------------
    )