Skip to content
Merged
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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ Extra packages:

| Package | Install command | Version |
|---------------|-----------------------------------------|----------|
| SQLAlchemy | `pip install PyAthena[SQLAlchemy]` | >=2.0.44 |
| AioSQLAlchemy | `pip install PyAthena[AioSQLAlchemy]` | >=2.0.44 |
| SQLAlchemy | `pip install PyAthena[SQLAlchemy]` | >=2.0.52 |
| AioSQLAlchemy | `pip install PyAthena[AioSQLAlchemy]` | >=2.0.52 |
| pandas | `pip install PyAthena[Pandas]` | >=3.0.0 |
| Arrow | `pip install PyAthena[Arrow]` | >=22.0.0 |
| Polars | `pip install PyAthena[Polars]` | >=1.39.0 |
Expand Down
4 changes: 2 additions & 2 deletions docs/introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ Extra packages:

| Package | Install command | Version |
|---------------|-----------------------------------------|----------|
| SQLAlchemy | `pip install PyAthena[SQLAlchemy]` | >=2.0.44 |
| AioSQLAlchemy | `pip install PyAthena[AioSQLAlchemy]` | >=2.0.44 |
| SQLAlchemy | `pip install PyAthena[SQLAlchemy]` | >=2.0.52 |
| AioSQLAlchemy | `pip install PyAthena[AioSQLAlchemy]` | >=2.0.52 |
| pandas | `pip install PyAthena[Pandas]` | >=3.0.0 |
| Arrow | `pip install PyAthena[Arrow]` | >=22.0.0 |
| Polars | `pip install PyAthena[Polars]` | >=1.39.0 |
Expand Down
8 changes: 5 additions & 3 deletions docs/sqlalchemy.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

# SQLAlchemy

Install SQLAlchemy with `pip install "SQLAlchemy>=2.0.44"` or `pip install PyAthena[sqlalchemy]`.
Supported SQLAlchemy is 2.0.44 or higher.
Install SQLAlchemy with `pip install "SQLAlchemy>=2.0.52"` or `pip install PyAthena[sqlalchemy]`.
Supported SQLAlchemy is 2.0.52 or higher.

For async support (`create_async_engine`), install with `pip install PyAthena[aiosqlalchemy]`.

Expand Down Expand Up @@ -841,13 +841,15 @@ Athena `FLOAT` and `REAL` are the same 32-bit floating-point type, which keeps a
Use `Double` for 64-bit values.
`Float(precision)` does not change the Athena type.
A value of a floating-point type rendered inline, as with `literal_binds`, `literal_execute`, or in an ARRAY literal, is written with Python's `repr()` for a `float`, which Athena reads as the same `DOUBLE` value, and as `nan()`, `infinity()`, and `-infinity()` for NaN and infinity, also of a `Decimal` or a NumPy value.
A value that is not a real number, such as a string, is written by SQLAlchemy's `Float`, which writes a numeric string such as `"1.250"` as is and rejects a value for which `decimal.Decimal(value)` raises, such as `"1 OR 1=1"`.

## Fixed-point types

The dialect adapts `Numeric`, `NUMERIC`, and `DECIMAL` to `AthenaNumeric`.
A `Decimal` of a fixed-point type rendered inline, as with `literal_binds`, `literal_execute`, or in an ARRAY literal, is written with `decimal_literal()`: a DECIMAL literal with the value's own scale and no exponent, such as `DECIMAL '5.520'` for `Decimal("5.520")` and `DECIMAL '1000'` for `Decimal("1E+3")`.
Athena rejects a DECIMAL literal whose precision or scale is above 38, such as the one for `Decimal("1E-39")`, with scale 39, and a NaN or infinity, such as `DECIMAL 'NaN'` or `DECIMAL '-Infinity'`.
A `float` is written as for a floating-point type, and other values, such as an `int`, as SQLAlchemy's `Numeric` writes them.
A `float` is written as for a floating-point type, and other values, such as an `int` or a numeric string, as SQLAlchemy's `Numeric` writes them; it rejects a value for which `decimal.Decimal(value)` raises, such as `"1 OR 1=1"` or a NumPy integer.

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 (Codex codex exec -s read-only, static review plus offline Python; no AWS): base 0efea77f0bd43cdcba169414427c639b2e6bd15e

  • Initial review of ..eab1e07f (session 01a22c3e-ccae-7372-a007-2bf3a789f547). Codex confirmed the floor in every place it is stated, the lock (uv lock --check passes, and the 10 reverted marker rewrites are equivalent), 580 offline PyAthena tests passing on 2.0.52, 2.0.58 and 2.1.9, and the TrueDivTest override (both parameter axes kept, 4 of 10 combinations skipped, the guard keeps the inherited tests before 2.0.55). Findings:
    1. The docs said CompileError, but literal_execute raises StatementError with orig CompileError at execution. Fixed in 171daf16. The test stays at compile time; the wrapping at execution is SQLAlchemy's generic behavior.
    2. The docs overstated rejection: a numeric string such as "1.250" renders. Fixed in 171daf16 and 06fcc379 (the rule is now "decimal.Decimal(value) raises").
    3. SQLAlchemy up to 2.0.55 collides expanding bind names (ids with [4, 5] vs ids_1). Rejected: an upstream bug for every dialect; the floor follows what PyAthena's own contracts need (Require SQLAlchemy 2.0.52 and check the values of Float and binary literals #1574 decision).
    4. 2.1.9 cannot import the compliance suite (DeprecatedCompoundSelectTest). Pre-existing; fixed by Decode float ARRAY elements and import the compliance suite on SQLAlchemy 2.1 (GH-1569) #1577.
  • Follow-up 1 (eab1e07f..171daf16, session 01a22c4d-2cf7-7a71-8049-61fc7aef9604): two qualifications, None and the decimal context. The rule was restated as "Decimal(value) raises".
  • Follow-up 2 (171daf16..f4b8274c, session 01a22c51-cc18-7582-af22-0ee650f99f83): the added "None is written as NULL" does not hold for evaluates_none() types. The sentence was removed in 06fcc379180b04237e8edabec2ae745dbd1d51b3; such a None is rejected under the stated rule.

