Skip to content

Classify a TypeDecorator division operand by its impl - #1635

Merged
laughingman7743 merged 5 commits into
masterfrom
fix/1586-division-type-decorator
Dec 1, 2026
Merged

laughingman7743 merged 5 commits into
masterfrom
fix/1586-division-type-decorator

Conversation

@laughingman7743

@laughingman7743 laughingman7743 commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

WHAT

Fixes the TypeDecorator part of #1586 and documents the rest, as decided on the issue (Codex and Claude Fable 5.2 consulted; the maintainer approved D1 = document, D2 = read impl_instance, D3 = document).

  • visit_truediv_binary() classifies each operand by its type with every TypeDecorator layer replaced by its declared impl (impl_instance), and _cast_decimal_literal_column() reads the scale the same way. A with_variant() type is still read as its base type, since the statement cache key does not include the variants (SQLAlchemy: true division of DECIMAL(p, s) columns casts both operands to DECIMAL(38, 0) #1450, d0bc81d).

    Expression Before After
    D(Integer) / Integer d / CAST(i AS DECIMAL): Athena computes decimal(10,0), 5 / 2 = 3 d / CAST(i AS DOUBLE) = 2.5
    Integer / F(Float) i / CAST(c AS REAL): 1 / 3 = 0.33333334 CAST(i AS DOUBLE) / CAST(c AS DOUBLE)
    F(Float) / Integer c / CAST(i AS DECIMAL) (REAL for a REAL column) CAST(c AS DOUBLE) / CAST(i AS DOUBLE)
    N(Numeric) / Integer e / CAST(i AS DECIMAL) e / i, as for Numeric
    literal_column("5.52", N(Numeric(10, 2))) / Integer 5.52 / CAST(i AS DECIMAL) CAST(5.52 AS DECIMAL(38, 2)) / i
    (F * Integer) / Integer DOUBLE on SQLAlchemy 2.0, CAST(j AS DECIMAL) on 2.1 DOUBLE on both
  • docs/sqlalchemy.md (Division):

    • the TypeDecorator (declared impl, not load_dialect_impl()) / variant rule;
    • a literal_column() cast to DECIMAL keeps the type, not the digits beyond double precision, with the measured example and how to keep every digit (Decimal bind or a DECIMAL literal in the text);
    • SQLAlchemy gives a quotient its own type when the expression is built, with measured examples: Integer / Integer → Numeric() and a DECIMAL(10, 2) column (such as a reflected one) / Float → DECIMAL() on every version, Numeric(10, 2) / Float() → Numeric(10, 2) on 2.1 (Float() on 2.0), while Athena computes those quotients as DOUBLE. That type applies to an ARRAY built from the quotient and to a concat() list: a Numeric type (default asdecimal) returns Decimal elements and casts the list to an ARRAY of its DECIMAL type (rounds 0.255 to 0.26 for Numeric(10, 2)) or raises CompileError without a precision. type_coerce() with the Athena type (Double() for a DOUBLE quotient) is the workaround.

Not changed (approved): the expression type of a quotient (SQLAlchemy fixes it when building the expression, before the dialect compiles), the DOUBLE rendering of those quotients, and the rendering of literal_column(text, Numeric(p, s)) (recognizing a plain number would mean parsing SQL text). The two TrueDivTest.test_truediv_divisor skips from #1600 stay: that test casts with cast() itself.

WHY

Closes #1586. A TypeDecorator operand fell through to SQLAlchemy's default division, which gave wrong results (integer-rounded DECIMAL, single-precision REAL) and differed between SQLAlchemy 2.0 and 2.1.

TEST

Tested commit: fe31099 (base e0ab487); also a trial merge with master de94aa9 (lint ok, just test offline 5003 passed, tests/pyathena/sqlalchemy/ offline 772 passed on 2.0.52 and 778 on 2.1.9). The live runs and the probe ran on b761fea; the compiler logic is unchanged since then (later commits pass the classified type into _cast_decimal_literal_column() and change docstrings, docs, and offline tests).

  • just lint, just docs lint: pass.
  • just test offline: 4944 passed, 6 skipped.
  • pytest -m "not aws" tests/pyathena/sqlalchemy/test_compiler.py -k truediv on SQLAlchemy 2.0.52, 2.0.58 (locked), 2.1.9: 15 passed each.
  • Mutation: with master's compiler the five new decorator cases fail on 2.1.9, and four on 2.0.52 / 2.0.58 (SQLAlchemy 2.0 types the decorated product FLOAT, so that case already rendered DOUBLE); resolving dialect_impl() before unwrapping fails the outer-variant case, dialect_impl() after unwrapping fails the inner-variant case, and calling load_dialect_impl() while unwrapping fails the _DialectNumericFloat case.
  • Live (targeted): pytest -n 1 tests/pyathena/sqlalchemy/test_base.py -k truediv: 2 passed; with master's compiler test_truediv_type_decorator fails with [Decimal('3'), 0.33333334].
  • Live probe (approved, one constant SELECT, 0 bytes): typeof(5 / CAST(2 AS DECIMAL)) = decimal(10,0), value 3; REAL '1' / CAST(3 AS DECIMAL) and 1 / CAST(3 AS REAL) = real 0.33333334; DECIMAL / DOUBLE and INTEGER / DOUBLE = double; ARRAY[DOUBLE '0.5'] || CAST(ARRAY[0.255] AS ARRAY(DECIMAL(10, 2))) = array(double), element 0.26 (ARRAY(REAL): 0.2549999952316284); CAST(DECIMAL '5.0279…' AS DECIMAL(38, 20)) / CAST(DECIMAL '0.7182…' AS DECIMAL(38, 20)) = 7.00000000000000000000, the bare-literal form 7.00000000000000083533.
  • Differential check (not committed; /tmp/pyathena-1586/diff/): 526 cases × SQLAlchemy 2.0.52 / 2.0.58 / 2.1.9 — operand types Integer, BigInteger, Numeric, Numeric(10,2), DECIMAL(10,4), Float, Double, TypeDecorators of Float / Double / Integer / Numeric(10,2) / Numeric / a decorator, and with_variant() on Numeric, Integer, and a Float decorator; as columns, literal_column(), untyped and typed binds, products, nested quotients, array_agg(...).concat([0.255]) with and without type_coerce(..., Double()), and the compiled cache across variant/plain statements. Fields: expression type, compiled SQL, literal-binds SQL, executed SQL, errors. Base run twice (identical). Expected rule written before implementing: rows without a TypeDecorator unchanged; rows with one render as the same row with each decorator replaced by its impl, expression types unchanged. Result: 203 / 203 / 209 expected changes, all present, 0 other differences. Three rule artifacts found on the first branch run are encoded as explicit expectations (one case key collision; two literal-binds values that keep the variant's literal processor, as on master).
  • just test sqla / sqla-async: not run locally. The compliance suites (2.0.52, 2.0.58, 2.1.9) and tests/sqlalchemy/test_suite.py use TypeDecorators only for interval, date, string, and ARRAY types, never as a division operand; CI runs them when the PR is Ready.
  • Reviews (recorded inline): self-review round 1 (/code-review + /simplify), round 2 (claims), Codex independent review + 2 follow-ups (last: CLEAN). Rejected with evidence: cache reuse for pass-through or cache_ok=False decorators — SQLAlchemy's own type-dependent rendering (CAST, bind_expression()) is reused the same way.

🤖 Generated with Claude Code

visit_truediv_binary() read each operand's own type, so a TypeDecorator
operand fell through to SQLAlchemy's default division: an Integer
decorator divided by an Integer rendered `a / CAST(b AS DECIMAL)`, which
Athena computes as decimal(10, 0) (5 / 2 = 3), and an Integer divided by
a Float decorator cast the divisor to REAL. Read the declared impl of
each TypeDecorator layer, as SQLAlchemy does to type the quotient, also
for the scale of a literal_column cast. Variants are still not read,
since the statement cache key does not include them (GH-1450).

Document that SQLAlchemy can type a quotient differently from the DOUBLE
that Athena computes (Integer / Integer, and Numeric / Float on
SQLAlchemy 2.1), what that does to ARRAY elements and concat() binds,
and type_coerce(quotient, Double()) as the way to give it the Athena
type. Also document that a literal_column() cast to DECIMAL keeps the
type, not the digits beyond double precision, and how to keep them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@laughingman7743 laughingman7743 added this to the 5.0.0 milestone Nov 30, 2026
Round-one review repairs:
- _cast_decimal_literal_column() takes the type that
  visit_truediv_binary() already classified instead of unwrapping the
  operand again.
- Drop the decorated FLOAT dividend case, which the variant case
  already covers, and keep the ARRAY test to the documented
  type_coerce() workaround instead of SQLAlchemy's typing and the full
  ARRAY envelope.
- Docs: a TypeDecorator divides as its declared impl; SQLAlchemy types
  a quotient of two Numeric operands as the divisor while Athena gives
  it the larger scale.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
"""
type_ = operand.type
while isinstance(type_, types.TypeDecorator):
type_ = type_.impl_instance

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Self-review round 1 (behavior and implementation) — base e0ab4875a54bcd351df38f24c235025cac717b3d, reviewed head b761feac771350d59b834c14e0faf71f1a64e749; repairs in 342bdf68.

Covered: visit_truediv_binary() and _cast_decimal_literal_column() (every operand-type read in the division rule), the fallback to SQLAlchemy's visit_truediv_binary, other arithmetic (// uses _type_affinity, which forwards to the impl; + - * % do not classify types), the tests in test_compiler.py / test_base.py, and the Division docs. Passes: /code-review high and /simplify (reuse, simplification, efficiency, altitude) on a detached snapshot; differential check rerun on the repaired head: 526 cases × 2.0.52 / 2.0.58 / 2.1.9, 203 / 203 / 209 expected changes, 0 other differences.

Result: FINDINGS, repaired (see the threads on the repaired lines). Rejected with reasons:

  1. Cached SQL with a pass-through decorator (class D(TypeDecorator): impl = Numeric; cache_ok = True, D(10, 2) then D(10, 4) both send CAST(5.5252 AS DECIMAL(38, 2))). D(10, 2)._static_cache_key == D(10, 4)._static_cache_key == (D,), and SQLAlchemy's own rendering has the same result for such a type: on 2.0.58 and 2.1.9, select(cast(column("x"), D(10, 2))) then D(10, 4) on one connection both send CAST(x AS DECIMAL(10, 2)). cache_ok = True asserts that the attributes named by __init__ determine the SQL; a decorator that stores them (def __init__(self, precision=None, scale=None) setting self.precision/self.scale) gets distinct keys ((E, ('scale', 2), ('precision', 10)) vs ('scale', 4)). This is the decorator's cache contract, not a PyAthena check to add.
  2. load_dialect_impl() is not read: approved design (D2) — the declared impl is what SQLAlchemy reads to type the quotient and what the cache key covers; a decorator that picks another type only for Athena divides as its declared impl. The docs now say "declared impl".
  3. Reuse _ArrayTypeInspector: its unwrapping resolves with_variant() and load_dialect_impl(), which is the variant resolution reverted in d0bc81d (SQLAlchemy: true division of DECIMAL(p, s) columns casts both operands to DECIMAL(38, 0) #1450); the impl-only loop is the only variant-free unwrap in pyathena/.

if isinstance(left_type, types.Numeric) or isinstance(right_type, types.Numeric):
return (
self.process(self._cast_decimal_literal_column(binary.left), **kw)
self.process(self._cast_decimal_literal_column(binary.left, left_type), **kw)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 1 finding (simplification): _cast_decimal_literal_column() unwrapped the operand type a second time although visit_truediv_binary() had just classified it. Repaired in 342bdf68: the classified type is passed in.

"SELECT CAST(5.52 AS DECIMAL(38, 2)) / DECIMAL '1.2345' AS anon_1"
)

def test_visit_truediv_binary_double_quotient_in_array(self):

@laughingman7743 laughingman7743 Nov 30, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 1 findings (test quality), repaired in 342bdf68:

  • The decorated(Float()) / Integer case repeated the variant case (same decorated FLOAT dividend, same SQL); removed. Mutation on the repaired tests: master's compiler fails all 5 remaining decorator cases on 2.1.9 (on 2.0 the product case passes, since SQLAlchemy types the product FLOAT); reading types through dialect_impl() fails the variant case.
  • This test asserted SQLAlchemy's quotient typing (CompileError, Decimal elements) and the full ARRAY JSON envelope. It now checks only the documented workaround: the division SQL with the list cast to ARRAY(DOUBLE), and float elements.

"3",
]

def test_truediv_type_decorator(self, engine):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 1 (test cost): two passes asked whether this live test is needed. Kept: it is the only evidence of the results a caller gets, which master gets wrong ([Decimal('3'), 0.33333334] with master's compiler); the offline cases pin only SQL text. It is one constant SELECT that scans 0 bytes.

Comment thread docs/sqlalchemy.md Outdated
A result column of such a quotient returns a `float`.
In an ARRAY of the quotient, such as one built with `func.array_agg()`, the elements are returned as `Decimal`, and a list concatenated with `concat()` is cast to `ARRAY(DECIMAL(p, s))` with the precision and scale of the quotient type, which rounds `0.255` to `0.26` for `DECIMAL(10, 2)`, or raises `CompileError` if the type has no precision.
A quotient typed `Float` casts such a list to `ARRAY(REAL)`, which keeps about seven significant digits.
A quotient of two `Numeric` operands has the type of the divisor in SQLAlchemy, while Athena gives it the larger scale of the two.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 1 findings (docs), repaired in 342bdf68: the TypeDecorator sentence now says declared impl, and this section also covers DECIMAL quotients — SQLAlchemy 2.0.52 and 2.1.9 type Numeric(10, 2) / Numeric(10, 4) as Numeric(10, 4) and Numeric(10, 4) / Numeric(10, 2) as Numeric(10, 2) (the divisor), while Athena gives the quotient the larger scale. Not applied: shortening this section to two sentences; the version-dependent typing is what #1586 is about, and the approved D1 is to document it.

Comment thread docs/sqlalchemy.md
Columns, expressions, aggregates, and `cast()` keep their Athena types, and a bind parameter takes its type from its value, such as `DECIMAL '1.2345'` for a `Decimal`.
Athena reads a decimal literal such as `5.52` as `DOUBLE`, so a `literal_column()` with a precision is cast, and `literal_column("5.52", Numeric())`, without a precision, divides as `DOUBLE`.
The cast gives the DECIMAL type, not the digits of the text: Athena converts the `DOUBLE` value, which keeps about 15 to 17 significant digits.
For example, `literal_column("5.02797279921331664759", Numeric(22, 20)) / literal_column("0.71828182845904523537", Numeric(22, 20))` returns `7.00000000000000083533`, not `7`.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Self-review round 2 (claims, compatibility, operations) — base e0ab4875a54bcd351df38f24c235025cac717b3d, head 342bdf68f9772306eae836ba55a148db040b9fe1. Result: claims hold; the PR body's test counts and mutation numbers were stale after round 1 and are corrected. No code change.

Claims checked, with evidence:

  • Before/after table in the PR body: rendering from the differential check (2.0.52 / 2.0.58 / 2.1.9); Athena results from the approved probe (query 0e7311c8-7b5e-424a-8827-9ef8256817ee, 0 bytes): typeof(5 / CAST(2 AS DECIMAL)) = decimal(10,0), value 3; REAL '1' / CAST(3 AS DECIMAL) = real; 1 / CAST(3 AS REAL) = 0.33333334; and the live test on master's compiler ([Decimal('3'), 0.33333334]).
  • This example (7.00000000000000083533): the probe ran exactly the SQL this expression renders, CAST(5.02797279921331664759 AS DECIMAL(38, 20)) / CAST(0.71828182845904523537 AS DECIMAL(38, 20)); the DECIMAL-literal form CAST(DECIMAL '…' AS DECIMAL(38, 20)) / … returned 7.00000000000000000000. The Decimal bind form (DECIMAL '…' / DECIMAL '…') was not measured at 20 digits; it relies on the same DECIMAL literal and on Athena's DECIMAL division (measured at scale 2 by test_truediv_decimal).
  • Quotient types: Integer / Integer is Numeric() and Numeric(10, 2) / Float is Float() on 2.0.52 / 2.0.58 and Numeric(10, 2) on 2.1.9 (harness types); Numeric(10, 2) / Numeric(10, 4) is Numeric(10, 4) and the reverse Numeric(10, 2) on 2.0.52 and 2.1.9.
  • ARRAY consequences: Decimal elements and float scalars (fetched_scalar, and Codex's consultation run on 2.0.58); concat rounding 0.255 → 0.26 for DECIMAL(10, 2) and 0.2549999952316284 through REAL (probe); the type_coerce(..., Double()) example compiles to CAST(ARRAY[0.25] AS ARRAY(DOUBLE)) (test).
  • "as SQLAlchemy reads it to type the quotient": TypeDecorator.comparator_factory builds on impl_instance.comparator_factory (sqlalchemy/sql/type_api.py).
  • Variants not in the cache key: the harness cache: rows execute variant and plain statements on one engine in both orders with identical SQL.

Callers: _cast_decimal_literal_column() changed signature; it is private and only called from visit_truediv_binary() (no other reference in pyathena/, tests/, benchmarks/); AthenaStatementCompiler is used by the sync and async dialects alike through AthenaDialect.statement_compiler. A division without a TypeDecorator operand renders as before (harness rule 1). AWS: no request pattern changes; one live query added to test_base.py (0 bytes scanned). Docs: no other prose in docs/ describes division typing; docs/sqlalchemy.md "Fixed-point types" still recommends a TypeDecorator with a Numeric implementation, which this change now classifies as Numeric in a division.

Independent review repairs:
- Docs: SQLAlchemy types a quotient with a DECIMAL dividend, such as a
  reflected decimal column, as DECIMAL() without a precision on 2.0 and
  2.1, also with a Float divisor; list the quotient types as a table,
  and state the float and Decimal results for the default asdecimal.
- The division operand docstring no longer says SQLAlchemy replaces a
  TypeDecorator to type the quotient, and names load_dialect_impl().
- Tests: a variant inside the impl and a load_dialect_impl() override
  are not read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
"""
left_type = binary.left.type
right_type = binary.right.type
left_type = self._division_operand_type(binary.left)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent review (relayed) — reviewer: Codex CLI 0.172.0 (gpt-6.2-astra, reasoning effort max), codex exec -s read-only, session 01a22edf-c5cf-7493-92e2-249c38373294. Static review of e0ab4875a54bcd351df38f24c235025cac717b3d..342bdf68f9772306eae836ba55a148db040b9fe1 on a detached snapshot (unchanged afterwards); no PR text or prior findings given. Covered: all four changed files; operand classification, nested decorators, variants, products, binds, literal columns, statement caching, scalar and ARRAY result processing; SQLAlchemy 2.0.52–2.0.58 and 2.1.0–2.1.9 arithmetic typing sources. Result: FINDINGS (5).

Finding 1 (High, reviewer): with bindparam("d", type_=T()) where T is a cache_ok=False decorator over Float and then one over Integer, SQLAlchemy caches the enclosing SELECT (the bind keys hold the same NO_CACHE sentinel), so the second execution reuses the first one's casts: literal_column("5", DECIMAL(10, 0)) / d returns 2.5 where CAST(5 AS DECIMAL(38, 0)) / 2 (= 3) is required, or the reverse.

Author response: rejected (upstream cache behavior). Reproduced on 2.0.52 and 2.1.9: _generate_cache_key() is not None for such a statement, and both executions send the first SQL. SQLAlchemy's own type-dependent rendering of a bind is reused the same way: with two cache_ok=False Integer decorators whose bind_expression() returns b + 1 and b + 2, select(column("x") == bindparam("d", type_=T())) sends x = %(d)s + %(param_1)s with the first type's offset for both. SQLAlchemy documents that cache_ok = False keeps statements using the type out of the cache; the bind key does not honor that, which affects every rendering rule that reads a bind type (also PyAthena's existing FLOAT/INTEGER classification of plain types and ARRAY bind casts). PyAthena does not work around SQLAlchemy defects.

Comment thread docs/sqlalchemy.md Outdated

SQLAlchemy gives a quotient its own type, which can differ from the type that Athena computes.
A quotient of two `Integer` operands is a `DOUBLE` in Athena and a `Numeric` in SQLAlchemy.
So is a quotient of a `Numeric` dividend and a `Float` divisor with SQLAlchemy 2.1, which types it as the dividend; SQLAlchemy 2.0 types it as `Float`.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Finding 2 (Medium, reviewer): PyAthena reflects a decimal column as DECIMAL; SQLAlchemy types DECIMAL(10, 2) / DECIMAL(12, 4) and DECIMAL(10, 2) / Float() as DECIMAL() without a precision on both 2.0 and 2.1, so array_agg(q).concat([0.255]) raises CompileError; the dividend/divisor rules here hold only for the exact Numeric class.

Author response: valid, repaired in 28f86a68. Confirmed on 2.0.52 and 2.1.9 (DECIMAL dividend → DECIMAL() with a DECIMAL, Numeric, Float, or Integer divisor; Numeric dividend with a DECIMAL divisor → the divisor's type). The section now lists the quotient types in a table by operand class, including the reflected-column case.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Self-review of this repair (both perspectives) found two more inaccuracies in the new table, fixed in 3f54e634: SQLAlchemy 2.0 types Numeric(10, 2) / Double() as Double() (the divisor's type, not Float()), so the row now reads "the divisor's type with SQLAlchemy 2.0"; NUMERIC(10, 2) as a dividend also gives NUMERIC() without a precision (2.0.52 and 2.1.9), now in the DECIMAL row; and the REAL sentence now excludes Double, whose ARRAY bind is cast to DOUBLE. Code and tests unchanged by this commit; differential check unchanged (compiler change limited to the docstring since 342bdf68).

Comment thread docs/sqlalchemy.md Outdated
SQLAlchemy gives a quotient its own type, which can differ from the type that Athena computes.
A quotient of two `Integer` operands is a `DOUBLE` in Athena and a `Numeric` in SQLAlchemy.
So is a quotient of a `Numeric` dividend and a `Float` divisor with SQLAlchemy 2.1, which types it as the dividend; SQLAlchemy 2.0 types it as `Float`.
A result column of such a quotient returns a `float`.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Finding 3 (Low, reviewer): the float and Decimal results depend on asdecimal (e.g. Numeric(10, 2, asdecimal=False) / Float() on 2.1 gives float elements; Float(asdecimal=True, decimal_return_scale=2) returns Decimal("0.33")).

Author response: valid, repaired in 28f86a68: the results are stated for the default asdecimal of each type.

Comment thread pyathena/sqlalchemy/compiler.py Outdated
def _division_operand_type(self, operand):
"""Return the type that classifies an operand of a division.

A ``TypeDecorator`` is read as its declared ``impl``, as SQLAlchemy reads it to

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Finding 4 (Low, reviewer): the docstring implies SQLAlchemy replaces the decorator to type the quotient; SQLAlchemy uses the impl's comparator but keeps the decorator as the quotient type (Integer / F(Float) is typed F()).

Author response: valid, repaired in 28f86a68: the docstring now states only PyAthena's rule (declared impl, without load_dialect_impl(); variants not read).

"SELECT CAST((x * y) AS DOUBLE) / CAST(z AS DOUBLE) AS anon_1",
),
(
# The statement cache key does not include a variant, so it is not read.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Finding 5 (Low, reviewer): the variant case puts the variant on the outer decorator, and no case overrides load_dialect_impl(), so resolving a variant after unwrapping or calling the hook while unwrapping would pass.

Author response: valid, repaired in 28f86a68: added 5 / decorated(Float().with_variant(Numeric(10, 0), "awsathena")) and a Float decorator whose load_dialect_impl() returns Numeric(10, 0); both must render DOUBLE. Mutations: dialect_impl() after unwrapping fails the first; load_dialect_impl() while unwrapping fails the second.

Reviewer's test table (summary): every added case and test protects distinct evidence; the product case passes before the change on 2.0 (product already FLOAT) and fails on 2.1; the ARRAY test protects the documented workaround, not the classification.

laughingman7743 and others added 2 commits December 1, 2026 09:07
Self-review of the independent-review repair: SQLAlchemy 2.0 types a
Numeric dividend with a Double divisor as Double(), the divisor's type,
not Float(); a NUMERIC dividend loses its precision like DECIMAL; and a
Double element type casts an ARRAY bind to DOUBLE, not REAL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The follow-up review found more operand combinations for which the
table of SQLAlchemy quotient types did not hold (an untyped divisor, a
Numeric bind left to Athena, an Athena variant of the quotient type, a
custom result processor, a precision-only Numeric). Replace the table
with the measured examples, the effect of the quotient type on ARRAY
elements and concat() lists, and the type_coerce() workaround, instead
of rules for every operand class.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread docs/sqlalchemy.md
```

SQLAlchemy gives a quotient its own type when the expression is built, which can differ from the type that Athena computes.
For example, SQLAlchemy types `Integer / Integer` as `Numeric()`, and a `DECIMAL(10, 2)` column, such as a reflected decimal column, divided by a `Float` as `DECIMAL()`, while Athena computes both quotients as `DOUBLE`.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent review follow-up 1 (relayed) — Codex CLI 0.172.0 (gpt-6.2-astra, effort max), codex exec -s read-only, session 01a22eed-f010-7573-9aeb-959e673ef0db; static review of the repair 342bdf68f9772306eae836ba55a148db040b9fe1..3f54e634fded78e08019b4e20413c78d9bd1f7f5 (docs table, docstring, two new test parameters) on a detached snapshot (unchanged). Result: FINDINGS (5), all on the table of quotient types that the repair added:

  1. (Medium) A DECIMAL dividend keeps its precision with an untyped (NullType) divisor, e.g. DECIMAL(10, 2) / literal_column("2"), so concat() compiles with ARRAY(DECIMAL(10, 2)) instead of the predicted CompileError.
  2. (Medium) The fixed-point rows promise an Athena DECIMAL unconditionally, but numeric binds are left uncast: literal(5, Numeric(10, 2)) / literal(2, Numeric(10, 2)) sends 5 / 2 and returns 2.
  3. (Medium) ARRAY casts and decoding use the dialect-resolved element type: Integer / Float().with_variant(Numeric(10, 2), "awsathena") divides as DOUBLE, but concat([0.255]) binds ARRAY(DECIMAL(10, 2)) and decodes Decimal.
  4. (Low) The scalar float statement needs a qualification for a decorator's process_result_value().
  5. (Low) A precision-only Numeric(10) casts to ARRAY(DECIMAL(10)), not DECIMAL(p, s).
    Clean: the _division_operand_type() docstring; both new test parameters (each fails under its mutation and protects distinct SQL).

Author response: valid, repaired in fe31099d by narrowing the claims instead of extending the table. Each pass found another operand combination for which a rule table of SQLAlchemy's typing did not hold; the section now states the measured examples (Integer / Integer → Numeric(), a DECIMAL(10, 2) column / Float → DECIMAL(), Numeric(10, 2) / Float() on 2.1 vs 2.0), that the quotient type applies to an ARRAY built from it and to a concat() list, the Numeric consequences with the default asdecimal (Decimal elements; a cast to an ARRAY of its DECIMAL type, rounding 0.255 to 0.26 for Numeric(10, 2), or CompileError without a precision), and the type_coerce() workaround. The scalar-result and REAL sentences are removed (2, 4, 5 no longer apply; 1 and 3 are covered by "the quotient type applies").

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent review follow-up 2 (relayed) — Codex CLI 0.172.0 (gpt-6.2-astra, effort max), codex exec -s read-only, session 01a22ef5-bc1a-77e1-a2ec-741e2adb861f; static review of 3f54e634fded78e08019b4e20413c78d9bd1f7f5..fe31099d7d26a5ed51bcc080af1f5d8e4eab1df1 (this paragraph) on a detached snapshot (unchanged). Result: CLEAN — the stated quotient types match SQLAlchemy 2.0.52–2.0.58 and 2.1.0–2.1.9; the division SQL, ARRAY bind casts, and Decimal results match PyAthena; the rounding example agrees with the Athena measurement.

@laughingman7743
laughingman7743 marked this pull request as ready for review December 1, 2026 00:22
@laughingman7743
laughingman7743 merged commit 1821a6e into master Dec 1, 2026
16 checks passed
@laughingman7743
laughingman7743 deleted the fix/1586-division-type-decorator branch December 1, 2026 00:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Give DOUBLE division results a consistent type on SQLAlchemy 2.1

1 participant