Repository navigation
[coverage] Conformance findings: PARAMQUERY-021 (#901) #1006
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 11 commits
8c170bf
5e09830
d578b17
72cdd60
864acfa
2823eed
2518fc6
6177ab4
2b3a85a
25634d4
1eff019
9036107
1bda507
97b8aca
38f7f25
7d98487
d3ed2c7
47b4968
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,11 +2,15 @@ | |
|
|
||
| import datetime | ||
| import decimal | ||
| import logging | ||
| import warnings | ||
| from enum import Enum, auto | ||
| from typing import Optional, Sequence, Any, TYPE_CHECKING | ||
|
|
||
| from databricks.sql.exc import NotSupportedError | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| if TYPE_CHECKING: | ||
| # Type-annotation-only imports. ``from __future__ import annotations`` keeps | ||
| # these out of the runtime import graph; the ``TSparkParameter*`` objects | ||
|
|
@@ -600,6 +604,14 @@ def __init__( | |
| If set, `scale` and `precision` must both be set. If neither is set, the value | ||
| will be casted to the smallest possible DECIMAL type that can contain it. | ||
|
|
||
| When set, `precision` and `scale` declare a DECIMAL(precision, scale) type. If | ||
| the value has more fractional digits than `scale`, the bound scale (and so the | ||
| precision) is widened to fit them (capped at precision 38) so they are not lost; | ||
| the declared integer room (`precision - scale`) is kept, so a value with more | ||
| integer digits than that is still rejected by the server as out of range. | ||
| Round the `Decimal` yourself (e.g. with `Decimal.quantize`) before binding if | ||
| you need it narrowed to the declared scale. | ||
|
|
||
| :value: | ||
| The value to bind for this parameter. This will be casted to a DECIMAL. | ||
| :name: | ||
|
|
@@ -615,34 +627,196 @@ def __init__( | |
|
|
||
| The `name` argument to this function would be `my_param`. | ||
| :scale: | ||
| The maximum precision (total number of digits) of the number between 1 and 38. | ||
| The number of digits to the right of the decimal point. If the value itself | ||
| has more fractional digits, the value's scale is used so no digits are lost | ||
| (unless the value needs more than 38 digits in total; the excess fractional | ||
| digits are then rounded by the server). | ||
| :precision: | ||
| The number of digits to the right of the decimal point. | ||
| The precision (total number of digits) of the number, between 1 and 38. | ||
| `precision - scale` integer digits are allowed; if the scale is widened to | ||
| fit the value, the precision grows by the same amount (up to 38). | ||
| """ | ||
| self.value: decimal.Decimal = value | ||
| self.name = name | ||
| self.scale = scale | ||
| self.precision = precision | ||
| self._legacy_swapped = False | ||
|
|
||
| if not self.valid_scale_and_precision(): | ||
| raise ValueError( | ||
| "DecimalParameter requires both or none of scale and precision to be set" | ||
| "DecimalParameter requires both or none of scale and precision to be set, " | ||
| "as integers" | ||
| ) | ||
|
|
||
| if self.precision == 0: | ||
| # Earlier releases treated precision=0 as falsy, i.e. "unset", and inferred | ||
| # the type from the value. Keep that behaviour for now (swapping e.g. | ||
| # scale=5, precision=0 into DECIMAL(5,0) would silently round the value), | ||
| # but warn so callers migrate before this becomes an error, like the | ||
| # other legacy-convention calls below. | ||
| warnings.warn( | ||
| "DecimalParameter received precision=0 (scale={}); ignoring scale and " | ||
| "precision and inferring the DECIMAL type from the value, as earlier " | ||
| "releases did. `precision` must be between 1 and {}; pass both as None " | ||
| "to infer the type. This will raise ValueError in a future " | ||
| "release.".format(self.scale, self.MAX_PRECISION), | ||
| FutureWarning, | ||
| stacklevel=2, | ||
| ) | ||
| self.scale = None | ||
| self.precision = None | ||
|
|
||
| if self.scale is not None and self.precision is not None: | ||
| # Range-check the raw arguments *before* the legacy swap below, so a call | ||
| # that is simply invalid (rather than written for the legacy convention) | ||
| # gets an error naming the argument the caller actually passed, and no | ||
| # misleading migration warning. | ||
| if self.scale < 0: | ||
| raise ValueError( | ||
| "DecimalParameter scale must be >= 0, got {}".format(self.scale) | ||
| ) | ||
| if not 1 <= self.precision <= self.MAX_PRECISION: | ||
|
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
|
||
| raise ValueError( | ||
| "DecimalParameter precision must be between 1 and {}, got {}".format( | ||
| self.MAX_PRECISION, self.precision | ||
| ) | ||
| ) | ||
| if self.scale > self.MAX_PRECISION: | ||
| raise ValueError( | ||
| "DecimalParameter scale must be between 0 and {}, got {}".format( | ||
| self.MAX_PRECISION, self.scale | ||
| ) | ||
| ) | ||
|
|
||
| if ( | ||
| self.scale is not None | ||
| and self.precision is not None | ||
| and self.scale > self.precision | ||
|
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
|
||
| ): | ||
| # Earlier releases documented these arguments the other way round | ||
| # (scale = total digits, precision = fractional digits). A valid | ||
| # DECIMAL can never have scale > precision, so this can only be a call | ||
| # written for the old convention: keep it working for now (swap the | ||
| # arguments) but warn so callers migrate before this becomes an error. | ||
| warnings.warn( | ||
| "DecimalParameter received scale ({}) > precision ({}); interpreting the " | ||
| "arguments using the legacy (swapped) convention as DECIMAL({},{}). " | ||
| "`precision` is the total number of digits and `scale` is the number of " | ||
| "digits after the decimal point, as in SQL DECIMAL(precision, scale). " | ||
| "Swap your arguments; this will raise ValueError in a future " | ||
| "release. Legacy-convention calls keep the previous behaviour (the " | ||
| "server rounds the value to the declared scale); with correctly " | ||
| "ordered arguments the bound scale is widened to fit the value's " | ||
| "fractional digits instead.".format( | ||
| self.scale, self.precision, self.scale, self.precision | ||
| ), | ||
| # FutureWarning (not DeprecationWarning) so end users see it by | ||
| # default, not only when the call originates from __main__. | ||
| FutureWarning, | ||
| stacklevel=2, | ||
| ) | ||
| self.scale, self.precision = self.precision, self.scale | ||
|
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
|
||
| # Preserve the old bound type exactly (no widening) for these callers, | ||
| # so the only change they see is the warning. | ||
| # No re-validation needed: the swapped scale is the raw precision | ||
| # (already 1..38) and the swapped precision is the raw scale (already | ||
| # > that and <= 38), so the result is always a valid DECIMAL. | ||
| self._legacy_swapped = True | ||
|
|
||
|
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
|
||
| def valid_scale_and_precision(self): | ||
| def _is_int(x): | ||
| # bool is a subclass of int; reject it so precision=True/scale=False | ||
| # cannot silently bind DECIMAL(1,0). | ||
| return isinstance(x, int) and not isinstance(x, bool) | ||
|
|
||
| if (self.scale is None and self.precision is None) or ( | ||
| isinstance(self.scale, int) and isinstance(self.precision, int) | ||
| _is_int(self.scale) and _is_int(self.precision) | ||
| ): | ||
| return True | ||
| else: | ||
| return False | ||
|
|
||
| def _cast_expr(self): | ||
| if self.scale and self.precision: | ||
| return self.CAST_EXPR.format(self.scale, self.precision) | ||
| if self.scale is not None and self.precision is not None: | ||
|
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
|
||
| if self._legacy_swapped: | ||
| # Legacy-convention call: bind the declared type unchanged, as | ||
| # earlier releases did, so existing rounding is preserved. | ||
| return self.CAST_EXPR.format(self.precision, self.scale) | ||
| precision, scale = self._effective_precision_and_scale( | ||
| self.precision, self.scale | ||
| ) | ||
| if (precision, scale) != (self.precision, self.scale): | ||
| logger.debug( | ||
| "DecimalParameter declared DECIMAL(%d,%d) is bound as DECIMAL(%d,%d) " | ||
| "to fit the value's fractional digits (precision capped at 38)", | ||
| self.precision, | ||
| self.scale, | ||
| precision, | ||
| scale, | ||
| ) | ||
| # SQL DECIMAL type syntax is DECIMAL(precision, scale) | ||
| return self.CAST_EXPR.format(precision, scale) | ||
| else: | ||
| return self.calculate_decimal_cast_string(self.value) | ||
|
|
||
| MAX_PRECISION = 38 | ||
|
|
||
|
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
|
||
| def _effective_precision_and_scale(self, precision: int, scale: int): | ||
| """Widen a declared DECIMAL(precision, scale) so the value's fractional digits | ||
| fit: the value's own scale is authoritative over an under-declared target | ||
| scale. The declared integer room (``precision - scale``) is never widened, so | ||
| a value with more integer digits is still rejected by the server as out of | ||
| range, as in earlier releases. | ||
|
|
||
| Exception: the total is capped at MAX_PRECISION (38) digits. If the value | ||
| needs more than that (e.g. a scale over 38), the cast is clamped and the | ||
| server rounds away the fractional digits that do not fit. | ||
| """ | ||
|
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
|
||
| value = self.value | ||
| if not isinstance(value, decimal.Decimal): | ||
|
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
|
||
| # The value is sent to the server as str(value), so inspect that same | ||
| # textual form; this makes int / float / str values widen like Decimals. | ||
| try: | ||
| value = decimal.Decimal(str(value)) | ||
| except (decimal.InvalidOperation, ValueError, TypeError): | ||
| return precision, scale | ||
| sign, digits, exponent = value.as_tuple() | ||
| if not isinstance(exponent, int): | ||
| # NaN / Infinity: leave the declared type as-is | ||
| return precision, scale | ||
|
|
||
| # Trailing fractional zeros carry no information, so ignore them: otherwise | ||
| # Decimal("1.50") and Decimal("1.5") would bind different types for the same | ||
| # declared parameter. (Stripping keeps len(digits) + exponent unchanged.) | ||
| while exponent < 0 and len(digits) > 1 and digits[-1] == 0: | ||
| digits = digits[:-1] | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔵 Low — The trailing-zero loop re-slices the whole digit tuple on every iteration, so a value with a very long run of fractional zeros takes quadratic time. Scan backward with an index and slice once. 🔀 Found by GPT-6.1 Sol · confirmed by the judge There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔵 Low — Trailing zeros are stripped by re-slicing the digit tuple once per zero, so the cost is quadratic in the number of trailing zeros. This only matters for absurdly long Decimals, since DECIMAL is capped at 38 digits. Find the last non-zero digit, slice once, and adjust the exponent by the number removed. 🔀 Found by GPT-6.1 Sol · confirmed by the judge |
||
| exponent += 1 | ||
| if digits == (0,): | ||
| # Zero (e.g. Decimal("0.000")) has no significant fractional digits | ||
| exponent = max(exponent, 0) | ||
|
|
||
| value_scale = max(-exponent, 0) | ||
|
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
|
||
| declared_int_digits = precision - scale | ||
| # Integer room is never widened past the declared one: an overflowing value | ||
| # is left for the server to reject as out of range. | ||
| value_int_digits = min(max(len(digits) + exponent, 0), declared_int_digits) | ||
|
|
||
| desired_scale = max(scale, value_scale) | ||
|
|
||
| # Allocate the (at most MAX_PRECISION) digits by priority so that, when the | ||
| # cap is hit, the value's own digits win over extra declared room | ||
| # (similar to Spark's decimal precision adjustment): | ||
| # 1. the value's integer digits, 2. the value's fractional digits, | ||
| # 3. extra declared integer room, 4. extra declared fractional room. | ||
| int_digits = value_int_digits | ||
| effective_scale = min(value_scale, self.MAX_PRECISION - int_digits) | ||
| remaining = self.MAX_PRECISION - int_digits - effective_scale | ||
| extra_int = min(declared_int_digits - int_digits, remaining) | ||
| int_digits += extra_int | ||
| remaining -= extra_int | ||
| effective_scale += min(desired_scale - effective_scale, remaining) | ||
| return int_digits + effective_scale, effective_scale | ||
|
|
||
| def calculate_decimal_cast_string(self, input: decimal.Decimal) -> str: | ||
| """Returns the smallest SQL cast argument that can contain the passed decimal | ||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔵 Low — The
precision == 0fallback runs before the range checks and setsscale/precisiontoNone. As a result,scaleis never validated on this path.DecimalParameter(v, scale=-1, precision=0)andDecimalParameter(v, scale=500, precision=0)only emit theFutureWarningand fall back to inference. The equivalent call with a nonzero precision, such asscale=-1, precision=10, raisesValueError("scale must be >= 0").The CHANGELOG says a negative
scalenow raises, but that is not true whenprecision=0. Earlier releases accepted these inputs too, so this is not a regression. Still, a clearly invalidscaleis probably better reported here than hidden behind a migration warning. Suggested fix: run thescale < 0/scale > MAX_PRECISIONchecks before the precision=0 fallback, or note this exception in the CHANGELOG.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add a test for the precision=0 invalid-scale case.
Pushed 1bda507.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for picking this up. I can't see the fix at head, though. The
precision == 0branch still runs before the range checks and sets both fields toNone, soDecimalParameter(v, scale=-1, precision=0)andscale=500, precision=0still only warn and fall back to inference. The only precision=0 test intests/unit/test_parameters.pyistest_decimal_precision_zero_falls_back_to_inferred_type_with_warning, and it uses only valid scales (0, 5, 10), so it doesn't cover the invalid-scale case. The CHANGELOG still says "a negativescale" raises, without mentioning that precision=0 is an exception. To close this, either move thescale < 0/scale > MAX_PRECISIONchecks above the precision=0 fallback and add a test assertingValueErrorfor those inputs, or note the exception in the CHANGELOG. I'm leaving this open for a human to look at.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The fix is already in the current branch head; I made no edits and the working tree is clean. In
DecimalParameter.__init__(src/databricks/sql/parameters/native.py), thescale < 0andscale > MAX_PRECISIONchecks now run before theprecision == 0fallback, soscale=-1, precision=0andscale=500, precision=0raiseValueErrorinstead of only warning. The new testtest_decimal_precision_zero_with_invalid_scale_raisesin tests/unit/test_parameters.py covers both inputs and turnsFutureWarninginto an error, so the migration warning can't hide a missing raise.tests/unit/test_parameters.pypasses (104 tests, run with-m "not realkernel"). The CHANGELOG line about a negativescaleraising is now true on every path, so it needs no exception note. The review-bot probably looked at an older ref. A human should confirm the fix at head and resolve the thread.