googleapis / googleapis/google-cloud-go
spanner: support json.RawMessage or []byte for reading
- Dominant language
- Go
- Stars
- 4.5k
- Forks
- 1.6k
- Avg merge
- 1d 13h
- Merged PRs (30d)
- 109
Description
## Is your feature request related to a problem? Please describe.
Currently it's not possible to scan JSON columns into a `[]byte` or `json.RawMessage`.
``` go
var result json.RawMesage
row := client.Single().Query(ctx,
spanner.Statement{SQL: `SELECT (JSON '{"a":123, "x": {}, "y": {}}')`},
)
err = row.Do(func(row *spanner.Row) error {
return row.Columns(&result)
})
fmt.Println(err)
// failed to decode column 0, type *json.RawMessage cannot be used for decoding JSON
fmt.Println(result)
```
Currently the supported types are `spanner.NullJSON` and `spanner.PGJsonB`. Both end up decoding into an `interface{}`, which may introduce an additional `json.Marshal` and `json.Unmarshal` to get the values into a specific type.
Allowing to use `json.RawMessage` or `[]byte` would allow the user to manage the json unmarshaling directly themselves.
## Describe the solution you'd like
Ideally one (or few) of these can be used to decode json:
* `[]byte` and `*[]byte`
* `json.RawMessage` and `*json.RawMessage`
## Describe alternatives you've considered
It seems that it's possible to write a custom type to work around this problem with:
``` go
type rawJSON struct {
Data []byte
}
func (v *rawJSON) DecodeSpanner(data any) error {
v.Data = []byte(data.(string))
return nil
}
```
The other option would be to force in the database query to convert the json column to `[]byte`.
And an additional approach would be to use `spanner.GenericColumnValue` as the destination.
Contributor guide
Assessment
This issue has not been assessed yet.