Go and pgx: cannot convert [+11111111111] to Text

Issue

I’m new to golang and pgx and I’m running into an issue when I try to run a simple query. I have the following table in postgres.

CREATE TABLE users (
    user_id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
    phone_number TEXT NOT NULL UNIQUE, 
);

When I try to run the following query:

func sampleFunc(db dbClient){
    number := "+111111111"
    rows, err := db.Query(context.Background(), "SELECT user_id FROM users WHERE phone_number=$1::TEXT;", number)
    if err != nil {
        log.Println(err)
        return false, err
    }
}

I get the following error: cannot convert [+111111111] to Text.

EDIT 03/05/2022

I should note that I’m wrapping the pgxpool.Pool in my own struct, and for some reason there’s actually no issue when I use the pgxpool directly.

type dbClient interface {
    Query(ctx context.Context, query string, args ...interface{}) (pgx.Rows, error)
}

type SQLClient struct {
    Conn *pgxpool.Pool
}

func (db *SQLClient) Query(ctx context.Context, query string, args ...interface{}) (pgx.Rows, error) {
    return db.Conn.Query(ctx, query, args)
}

I’m assuming that then something is happening with the type information, but still can’t figure out how to go about fixing it.

When I print the args type info in SQLClient.Query, by using fmt.Println(reflect.TypeOf(args)), I get the following: []interface {}

Solution

You forgot to add ... to the args argument passed to db.Conn.Query().

func (db *SQLClient) Query(ctx context.Context, query string, args ...interface{}) (pgx.Rows, error) {
    return db.Conn.Query(ctx, query, args...)
}

The spec.

Answered By – mkopriva

Answer Checked By – Marie Seifert (GoLangFix Admin)

Leave a Reply

Your email address will not be published.