-
Notifications
You must be signed in to change notification settings - Fork 848
Numeric and decimal support
The Go language does not have a standard decimal type. pgx supports the PostgreSQL numeric
type out of the box. However, in the absence of a proper Go type it can only be used when translated to a float64
or string
. This is obviously not ideal.
The recommended solution is to use the github.com/shopspring/decimal package. pgx has support for integrating with this package, but to avoid a mandatory external dependency the integration is in a separate package.
To use it add the following line to your imports:
shopspring "github.com/jackc/pgtype/ext/shopspring-numeric"
Then run the following to register the data type with a connection:
conn.ConnInfo().RegisterDataType(pgtype.DataType{
Value: &shopspring.Numeric{},
Name: "numeric",
OID: pgtype.NumericOID,
})
If you are using pgxpool
the previous command should be run in an AfterConnect
hook to ensure it is available on every connection.
You will now be able to use a decimal.Decimal
as an query argument or scan destination.