Repository navigation
[4.x] Backport the SQLAlchemy fixes #1577, #1612, #1607, #1631, #1641 and #1630 (GH-1649) - #1652
laughingman7743 wants to merge 29 commits into
Conversation
…hemy 2.1 (GH-1569) SQLAlchemy 2.1 no longer makes Float a subclass of Numeric, so the elements of an ARRAY of a Float type, including MAP values and ROW fields nested in it, came back as strings. Convert them for Numeric and Float alike. The compliance suite imported DeprecatedCompoundSelectTest, which 2.1 removed; define its subclass only when SQLAlchemy has it. The live quantifier test selects any_(flags) != True instead of the ungrouped ~comparison, whose meaning differs between 2.0 and 2.1. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit f50587a)
An ARRAY element of a Float type with asdecimal=True became
Decimal(text), ignoring decimal_return_scale, while a column of the
same type, or the indexed element, went through SQLAlchemy's Float
result processor. Pass the element as a float to that processor, so
both give the same value: Float(asdecimal=True, decimal_return_scale=2)
returns Decimal('1.38') for 1.375 in both, and the default scale of
Float and Double rounds to 10 digits.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit a4dd6f2)
…H-1569) Decoding a float ARRAY created SQLAlchemy's result processor for every element, which made 100,000 Double elements 1.5 to 2 times as slow to decode as before the previous commit. Keep the processor of each element type on the value processor, and use it for String elements too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 92fec38)
…and reuse decorator implementations (GH-1569) A TypeDecorator whose load_dialect_impl() returns a new type on each call gave every element a new implementation, so the per-type processor cache grew by one entry per element. Reuse the implementation of each declared decorator across elements, as a column reuses its dialect implementation across rows. Both caches are keyed by id() and keep the type, since a TypeDecorator need not be hashable. An element whose declared type resolves to a Float type through variants and TypeDecorators now goes, as a float, to the declared type's own result processor, as a column of that type does. A decorator that overrides result_processor() received the implementation's rounded Decimal, one that calls super() ran the implementation's processor twice, and a decorator chosen as a variant was called on an already-decoded value instead of through the declared type. The decimal_return_scale test uses 2.675, which the column rounds to 2.67 and rounding its text would give 2.68. The docs state the rule for the float passed to the processor, and limit the Decimal rounding to SQLAlchemy's own processor. Adapted on 4.x, tests/pyathena/sqlalchemy/test_array.py: the RawDouble case of test_float_decorator_elements_receive_floats expects the implementation Double. On master the dialect maps types.Double to AthenaDouble (954f5e2, GH-1504, master only); 4.x keeps Double. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 7798902)
…H-1571) The statement compiler chose the any_match()/all_match() lambda variable by scanning the compiled statement. The DDL compiler's statement compiler, which compiles the SELECT of SQLAlchemy 2.1's CreateView and Select.into(), has no statement, so an unqualified column named _pyathena_element_0 in the comparison was captured by the lambda. A bare expression compiled on its own also missed the table, alias, or schema that qualifies a column. The name now avoids the names that the comparison renders: its columns, the tables, aliases, and schemas that qualify them, and its textual SQL. The JSON projection of ARRAY columns in a stored SELECT comes from SQLAlchemy 2.1 applying column_expression() to it (tracked in GH-1608); docs/sqlalchemy.md now describes Select.into() and CreateView with that limitation. Conflict on 4.x, tests/pyathena/sqlalchemy/test_compiler.py: 4.x already has the _StrProxy helper (from the #1582 backport, #1640) where this commit adds the requires_create_view block; the block is added before _StrProxy, in master's order, and the sa_schema import is added (master already imported URL, which 4.x does not use). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 852b1a5)
…envelope (GH-1571) Collect names straight into one set, and state that schemas are checked as declared: SQLAlchemy reuses a compiled statement with any schema_translate_map, so the translated names are unknown at compile time. Keep the six name sources on the public compile path, with one case for the statement-less compiler of the DDL compiler and one per stored SELECT construct on SQLAlchemy 2.1. The docs now say that the stored varchar column holds PyAthena's JSON transport envelope, not the array's JSON. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 542947b)
Scanning only the comparison lost a protection that the statement scan gave: SQL that a comparison renders without showing it as an element, such as a TypeDecorator.bind_expression() or a filter() lambda bound as a parameter, was protected when the statement also named the column. The name now avoids the names of the comparison and of the statement, collected the same way. When the compiler has no statement, as for the SELECT that CreateView or Select.into() stores, the statement is the outermost SELECT being compiled, so a stored SELECT chooses the same names as the same SELECT compiled on its own. The docs state which names the variable avoids, and that CreateView and Select.into() store a textual SELECT, including one with typed columns, as written. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 3c75462)
) The docstring states that only the comparison is scanned when there is neither a statement nor a SELECT being compiled. The docs name the qualifiers the variable avoids and give the unchecked SQL as one instruction. The tests share one helper for the DDL compiler's statement compiler. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 28c44d1)
…cs (GH-1571) The statement-scope test now puts the comparison in a subquery and the conflicting name only in the outer SELECT, so it fails if the scope were the innermost statement. The docstring names the outermost statement, which can be DML, and the docs add the names SQLAlchemy gives anonymous aliases and labels to the SQL that is not checked. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 75d697b)
) The statement-scope test puts the comparison in an EXISTS subquery over an alias, which Athena can run, and says why the comparison sits in a subquery. The docs say the variable avoids named aliases; anonymous alias names are listed as not checked. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 5187e0a)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 6ccf094)
…H-1571) The docs name what the scan checks (column, table, named alias, and declared schema names, and text() SQL) and list string ORDER BY labels and names known only at compile or execution time as unchecked. The statement-scope test needs no alias: the inner SELECT keeps its FROM. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit dc36357)
The docs no longer enumerate the names the check covers; they say it avoids the names PyAthena finds, give examples it does not find, and ask users not to start names with _pyathena_element. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit d1ffdde)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit e14c078)
GH-1570) SQLAlchemy 2.1 warns when an expression uses an operator that the operator_classes of its type do not declare, and plans to raise InvalidRequestError instead. AthenaTimestamp, AthenaDate, AthenaMap and AthenaStruct declared none, so IS NULL, comparisons, ordering and date arithmetic on them emitted SADeprecationWarning. Declare DATETIME for the temporal types, as SQLAlchemy's DateTime and Date do, and BASE | COMPARISON for MAP and ROW. IS NULL belongs to COMPARISON before 2.1.7 and to BASE from 2.1.7. EQUALITY and ORDERING exist only from 2.1.9, so MAP also allows ordering, which Athena rejects. SQLAlchemy 2.0 has no OperatorClass, so the attribute is declared only when it exists. Conflict on 4.x, tests/pyathena/sqlalchemy/test_types.py: 4.x's file has only the JSON tests (the Float, Numeric and DOUBLE tests and their imports come from master-only changes). Only this commit's delta is applied: the warnings, column, exc and type imports, and the new operator test at the end of the file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 12ee3cc)
…tic Athena runs (GH-1570) Athena has no date - date operator, so the temporal cases add an INTERVAL instead. The operator tests move to the test files that mirror temporal.py, struct.py and map.py. Conflict on 4.x, tests/pyathena/sqlalchemy/test_types.py: the commit moves the operator test out of the file and restores the file as it was before 12ee3cc, as on master; on 4.x that is 4.x's file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 80fd176)
) LIKE is outside every declared class, so on SQLAlchemy 2.1 it still warns for the temporal, MAP and ROW types. A declaration broadened to OperatorClass.ANY fails these tests; they skip on SQLAlchemy 2.0, which has no operator classes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 6d9a9e7)
GH-1570) The four types each checked hasattr(operators, "OperatorClass") in their class body. pyathena.sqlalchemy.util now checks it once and exposes DATETIME_OPERATOR_CLASSES and COMPARISON_OPERATOR_CLASSES, and each type assigns its value in one line. On SQLAlchemy 2.0, which has no OperatorClass and does not read operator_classes, the values are None. Subclassing SQLAlchemy's DateTime and Date instead was measured and changes behavior: the types of temporal arithmetic (Interval, Integer), the element bind processing of an ARRAY of AthenaTimestamp(precision), and the type affinity. MAP and ROW have no fitting SQLAlchemy base. Conflict on 4.x, pyathena/sqlalchemy/temporal.py, imports: 4.x imports the private _date_literal, _escape_trino and _timestamp_literal from pyathena.formatter (the public literal functions are master only); that import is kept, and the DATETIME_OPERATOR_CLASSES import is added. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit c496534)
…-1609) Athena parses CREATE VIEW, DROP VIEW, and CREATE TABLE AS with Trino, which rejects the backticks that the DDL compiler's Hive preparer gave a name that needs quoting. The DDL compiler now keeps the dialect's DML preparer, and its schema-translate copy, for these statements, chosen by the statement's visit name, so their names and translated schemas, including the schemas of the tables in the stored SELECT, use double quotes. Other DDL keeps backticks. Conflict on 4.x, pyathena/sqlalchemy/compiler.py, AthenaDDLCompiler class attributes: on master they precede _PARTITION_TRANSFORM_ARGUMENTS, which is master only; on 4.x they are added at the top of the class body. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 1e9c6fd)
The name test checks only the quoted target and covers the names that the two preparers quote differently; the schema-translate test drops a DROP TABLE check that an existing test already makes. The setter and DML preparer docstrings refer to the Trino statements instead of repeating them, and the docs state the quoting without the parser rationale. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 90b357d)
SQLAlchemy 2.0, which the lock file pins, has DropView as the private _DropView, so the DROP VIEW quoting test now runs there and on 2.1; only CREATE VIEW and CREATE TABLE AS need SQLAlchemy 2.1. The setter docstring names Compiled.__init__. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 1e992c1)
The DROP VIEW part of the schema-translate test moves to its own test, which runs on SQLAlchemy 2.0 through the private _DropView, and the DROP VIEW name test is named like the other Trino DDL tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 1eecb98)
Athena engine v3 parses DML with Trino, which rejects alter, json_array, json_exists, json_object, json_query, json_table, json_value, listagg, skip, and trim as unquoted identifiers (measured), but Athena's list of SELECT reserved words omits them, so the DML preparer left them unquoted. They are now part of SELECT_STATEMENT_RESERVED_WORDS. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 3c65942)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 5ca914f)
A dict compared with, or written to, an AthenaMap/MAP column renders as
CAST(MAP(ARRAY[keys], ARRAY[values]) AS MAP(k, v)), and a dict or tuple
for an AthenaStruct/STRUCT column as CAST(ROW(...) AS ROW(...)) in the
declared field order, bound and inline. Before, a MAP value failed with
CompileError inline and TypeError when bound.
- The ARRAY value processor, which already rendered nested MAP and ROW
elements, binds and renders these values. AthenaMap and AthenaStruct
derive from a new base in pyathena/sqlalchemy/array.py, which supplies
the processors; each type supplies its constructor name, element types,
and how to split and decode a value. The processor dispatches on that
base, so array.py no longer imports map.py and struct.py, which import
it, and the classes stay in their modules.
- The bind_expression() cast also gives an empty or NULL-only value its
declared types. A MAP or ROW whose types are not known as this dialect
resolves them (a reflected NullType, a variant resolving to it, or a
ROW without fields) binds without the cast, and a ROW without fields
passes its value to the cursor as it is.
- AthenaStruct.adapt() keeps the fields and with_variant() mappings.
- The type inspector resolves each declared TypeDecorator once, for the
compiler as for the value processors, so executing a cached statement
does not keep the new types that load_dialect_impl() returns.
- SQLAlchemy renders a bind expression around the empty-set expression
of an empty IN, and splits a literal-execute IN value at ", ", which
break ARRAY (as on master), MAP, and ROW values. The docs say so, and
strict xfail tests notice an upstream fix.
- The precision error now says "ARRAY, MAP, and ROW decimal values".
Adapted on 4.x, tests/pyathena/sqlalchemy/test_array.py: the ARRAY case
of test_in_casts_each_value uses an INTEGER array instead of a
Numeric(5, 2) array of Decimal("1.234"). On 4.x, literal_binds renders
that Decimal as 1.234, not DECIMAL '1.234' (467d395, GH-1483, master
only), while the bound path renders DECIMAL '1.234'; the INTEGER array
renders the same on both paths, and the case still checks that IN casts
each ARRAY value.
Conflict on 4.x, pyathena/sqlalchemy/array.py, imports: 4.x imports only
_ComplexParameter from pyathena.formatter (varbinary_literal is master
only). As on master, the AthenaMap and AthenaStruct imports are removed,
since map.py and struct.py now import from array.py.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 32fd6bb)
| A `dict` or a tuple compared with, or written to, an `AthenaStruct` or `STRUCT` column is rendered as a ROW constructor cast to the declared type, bound or inline. | ||
| A `dict` must have exactly the declared field names, and the values follow the declared field order; a tuple is matched by position. | ||
| A MAP or ROW whose types are not known, such as a ROW without fields, binds its value without the cast. | ||
| In an executed statement, `in_()` on an ARRAY, MAP, or ROW column of known types renders invalid SQL when the list is empty; check for an empty list before calling `in_()`. |
There was a problem hiding this comment.
Self-review round one (implementation behavior): CLEAN, with one behavior change carried from master (below)
Base da0590dd6944b6f34360c8e7cd1debd9c5f3beb9 (merge base with 4.x), head dcee17fa.
Covered: pyathena/sqlalchemy/array.py, compiler.py, constants.py, map.py, struct.py, temporal.py, util.py, docs/sqlalchemy.md, and the SQLAlchemy test files.
- Backport fidelity. Every changed line of the branch is in master's diffs; the master lines that are missing cancel in pairs, apart from the two test adaptations in the PR body. The 4.x code around the picked hunks matches master's before each PR:
array.pydiffers only by master'svarbinary_literalfor binary element literals, which no picked hunk touches.compiler.pydiffers in the division, time-travel and DDL-option code, not in_array_lambda_name()or the DDL preparer setter/__init__. - Types. On 4.x, as on master, the classes that subclass
TypeEnginedirectly areAthenaTimestamp,AthenaDate,AthenaMapandAthenaStruct, so Declare the operator classes of the Athena temporal, MAP and ROW types (GH-1570) #1607 covers all of them. - Decode float ARRAY elements and import the compliance suite on SQLAlchemy 2.1 (GH-1569) #1577 on 4.x. 4.x has no
types.Double → AthenaDoublecolspec (Float parameters and literals: sequences round to 6 decimals, NaN and infinity render as identifiers #1504 is master only), so a Float element resolves to SQLAlchemy'sDouble/Float, which is also what a column of that type gets on 4.x; the adaptedtest_float_decorator_elements_receive_floatsexpectation states that. - Test quality. With the branch's tests on 4.x's
pyathena/, the tests of each backported change fail (2.0.44: 48; 2.1.9: 77, 7 of them already failing on 4.x).test_empty_inis a strict xfail; on that source it XPASSes for MAP and ROW. - Behavior change (not repaired; master's decision). At this line: on 4.4.0,
column("c", AthenaMap(...)).in_([])and the ROW equivalent renderc IN (NULL) AND (1 != 1). After32fd6bbethey render invalid SQL, because SQLAlchemy puts the newbind_expression()cast around the empty-set expression; ARRAY already did on 4.x. Master's Render timedelta, MAP, and ROW values as Athena literals (GH-1616) #1630 chose this over SQLAlchemy's bind-cast API (its PR body says why). The PR body lists it under release notes, and the maintainer is asked whether 4.4.1 should carry it. - Benchmarks reference none of the changed internals.
|
|
||
| Typed SQLAlchemy SELECT expressions use a JSON transport projection to preserve nested values and strings containing commas, quotes, whitespace, or the word `null`. | ||
| Scalar leaves for supported Athena table types are decoded according to the declared type, preserving decimal precision, dates, timestamps, and binary values. | ||
| A floating-point leaf is passed as a Python `float` to the result processor of its declared type, including a variant's or a `TypeDecorator`'s. |
There was a problem hiding this comment.
Self-review round two (claims, compatibility, operational effects): FINDINGS, repaired in the PR description
Base da0590dd6944b6f34360c8e7cd1debd9c5f3beb9, head dcee17fa2758da5e4dd37abbdb69dd86dac187a7.
Claims checked:
- asdecimal release note (this paragraph and the PR body): measured on
4.xda0590d and this head.AthenaArray(Float(asdecimal=True))of[0.30000000000000004, 1.375]: 4.x gaveDecimal('0.3000000000000000444…')on 2.0.44 and floats on 2.1.9; the branch givesDecimal('0.3000000000'),Decimal('1.3750000000')on both. The body said only "SQLAlchemy 2.0"; corrected to state both versions and the measured 4.x values. - "On 4.4.0,
in_([])on MAP or ROW renderedc IN (NULL) AND (1 != 1)": observed on da0590d (strict xfail XPASS), not on the 4.4.0 tag; corrected to name da0590d. - "Master's PRs measured the rendered SQL on Athena": Keep the ARRAY lambda variable from capturing names in stored and ordinary SELECTs (GH-1571) #1612 measured nothing live itself; narrowed to Declare the operator classes of the Athena temporal, MAP and ROW types (GH-1570) #1607, Render timedelta, MAP, and ROW values as Athena literals (GH-1616) #1630, Quote CREATE VIEW, DROP VIEW, and CREATE TABLE AS names for Trino (GH-1609) #1631 and Quote the Trino reserved words that Athena's SELECT list lacks (GH-1634) #1641.
- Docs examples (MAP/STRUCT values,
DROP VIEW "1view"): render as written on 2.1.9. The MAP paragraph's "As in ARRAY values, aNumeric… needs a precision" points atdocs/sqlalchemy.md:1235, which exists on 4.x. - No
WindowFunctionTestguard:sqlalchemy.testing.suiteof 2.0.44 hasWindowFunctionTest; 2.1.9 lacks onlyDeprecatedCompoundSelectTest, which Decode float ARRAY elements and import the compliance suite on SQLAlchemy 2.1 (GH-1569) #1577's guard handles. - The 7 failures on 2.1.9 are pre-existing: the same 7 fail on da0590d with
python -m pytestand the 2.1.9 overlay. An earlier local run seemed to pass on da0590d only because a fresh.venv'spytestscript ignored the--withoverlay and ran 2.0.46; the PR body's numbers come frompython -m pytest, with the version printed in the header.
Existing callers: no public signature changes. Rendered SQL changes are the ones listed in the PR body; the empty-in_() change for MAP/ROW is a behavior change carried from master's #1630, which the maintainer is asked to confirm for 4.4.1.
AWS operator: no new requests; statements that Athena previously rejected (unquoted reserved words, Hive-quoted view names, dict MAP/ROW values) now run. The compliance suites and AWS tests run in CI when the PR is Ready.
| @@ -86,6 +92,49 @@ def _static_cache_key(self): | |||
| tuple((name, type_._static_cache_key) for name, type_ in self.fields.items()), | |||
There was a problem hiding this comment.
Independent review (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, reasoning effort max, sandbox read-only, session 01a2322e-3a5e-7df1-b018-f52288aef726. Static review only, of a detached snapshot of head dcee17fa2758da5e4dd37abbdb69dd86dac187a7 against merge base da0590dd6944b6f34360c8e7cd1debd9c5f3beb9, given the literal diff, the master merge commits, and the repository conventions; no PR text or prior findings. The snapshot was unchanged after the review.
Reviewer output, verbatim:
Statically verified. The supplied diff matches da0590dd..dcee17fa. All 28 expected commits appear exactly once, and the conflict resolutions preserve the production hunks. I traced ARRAY decoding through Float, decorators, variants, MAP values and ROW fields, lambda naming, operator declarations, DDL schema translation, DML quoting, composite binds, literals, caching, tests and documentation. I checked local SQLAlchemy sources for 2.0.44–2.0.58 and 2.1.0–2.1.9. The lambda scope, CREATE VIEW/DROP VIEW/CTAS preparer selection and ten reserved-word additions match their documented behavior.
FINDINGS
- High · also on master. Executing
m.in_([])on a typed MAP previously produced a valid false predicate. The new cast producesm IN (CAST(NULL) AND (1 != 1 AS MAP(VARCHAR, INTEGER))).NOT INand ROW have the same regression. With expandingliteral_execute=True, splitting a ROW containing"a, b"can silently change the string being compared. The docs acknowledge both failures. ARRAY already had them.array.py:81 - High · also on master. Execute two
select(literal(...))statements on one engine. Give ROW fieldxtypeString()first, thenString().with_variant(Integer(), "awsathena"). Their cache keys coincide because the field key omits the variant. The second execution reusesROW(x VARCHAR)and the first bind processor despite requiringROW(x INTEGER).struct.py:92 - High · 4.x only. Inline
MAP(Numeric(38,0), Integer)keysDecimal("1E+30")andDecimal("1.000000000000000001E+30")render as bare exponents. Both become the same DOUBLE, so MAP rejects duplicate keys before the outer cast. Bound keys remain distinct. Master emits DECIMAL literals. The adapted INTEGER test is correct but drops this distinction. For its original input, 4.x emits1.234inline andDECIMAL '1.234'bound.array.py:503test_array.py:224 - High · also on master. For
ROW(n DECIMAL(5,2), tag VARCHAR), comparing a stored(1.23, 'x')with the bound tuple(Decimal("1.234"), "x")previously returned false. Casting the comparison operand rounds it to1.23, so the same predicate now matches. Separately, insertingNoneintoAthenaMap(String, Numeric())previously sent SQL NULL and now raisesCompileErrorfor missing precision.compiler.py:1167 - Medium · also on master. Fetching
["1.5"]through an ARRAY of a FloatTypeDecoratorwith__hash__ = NoneraisesTypeError. The processor cache usesid(), butdialect_impl()still hashes the decorator. This decoded successfully on the 2.0 base. The unhashable-Integer test bypasses this path.array.py:539 - Medium · fixed on master by
7cd34762. A ROW field declaredInterval(native=False)bindstimedelta(days=1)as the epoch plus one day. Inline rendering skips that conversion and emits invalidTIMESTAMP '1 day, 0:00:00'.array.py:486 - Low · also on master. On SQLAlchemy 2.1.9, MAP declares ordering support.
m < mtherefore compiles without a warning and Athena rejects it. That version exposesEQUALITYseparately.map.py:51 - Low · backport test adaptation.
Doubleis the correct 4.x expectation forRawDouble. Both cases now expect it, so incorrectly adapting the variant directly also passes. Master distinguishes those paths throughAthenaDouble. A test decorator whoseload_dialect_impl()returns a distinguishable Double subclass would restore coverage.test_array.py:580 - Low · also on master. Replacing
~comparisonwith explicit!= Truedrops coverage of documented ungrouped negation. For[True, False], a regression in that expression can now pass the suite. Its expected result is true on 2.0 and false on 2.1.test_suite.py:462
Author verification (Claude), offline compile/decode on 4.x da0590d and this head, SQLAlchemy 2.0.44 and 2.1.9 (same result on both):
| Finding | da0590d | this head (= master) |
|---|---|---|
Medium, unhashable Float TypeDecorator in an ARRAY |
[1.5] (2.0.44) |
TypeError: unhashable type — regression, from #1577 |
High (second part), insert(t).values(m=None) on AthenaMap(String, Numeric()) |
VALUES (null) |
CompileError (precision required) — regression, from #1630 |
| High, ROW literals whose field types differ only by a variant | equal cache keys, same SQL (1) |
equal cache keys, CAST(ROW(1) AS ROW(x VARCHAR)) vs … x INTEGER — wrong SQL from a shared compiled cache, from #1630 |
High (first part), r == (Decimal("1.234"), "x") on ROW(n DECIMAL(5, 2), tag VARCHAR) |
r = (DECIMAL '1.234', 'x') |
r = CAST(ROW(DECIMAL '1.234', 'x') AS ROW(n DECIMAL(5, 2), …)) — behavior change (rounds before comparing), from #1630 |
Triage of the rest: the empty in_() and literal_execute finding is the accepted behavior change in the PR body (maintainer: keep it in 4.4.1 with a release note). MAP ordering on 2.1.9 is the limitation #1607 states. The ROW Interval inline finding was failing before on 4.x (a ROW dict did not render), and master's fix 7cd3476 is master only. The 4.x-only inline Decimal exponent finding follows from 4.x's literal rendering, whose fix (GH-1483) was kept master only. The RawDouble test adaptation finding is valid for this PR and will be repaired. The test_suite.py finding is the same on master.
The three regressions above are master defects that this backport would carry into 4.4.1; they go to a master issue, and the PR stays Draft until the maintainer decides how 4.4.1 handles them.
There was a problem hiding this comment.
Repair of the Low finding on the RawDouble test adaptation: cf2d2a8 (4.x only, test only). RawDouble.load_dialect_impl() returns a Double subclass, _DialectDouble, so the declared decorator's case of test_float_decorator_elements_receive_floats expects _DialectDouble and the variant's case keeps Double. Mutation: a processor that skips the dialect resolution of the declared decorator (type_.result_processor() instead of type_.dialect_impl(dialect).result_processor() in _ArrayValueProcessor._result_processor()) now fails both cases; before the repair it passed. tests/pyathena/sqlalchemy/test_array.py: 179 passed, 7 xfailed on SQLAlchemy 2.0.44 and 2.1.9; just lint passed.
The three regressions are filed as #1657 (milestone 5.0.0); the executor findings of #1650 as #1656. This PR stays Draft until #1657's fixes are on master and added here.
test_float_decorator_elements_receive_floats expected Double for both cases on 4.x, since 4.x maps no Double to a dialect type (master maps it to AthenaDouble, 954f5e2, master only). A processor that skipped the dialect resolution of the declared decorator then still passed. RawDouble now loads a Double subclass, _DialectDouble, for the dialect, so the declared decorator's case expects _DialectDouble and the variant's case keeps Double; the test fails again when the decorator is not resolved for the dialect. Found in the independent review of the 4.x backport (GH-1649). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
WHAT
The SQLAlchemy part of the 4.4.1 backport (#1649): the master PRs below, in master merge order. Each commit is a
git cherry-pick -xof the master commit. #1589 (#1506) is ported in a separate PR, since it needs adapting to4.x's private formatter helpers.4.xTypeDecorator) are converted as a column of the same declared type; on SQLAlchemy 2.1 they came back as strings. The compliance suite imports on SQLAlchemy 2.1.any_match()/all_match()lambda variable avoids the names of the comparison and of the statement, also in the SELECT that SQLAlchemy 2.1CreateViewandSelect.into()store, and for a schema named_pyathena_element_0.AthenaTimestamp,AthenaDate,AthenaMapandAthenaStructdeclareoperator_classeson SQLAlchemy 2.1, which otherwise warns onIS NULL,=,<,INand date arithmetic.CREATE VIEW,DROP VIEWandCREATE TABLE AS(SQLAlchemy 2.1CreateView,DropView,Select.into(), and 2.0's_DropView) quote names with Trino's double quotes and SELECT reserved words; other DDL keeps backticks.alter,json_array,json_exists,json_object,json_query,json_table,json_value,listagg,skipandtrim.32fd6bbeonlydictcompared with or written to a MAP column, and adictor tuple for a ROW column, render as cast constructors instead of failing. The INTERVAL commit7cd34762is master only (breaking for an existingColumn(Interval)).Release notes (bug fixes, as described in each master PR):
floatby the declared type's result processor instead of being returned as strings; the operator warnings above no longer appear;CreateView/Select.into()keep the lambda variable of a stored SELECT from capturing a column name.Floattype withasdecimal=Truebecome aDecimalrounded todecimal_return_scale(10 digits unless set), as the column's values do:0.30000000000000004→Decimal('0.3000000000'). On4.xda0590d, SQLAlchemy 2.0.44 gaveDecimal('0.3000000000000000444089209850062616169452667236328125'), and 2.1.9 gave thefloat.CREATE VIEW/DROP VIEW/CTAS, and the ten reserved words in DML, as above.CAST(MAP(ARRAY[...], ARRAY[...]) AS MAP(...))andCAST(ROW(...) AS ROW(...)), bound or inline.in_()list for a MAP or ROW column now renders invalid SQL, as it already did for ARRAY on4.x. SQLAlchemy renders the type'sbind_expression()around the empty-set expression. On4.xda0590d,in_([])on a MAP or ROW column rendersc IN (NULL) AND (1 != 1). Master accepted this in Render timedelta, MAP, and ROW values as Athena literals (GH-1616) #1630 (its PR body records the choice), anddocs/sqlalchemy.mdsays to check for an empty list before callingin_(). The strict xfail testtest_empty_incovers it.Conflicts (recorded in the commit messages, resolved with each commit's own delta):
tests/pyathena/sqlalchemy/test_compiler.py: 4.x already has_StrProxy([4.x] Backport #1582 and #1633 #1640); therequires_create_viewblock is added before it, in master's order, with thesa_schemaimport only (master'sURLimport is not used on 4.x).tests/pyathena/sqlalchemy/test_types.py: 4.x's file has only the JSON tests; the first commit adds its operator test there, and the second moves it to the type test files and restores 4.x's file, as on master.pyathena/sqlalchemy/temporal.py: 4.x imports the private_date_literal,_escape_trinoand_timestamp_literal; that import is kept.pyathena/sqlalchemy/compiler.py: master's_PARTITION_TRANSFORM_ARGUMENTS(master only) followed the new class attributes.pyathena/sqlalchemy/array.py: 4.x imports novarbinary_literal(master only); theAthenaMap/AthenaStructimports are removed as on master.Test expectations adapted to
4.x(each in the commit that adds the test):test_float_decorator_elements_receive_floats: theRawDoublecase expects the implementationDouble; master mapstypes.DoubletoAthenaDouble(954f5e2, Float parameters and literals: sequences round to 6 decimals, NaN and infinity render as identifiers #1504, master only).test_in_casts_each_value: the ARRAY case uses an INTEGER array instead ofNumeric(5, 2)withDecimal("1.234"). Withliteral_binds, 4.x renders that Decimal as1.234, while the bound path rendersDECIMAL '1.234'; master rendersDECIMAL '1.234'on both paths (467d395, SQLAlchemy: inline Numeric values render as bare numbers, which Athena reads as DOUBLE #1483, master only). The case still checks that IN casts each ARRAY value.WHY
Part of #1649.
4.xallows SQLAlchemy 2.1 (sqlalchemy>=2.0.44) and has the same compiler and type code, so these defects exist on 4.4.0. Handoffs on #1569, #1571, #1609, #1616 and #1634.#1569's handoff asked for a
WindowFunctionTestimport guard at SQLAlchemy 2.0.23.4.xnow requires 2.0.44, which hasWindowFunctionTest, so no guard is added.TEST
Tested commit: dcee17f, on
4.xda0590d.32fd6bbe). The master lines missing from the branch cancel in add/remove pairs (a line added by one PR and changed by a later one), apart from the two test adaptations above.just lint,just docs lint: passed.ruff check --select F821,F401,F811of the changed Python files passes at every commit.just test offline: 4341 passed, 12 skipped, 7 xfailed (locked SQLAlchemy 2.0.46, Python 3.15).tests/pyathena/sqlalchemy/andtests/pyathena/aio/sqlalchemy/offline, Python 3.12, run withpython -m pytestunderuv run --with sqlalchemy==<v>(the header showed the version):4.xminimum): 688 passed, 12 skipped, 7 xfailed.4.xda0590d: 612 passed.4.xda0590d (test_create_table_default_location×4,test_create_table_without_base_location_raises×2,test_create_table_s3tables_catalog_from_cursor_kwargs). They are the pre-connect cases that the4.xadaptation of Take SQLAlchemy DDL options in connect_args from the first connection (GH-1542) #1559 ([4.x] Take SQLAlchemy DDL options in connect_args from the first connection (adapted #1559) #1594) accepted, and this PR does not change them.4.x'spyathena/, the tests of every backported change fail (2.0.44: 48 failed; 2.1.9: 77 failed, including the 7 above). Examples:test_trino_reserved_words,test_trino_ddl_quotes_names_with_double_quotes,test_supported_operators_do_not_warn(2.1.9),test_array_lambda_does_not_capture_column_names,test_float_decorator_elements_receive_floats,TestAthenaMap::test_value, andTestAthenaStruct::test_value. On that source,test_empty_inpasses for MAP and ROW (strict xfail → XPASS), which is the behavior change above.docs/sqlalchemy.mdparagraphs render as documented on 2.1.9 (MAP and STRUCT values,DROP VIEW "1view").just test sqla,sqla-async). They run in CI when this PR is marked Ready. On master, Declare the operator classes of the Athena temporal, MAP and ROW types (GH-1570) #1607, Render timedelta, MAP, and ROW values as Athena literals (GH-1616) #1630, Quote CREATE VIEW, DROP VIEW, and CREATE TABLE AS names for Trino (GH-1609) #1631 and Quote the Trino reserved words that Athena's SELECT list lacks (GH-1634) #1641 measured their SQL on Athena.🤖 Generated with Claude Code