jackc / pgtype

MIT License
300 stars 111 forks source link

Reset jsonb before unmarshal #185

Closed d0ubletr0uble closed 1 year ago

d0ubletr0uble commented 1 year ago

Issue: suppose database table has 2 columns:

name varchar(255) metadata jsonb
user1 {"color": "green", "language": "EN"}
user2 {"language": "DE"}

when reading this table in a loop to a slice of User structs

type User struct {
    Username string
    Metadata Metadata
}

type Metadata struct {
    Color    string `json:"color"`
    Language string `json:"language"`
}

final result would be:

[]User{
  {user1 {green EN}},
  {user2 {green DE}} <---
}

"color": "green" property is present in 2nd struct even though database field doesn't have it. It should be "color": "".

This happens when rows.Scan is used in a loop using same struct as a receiver which is then copied to a slice. json.Unmarshal doesn't reset struct fields from previous iteration to default values.

Suggestion: reset dst to default value before calling json.Unmarshal

jackc commented 1 year ago

Thanks. Looks reasonable.

I added the missing reflect import.