From bbabf5c7339032a23fe170aa12f5d9a0771e4312 Mon Sep 17 00:00:00 2001 From: jordi fita mas Date: Mon, 22 May 2023 11:06:06 +0200 Subject: [PATCH] Use a null as product ID when adding new products to invoices MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Otherwise, pgx (rightfully) tries to convert a "" into a integer, as this is the field’s type, cannot, and panics with an error. Added a IntegerOrNull method to FormField because this is exactly the same that happens with the invoiceProductId, and made no sense to have to do the logic twice, or in a function inside form. --- pkg/form.go | 9 +++++++++ pkg/pgtypes.go | 10 ++-------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/pkg/form.go b/pkg/form.go index acbdb14..ee19eb6 100644 --- a/pkg/form.go +++ b/pkg/form.go @@ -70,6 +70,15 @@ func (field *InputField) Integer() int { return value } +func (field *InputField) IntegerOrNil() interface{} { + if field.Val != "" { + if i := field.Integer(); i > 0 { + return i + } + } + return nil +} + func (field *InputField) Float64() float64 { value, err := strconv.ParseFloat(field.Val, 64) if err != nil { diff --git a/pkg/pgtypes.go b/pkg/pgtypes.go index 9582974..ab77a34 100644 --- a/pkg/pgtypes.go +++ b/pkg/pgtypes.go @@ -48,15 +48,9 @@ func (src EditedInvoiceProductArray) EncodeBinary(ci *pgtype.ConnInfo, buf []byt } var values [][]interface{} for _, form := range src { - var invoiceProductId interface{} = nil - if form.InvoiceProductId.Val != "" { - if id := form.InvoiceProductId.Integer(); id > 0 { - invoiceProductId = id - } - } values = append(values, []interface{}{ - invoiceProductId, - form.ProductId.Val, + form.InvoiceProductId.IntegerOrNil(), + form.ProductId.IntegerOrNil(), form.Name.Val, form.Description.Val, form.Price.Val,