pgtype icon indicating copy to clipboard operation
pgtype copied to clipboard

Null text columns don't work with string pointers

Open sbowman opened this issue 5 years ago • 1 comments

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
}

sbowman avatar Oct 05 '20 18:10 sbowman

There shouldn't be any difference between text and varchar. I think something else might be going on.

  1. The error message references dest[3], but only 3 values are passed into Scan.
  2. AFAIK illegal base64 data isn't an error that pgx types will produce. Maybe another type is registered somehow?

jackc avatar Oct 06 '20 00:10 jackc