Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
9d20ca5
Place a time-travel hint before a generated alias and accept irregula…
laughingman7743 Nov 30, 2026
14026b2
Tighten the hint placement comments and docs after the first self-rev…
laughingman7743 Nov 30, 2026
c0130b3
Split a table's hint only before an alias, and match ASCII keywords o…
laughingman7743 Nov 30, 2026
a01ae48
Match the hint as the merge base did and split before an AS keyword (…
laughingman7743 Nov 30, 2026
ae42f3b
Render a table again only for text with an alias, and pin the hook ca…
laughingman7743 Nov 30, 2026
ab3f9ae
Fall back when SQLAlchemy cannot render a hooked table, and keep the …
laughingman7743 Nov 30, 2026
0ced9e7
Fall back on any error from the comparison rendering (GH-1575)
laughingman7743 Nov 30, 2026
395aa4f
Compare the hooked text inside the fallback, and check iscrud before …
laughingman7743 Nov 30, 2026
3303fb4
Read only string hints, and split an alias as the merge base did (GH-…
laughingman7743 Nov 30, 2026
1ca5ad2
Render again only tables and aliases with string names (GH-1575)
laughingman7743 Nov 30, 2026
d7fe1b2
Check the type of a name itself before rendering it again (GH-1575)
laughingman7743 Nov 30, 2026
7653b90
Check the type of a hint itself before reading it (GH-1575)
laughingman7743 Nov 30, 2026
7c4ea06
Name the name types that SQLAlchemy cannot render in the hook tests (…
laughingman7743 Nov 30, 2026
fe46dce
Pass the caller's own table text to the next hint hook (GH-1575)
laughingman7743 Nov 30, 2026
e246ba0
Require a name after AS, and test the CTE target and the alias name g…
laughingman7743 Nov 30, 2026
ef7cb12
Word the hint pattern comments and the docs as they work (GH-1575)
laughingman7743 Nov 30, 2026
e5911eb
Say to pass parameters to execute() for a selected alias with a time-…
laughingman7743 Nov 30, 2026
0003c1a
Name every call that drops the hint, and import what the example uses…
laughingman7743 Nov 30, 2026
a39611b
Name join() among the calls that pass the alias itself (GH-1576)
laughingman7743 Nov 30, 2026
d9b21f3
Describe the dropped hint by what the statement is given, and uninden…
laughingman7743 Nov 30, 2026
b3ff610
State the rule for any alias with a time-travel hint, with examples (…
laughingman7743 Dec 1, 2026
286b3b0
Scope the empty-name comment of the hook rename test to SQLAlchemy 2.…
laughingman7743 Dec 1, 2026
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
21 changes: 21 additions & 0 deletions docs/sqlalchemy.md
Original file line number Diff line number Diff line change
Expand Up @@ -566,6 +566,9 @@ or `table_name$history` metadata. Again the hint goes after the select statement
```

To query an aliased table, pass the alias to `with_hint()`. The hint is rendered between the table name and the alias.
When a SELECT uses a table without a schema and an unaliased table of the same name with a schema, SQLAlchemy can give
the table without a schema an alias such as `events_1`. When the SELECT uses that table itself, pass the table to
`with_hint()`; when it uses an alias of the table, pass the alias.

```python
snapshot = table.alias("snapshot")
Expand All @@ -576,6 +579,24 @@ To query an aliased table, pass the alias to `with_hint()`. The hint is rendered
SELECT snapshot.id FROM table_name FOR VERSION AS OF 949530903748831860 AS snapshot
```

For a statement with a time-travel hint on an alias, pass the parameters to `execute()`, not to `Select.params()` or
`Select.unique_params()`. Those methods can drop the hint without an error, for example when the alias itself is
given to the statement as in `select(snapshot)`, `select_from(snapshot)` or `join(snapshot, ...)`, and the query then
reads the current snapshot of the table instead of the requested version. On SQLAlchemy 2.0 both methods can drop the
hint; on SQLAlchemy 2.1, `Select.unique_params()` can.

```python
from sqlalchemy import bindparam, select

snapshot = table.alias("snapshot")
query = (
select(snapshot)
.where(snapshot.c.id == bindparam("id"))
.with_hint(snapshot, "FOR VERSION AS OF 949530903748831860")
)
connection.execute(query, {"id": 1})
```

(sqlalchemy-query-execution-callback)=

## Query Execution Callback
Expand Down
99 changes: 80 additions & 19 deletions pyathena/sqlalchemy/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -659,11 +659,18 @@ class AthenaStatementCompiler(SQLCompiler):
https://docs.aws.amazon.com/athena/latest/ug/ddl-sql-reference.html
"""

_TIME_TRAVEL_HINTS: ClassVar[tuple[str, ...]] = (
"FOR TIMESTAMP AS OF",
"FOR SYSTEM_TIME AS OF",
"FOR VERSION AS OF",
"FOR SYSTEM_VERSION AS OF",
# The start of a time-travel hint, matched against hint.upper(), with any
# of the whitespace that Athena reads before and between the keywords.
_TIME_TRAVEL_HINT_PATTERN: ClassVar[re.Pattern[str]] = re.compile(

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 (/code-review medium, focused on faithfulness), scope 0b909e10..b3ff6109: CLEAN.

Self-review round two (claims), same scope: CLEAN.

  • The per-PR line equality and the three patch-ID differences that come only from context (21da68c, c60f169, 3f7ba6c) were measured with git diff and git patch-id --stable.
  • The 4.x floor and the test counts were measured in this session: just test offline passed 4253, and the time-travel/hint tests passed 36 on 2.0.44 and 2.1.9.
  • The differential check: the 4.x base is stable over two runs on 2.0.44 and 2.1.9, the branch has exactly the 2536 expected differences, and its output is identical to master's head.
  • Track upstream: SQLAlchemy 2.0 params()/unique_params() drop the FROM hint of a selected alias #1576 is CLOSED (NOT_PLANNED), as the PR says.
  • The release notes match the master PRs' scope.

r"[ \t\r\n]*FOR[ \t\r\n]+(?:TIMESTAMP|SYSTEM_TIME|VERSION|SYSTEM_VERSION)"
r"[ \t\r\n]+AS[ \t\r\n]+OF"
)
# Whitespace, AS, whitespace, and the first character of a name, as an
# alias follows a rendered table; the rendered table that precedes the
# match marks where the alias starts. A match starts only at the first
# whitespace of a run, so a search stays linear.
_ALIAS_KEYWORD_PATTERN: ClassVar[re.Pattern[str]] = re.compile(
r"(?<![ \t\r\n])[ \t\r\n]+[Aa][Ss][ \t\r\n]+[^ \t\r\n]"
)

@util.memoized_property
Expand Down Expand Up @@ -1180,13 +1187,17 @@ def get_from_hint_text(self, table, text):

@override
def format_from_hint_text(self, sqltext, table, hint, iscrud):
"""Place a time-travel hint of an aliased table before the alias.
"""Place a time-travel hint of a table before the table's alias.

Athena reads ``FOR ... AS OF`` between a table and its alias.
``SQLCompiler.visit_alias()`` passes the rendered table followed by the
alias, so the hint goes before that alias suffix and the table keeps its
quoting and schema translation. Other hints, unaliased tables, and
subqueries keep SQLAlchemy's placement after the text.
alias; in a SELECT, ``SQLCompiler.visit_table()`` passes a table without
a schema followed by the alias that it can generate when the FROM
clause also has an unaliased table of the same name with a schema. The
hint goes between the table and the alias, so the table keeps its
quoting and schema translation. Other hints, tables without an alias,
unaliased DML target tables, and subqueries keep SQLAlchemy's placement
after the text.

Args:
sqltext: The rendered FROM element.
Expand All @@ -1201,20 +1212,70 @@ def format_from_hint_text(self, sqltext, table, hint, iscrud):
while isinstance(element, FromClauseAlias):
element = element.element
if (
element is not table
and isinstance(element, TableClause)
and hint.upper().startswith(self._TIME_TRAVEL_HINTS)
isinstance(element, TableClause)
# A DML target table keeps the default placement: its text may end
# with what a subclass hook appended.
and not (element is table and iscrud)
# A hint that is not a string, unlike SQLAlchemy's annotation, is
# not read. The type itself, not isinstance(), which a proxy can
# satisfy.
and issubclass(type(hint), str)
and self._TIME_TRAVEL_HINT_PATTERN.match(hint.upper())
):
# SQLCompiler's own alias name, as visit_alias() rendered it,
# without what a subclass hook may append.
suffix = self.get_render_as_alias_suffix(
SQLCompiler.visit_alias(self, table, ashint=True)
)
prefix = sqltext.removesuffix(suffix)
if prefix != sqltext:
try:
parts = self._split_alias(sqltext, table, element is table)
except Exception:
# A table or an alias that only a subclass hook can render.
parts = None
if parts is not None:
prefix, suffix = parts
return super().format_from_hint_text(prefix, table, hint, iscrud) + suffix
return super().format_from_hint_text(sqltext, table, hint, iscrud)

def _split_alias(self, sqltext, table, is_table):
"""Split the rendered text of a FROM element before its alias.

For an alias, the suffix is SQLCompiler's own alias name, as
``visit_alias()`` rendered it, without what a subclass hook may append.
For a table, the text must continue the table as ``visit_table()``
renders it with AS and a name, such as the alias that it generates;
other text, such as a name that a subclass hook rendered differently,
does not split, and text without AS does not render the table again.
Only names that are strings, as SQLAlchemy annotates them, are rendered
again: the identifier preparer caches what it quotes for later
statements.

Args:
sqltext: The rendered FROM element.
table: The table or alias that the hint applies to.
is_table: Whether ``table`` is a table rather than an alias.

Returns:
The text before the alias and the alias suffix, or ``None`` when the
text does not split.
"""
# The type itself, not isinstance(), which a proxy can satisfy.
schema = table.schema if is_table else None
if not issubclass(type(table.name), str) or not (
schema is None or issubclass(type(schema), str)
):
return None
if is_table:
if self._ALIAS_KEYWORD_PATTERN.search(sqltext) is None:
return None
prefix = SQLCompiler.visit_table(self, table, asfrom=True)
suffix = sqltext.removeprefix(prefix)
if sqltext.startswith(prefix) and self._ALIAS_KEYWORD_PATTERN.match(suffix):
# The caller's text, not the rendering, which can be a
# quoted_name.
return sqltext[: len(prefix)], suffix
return None
suffix = self.get_render_as_alias_suffix(SQLCompiler.visit_alias(self, table, ashint=True))
prefix = sqltext.removesuffix(suffix)
if prefix != sqltext:
return prefix, suffix
return None


class AthenaDDLCompiler(DDLCompiler):
"""DDL compiler for Amazon Athena CREATE TABLE and related statements.
Expand Down
Loading