From b74dc3108fa0d225aa52721bdd7b77b1d60cbc57 Mon Sep 17 00:00:00 2001 From: Christoph Heer Date: Wed, 25 Nov 2015 20:06:55 +0100 Subject: [PATCH] Respect decimal precision of HANA --- pyhdb/protocol/types.py | 9 +++++++-- tests/types/test_int.py | 4 +++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/pyhdb/protocol/types.py b/pyhdb/protocol/types.py index 70adf4c..febf5ce 100644 --- a/pyhdb/protocol/types.py +++ b/pyhdb/protocol/types.py @@ -180,8 +180,13 @@ def prepare(cls, value): if value is None: return struct.pack('b', 0) + if isinstance(value, float): + value = decimal.Decimal(value) + sign, digits, exponent = value.as_tuple() - mantissa = int(''.join(map(str, value.as_tuple().digits))) + if len(digits) > 34: + exponent += len(digits) - 34 + mantissa = int(''.join(map(str, digits[:34]))) exponent += 6176 packed = bytearray(16) @@ -192,8 +197,8 @@ def prepare(cls, value): for i in iter_range(2, 16): packed[i] = (mantissa >> shift) & 0xFF shift -= 8 - packed.reverse() + packed.reverse() return struct.pack('b', cls.type_code) + packed diff --git a/tests/types/test_int.py b/tests/types/test_int.py index 134f067..c109d11 100644 --- a/tests/types/test_int.py +++ b/tests/types/test_int.py @@ -185,7 +185,9 @@ def test_pack_double(input, expected): (Decimal('-312313212312321.1245678910111213142'), b"\x05\x56\xe6\x47\x6f\x0e\xde\xd6\x93\x68\xb0\x26\x78\xfb\x99\x1a\xb0"), (Decimal('3.14159265359'), - b"\x05\x4f\xf6\x59\x25\x49\x00\x00\x00\x00\x00\x00\x00\x00\x00\x2a\x30") + b"\x05\x4f\xf6\x59\x25\x49\x00\x00\x00\x00\x00\x00\x00\x00\x00\x2a\x30"), + (Decimal("-15.756299999999999528199623455293476581573486328125"), + b"\x05\x03\xa0\x1d\x27\x14\xb4\xd7\xc3\x92\x8e\x1c\x3f\xaf\x4d\x00\xb0") ]) def test_pack_decimal(input, expected): assert types.Decimal.prepare(input) == expected