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

Function decodeNumeric

server/types.go:986–1067  ·  view source on GitHub ↗

decodeNumeric decodes PostgreSQL binary numeric format into a string.

(data []byte)

Source from the content-addressed store, hash-verified

984
985// decodeNumeric decodes PostgreSQL binary numeric format into a string.
986func decodeNumeric(data []byte) (string, error) {
987 if len(data) < 8 {
988 return "", fmt.Errorf("insufficient data for numeric: got %d bytes, need at least 8", len(data))
989 }
990
991 ndigits := int(binary.BigEndian.Uint16(data[0:]))
992 weight := int16(binary.BigEndian.Uint16(data[2:]))
993 sign := binary.BigEndian.Uint16(data[4:])
994 dscale := int(binary.BigEndian.Uint16(data[6:]))
995
996 if len(data) < 8+2*ndigits {
997 return "", fmt.Errorf("insufficient data for numeric digits: got %d bytes, need %d", len(data), 8+2*ndigits)
998 }
999
1000 // Special values
1001 if sign == 0xC000 {
1002 return "NaN", nil
1003 }
1004
1005 // Read base-10000 digits
1006 digits := make([]int16, ndigits)
1007 for i := 0; i < ndigits; i++ {
1008 digits[i] = int16(binary.BigEndian.Uint16(data[8+2*i:]))
1009 }
1010
1011 // Reconstruct the unscaled value
1012 val := new(big.Int)
1013 base := big.NewInt(10000)
1014 for _, d := range digits {
1015 val.Mul(val, base)
1016 val.Add(val, big.NewInt(int64(d)))
1017 }
1018
1019 // The digits represent: sum(digits[i] * 10000^(weight-i))
1020 // After reading all ndigits groups, we have val * 10000^(weight - ndigits + 1)
1021 // We need to convert to a fixed-point number with dscale decimal places.
1022 // Exponent in terms of decimal digits: 4 * (weight - ndigits + 1)
1023 exp := 4 * (int(weight) - ndigits + 1)
1024
1025 // We want the value as: val * 10^exp, displayed with dscale decimal places.
1026 // Shift so we have dscale fractional digits: multiply by 10^(dscale + exp)
1027 shift := dscale + exp
1028 if shift > 0 {
1029 factor := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(shift)), nil)
1030 val.Mul(val, factor)
1031 } else if shift < 0 {
1032 factor := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(-shift)), nil)
1033 val.Div(val, factor)
1034 }
1035
1036 // Now val is the unscaled integer with dscale implied decimal places
1037 negative := sign == 0x4000
1038 if negative {
1039 val.Neg(val)
1040 }
1041
1042 // Format as decimal string
1043 str := val.String()

Callers 6

TestEncodeNumericFunction · 0.85
TestDecodeNumericFunction · 0.85
TestDecodeNumericRawFunction · 0.85
decodeBinaryCopyFunction · 0.85
decodeBinaryFunction · 0.85

Calls 2

AddMethod · 0.80
StringMethod · 0.45

Tested by 4

TestEncodeNumericFunction · 0.68
TestDecodeNumericFunction · 0.68
TestDecodeNumericRawFunction · 0.68