Properly register array and composite PostgreSQL types with pgtype

I have moved everything into a different file, even though it is related
to “db”, because it was starting to get a bit ugly.

Apparently i was doing too much work and had to read the code to
understand what i was supposed to do, because pgtypes’ documentation,
as all other projects from the same author, is almost non-existent.
This commit is contained in:
jordi fita mas 2023-02-20 11:42:21 +01:00
parent 98ac17a129
commit b3004486f0
5 changed files with 96 additions and 68 deletions

1
go.mod
View File

@ -10,7 +10,6 @@ require (
)
require (
github.com/jackc/pgio v1.0.0
github.com/jackc/pgtype v1.12.0
golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90 // indirect
)

View File

@ -4,8 +4,6 @@ import (
"context"
"log"
"github.com/jackc/pgio"
"github.com/jackc/pgtype"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
)
@ -14,66 +12,6 @@ type Db struct {
*pgxpool.Pool
}
type newInvoiceProductArray []*invoiceProductForm
type discountRate struct {
pgtype.Numeric
}
func (form *invoiceProductForm) EncodeBinary(ci *pgtype.ConnInfo, buf []byte) (newBuff []byte, err error) {
productId := &pgtype.Int4{}
if err = productId.Set(form.ProductId.Val); err != nil {
return
}
name := &pgtype.Text{String: form.Name.Val, Status: pgtype.Present}
description := &pgtype.Text{String: form.Description.Val, Status: pgtype.Present}
price := &pgtype.Text{String: form.Price.Val, Status: pgtype.Present}
quantity := &pgtype.Int4{}
if err = quantity.Set(form.Quantity.Val); err != nil {
return
}
discount := &discountRate{}
if err = discount.Set(form.Discount.Val); err != nil {
return
}
tax := &pgtype.Int4Array{}
if err = tax.Set(form.Tax.Selected); err != nil {
return
}
ct := pgtype.CompositeFields{productId, name, description, price, quantity, discount, tax}
return ct.EncodeBinary(ci, buf)
}
func (src newInvoiceProductArray) EncodeBinary(ci *pgtype.ConnInfo, buf []byte) ([]byte, error) {
arrayHeader := pgtype.ArrayHeader{
Dimensions: []pgtype.ArrayDimension{{Length: int32(len(src)), LowerBound: 1}},
}
/*typeName := "numerus.new_invoice_product"
if dt, ok := ci.DataTypeForName(typeName); ok {
arrayHeader.ElementOID = int32(dt.OID)
} else {
return nil, fmt.Errorf("unable to find oid for type name %v", typeName)
}*/
arrayHeader.ElementOID = 69053
buf = arrayHeader.EncodeBinary(ci, buf)
for i := range src {
sp := len(buf)
buf = pgio.AppendInt32(buf, -1)
elemBuf, err := src[i].EncodeBinary(ci, buf)
if err != nil {
return nil, err
}
if elemBuf != nil {
buf = elemBuf
pgio.SetInt32(buf[sp:], int32(len(buf[sp:])-4))
}
}
return buf, nil
}
func NewDatabase(ctx context.Context, connString string) (*Db, error) {
config, err := pgxpool.ParseConfig(connString)
if err != nil {
@ -81,9 +19,10 @@ func NewDatabase(ctx context.Context, connString string) (*Db, error) {
}
config.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
_, err := conn.Exec(context.Background(), "SET search_path TO numerus, public")
conn.ConnInfo().RegisterDataType(pgtype.DataType{Value: &discountRate{}, Name: "discount_rate", OID: 69002})
return err
if _, err := conn.Exec(ctx, "SET search_path TO numerus, public"); err != nil {
return err
}
return registerPgTypes(ctx, conn)
}
config.BeforeAcquire = func(ctx context.Context, conn *pgx.Conn) bool {

View File

@ -48,7 +48,18 @@ func (field *InputField) FillValue(r *http.Request) {
}
func (field *InputField) Integer() int {
value, _ := strconv.Atoi(field.Val)
value, err := strconv.Atoi(field.Val)
if err != nil {
panic(err)
}
return value
}
func (field *InputField) Float64() float64 {
value, err := strconv.ParseFloat(field.Val, 64)
if err != nil {
panic(err)
}
return value
}

View File

@ -138,7 +138,7 @@ func HandleAddInvoice(w http.ResponseWriter, r *http.Request, _ httprouter.Param
mustRenderNewInvoiceForm(w, r, form)
return
}
conn.MustExec(r.Context(), "select add_invoice($1, $2, $3, $4, $5, $6)", company.Id, form.Number, form.Date, form.Customer, form.Notes, newInvoiceProductArray(form.Products))
conn.MustExec(r.Context(), "select add_invoice($1, $2, $3, $4, $5, $6)", company.Id, form.Number, form.Date, form.Customer, form.Notes, NewInvoiceProductArray(form.Products))
http.Redirect(w, r, companyURI(company, "/invoices"), http.StatusSeeOther)
default:
http.Error(w, gettext("Invalid action", locale), http.StatusBadRequest)

79
pkg/pgtypes.go Normal file
View File

@ -0,0 +1,79 @@
package pkg
import (
"context"
"fmt"
"github.com/jackc/pgtype"
"github.com/jackc/pgx/v4"
)
type NewInvoiceProductArray []*invoiceProductForm
func (src NewInvoiceProductArray) EncodeBinary(ci *pgtype.ConnInfo, buf []byte) ([]byte, error) {
typeName := "new_invoice_product[]"
dt, ok := ci.DataTypeForName(typeName)
if !ok {
return nil, fmt.Errorf("unable to find oid for type name %v", typeName)
}
var values [][]interface{}
for _, form := range src {
values = append(values, []interface{}{
form.ProductId.Val,
form.Name.Val,
form.Description.Val,
form.Price.Val,
form.Quantity.Val,
form.Discount.Float64() / 100.0,
form.Tax.Selected,
})
}
array := pgtype.NewValue(dt.Value).(pgtype.ValueTranscoder)
if err := array.Set(values); err != nil {
return nil, err
}
return array.EncodeBinary(ci, buf)
}
func registerPgTypes(ctx context.Context, conn *pgx.Conn) error {
discountRateOID, err := registerPgType(ctx, conn, &pgtype.Numeric{}, "discount_rate")
if err != nil {
return err
}
newInvoiceProduct, err := pgtype.NewCompositeType(
"new_invoice_product",
[]pgtype.CompositeTypeField{
{"product_id", pgtype.Int4OID},
{"name", pgtype.TextOID},
{"description", pgtype.TextOID},
{"price", pgtype.TextOID},
{"quantity", pgtype.Int4OID},
{"discount_rate", discountRateOID},
{"tax", pgtype.Int4ArrayOID},
},
conn.ConnInfo(),
)
if err != nil {
return err
}
newInvoiceProductOID, err := registerPgType(ctx, conn, newInvoiceProduct, newInvoiceProduct.TypeName())
if err != nil {
return err
}
newInvoiceProductArray := pgtype.NewArrayType("new_invoice_product[]", newInvoiceProductOID, func() pgtype.ValueTranscoder {
value := newInvoiceProduct.NewTypeValue()
return value.(pgtype.ValueTranscoder)
})
_, err = registerPgType(ctx, conn, newInvoiceProductArray, newInvoiceProductArray.TypeName())
if err != nil {
return err
}
return nil
}
func registerPgType(ctx context.Context, conn *pgx.Conn, value pgtype.Value, name string) (oid uint32, err error) {
if err = conn.QueryRow(ctx, "select $1::regtype::oid", name).Scan(&oid); err != nil {
return
}
conn.ConnInfo().RegisterDataType(pgtype.DataType{Value: value, Name: name, OID: oid})
return
}