-
Notifications
You must be signed in to change notification settings - Fork 837
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Decode custom type #809
Comments
There are several ways of doing this.
|
Hi @jackc do we have example for Array of CustomCompositeTypes? // RichText respresnts rich_text custom type
type RichText struct {
Raw pgtype.Text
Rendered pgtype.Text
}
// DecodeBinary implements
func (c *RichText) DecodeBinary(ci *pgtype.ConnInfo, src []byte) error {
if src == nil {
return errors.New("NULL values can't be decoded. Scan into a &*RichText to handle NULLs")
}
if err := (pgtype.CompositeFields{&c.Raw, &c.Rendered}).DecodeBinary(ci, src); err != nil {
return err
}
return nil
}
// EncodeBinary implements
func (c RichText) EncodeBinary(ci *pgtype.ConnInfo, buf []byte) (newBuf []byte, err error) {
return (pgtype.CompositeFields{&c.Raw, &c.Rendered}).EncodeBinary(ci, buf)
} |
There are several ways of handling arrays, but the simplest is probably |
If anyone reading this is using PostgreSQL user defined functions that return custom composite types with arrays, I've found that it's much easier to wrap the function (or query) in Something like this: var result map[string]interface{}
q, err := conn.Query(context.Background(), "SELECT * FROM to_json(your_plpgsql_function_goes_here($1, $2, $3));", args...)
// error checking
q.Rows.Next()
err = q.Rows.Scan(&queryResponseJson)
// error checking again
err = json.Unmarshal([]byte(queryResponseJson), &result)
// error checking again
fmt.Println(result) |
FWIW, I've done that a fair amount too. Much less ceremony. That said, there are two things to be aware of:
|
Env
pgx version: 4.8.1
go version: 1.14.2
Problem
Hey. I have a question. I want to get a list of events containing a nested aggregated array with prices in one request. Prices, in turn, can contain their own nested structures, but in the example below, I did not indicate this. What is the correct way to decode data from PostgreSQL to structures? It would be great if you could help with my example below. Thank.
Example code
The text was updated successfully, but these errors were encountered: