Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 12 additions & 15 deletions src/databricks/sql/parameters/native.py
Original file line number Diff line number Diff line change
Expand Up @@ -651,23 +651,20 @@ def calculate_decimal_cast_string(self, input: decimal.Decimal) -> str:
Output: DECIMAL(8,4)
"""

string_decimal = str(input)

if string_decimal.startswith("0."):
# This decimal is less than 1
overall = after = len(string_decimal) - 2
elif "." not in string_decimal:
# This decimal has no fractional component
overall = len(string_decimal)
after = 0
# Derive precision/scale from the exact numeric value rather than str(),
# whose sign and exponent notation (e.g. "1.5E+3", "-12.34") would be
# miscounted as extra digits.
_, digits, exponent = input.as_tuple()
if exponent >= 0:
# Integer value: `digits` followed by `exponent` trailing zeros.
scale = 0
precision = len(digits) + exponent
else:
# This decimal has both whole and fractional parts
parts = string_decimal.split(".")
parts_lengths = [len(i) for i in parts]
before, after = parts_lengths[:2]
overall = before + after
scale = -exponent
# A value < 1 still needs `scale` digits of precision.
precision = max(len(digits), scale)

return self.CAST_EXPR.format(overall, after)
return self.CAST_EXPR.format(precision, scale)


def dbsql_parameter_from_int(value: int, name: Optional[str] = None):
Expand Down
6 changes: 6 additions & 0 deletions tests/unit/test_parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,12 @@ def test_parameters_enabled(self, test_input, expected):
(Decimal("123456789.123456789"), "DECIMAL(18,9)"),
(Decimal("12345678912345678912345678912345678912"), "DECIMAL(38,0)"),
(Decimal("1234.56"), "DECIMAL(6,2)"),
# Exponent notation (e.g. from Decimal.normalize()) and negative values
# must be sized from the numeric value, not str().
(Decimal("1500").normalize(), "DECIMAL(4,0)"),
(Decimal("1e5"), "DECIMAL(6,0)"),
(Decimal("-" + "9" * 38), "DECIMAL(38,0)"),
(Decimal("-12.34"), "DECIMAL(4,2)"),
),
)
def test_calculate_decimal_cast_string(value, expected):
Expand Down