gosqlx

How to pass variable ids to statement.Query() in golang?


I have this query in postgres which queries 1 or n users based on the parameters passed:

select name, phone from clients where id in ('id1','id2')

Now when I try to use this at golang I'm having problems approaching how to pass this type of variable arguments to the statement.Query() function:

ids := []string{"0aa6c0c5-e44e-4187-b128-6ae4b2258df0", "606b0182-269f-469a-bb29-26da4fa0302b"}
rows, err := stmt.Query(ids...)

This throws error: Cannot use 'ids' (type []string) as type []interface{}

When I check in source code query it can receive many variables of type interface:

func (s *Stmt) Query(args ...interface{}) (*Rows, error) {
    return s.QueryContext(context.Background(), args...)
}

If I do this manually it works:

rows, err := stmt.Query("0aa6c0c5-e44e-4187-b128-6ae4b2258df0", "606b0182-269f-469a-bb29-26da4fa0302b")

But of course I need the args to be 1 or many more, and dynamically generated.

I'm using Sqlx lib.


Solution

  • As we can see on the Query() method scheme and also from the error message, the method requires an argument in []interface{} type.

    func (s *Stmt) Query(args ...interface{}) (*Rows, error) {
        return s.QueryContext(context.Background(), args...)
    }
    

    In your code, the ids variable hold []string data. Change it to []interface{} so it'll meet Query() requirements, then it'll work.

    ids := []interface{}{
        "0aa6c0c5-e44e-4187-b128-6ae4b2258df0",
        "606b0182-269f-469a-bb29-26da4fa0302b",
    }
    rows, err := stmt.Query(ids...)