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 {}
number
variable's value it is going to already be formatted astext
anyway, there's not even any need to try to type cast it (unless, of course, its value is very different from what you've shown). Consider providing a minimal reproducible example....
, i.e.return db.Conn.Query(ctx, query, args...)
. That's why you get[
and]
around the number in the error message. You are passingargs
which is a slice, not the phone number string.