bun icon indicating copy to clipboard operation
bun copied to clipboard

Unable to query single JSONB column into custom type

Open svanharmelen opened this issue 2 years ago • 0 comments

Using this code:

type Data struct {
	Label string `json:"label"`
	Value int `json:"value"`
}

func (d Data) Value() (driver.Value, error) {
	data, err := json.Marshal(d)
	if err != nil {
		return nil, err
	}
	return string(data), nil
}

func (d *Data) Scan(value interface{}) error {
	return json.Unmarshal(value.([]byte), &d)
}

func main() {
	// Omitted the DB init stuff...

	var data []Data
	err := db.NewSelect().
		ModelTableExpr("table_with_data_colum AS t")).
		Column("t.data").
		Where("t.id = ?", 12).
		Scan(context.Background(), &data)
	if err != nil {
		log.Fatal(err)
	}
}

I get this error:

sql: Scan error on column index 0, name \"data\": bun: Data does not have column \"data\""

While I would expect a marshaled slice of Data types. When using a struct like this:

type Data struct {
	Data struct {
		Label string `json:"label"`
		Value int `json:"value"`
	} `json:"data"`
}

It works like expected, so isn't it possible to just fetch that one column directly without having to embed that in a dummy struct?

svanharmelen avatar Jul 11 '23 10:07 svanharmelen