1

When I implement a query by selecting all the elements using * operator, the query is not mapped to the struct.

query := gocb.NewN1qlQuery("SELECT * FROM `item-bucket` WHERE itemBarcode=$1")
queryParams = append(queryParams, itemBarcode)
rows, err := itemBucket.ExecuteN1qlQuery(query, queryParams)

var row ItemEntity
for rows.Next(&row) {
    fmt.Printf("Results: %+v\n", row)
}

However, when I add each of the fields into the query, it is directly mapped.

query := gocb.NewN1qlQuery("SELECT itemBarcode, color, price FROM `item-bucket` WHERE itemBarcode=$1")
queryParams = append(queryParams, itemBarcode)
rows, err := itemBucket.ExecuteN1qlQuery(query, queryParams)

var row ItemEntity
for rows.Next(&row) {
    fmt.Printf("Results: %+v\n", row)
}

Is there a way to map directly to struct using the * operator?

The Go version of the project is 1.6

hakansander
  • 337
  • 4
  • 13
  • 1
    I'm not a Go developer, but to get around the same issue in .NET, I don't use a naked *, I use an alias like: `SELECT b.* FROM mybucket b` - and generally speaking, avoid ANY asterisk is a good idea, of course :) – Matthew Groves Mar 14 '22 at 16:32

1 Answers1

0

Have a look into sqlx, where their README contains examples using queries like SELECT * FROM x. If your database column names don't match your struct field names directly, you can specify them as struct tags like:

type ItemBucket struct {
    ItemBarcode string `db:"itemBarcode"`
    Color       string `db:"last_name"`
    ...
}
j3st
  • 345
  • 1
  • 8