Snapshot and PR worktrees were clean after each run.

SQLAlchemy raises such a rejection as `CompileError` when the statement is compiled, and, for a `literal_execute` parameter, as a `StatementError` whose `orig` is the `CompileError` when the statement is executed.

A subclass of `Numeric` other than a floating-point type is adapted to `AthenaNumeric` too, so its own processors, such as `literal_processor()` and `result_processor()`, are not used.
To change how a value is processed, subclass `AthenaNumeric`, or use a `TypeDecorator` with a `Numeric` implementation.
Expand Down
6 changes: 3 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,9 @@ awsathena = "pyathena.sqlalchemy.rest:AthenaRestDialect"
"awsathena.aios3fs" = "pyathena.aio.sqlalchemy.s3fs:AthenaAioS3FSDialect"

[project.optional-dependencies]
sqlalchemy = ["sqlalchemy>=2.0.44"]
sqlalchemy = ["sqlalchemy>=2.0.52"]

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 two (claims, compatibility, evidence): CLEAN

Base 0efea77f0bd43cdcba169414427c639b2e6bd15e, head eab1e07f83beb12cb511d686269dc717f7e4841c. Claims checked:

  • "From 2.0.52, a non-number raises CompileError": test_non_numeric_literal_raises passes on 2.0.52, 2.0.58 and 2.1.9 and fails 4/4 on 2.0.51.
  • NumPy note: np.int64(7) raises CompileError in Numeric(10, 0) and renders 7 in Float on 2.0.52 and 2.1.9.
  • Skip reasons: both measured against Athena (see round one). The other 6 test_truediv_divisor cases and the historic-date tests (years 1–1969) pass live on the default and the async driver. The check-constraint and RETURNING tests that 2.0.58 adds are skipped by requirements (14 skipped).
  • Lock: uv lock --locked passes on Python 3.15 and 3.12. Only the SQLAlchemy entry and three specifiers change.
  • Compatibility: installations on 2.0.44–2.0.51 must upgrade SQLAlchemy within 2.0; the PR body states this for release notes. 4.x follows through the backport session.
  • Offline evidence on eab1e07f83beb12cb511d686269dc717f7e4841c: 724 passed on 2.0.58, 2.0.52 and 2.1.9; 4491 passed for tests/pyathena.

