pgtype
pgtype copied to clipboard
Null text columns don't work with string pointers
If I have aTEXT column in my database table with null values in it, I'm unable to load that into a *string variable.
Here's a really simple example. Suppose the avatar column is a TEXT column with a null value:
type User struct {
ID uuid.UUID
Email string
Avatar *string
}
row := conn.QueryRow(ctx, "select id, email, avatar from users where id = $1", userID)
if err := row.Scan(&user.ID, &user.Email, &user.Avatar); err != nil {
fmt.Printf("Unable to get record: %s\n", err)
}
When I run that code, I get an error something like this:
can't scan into dest[3]: illegal base64 data at input byte 5
I can use string pointers if I change the column type to a VARCHAR. Or I can use a pgtype.Text variable directly instead:
var user User
var avatar pgtype.Text
row := conn.QueryRow(ctx, "select id, email, avatar from users where id = $1", userID)
if err := row.Scan(&user.ID, &user.Email, &avatar); err != nil {
fmt.Printf("Unable to get record: %s\n", err)
}
if avatar.Status == pgtype.Present {
user.Avatar = avatar.String
} else {
user.Avatar = nil
}
There shouldn't be any difference between text and varchar. I think something else might be going on.
- The error message references
dest[3], but only 3 values are passed intoScan. - AFAIK
illegal base64 dataisn't an error that pgx types will produce. Maybe another type is registered somehow?