MCPcopy Create free account
hub / github.com/PostHog/duckgres / encodeNumeric

Function encodeNumeric

server/types.go:682–800  ·  view source on GitHub ↗

encodeNumeric encodes a value in PostgreSQL binary numeric format. PostgreSQL binary numeric layout: int16 ndigits - number of base-10000 digit groups int16 weight - weight of first digit (number of groups before decimal point - 1) int16 sign - 0x0000 = positive, 0x4000 = negative int16

(v interface{})

Source from the content-addressed store, hash-verified

680// int16 dscale - number of digits after decimal point (display scale)
681// int16[] digits - base-10000 digit groups
682func encodeNumeric(v interface{}) []byte {
683 var val *big.Int
684 var dscale int16
685
686 switch x := normalizeDriverValue(v).(type) {
687 case arrowmap.DecimalValue:
688 val = new(big.Int).Set(x.Value)
689 dscale = int16(x.Scale)
690 case *big.Int:
691 // HUGEINT comes from the Go driver as *big.Int (scale 0)
692 val = new(big.Int).Set(x)
693 dscale = 0
694 case string:
695 // Arrow Flight returns decimals with non-zero scale as strings like "123.45".
696 // Parse the string back into unscaled big.Int + scale.
697 s := x
698 neg := false
699 if len(s) > 0 && s[0] == '-' {
700 neg = true
701 s = s[1:]
702 }
703 if dotIdx := strings.Index(s, "."); dotIdx >= 0 {
704 dscale = int16(len(s) - dotIdx - 1)
705 s = s[:dotIdx] + s[dotIdx+1:]
706 }
707 val = new(big.Int)
708 if _, ok := val.SetString(s, 10); !ok {
709 return encodeText(v)
710 }
711 if neg {
712 val.Neg(val)
713 }
714 default:
715 // Fallback: try to format as text and let the caller handle it
716 return encodeText(v)
717 }
718
719 // Handle sign
720 var sign int16
721 if val.Sign() < 0 {
722 sign = 0x4000 // NUMERIC_NEG
723 val.Neg(val)
724 }
725
726 // Handle zero
727 if val.Sign() == 0 {
728 buf := make([]byte, 8)
729 // ndigits=0, weight=0, sign=0, dscale=dscale
730 binary.BigEndian.PutUint16(buf[6:], uint16(dscale))
731 return buf
732 }
733
734 // Convert unscaled value to base-10000 digits aligned to the decimal point.
735 // The unscaled value represents: val * 10^(-scale)
736 // PostgreSQL numeric uses base-10000 groups where each group covers 4 decimal digits.
737 // We need to pad the unscaled value so the fractional part fills complete groups.
738 fracGroups := (int(dscale) + 3) / 4 // ceiling division
739 padding := fracGroups*4 - int(dscale)

Callers 4

TestEncodeNumericFunction · 0.85
TestDecodeNumericFunction · 0.85
encodeBinaryFunction · 0.85

Calls 2

normalizeDriverValueFunction · 0.85
encodeTextFunction · 0.85

Tested by 3

TestEncodeNumericFunction · 0.68
TestDecodeNumericFunction · 0.68