aiosqlalchemy = [
"sqlalchemy[asyncio]>=2.0.44",
"sqlalchemy[asyncio]>=2.0.52",
]
pandas = [
"pandas>=3.0.0",
Expand All @@ -89,7 +89,7 @@ polars = [

[dependency-groups]
dev = [
"sqlalchemy[asyncio]>=2.0.44",
"sqlalchemy[asyncio]>=2.0.52",
"pandas>=3.0.0",
"pyarrow>=22.0.0",
"polars>=1.39.0",
Expand Down
26 changes: 10 additions & 16 deletions tests/pyathena/sqlalchemy/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import numpy as np
import pytest
from sqlalchemy import cast, column, literal, select, types
from sqlalchemy import cast, column, exc, literal, select, types

from pyathena.sqlalchemy.rest import AthenaRestDialect
from pyathena.sqlalchemy.types import AthenaArray
Expand Down Expand Up @@ -134,21 +134,15 @@ def test_result(self, type_, expected):


@pytest.mark.parametrize("type_", [types.Numeric(10, 2), types.Float()])
def test_other_literal_values_render_as_sqlalchemy(type_):
# A value that is neither a Decimal nor a real number takes SQLAlchemy's own
# literal processor, which checks that the value is a number in 2.0.52 and
# later.
dialect = AthenaRestDialect()
value = "1 OR 1=1"

def outcome(processor):
try:
return processor(value)
except Exception as e:
return type(e)

adapted = type_.dialect_impl(dialect).literal_processor(dialect)
assert outcome(adapted) == outcome(type_.literal_processor(dialect))
@pytest.mark.parametrize(
("literal_execute", "compile_kwargs"),
[(False, {"literal_binds": True}), (True, {"render_postcompile": True})],
)
def test_non_numeric_literal_raises(type_, literal_execute, compile_kwargs):

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 one (implementation behavior): FINDINGS, repaired

Base 0efea77f0bd43cdcba169414427c639b2e6bd15e, head c4430adb/096febbd → eab1e07f83beb12cb511d686269dc717f7e4841c. Covered: the extras and dev group, README and docs versions, the uv.lock SQLAlchemy entry, the new compliance tests that the 2.0.58 lock collects, and the literal processors that rely on the floor. Passes: /code-review high and /simplify (reuse, simplification, efficiency, altitude).

Repaired:

  • The comparison test also passed on 2.0.51, so it did not protect the guarantee the floor exists for. It is replaced by test_non_numeric_literal_raises (literal_binds and literal_execute), which fails on 2.0.51 (ffbabb74).
  • The skip matched only the dividend; it now matches both operands, and the pairs are inlined (ffbabb74, eab1e07f).
  • The docs now state that a non-number raises CompileError for both fixed-point and floating-point types (ffbabb74).

Rejected:

  • np.int64 in a Numeric literal raises CompileError from 2.0.52. This is SQLAlchemy's behavior, already recorded on CI tests SQLAlchemy only at the locked version, not the declared minimum or the latest release #1543 as an inherited upstream change kept as is; the PR body and docs state it.
  • The suggestion that the 38-digit rejection comes from the division: measured, SELECT CAST(30000000000000000000000000000000000000 AS DECIMAL(38, 0)) alone fails with Queries of this type are not supported, while dividing the values cast from strings returns Decimal('3').
  • A requirement instead of a test override: precision_numerics_many_significant_digits also gates other upstream tests that pass on Athena, and the 38-digit pair has no requirement.
  • Regenerating the lock with uv's marker rewrites: both consultants preferred the minimal diff, and uv lock --locked passes.
  • Pre-existing and recorded on Give DOUBLE division results a consistent type on SQLAlchemy 2.1 #1586 (division design): a literal_column() decimal with more than about 17 significant digits loses precision in a division, because Athena reads the text as DOUBLE before the cast.

# SQLAlchemy's own literal processor checks that the value is a number.
expression = literal("1 OR 1=1", type_, literal_execute=literal_execute)
with pytest.raises(exc.CompileError):
_literal_sql(expression, compile_kwargs)


class TestAthenaFloat:
Expand Down
21 changes: 21 additions & 0 deletions tests/sqlalchemy/test_suite.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import functools
import json as _json
import logging
from datetime import date
Expand Down Expand Up @@ -53,6 +54,7 @@
from sqlalchemy.testing.suite import RowFetchTest as _RowFetchTest
from sqlalchemy.testing.suite import SameNamedSchemaTableTest as _SameNamedSchemaTableTest
from sqlalchemy.testing.suite import SimpleUpdateDeleteTest as _SimpleUpdateDeleteTest
from sqlalchemy.testing.suite import TrueDivTest as _TrueDivTest
from sqlalchemy.testing.suite import WindowFunctionTest as _WindowFunctionTest

from pyathena.error import OperationalError
Expand Down Expand Up @@ -1299,3 +1301,22 @@ class SameNamedSchemaTableTest(_InsertFixtureRowsOnce, _SameNamedSchemaTableTest

class WindowFunctionTest(_InsertFixtureRowsOnce, _WindowFunctionTest):
pass


class TrueDivTest(_TrueDivTest):
if hasattr(_TrueDivTest, "test_truediv_divisor"): # SQLAlchemy 2.0.55 and later

@functools.wraps(_TrueDivTest.test_truediv_divisor)
def test_truediv_divisor(self, **kwargs):
# SQLAlchemy's combinations also pass exclusion arguments. Athena
# reads the literal text "5.02797279921331664759" as DOUBLE and
# rejects an integer literal outside BIGINT, such as 38 digits.
if (kwargs["left"], kwargs["right"]) in {
("5.02797279921331664759", "0.71828182845904523537"),
(
"30000000000000000000000000000000000000",
"10000000000000000000000000000000000000",
),
}:
pytest.skip("Athena cannot read this literal_column() text as DECIMAL.")
super().test_truediv_divisor(**kwargs)
Loading