Created Better UUID and Numeric Types (markdown)

Jack Christensen 2020-05-30 13:59:16 -05:00
parent f700e10694
commit e0895c38e8

@ -0,0 +1,36 @@
The Go standard library does not have types directly corresponding to PostgreSQL `uuid` and `numeric`. 3rd party libraries are available but pgx does not use them by default to avoid external dependencies.
However, pgx supports both the ability to register new data types and to override the default handling of currently supported types. There are packages available to use `github.com/gofrs/uuid` and `github.com/shopspring/decimal`.
Import the following packages:
```go
import (
pgtypeuuid "github.com/jackc/pgtype/ext/gofrs-uuid"
shopspring "github.com/jackc/pgtype/ext/shopspring-numeric"
)
```
Then register the data types for your connection. If you are using a connection pool this should be done in the `AfterConnect` hook.
```go
dbconfig, err := pgxpool.ParseConfig(databaseURL)
if err != nil {
// handle error
}
dbconfig.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
conn.ConnInfo().RegisterDataType(pgtype.DataType{
Value: &pgtypeuuid.UUID{},
Name: "uuid",
OID: pgtype.UUIDOID,
})
conn.ConnInfo().RegisterDataType(pgtype.DataType{
Value: &shopspring.Numeric{},
Name: "numeric",
OID: pgtype.NumericOID,
})
return nil
}
```