From: Daniele Varrazzo Date: Sat, 8 May 2021 17:13:21 +0000 (+0200) Subject: Don't dump an excess of right 0's in Decimal to numeric X-Git-Tag: 3.0.dev0~48^2~4 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=6c111eecb624ec0b5042edf8f1494c204fd697d8;p=thirdparty%2Fpsycopg.git Don't dump an excess of right 0's in Decimal to numeric --- diff --git a/psycopg3/psycopg3/types/numeric.py b/psycopg3/psycopg3/types/numeric.py index e2c1214df..ebfeb9896 100644 --- a/psycopg3/psycopg3/types/numeric.py +++ b/psycopg3/psycopg3/types/numeric.py @@ -395,7 +395,15 @@ class DecimalBinaryDumper(Dumper): weights = (1000, 100, 10, 1) wi = 0 - ndigits = len(digits) + ndigits = nzdigits = len(digits) + + # Find the last nonzero digit + while nzdigits > 0 and digits[nzdigits - 1] == 0: + nzdigits -= 1 + + if not nzdigits: + return _pack_numeric_head(0, 0, NUMERIC_POS, -exp) + if exp <= 0: dscale = -exp else: @@ -410,9 +418,10 @@ class DecimalBinaryDumper(Dumper): wi = DEC_DIGITS - mod ndigits += wi + tmp = nzdigits + wi out = bytearray( _pack_numeric_head( - 0, # ndigits, filled ahead + tmp // DEC_DIGITS + (tmp % DEC_DIGITS and 1), # ndigits (ndigits + exp) // DEC_DIGITS - 1, # weight NUMERIC_NEG if sign else NUMERIC_POS, # sign dscale, @@ -420,8 +429,8 @@ class DecimalBinaryDumper(Dumper): ) pgdigit = 0 - for digit in digits: - pgdigit += weights[wi] * digit + for i in range(nzdigits): + pgdigit += weights[wi] * digits[i] wi += 1 if wi >= DEC_DIGITS: out += _pack_uint2(pgdigit) @@ -430,5 +439,4 @@ class DecimalBinaryDumper(Dumper): if pgdigit: out += _pack_uint2(pgdigit) - out[:2] = _pack_uint2((len(out) - 8) // 2) # num of pg digits return out