Skip to content

Commit

Permalink
Fix panic unmarshalling nil into types.NullDecimal
Browse files Browse the repository at this point in the history
- Add overrides for String() and Format() so NullDecimal's which are
  null do not panic.
  • Loading branch information
aarondl committed Sep 26, 2021
1 parent 7a6cca0 commit 350546a
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion types/decimal.go
@@ -1,6 +1,7 @@
package types

import (
"bytes"
"database/sql"
"database/sql/driver"
"errors"
Expand All @@ -14,6 +15,8 @@ var (
// decimals. It should be set once before any sqlboiler and then
// assumed to be read-only after sqlboiler's first use.
DecimalContext decimal.Context

nullBytes = []byte("null")
)

var (
Expand Down Expand Up @@ -101,17 +104,40 @@ func (n *NullDecimal) Scan(val interface{}) error {

// UnmarshalJSON allows marshalling JSON into a null pointer
func (n *NullDecimal) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, nullBytes) {
if n != nil {
n.Big = nil
}
return nil
}

if n.Big == nil {
n.Big = decimal.WithContext(DecimalContext)
}

return n.Big.UnmarshalJSON(data)
}

// String impl
func (n NullDecimal) String() string {
if n.Big == nil {
return "nil"
}
return n.Big.String()
}

func (n NullDecimal) Format(f fmt.State, verb rune) {
if n.Big == nil {
fmt.Fprint(f, "nil")
return
}
n.Big.Format(f, verb)
}

// MarshalJSON marshals a decimal value
func (n NullDecimal) MarshalJSON() ([]byte, error) {
if n.Big == nil {
return []byte("null"), nil
return nullBytes, nil
}

return n.Big.MarshalText()
Expand Down

0 comments on commit 350546a

Please sign in to comment.