diff --git a/Better-UUID-and-Numeric-Types.md b/Better-UUID-and-Numeric-Types.md new file mode 100644 index 0000000..fd7c69e --- /dev/null +++ b/Better-UUID-and-Numeric-Types.md @@ -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 +} +``` +