pgx/composite_test.go
Maxim Ivanov 5f0d5f4255 Remove pgtype.Row(), introduce Composite.Scan()
pgtype.Row() was optimized for a single line use
without much ceremony at a cost of OID registration,
which is cumbersome. In practice it so much incovnenience
to create new Composite just before making a query.

So now there is just a Composite type and 2 helper methods:

- SetFields sets composite fields to values passed. This assignment
  fails if types passed are not assignable to Values pgtype is
  made of.

- Scan acts exactly like query.Scan, but for a composite value. Passed
  values are set to values from SQL composite.
2020-04-27 00:48:02 +01:00

56 lines
1.3 KiB
Go

package pgtype_test
import (
"context"
"fmt"
"os"
"github.com/jackc/pgtype"
pgx "github.com/jackc/pgx/v4"
)
//ExampleComposite demonstrates use of Row() function to pass and receive
// back composite types without creating boilderplate custom types.
func Example_composite() {
conn, err := pgx.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE"))
E(err)
defer conn.Close(context.Background())
_, err = conn.Exec(context.Background(), `drop type if exists mytype;
create type mytype as (
a int4,
b text
);`)
E(err)
defer conn.Exec(context.Background(), "drop type mytype")
var isNull bool
var a int
var b *string
c := pgtype.NewComposite(&pgtype.Int4{}, &pgtype.Text{})
c.SetFields(2, "bar")
err = conn.QueryRow(context.Background(), "select $1::mytype", c).
Scan(c.Scan(&isNull, &a, &b))
E(err)
fmt.Printf("First: isNull=%v a=%d b=%s\n", isNull, a, *b)
err = conn.QueryRow(context.Background(), "select (1, NULL)::mytype").Scan(c.Scan(&isNull, &a, &b))
E(err)
fmt.Printf("Second: isNull=%v a=%d b=%v\n", isNull, a, b)
err = conn.QueryRow(context.Background(), "select NULL::mytype").Scan(c.Scan(&isNull, &a, &b))
E(err)
fmt.Printf("Third: isNull=%v\n", isNull)
// Output:
// First: isNull=false a=2 b=bar
// Second: isNull=false a=1 b=<nil>
// Third: isNull=true
}