fix(10.1-03): fill numeric model fields from JSON numbers

- lagoon.Fill converts a json.Number (from a UseNumber decoder, as cabana's
  save path uses) into integer, unsigned and float fields; a fraction or an
  overflow is an error
- before this, saving a type: number field into an *int column was a 500
- README documents the conversion
This commit is contained in:
Jakub Zych
2026-09-29 02:24:25 +02:00
parent 9d23ac5832
commit c3efbc3428
3 changed files with 72 additions and 1 deletions

View File

@@ -2,6 +2,7 @@ package lagoon
import (
"bytes"
"encoding/json"
"log/slog"
"strings"
"testing"
@@ -160,3 +161,35 @@ func TestFillEncryptedTakesPlaintext(t *testing.T) {
t.Fatalf("nil must clear: api_key=%q token=%v", row.APIKey.Reveal(), row.Token)
}
}
// TestFillJSONNumber covers request bodies decoded with UseNumber: a
// json.Number fills integer, unsigned and float fields (plain or pointer), a
// string field keeps the number's text, and a fraction or an overflow into an
// integer field is an error rather than a silent truncation.
func TestFillJSONNumber(t *testing.T) {
type numbers struct {
Year *int `gorm:"column:year"`
Count uint8 `gorm:"column:count"`
Price float64 `gorm:"column:price"`
Code string `gorm:"column:code"`
}
allowed := []string{"year", "count", "price", "code"}
var row numbers
err := Fill(&row, allowed, map[string]any{
"year": json.Number("1977"),
"count": json.Number("200"),
"price": json.Number("12.5"),
"code": json.Number("0042"),
}, true)
if err != nil {
t.Fatal(err)
}
if row.Year == nil || *row.Year != 1977 || row.Count != 200 || row.Price != 12.5 || row.Code != "0042" {
t.Fatalf("row = %+v (year %v)", row, row.Year)
}
for key, value := range map[string]json.Number{"year": "1977.5", "count": "256"} {
if err := Fill(&row, allowed, map[string]any{key: value}, true); err == nil {
t.Fatalf("%s = %s filled without an error", key, value)
}
}
}