Repository navigation
Place a time-travel hint before a generated alias and accept irregular whitespace (GH-1575) - #1582
Conversation
| if prefix != sqltext: | ||
| if element is table: | ||
| # The table as visit_table() renders it without the alias. | ||
| prefix = SQLCompiler.visit_table(self, table, asfrom=True) |
There was a problem hiding this comment.
Self-review round one (implementation behavior, contracts, simplicity, tests): FINDINGS, repaired.
Scope: d653ea7132ee007bb7dee780badc6c5a19810888..eb46fa4e (initial pass, full diff: compiler, tests, docs), repairs at 169f0e119b715622fc3f3792b9624521a0fa0302. /code-review (high) found no correctness defects. It checked joins, %(name)s hints, INSERT FROM SELECT, UPDATE with an IN subquery, schema_translate_map, truncated 200-character names, an alias and an ambiguous table in one statement, and prepending hooks. /simplify ran 4 angles (reuse, simplification, efficiency, altitude).
Repaired in 169f0e1:
- The docstring now gives the exact generated-alias condition: a table of the same name with a schema.
- The DML comment moved next to the
iscrudcondition (line 1243). - A comment explains the split check (line 1261).
- Docs: see the
docs/sqlalchemy.mdthread.
Rejected, with reasons:
- Override
visit_table()to place the hint before the generated alias. Excluded by the agreed design (Render the time-travel hint of an aliased table before its alias #1547:format_from_hint_text()only, no private API).SQLCompiler.visit_table()is SQLAlchemy's public renderer. Ause_schema=Falsecall never has a generated alias (the alias needsnot effective_schema), so it cannot reach a wrong split. - Raise
CompileErrorwhen the split fails. The fallback to SQLAlchemy's placement is the agreed contract. SQLAlchemy's own callers always pass text that starts with the table (SELECT) or are excluded (iscrud). - Skip the second render when the table has a schema. That would not be behavior-identical, because
schema_translate_mapcan give a schemaless table a schema. The render costs a few quote calls per compile of a hinted table, and compiled statements are cached. if suffix:to skip the render. The suffix is computed from the render, so nothing is saved.- Recognize a leading comment (
/* c */ FOR ...). Outside SQLAlchemy time-travel hint follows a SQLAlchemy-generated alias and misses hints with irregular whitespace #1575 (whitespace only). Listed in the PR as not changed. - Strip leading whitespace. SQLAlchemy time-travel hint follows a SQLAlchemy-generated alias and misses hints with irregular whitespace #1575 renders the hint text unchanged.
- Keep
_TIME_TRAVEL_HINTS. It came with Render the time-travel hint of an aliased table before its alias #1547, which is unreleased, and goes to4.xtogether with this PR.
Validation after the repairs: just lint, just docs lint, tests/pyathena/sqlalchemy/test_compiler.py (284 passed). Harness on SQLAlchemy 2.0.23/2.0.46/2.1.9: identical to eb46fa4e (0 of 9112 differ).
|
|
||
| To query an aliased table, pass the alias to `with_hint()`. The hint is rendered between the table name and the alias. | ||
| When a statement uses a table without a schema and a table of the same name with a schema, SQLAlchemy gives the table | ||
| without a schema an alias such as `events_1`. Pass that table to `with_hint()`. |
There was a problem hiding this comment.
Round one repair: the first version said that "the same applies" to the generated alias. That suggested passing an alias, which the caller cannot name. The text now says which table gets the alias and that the table itself goes to with_hint(). A clause repeating the previous sentence was dropped (/simplify, reuse angle).
| element = table | ||
| while isinstance(element, FromClauseAlias): | ||
| element = element.element | ||
| # A DML target table has no generated alias, and its text may end with |
There was a problem hiding this comment.
Self-review round two (claims, existing callers, documentation reader, evidence): FINDINGS in the PR text only, corrected. No code change.
Scope: d653ea7132ee007bb7dee780badc6c5a19810888..169f0e119b715622fc3f3792b9624521a0fa0302, full pass over the PR body, the docstring and comments, docs/sqlalchemy.md and both commit messages.
Claims checked against evidence:
- A DML target never gets a generated alias (line 1243). On SQLAlchemy 2.0.23 and 2.1.9, only the SELECT path passes
ambiguous_table_name_maptovisit_table().visit_update()andvisit_delete()never mention it. The harnessUPDATE/DELETErows are unchanged. - The generated alias needs a same-named table with a schema; a map that gives the schemaless table a schema removes it. Harness
pair|*|map=translateandexec|none_to_tenant|*are unchanged. Exception: a lightweighttable()ignores the map (recorded in the PR). - Before Render the time-travel hint of an aliased table before its alias #1547 this raised
AttributeError. The pre-Render the time-travel hint of an aliased table before its alias #1547 code calledtable.original.fullnameon aTable. _TIME_TRAVEL_HINTSwas never released. It was added in 1535f6f (Render the time-travel hint of an aliased table before its alias #1547);v4.3.0,v4.2.xandorigin/4.xdo not have it.removeprefixneeds Python 3.9, and4.xrequires 3.11 or later.- Mutation claims. I ran the mutant that removes the
prefix + suffix == sqltextcheck: the hook test kills it. Skipping the check only for a table survives, as the PR says.
Corrected in the PR body:
- "Athena rejects the statement in both placements" was a grammar inference, not a measurement. It is now worded as such.
- "2.0.23 does not import on Python 3.13 or later" was observed only on 3.15. It is narrowed to 3.15.
- One harness case on 2.0.23 does not follow the stated transformation (the
AS events_1 AS aquirk). It is now named as the exception. - The tested commit is now 169f0e1.
just test offlinewas rerun there: 4434 passed.
Not measured: whether Athena accepts the moved clauses (events FOR VERSION AS OF 1 AS events_1, line breaks between the keywords). The clause order is the one #1547 already uses for aliases; only the alias source and the whitespace differ. A small parse-only live probe is pending the maintainer's approval.
43991d8 to
05170fd
Compare
| # hook appended or a name that it rendered differently. | ||
| prefix = SQLCompiler.visit_table(self, table, asfrom=True) | ||
| suffix = sqltext.removeprefix(prefix) | ||
| split = sqltext.startswith(prefix + self.get_render_as_alias_suffix("")) |
There was a problem hiding this comment.
Independent review (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22b9a-8a1a-7da3-ad01-36b3a7b4c095. This was a static review plus offline statement compilation on SQLAlchemy 2.0.23, 2.0.44, 2.0.46 and 2.1.9.
Scope: d653ea7132ee007bb7dee780badc6c5a19810888..169f0e119b715622fc3f3792b9624521a0fa0302, a full pass on a detached snapshot (left unchanged). The prompt had no PR number, PR text or prior findings.
Covered: SELECT/DML hint dispatch, explicit and generated aliases, ORM and cloned elements, truncated names, schema translation, compiled cache, CTEs, subqueries, lateral and table-valued aliases, TABLESAMPLE, and compiler hooks. Result: FINDINGS (6).
Finding 1 (verified, regression, fixed in 05170fd). A visit_table hook that renders events_archive and calls the hint hook itself got FROM events FOR VERSION AS OF 1_archive; the merge base gave FROM events_archive FOR VERSION AS OF 1. The table split now needs the alias marker of get_render_as_alias_suffix("") (AS) after the table. test_time_travel_hint_of_table_renamed_by_hook covers it. The test passes on the merge base and fails when the marker is dropped.
The marker check also leaves hook text appended to a DML target in place (UPDATE events /* table */ FOR ...). The iscrud check therefore became equivalent and was removed: the mutant without it survived. The harness output is identical to the version with the check (0 of 9115 differ on 2.0.23, 2.0.44, 2.0.46 and 2.1.9).
| # any ASCII whitespace between and before them. | ||
| _TIME_TRAVEL_HINT_PATTERN: ClassVar[re.Pattern[str]] = re.compile( | ||
| r"\s*FOR\s+(?:TIMESTAMP|SYSTEM_TIME|VERSION|SYSTEM_VERSION)\s+AS\s+OF\b", | ||
| re.ASCII | re.IGNORECASE, |
There was a problem hiding this comment.
Finding 4 (verified, fixed in 05170fd). With Unicode IGNORECASE, FOR VERSİON AS OF 1 (U+0130) was recognized and moved before an alias; the merge base left it after. The pattern is now re.ASCII | re.IGNORECASE, so keywords and whitespace are the ASCII ones Athena lexes.
Side effect, recorded in the PR as a behavior change: FOR VERſION AS OF 1 was recognized on the merge base through str.upper() and is not recognized now. NBSP is no longer recognized either, as on the merge base. Athena rejects all of these texts in either place.
Finding 6 (rejected). It asks for a test of the \b boundary. \b, and now re.ASCII, only decide where a text that is not a time-travel clause goes (AS OFFICE, AS OF1, VERSİON). Athena rejects that text in either place, so the placement is not a caller-observable contract (docs/testing.md, Choose what to test). The differential check pins these rows (like_*).
| ``` | ||
|
|
||
| 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 gives |
There was a problem hiding this comment.
Finding 5 (verified, fixed in 05170fd). With b = db_events.alias("b"), no alias is generated: SQLAlchemy builds _ambiguous_table_name_map from FROM objects that are tables with a schema, and an alias is not one (SelectState._normalize_froms, 2.0.46). The docs and the docstring now say "an unaliased table of the same name with a schema".
| ) | ||
| prefix = sqltext.removesuffix(suffix) | ||
| if prefix != sqltext: | ||
| if isinstance(element, TableClause) and self._TIME_TRAVEL_HINT_PATTERN.match(hint): |
There was a problem hiding this comment.
Finding 2 (rejected: a property of raw hint text, not of this placement). It reports that with_hint(events, "FOR VERSION AS OF 1 -- audit") in a pair emits FROM events FOR VERSION AS OF 1 -- audit AS events_1, db.events, and the comment removes db.events. A hint is raw SQL. A line comment in it comments out the rest of the line in every placement, including SQLAlchemy's default for any unaliased table followed by another FROM element. On the merge base, select_from(events, other).with_hint(events, "FOR VERSION AS OF 1 -- audit") already gives FROM events FOR VERSION AS OF 1 -- audit, other. Explicit aliases behave the same since #1547.
Finding 3 (rejected: consistent with #1547). It reports that delete(a).with_hint(" FOR VERSION AS OF 1") on an aliased target now goes before AS a. That is the placement #1547 already gives the canonical hint on an aliased DML target. Whitespace recognition only makes the spaced variant consistent with it. Athena's UPDATE/DELETE accept neither an alias nor a time-travel clause.
Pre-existing, noted by the reviewer: on 2.0.23, an explicit alias of the schemaless table in a pair renders events AS events_1 FOR VERSION AS OF 1 AS a, on both revisions. This is an upstream quirk (no enclosing_alias check in 2.0.23) and is recorded in the PR.
| "UPDATE events /* table */ FOR VERSION AS OF 1 SET " | ||
| ) | ||
|
|
||
| def test_time_travel_hint_of_table_renamed_by_hook(self): |
There was a problem hiding this comment.
Repair review, both perspectives (169f0e11..05170fdc).
- Implementation:
- The marker check keeps every SQLAlchemy-produced split: a generated alias always renders through
get_render_as_alias_suffix(). - A table without an alias and a DML target without a hook have no text after the table, so they keep the default placement.
- Limitation: a dialect subclass whose
get_render_as_alias_suffix()dropsAS(a bare space) would accept any text that starts with a space after the table. No Athena dialect does this. - Mutants are killed: no marker (both hook tests),
endswith→True(hook test), leading\s*, single spaces, aliases only.
- The marker check keeps every SQLAlchemy-produced split: a generated alias always renders through
- Claims:
- The docs and docstring wording was checked against
SelectState._normalize_froms(2.0.46) andvisit_table()(2.0.23 and 2.1.9). - The commit message claims match the mutants.
- The PR body now has the new counts (9114 cases, 2486 differ, all expected; written before the rerun in
expected.md), the tested commit, and the ASCII behavior change.
- The docs and docstring wording was checked against
- Validation:
just lintandjust docs lintpass, andjust test offlinegives 4435 passed.- On
4.x([4.x] Backport #1547, #1566, #1567 and #1551 #1578 head with the patch), 20 passed on 2.0.23 and 2.1.9. - The harness gives the same output on master and
4.xfor every version.
| split = ( | ||
| not iscrud | ||
| and sqltext.startswith(prefix) | ||
| and self._ALIAS_KEYWORD_PATTERN.match(suffix) is not None |
There was a problem hiding this comment.
Independent follow-up 1 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, fresh session. This was a static review plus offline compilation on SQLAlchemy 2.0.23, 2.0.44, 2.0.46–2.0.48, 2.0.58 and 2.1.9.
Scope: the repair 169f0e11..05170fdc, on a detached snapshot (left unchanged). Codex confirmed earlier findings 1 (events_archive) and 4 (İ) fixed. Result: FINDINGS (3).
- F1:
get_render_as_alias_suffix("")broke subclasses that read the name (an override usingname[0]raisedIndexErroreven forSELECT 1 FROM events FOR VERSION AS OF 1). An override returningf" AS {name} /* trace */"no longer got the hint before the generated alias, a regression from 169f0e1. Verified. - F2: with the hinted table last,
-- auditcomments outAS events_1(FROM db.events, events FOR VERSION AS OF 1 -- audit AS events_1). - F3: the docs promised an alias too broadly;
schema_translate_map={None: "tenant"}gives none. Verified.
The A/B design choices were then put to Codex and Claude Fable 5.2 in parallel, two rounds (prompts /tmp/pyathena-1575/consult*.md, read-only):
- Split check. Both agreed on keeping
not iscrudand on not calling the hook with a made-up name. Fable found the CTE case: SQLAlchemy leaks the generated alias to anUPDATEinside a CTE, which disproved my earlier claim that "a DML target never gets one". Fable proposed a literalAS; Codex proposed whitespace + case-insensitiveAS(counterexample: an extension renderingas name). - Recognition. Both agreed on
hint.upper()with Trino's[ \t\r\n], which keeps the merge base'sſhandling whatever Athena does with it. Fable said to drop\b(exact parity with the merge base); Codex said to keep it and add a test. - Line comment (R2). Fable said to keep rejecting it here: a newline before the alias would not fix the comma/
JOINpaths that exist on the merge base. Codex proposed the newline.
Maintainer decisions: whitespace + case-insensitive AS, drop \b, line comments to a separate issue (#1598, sub-issue of #1494). Implemented in 5065068.
| ) | ||
| prefix = sqltext.removesuffix(suffix) | ||
| if prefix != sqltext: | ||
| if isinstance(element, TableClause) and self._TIME_TRAVEL_HINT_PATTERN.match(hint.upper()): |
There was a problem hiding this comment.
Repair review, both perspectives (05170fdc..50650688).
- Implementation:
- The table split is
not iscrud and sqltext.startswith(prefix) and _ALIAS_KEYWORD_PATTERN.match(suffix); the alias branch is unchanged. - Every mutant is killed by a test: no
iscrud, noAScheck, upper-case or literalASonly, no.upper(), no leading whitespace, single spaces, aliases only,endswith→True. - Two hook tests were added for the decided contract: the lower-case
ashook (fails on the merge base) and the DML target aliased by a hook (pinsiscrud).
- The table split is
- Claims:
- The commit message, docstring and docs now say "can generate".
- "DML target keeps the default placement" replaces the disproved "never gets a generated alias".
- The PR body was rewritten for the final design, its counts and tests.
- Differential check: expected differences were written before the run.
- 9120 cases. On 2.0.23, 2.0.44, 2.0.46 and 2.1.9, 2536 differ, all expected; the only exception is the known 2.0.23 quirk.
- The new
update_cte_pairrow is unchanged from the merge base. - The merge base is stable over two runs, and
4.xgives identical output.
- Tests:
just test offline: 4437 passed.- Time-travel/hint tests: 22 passed on 2.0.44 and 2.1.9 (master), and on 2.0.23 and 2.1.9 (
4.x). just lintandjust docs lintpass.
- F2: the hinted-last variant is the same raw-SQL hazard and is folded into A SQLAlchemy FROM hint that ends with a line comment swallows the rest of its line #1598. It fails at run time on both revisions (
events_1unresolved, or the hint after the alias on the merge base).
0e9d40d to
0eee58e
Compare
| # subclass hook rendered differently, keeps the default | ||
| # placement; a DML target and text without AS keep it without | ||
| # rendering the table again. | ||
| if iscrud or self._ALIAS_KEYWORD_PATTERN.search(sqltext) is None: |
There was a problem hiding this comment.
Independent follow-up 2 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22be9-139f-79f0-8d99-5963b4b63379.
- Scope:
05170fdc..506506882, on a detached snapshot (left unchanged). - Method: static review plus offline compilation across 37 cached SQLAlchemy releases, including 2.0.23, 2.0.44, 2.1.0 and 2.1.9.
- Earlier findings F1 and F3: resolved. Hint recognition matches the merge base's apart from whitespace.
- Result: FINDINGS (4), all verified and fixed in
0eee58e4(tested at 68e84b6; the head differs only in this comment).
- CompileError (regression). A renaming hook on a table whose schema SQLAlchemy cannot render under
schema_translate_map(tenant[42]) raisedCompileErrorfrom the re-render. The merge base compiled it (FROM events_archive FOR VERSION AS OF 1).- Fix: a DML target, and text with no
ASkeyword, now return the default placement before the table is rendered again. - Test:
test_time_travel_hint_of_table_renamed_by_hook[unrenderable_schema]. The pre-check mutant fails it.
- Fix: a DML target, and text with no
- Docstring. It now says "unaliased DML target tables". An aliased DML target follows the alias branch, unchanged since Render the time-travel hint of an aliased table before its alias #1547.
- Comment. It now describes the text that is split: it continues the rendered table with
ASand a name. It no longer attributes every such alias to SQLAlchemy. - Test hook. The suffix hook in
test_time_travel_hint_precedes_generated_alias_of_hooknow readsalias_name_text[0], so probing with""(the old F1) fails the test. A second rename case,[aliased](events_archive AS events), pins the anchoredAScheck, which the pre-check had made unprotected.
Validation:
- All 11 mutants are killed.
- The harness (9120 cases) gives the same output as 5065068 on 2.0.23, 2.0.44, 2.0.46 and 2.1.9. 2536 cases differ from the merge base, all expected.
4.xis identical. just test offline: 4438 passed. Time-travel/hint tests: 23 passed on 2.0.44 and 2.1.9 (master) and on 2.0.23 and 2.1.9 (4.x).just lintandjust docs lintpass.
Both self-review perspectives on the repair:
- No caller-visible change for SQLAlchemy's own rendering: harness 0 of 9121 differ from 5065068.
- Claims in the commit message and the PR body were updated (tested commit, counts, mutants).
| return super().format_from_hint_text(sqltext, table, hint, iscrud) | ||
| try: | ||
| prefix = SQLCompiler.visit_table(self, table, asfrom=True) | ||
| except exc.CompileError: |
There was a problem hiding this comment.
Independent follow-up 3 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22bfb-27c3-7a31-982c-7879906f2eea.
- Scope:
506506882..0eee58e4, on a detached snapshot (left unchanged). It compiled offline on SQLAlchemy 2.0.23, 2.0.44, 2.0.46, 2.1.0 and 2.1.9. - Previous (2)–(4): resolved.
- Result: FINDINGS (2), both verified:
- A hook rendering
"events AS archive"on a table whose schema SQLAlchemy cannot render (tenant[42]underschema_translate_map) still raisedCompileError. The merge base compiled it. - The unanchored
ASsearch was quadratic: 132 ms for a hook text with 8192 spaces.
- A hook rendering
Consultation, round 3 (Codex and Claude Fable 5.2, in parallel):
- Fable recommended (a): drop the pre-check and catch
CompileErrorfrom the re-render. - Codex recommended (c): (a) plus a linear pre-check. Its counterexample: a table without a name raises
IndexErroron the re-render, so the pre-check is observable. - Both agreed to state a scope and stop the chain of hook findings.
- Maintainer decisions: (c), and the scope now written in the PR body. Hook-related findings are fixed only when they change the output without hooks, or when a statement that compiled on the merge base raises.
Repair in 5d55abb:
- The re-render is wrapped in
try/except exc.CompileError, which falls back to the default placement. - The pre-check pattern gets the lookbehind
(?<![ \t\r\n]), so it starts only at the first whitespace of a run (8192 spaces: 0.2 ms). - The rename test gained the cases
unrenderable_schema_with_as(kills theexceptmutant) andempty_name(kills the pre-check mutant).
Validation:
- 13 of 14 mutants are killed. The lookbehind mutant only changes the running time; that was measured instead.
- The harness gives the same output as 0eee58e on 2.0.23, 2.0.44, 2.0.46 and 2.1.9 (2536 differ from the merge base, all expected), and
4.xis identical. just test offline: 4440 passed. Time-travel/hint tests: 25 passed on 2.0.44 and 2.1.9 (master) and on 2.0.23 and 2.1.9 (4.x).
Both self-review perspectives: the output for SQLAlchemy's own rendering is unchanged (harness). The commit message, comments and PR body state the scope and the fallback.
| SQLCompiler.visit_alias(self, table, ashint=True) | ||
| ) | ||
| except Exception: | ||
| # An alias that only a subclass hook can render. |
There was a problem hiding this comment.
Independent follow-up 4 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22c26-b9fe-7b01-b36e-59cf17fbc837.
Scope: 0eee58e4..5d55abb4, compiled offline on 35 SQLAlchemy releases from 2.0.23 to 2.0.58, plus 2.1.0 and 2.1.9. The earlier findings (1) and (2) are resolved, and the lookbehind changes no match result. FINDINGS (2), both within the agreed scope: a statement that compiled on the merge base raised.
Table(""), with a hook that rendersevents AS archive, raisesIndexErrorfrom the comparison render on SQLAlchemy 2.0.events.alias(""), with avisit_aliashook that supplies the name and the hint" FOR VERSION AS OF 1", raisesIndexErrorfromSQLCompiler.visit_alias(). The canonical hint already raised on the merge base.
It also noted two minor points. A comment implied the re-render is skipped for an unrenderable table. The test case with a bracketed schema and no AS duplicated a neighbor.
Consultation, round 4 (Codex and Claude Fable 5.2, in parallel): both recommended Z, catching any exception around the two comparison renders only.
- X (an empty-name check) changes the output without hooks:
events.alias(quoted_name("", True))would move the hint afterAS "". - Y (
CompileError+IndexError) leaves the next error.table(1)raisesAttributeError, and aquote()hook can raiseValueError. - Without hooks, these calls render what SQLAlchemy has just rendered, so Z changes no output.
Maintainer decision: Z. Implemented in 20c3d4f.
- Both comparison renders fall back to the default placement on any exception.
- The comment is corrected.
- The rename test now covers a plain rename, a rename with an alias, an unrenderable schema, an empty name and a name that is not a string; the duplicate case is gone. The new
test_time_travel_hint_of_alias_named_by_hookcovers the alias branch.
Validation.
- Mutants: 12 of 14 are killed. The two
CompileError+IndexErrormutants, one per branch, fail the non-string name tests. TheASpre-check and the lookbehind only skip work or change the running time; measured at 8192 spaces, 0.2 ms. - Harness: 0 of 9121 cases differ from 5d55abb on 2.0.23, 2.0.44, 2.0.46 and 2.1.9, and
4.xis identical. - Tests:
just test offlinegives 4442 passed. The time-travel and hint tests pass 27 on master (2.0.44 and 2.1.9) and on4.x(2.0.23 and 2.1.9).
Both self-review perspectives:
- There is no change without hooks, per the harness.
- The scope in the PR body now says "any error", and the commit message, the comments and the PR counts are updated.
| prefix = sqltext.removesuffix(suffix) | ||
| if prefix != sqltext: | ||
| try: | ||
| parts = self._split_alias(sqltext, table, element is table) |
There was a problem hiding this comment.
Independent follow-up 5 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22c41-cdac-7301-aff7-36ff24f33392.
- Scope:
5d55abb4..20c3d4f9, compiled offline on SQLAlchemy 2.0.23, 2.0.44, 2.0.46–2.0.48, 2.0.58 and 2.1.9. - Confirmed:
- The
IndexErrorcases are resolved. - Exceptions from the first render and from the hint formatting still propagate.
- The
- Result: FINDINGS (2). Both are within the agreed scope: a statement that compiled on the merge base raised. Both are verified and fixed in
5abb9239.
1. UserString names. SQLAlchemy renders a UserString name as a UserString, so removeprefix()/removesuffix() raised TypeError after the guarded call.
- Fix: the whole comparison (pre-check, rendering, string operations) moved into
_split_alias(), called inside the single fallback. This is the decided Z applied to the whole comparison, not only the render. - Tests:
[user_string_name]andtest_time_travel_hint_of_alias_named_by_hook[user_string].
2. update(t).values(id=1).with_hint(None). It compiled without a hint on the merge base; the branch raised AttributeError at hint.upper().
- Fix: the unaliased DML target is checked first.
- Test:
test_none_hint_of_dml_target_renders_no_hint. - A SELECT with a
Nonehint raises inside SQLAlchemy's own hint formatting (None % {...}), on the merge base too, so no change there. - I briefly added
isinstance(hint, str). I removed it again because its mutant survived: it only changed an aliased DML target withNone, which also raised on the merge base.
Pre-existing, noted: on 2.0.23, an explicit alias beside a same-named schema table renders two AS clauses even without a hint. This is upstream and already in the PR body.
Validation:
- Mutants: 11 of 13 are killed. These include a narrowed
except(killed by theUserStringtests), noiscrud, noAScheck, case-sensitiveAS, no.upper(), whitespace, aliases only,endswith→True, and the empty-name probe. The pre-check and the lookbehind only skip work or change running time (8192 spaces: 0.2 ms). - Harness: 0 of 9121 differ from 20c3d4f on 2.0.23, 2.0.44, 2.0.46 and 2.1.9, and
4.xis identical. - Tests:
just test offlinegives 4445 passed. Time-travel/hint tests: 30 passed on master (2.0.44, 2.1.9) and on4.x(2.0.23, 2.1.9). - Both self-review perspectives: no output change without hooks; the PR body counts and the scope wording are updated.
| and not (element is table and iscrud) | ||
| # A hint that is not a string, unlike SQLAlchemy's annotation, is | ||
| # not read. | ||
| and isinstance(hint, str) |
There was a problem hiding this comment.
Independent follow-up 6 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22c53-7db5-75b1-a3dc-1ca5c34483fd.
- Scope:
20c3d4f9..5abb9239, compiled offline on SQLAlchemy 2.0.23, 2.0.44, 2.0.58, 2.1.0 and 2.1.9. - Earlier repairs: confirmed fixed.
- Result: FINDINGS (3):
- A
tablesamplenamedUserString("s")moved the hint after its alias without hooks, becauseUserString.endswith()rejects aUserStringsuffix and the code fell back. - Hints that are not
str(UserString,bytes,Nonefrom a hook) raised athint.upper()or at the regex; some of these compiled on the merge base. - The DML comment ignored the generated alias inside a CTE.
- A
Consultation, round 5 (Codex and Claude Fable 5.2, in parallel). Both recommended R: a type boundary, plus the merge base's removesuffix()/!= alias split.
- Fable's R:
isinstance(hint, str)gate only. One remaining difference: aUserStringhint on a tablesample goes after the alias; there is no exception, and SQLAlchemy itself already raised for aUserStringhint on an ordinary alias. - Codex's R: keeps full parity through the merge base's
startswith()recognition for non-strhints, at the cost of a second recognition path. - Rejected option P (handle the types): a
strEnum hint would break, becausestr()returns"H.VERSION". - Maintainer decision: Fable's R, with the type rule now in the PR scope.
Repair in 6e5d283:
- Recognition is
isinstance(hint, str) and PATTERN.match(hint.upper()). - The alias split is back to
removesuffix()+prefix != sqltext. - The DML comment is corrected.
- New test
test_empty_hint_that_is_not_a_string_renders_no_hint(UserString(""),b""). It fails without thestrcheck.
Validation:
- Mutants: 13 of 16 are killed. The
endswith()split changes only output for non-strnames, which the scope excludes. The pre-check and the lookbehind only skip work or change running time. - Harness: 0 of 9121 differ from 5abb923 on 2.0.23, 2.0.44, 2.0.46 and 2.1.9, and
4.xis identical. just test offline: 4447 passed. Time-travel/hint tests: 32 passed on master (2.0.44, 2.1.9) and on4.x(2.0.23, 2.1.9).- Both self-review perspectives: no output change for
strinputs; the PR body states the type rule and the updated counts.
| text does not split. | ||
| """ | ||
| schema = table.schema if is_table else None | ||
| if not isinstance(table.name, str) or not isinstance(schema, (str, type(None))): |
There was a problem hiding this comment.
Independent follow-up 7 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22c75-3b63-7fa3-a135-db4dba0143c8. Scope: 5abb9239..6e5d2835, offline on SQLAlchemy 2.0.23, 2.0.44, 2.0.46, 2.0.58, 2.1.0 and 2.1.9. The previous findings are resolved. FINDINGS (2):
- Verified, fixed in 6d80811. A hook-rendered table named
UserString("events"), followed bytable("events")in the same SELECT, raisedTypeErrorin the FROM join. The merge base compiled it. Cause: the comparison render quoted theUserString, the identifier preparer cached it, and the cache returned it for the later plain"events"; the cache persists for later statements on the dialect.- Fix:
_split_alias()compares only tables and aliases whose name, and table schema, arestr, as the agreed type rule says. Others keep the default placement without rendering again. - Test:
test_time_travel_hint_of_hooked_table_keeps_quoting_cachefails on 6e5d283 and on the gate-removal mutant. The rename test'sUserStringcase, now duplicate, is dropped.
- Fix:
- Rejected. The finding says the
NoneDML hint test and the empty non-string hint tests pin SQLAlchemy's formatting beyond "no added exception". The PR scope states that such hints "are not read and keep the default placement", and these tests check that stated behavior. The file's convention compares the full compiled SQL, and the expected values are SQLAlchemy's own default output, independent of this change.
Validation:
- Mutants: 13 of 17 are killed. The survivors are the
endswith()alias split (non-strnames only), the narrowedexcept(thestrchecks stop the tested inputs first), the pre-check and the lookbehind (performance). - Harness: 0 of 9121 differ from 6e5d283 on 2.0.23, 2.0.44, 2.0.46 and 2.1.9, and
4.xis identical. just test offline: 4447 passed. Time-travel/hint tests: 32 passed on master (2.0.44, 2.1.9) and on4.x(2.0.23, 2.1.9).- Both self-review perspectives: no output change for
strinputs. The PR scope now names the str-only rendering.
| """ | ||
| # 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 ( |
There was a problem hiding this comment.
Independent follow-up 8 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22c88-8d0d-7511-b0e8-3a1e862220d3.
- Scope:
6e5d2835..6d808110, compiled offline on SQLAlchemy 2.0.23, 2.0.44, 2.0.46, 2.0.58, 2.1.0 and 2.1.9. - Previous findings: the
UserStringcache case is fixed, and the rejected point (2) was not raised again. - Result: FINDINGS (1), verified and fixed in bf6bb10.
- Finding: a Werkzeug
LocalProxy(lambda: "events")passesisinstance(name, str). The comparison render cached the proxy, and a later plaintable("events")raisedTypeError. The merge base compiled the statement. - Fix: names and schemas are checked with
issubclass(type(...), str), which a proxy cannot fake and which still acceptsstrsubclasses. - Test: a minimal
_StrProxy(the same__class__trick) parametrizes the cache test. It fails on 6d80811 and passes now. - Placement: the helper class sits before
_VersionHint, so the test patch applies cleanly to4.x.
- Finding: a Werkzeug
Validation:
- Harness: 0 of 9121 differ from 6d80811 on 2.0.23, 2.0.44, 2.0.46 and 2.1.9, and
4.xis identical. - Tests:
just test offlinegives 4448 passed. The time-travel and hint tests give 33 passed on master (2.0.44, 2.1.9) and on4.x(2.0.23, 2.1.9). - Both self-review perspectives: no output change for
strinputs. The PR scope names thetype()check.
Note for the maintainer: this was the third successive finding about inputs outside SQLAlchemy's str annotation (UserString, then a quoting-cache side effect, then an isinstance proxy). The fix stayed within the agreed type rule. If the next round reports another impersonating type, I will ask whether objects that fake str should be declared out of scope.
| # 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) |
There was a problem hiding this comment.
Independent follow-up 9 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22c9a-d287-7f91-90d8-38010a8fb85d. Scope: 6d808110..bf6bb108, offline on SQLAlchemy 2.0.23, 2.0.44, 2.0.46, 2.0.58, 2.1.0, 2.1.9. The LocalProxy cache case is resolved for names and schemas. FINDINGS (2):
- A table named by
markupsafe.Markup("events")(a realstrsubclass that overrides methods) with a hook: the comparison render caches theMarkupin the identifier preparer, so a later ordinary SELECT on the same dialect renders"My Schema".events. update(a).values(id=1).with_hint(MagicMock(spec=str))on an aliased target:isinstance(hint, str)accepts the mock, and the pattern raisesTypeErroronhint.upper(). The merge base compiled it.
Consultation, round 6 (Codex and Claude Fable 5.2, in parallel):
- Both: fix 2 with
issubclass(type(hint), str). - On 1, Fable: out of scope. Offline, SQLAlchemy alone (
select(table(Markup("events"))), no PyAthena, no hook) already poisons the cache the same way, so the cause is the name type. A fix would need excludingstrsubclasses (SQLAlchemy's ownquoted_name/_anonymous_labelare subclasses) or touching the private cache. - On 1, Codex: rebuild the comparison from
quoted_name(str.__str__(x))withquote/quote_schema/schema_for_object. That reimplementsvisit_table()rendering in PyAthena and still leaves SQLAlchemy's own poisoning.
Maintainer decision: 1 is out of scope; the scope in the PR body now names str subclasses that override str methods. Fix 2.
Repair in 983013a: the hint is read only when issubclass(type(hint), str). New test: test_hint_that_only_passes_isinstance_is_not_read fails on bf6bb10 and on an isinstance() mutant.
Validation after a machine restart that wiped /tmp:
- Harness rebuilt (9193 cases). The merge base is stable over two runs on 2.0.23, 2.0.44, 2.0.46, 2.0.52 and 2.1.9.
- Head: 2536 cases differ from the merge base, all expected; the only exception is the known 2.0.23 transform case. The head is identical to bf6bb10, and the current
4.x(a23d009), with and without the patch, matches master. just test offline: 4449 passed. Time-travel/hint tests: 34 passed on master (2.0.44, 2.0.52, 2.1.9) and on4.x(2.0.23, 2.1.9).- Mutants: the
type()checks for hints and names are each killed, by the mock test and the proxy test. A narrowedexceptsurvives, as recorded.
Both self-review perspectives: no output change for str inputs. The PR body now states that #1578 has merged, so this PR needs its own 4.x backport; the current master minimum (SQLAlchemy 2.0.52) is in the test list.
| parts = None | ||
| if parts is not None: | ||
| prefix, suffix = parts | ||
| return super().format_from_hint_text(prefix, table, hint, iscrud) + suffix |
There was a problem hiding this comment.
Independent follow-up 10 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22ce2-ec97-7021-96d4-571b116580d8. Scope: bf6bb108..983013a0, offline on seven SQLAlchemy releases from 2.0.23 through 2.1.9, including 2.0.44 and 2.0.52. The MagicMock(spec=str) regression is resolved, and the added test has a distinct contract. FINDINGS (2):
-
Rejected; maintainer decision after consulting Codex and Claude Fable 5.2, who agreed. A compiler mixin later in the MRO overrides
format_from_hint_text()and expands{alias}in the hint bysqltext.rsplit(" AS ", 1). For the generated alias it now receives onlyeventsand raisesValueError; on the merge base it receivedevents AS events_1. Reasons for rejecting:- To put the hint before the alias,
super()must receive the table text only. That is the contract for explicit aliases since Render the time-travel hint of an aliased table before its alias #1547, where the same mixin already fails on the merge base. - The merge base output put the hint after the alias, which Athena rejects.
- Catching the error and retrying with the full text would silently emit Athena-invalid SQL and hide the hook's bug.
The PR scope now states this ("A hook later in the MRO that overrides
format_from_hint_text()and reads an alias from itssqltextis out of scope, even if the statement compiled on the merge base"). - To put the hint before the alias,
-
Fixed in a6d6316. Two test comments claimed SQLAlchemy cannot render a name that is not a string; a proxy of a string renders. They now name the int case.
Validation: the change is comment-only (just lint passes; tests/pyathena/sqlalchemy/test_compiler.py 299 passed). The harness and test results of 983013a apply.
| 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 |
There was a problem hiding this comment.
Independent follow-up 11 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22cf6-12ac-7b62-becc-fdc299ef92a6.
- Scope: a final full pass of
d653ea71..a6d63168within the stated scope. Compiled offline on 45 SQLAlchemy releases from 2.0.23 to 2.1.9, without hooks, and matched the intended behavior. - Previous finding: the test comments now name the int case accurately.
- Result: FINDINGS (2), both verified and fixed in aeecb57. Neither needed a design decision.
- Table text passed to the next hint hook. For a generated alias, the table text passed on was the
quoted_namereturned by the comparison render. A hook callingsys.intern(sqltext)compiled on the merge base and now raisedTypeError.- Fix: the table text is now the caller's own span,
sqltext[: len(prefix)], a plainstrwith the same characters. - Test:
test_time_travel_hint_of_generated_alias_passes_text_of_its_ownfails on a6d6316.
- Fix: the table text is now the caller's own span,
- The mock hint test did not detect a read. The merge base reads the hint and still produces the same SQL.
- Fix: the mock's
upper()now raisesAssertionError. - The test fails on the merge base and on an
isinstance()mutant.
- Fix: the mock's
Validation:
- Harness: no change from a6d6316 on 2.0.23, 2.0.44, 2.0.46, 2.0.52 and 2.1.9, with the same 2536 expected differences from the merge base. The current
4.xgives identical output. - Tests:
just test offlinepassed 4450. The time-travel and hint tests passed 35 on master (2.0.44, 2.0.52, 2.1.9) and on4.x(2.0.23, 2.1.9). - Both self-review perspectives: there is no output change. The PR body now lists the new tests and counts.
| # The AS keyword and the name of an alias after a rendered table. 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]" |
There was a problem hiding this comment.
Independent follow-up 12 (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22d08-c917-7b90-905d-710fc887bba0.
- Scope:
a6d63168..aeecb57dplus a full pass, offline on eight SQLAlchemy releases (2.0.23–2.1.9). Ordinary SQLAlchemy rendering matched the intended placement. - Previous findings: both resolved.
- Result: FINDINGS (4).
- Rejected (maintainer decision after consulting Codex and Claude Fable 5.2, who both recommended rejection). A
class Name(str)table name with a hook: the comparison render cachesName("events")in the identifier preparer, and a hook thatsys.intern()s a later plaineventsraises.- Fable confirmed offline that SQLAlchemy itself shares that cache across statements, so the same happens without this change once any statement renders the table or one of its columns.
- There is no fix without private API.
- The scope now states that the effect of the comparison render on the identifier cache is SQLAlchemy's own.
- Fixed in 8f3d62f. Hooked text
events AS(AS without a name) was split. The alias keyword pattern now needs a name character after AS (test[as_without_name]). - Fixed. The alias-name guard was untested for its cache effect.
test_time_travel_hint_of_alias_named_by_hooknow uses a fresh dialect and checks that a latertable("archive")still renders; this fails without the guard. - Fixed. A
self.isupdatemutant passed the DML tests. The synthetic hook test is replaced by a hook-free test of anUPDATEinside a CTE that SQLAlchemy gives a generated alias; that test fails on the mutant.
Stop rule (maintainer decision, from the same consultation; Fable's wording). The next independent round is the final one. After it, only these are actionable:
- a difference from the merge base, in output or in a raised exception, for hook-free statements with
str/quoted_namenames and hints; - inaccurate comments, docs or tests in this diff.
Hook, other-type and shared-preparer-state findings are recorded, not fixed. Repairs get one round limited to the repair diff. This is now in the PR body.
Validation:
- Mutants for 2, 3 and 4 are each killed by the new tests.
- Harness: no change from aeecb57 on 2.0.23, 2.0.44, 2.0.46, 2.0.52 and 2.1.9 (2536 expected differences from the merge base), and
4.xis identical. just test offline: 4451 passed. Time-travel/hint tests: 36 passed on master (2.0.44, 2.0.52, 2.1.9) and on4.x(2.0.23, 2.1.9).
| 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 |
There was a problem hiding this comment.
Final independent round (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22d27-00c1-71b2-9c8d-5c16da568c81.
- Scope: the full diff
d653ea71..8f3d62f6, under the stop rule in the PR body. The reviewer compared 3,842 offline compilation cases per version across seven SQLAlchemy releases (2.0.23–2.1.9). - Result: every difference in compiled SQL or exceptions matched the intended placement changes. FINDINGS (3), all wording, actionable under the stop rule and fixed in 12f69a7:
- docs/sqlalchemy.md. "Pass that table to
with_hint()" holds only when the SELECT uses the table itself. The docs now say to pass the alias when the SELECT uses an alias of the table. - Pattern comment. The comment said "upper-cased hint text"; the pattern is matched against
hint.upper(), which keeps the case of aquoted_namewithquote=True, as on the merge base. Comment and PR body corrected. - Alias pattern comment. The pattern checks only the first character of a name, and the rendered-table prefix marks the alias boundary. Comment corrected.
- docs/sqlalchemy.md. "Pass that table to
- Note on the hook-recorder test: it checked only the type, so the merge base's full text would also pass. It now asserts
(str, "events").
Validation: comment, doc and test changes only. The harness on 2.0.46 gives 0 differences from 8f3d62f. just test offline passed 4451, and just lint and just docs lint pass.
Per the stop rule, this repair gets one round limited to the repair diff.
|
|
||
| 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 |
There was a problem hiding this comment.
Repair check (relayed): Codex CLI 0.172.0, model gpt-6.2-astra, codex exec -s read-only, session 01a22d39-a9d4-7933-b83f-230116171e79. Scope, per the stop rule: the repair diff 8f3d62f6..12f69a70 only. The reviewer checked that the three wording issues and the test note from the final round are resolved, and that the repair introduces nothing inaccurate and no behavior change. Result: CLEAN.
The independent review is complete under the stop rule recorded in the PR body.
…r whitespace (GH-1575) format_from_hint_text() placed a time-travel hint before the alias of an aliased table only. In a SELECT, SQLAlchemy also gives a table without a schema an alias when another table in the statement has the same name, and passes the plain table with that alias; the hint followed the alias. For a table, the text is split after the table as SQLCompiler.visit_table() renders it without the generated alias. A DML target has no generated alias and keeps the default placement. The hint is recognized with an anchored, case-insensitive pattern, so leading whitespace and any whitespace between the keywords (a line break, a tab, repeated spaces) are accepted. The hint text is rendered unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…iew (GH-1575) State the generated-alias condition precisely (a table of the same name with a schema), move the DML comment next to the iscrud check, explain the split check, and tell readers to pass the table itself to with_hint() for a generated alias. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nly (GH-1575) A compiler hook that renders the table under another name and calls the hint hook itself (events_archive) had its name split after "events". The text is now split only when the table is followed by the alias marker of get_render_as_alias_suffix(). This also leaves the text that a hook appends to a DML target in place, so the iscrud check is no longer needed. The hint pattern matches ASCII keywords and whitespace only, as Athena reads them; Unicode case folding no longer turns a lookalike such as "VERSİON" into a time-travel hint. The docs and docstring state that the generated alias needs an unaliased table of the same name with a schema. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…H-1575) Decided with the maintainer after consulting Codex and Claude Fable 5.2: - The hint is matched against hint.upper(), as the merge base did, with the whitespace that Athena reads ([ \t\r\n]) before and between the keywords and no word boundary. Only irregular whitespace changes the recognition; FOR VERſION and FOR VERSION AS OFTEN are recognized as before, and FOR VERSİON is not. - A table's text is split only when it is not a DML target and the rendered table is followed by whitespace, AS in any case, and whitespace. get_render_as_alias_suffix() is no longer called with an empty name, which broke subclasses that read the name. SQLAlchemy can give a DML target a generated alias inside a CTE; it keeps the default placement. - The docs say that SQLAlchemy can generate the alias. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ses (GH-1575) The plain-table branch rendered the table with SQLCompiler.visit_table() before it checked anything. A hook that renders the table under another name bypasses that rendering, and for a table that SQLCompiler cannot render (a schema name with square brackets under schema_translate_map) the hint then raised CompileError where the merge base compiled. The branch now leaves a DML target and text without an AS keyword at the default placement before it renders the table again. The docstring names unaliased DML target tables, which keep the default placement, and the comment describes the text that is split. The hook tests cover a table renamed with an alias and a suffix hook that reads the alias name. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…AS check linear (GH-1575) Decided with the maintainer after consulting Codex and Claude Fable 5.2: - The table is rendered again inside try/except CompileError. A hook that renders a table SQLAlchemy cannot render (a schema name with square brackets under schema_translate_map) and puts AS in its text (a quoted "events AS archive") now gets the default placement, as on the merge base, instead of an error. - The AS pre-check stays, so a hooked table without AS is never rendered again (a table without a name raised IndexError there). Its pattern starts only at the first whitespace of a run, so a search over a long run of whitespace is linear instead of quadratic. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Decided with the maintainer after consulting Codex and Claude Fable 5.2: the two calls that render the table or the alias again only to compare it with the text of a subclass hook now fall back to SQLAlchemy's default placement on any exception, not only CompileError. SQLAlchemy 2.0 raises IndexError for an empty name, and a name that is not a string raises AttributeError; listing exception types would leave the next one. Without hooks, these calls render what SQLAlchemy has just rendered, so they do not fail and the output does not change. The rename test drops the case without AS that duplicated its neighbor and adds an empty name and a name that is not a string; a new test covers an alias that only the hook can name. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…the hint (GH-1575) - The whole comparison with the text of a subclass hook, including the string operations after the rendering, now runs in AthenaStatementCompiler._split_alias() inside the fallback. SQLAlchemy renders a UserString name as a UserString, which made removeprefix() and removesuffix() raise TypeError after the guarded call. - An unaliased DML target is checked before the hint is read, so update(t).with_hint(None) renders no hint again, as on the merge base, instead of raising AttributeError at hint.upper(). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…1575) Decided with the maintainer after consulting Codex and Claude Fable 5.2: - A hint is recognized only when it is a str (str subclasses such as a str Enum included), as SQLAlchemy annotates it. Any other hint, such as a UserString or bytes, or None passed by a subclass hook, is not read and keeps SQLAlchemy's default placement; an empty one no longer raises where the merge base compiled. - The alias suffix is removed with removesuffix() and compared with !=, as on the merge base. UserString.endswith() rejects a UserString suffix, which moved the hint of a tablesample named by a UserString after its alias. - The DML comment no longer claims that a DML target never has a generated alias. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The comparison with the text of a subclass hook rendered the table or alias again even when its name or schema was not a str. SQLAlchemy's identifier preparer caches what it quotes, so a UserString name stayed in the cache and was returned for a later table named "events", which made the FROM clause raise TypeError where the merge base compiled. Only str names and schemas, as SQLAlchemy annotates them, are compared now; others keep the default placement without rendering again. The rename test drops its UserString case, which the new cache test covers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
isinstance() accepts a proxy that reports str as its __class__, such as Werkzeug's LocalProxy. Rendering a table named by such a proxy to compare it cached the proxy in the identifier preparer, and a later plain table of the same name raised TypeError in the FROM clause, where the merge base compiled. The name and schema are now checked with issubclass(type(...), str), which still accepts str subclasses. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
isinstance() accepts an object that only reports str as its class, such as MagicMock(spec=str). Such a hint on an aliased UPDATE target was read with hint.upper(), and the pattern raised TypeError on the result, where the merge base compiled the statement. The hint is now read only when issubclass(type(hint), str), as for names. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…H-1575) SQLAlchemy cannot render an int name; it renders other objects, such as a proxy of a string, so the comments name the int case instead of every name that is not a string. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
For a generated alias, the text before the alias was the rendering of SQLCompiler.visit_table(), which can be a quoted_name, and that object went to the next format_from_hint_text() in the MRO. A hook that requires an exact str, such as one calling sys.intern(), raised where the merge base compiled. The table text is now the same span of the text the caller passed. The mock hint test now fails if the hint is read, as its name says. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…uard (GH-1575) - A hooked text that ends with AS and no name, such as "events AS ", no longer splits; the alias keyword pattern now needs a name character after AS, as the docstring says. - An UPDATE inside a CTE gets the generated alias from SQLAlchemy; a hook-free test now pins that its hint keeps the default placement, replacing the synthetic hook test, which a check of self.isupdate instead of iscrud also passed. - The alias test with a hook-named alias now also checks that the comparison did not quote a UserString name into the identifier cache. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The time-travel pattern is matched against hint.upper(), which keeps the case of a quoted_name with quote=True. - The alias pattern checks the first character of a name; the rendered table before the match marks where the alias starts. - The docs say to pass the table itself when the SELECT uses it, and the alias when it uses an alias of the table. - The hook test checks the text it receives, not only its type. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
12f69a7 to
6dcc562
Compare
| "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( |
There was a problem hiding this comment.
Rebase before Ready. The PR conflicted with master (tests/pyathena/sqlalchemy/test_compiler.py: #1612 added a CreateView check next to where this PR added _StrProxy). I rebased onto master 244632e and pushed with --force-with-lease against 12f69a7.
git range-diff d653ea71..12f69a70 244632e2..6dcc5625: all 16 patches are equal, except the context of the commit that adds_StrProxy; both helpers are kept.- Upstream changes since d653ea7 that touch
pyathena/sqlalchemy/compiler.py(Keep the ARRAY lambda variable from capturing names in stored and ordinary SELECTs (GH-1571) #1612 lambda names, Name the catalog in the query context only when it is not AwsDataCatalog (GH-1604) #1624 catalog context, Keep no default schema from a connection that fails to initialize the dialect (GH-1572) #1583, Render inline Decimal values as Athena DECIMAL literals (GH-1483) #1573, Decode float ARRAY elements and import the compliance suite on SQLAlchemy 2.1 (GH-1569) #1577, Require SQLAlchemy 2.0.52 (GH-1574) #1600) do not touch the hint path. - Differential check: the new merge base, run twice, is stable on SQLAlchemy 2.0.52 (the new master minimum), 2.0.58 and 2.1.9. Its output equals the old merge base's. The rebased head is identical to 12f69a7 and still differs from the base in exactly the 2536 expected cases.
- Tests:
just lintandjust docs lintpass.just test offlinegives 4811 passed, 2 skipped. Time-travel/hint tests: 36 passed on 2.0.52 and 2.1.9.
No new review round: the patches are unchanged, and the upstream changes do not affect the reviewed contracts.
Appending the line break first made a quoted_name hint a plain str, so the time-travel recognition upper-cased a quote=True hint that #1582 leaves in its own case and moved it before the alias. Recognition now reads the hint as given, and only the text passed on to SQLAlchemy ends with the line break. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
WHAT
AthenaStatementCompiler.format_from_hint_text()places a time-travel hint (FOR TIMESTAMP AS OF,FOR SYSTEM_TIME AS OF,FOR VERSION AS OF,FOR SYSTEM_VERSION AS OF) before an alias in two more cases. The change stays insideformat_from_hint_text(). It uses no private SQLAlchemy API, renders the hint text unchanged, and keeps the fallback to SQLAlchemy's default placement.FROM events AS events_1, db.events).SQLCompiler.visit_table()then passes the table followed by that alias.SQLCompiler.visit_table(self, table, asfrom=True), which renders the table without the generated alias. The hint goes between the two parts:FROM events FOR VERSION AS OF 1 AS events_1, db.events.ASin any case, and whitespace right after the table.AS, and an error from that rendering falls back)hint.upper()against[ \t\r\n]*FOR[ \t\r\n]+(?:TIMESTAMP|SYSTEM_TIME|VERSION|SYSTEM_VERSION)[ \t\r\n]+AS[ \t\r\n]+OF. This replaces the fourstartswith()prefixes. The only change in recognition is whitespace: leading whitespace, and line breaks, tabs or repeated spaces between the keywords (as in a triple-quoted string). Upper-casing (hint.upper(), which keeps the case of aquoted_namewithquote=True) and prefix matching are the merge base's.for version as of,FOR VERſION AS OF(U+017F, whichstr.upper()folds toS) andFOR VERSION AS OFTENare recognized as before.FOR VERSİON AS OF(U+0130) and a NO-BREAK SPACE between the keywords are not recognized, as before.docs/sqlalchemy.md(time travel) states when SQLAlchemy can generate the alias and that the table itself goes towith_hint().The split check, the recognition and the scope below were decided by the maintainer after Codex and Claude Fable 5.2 were consulted.
Scope of the guarantee.
SQLCompiler.visit_table()renders it, withASand a name.AS, and a table or alias that SQLAlchemy cannot render: the comparison with the hook's text (_split_alias()) falls back on any error.str(subclasses included), as SQLAlchemy annotates them. Types are checked withtype(), which a proxy or mock cannot fake. A hint of any other type (UserString,bytes,None, a mock) is not read, and a table or alias whose name or schema is of another type is not rendered again; both keep the default placement. For such inputs PyAthena guarantees only that it adds no exception; differences in their output are not regressions.strsubclass that overridesstrmethods (for examplemarkupsafe.Markup) is out of scope. SQLAlchemy's identifier preparer caches such a name whenever SQLAlchemy itself renders the table, with the same effect on later statements.super().format_from_hint_text()receives the table text without the alias, whatever made the alias, as for explicit aliases since Render the time-travel hint of an aliased table before its alias #1547. A hook later in the MRO that overridesformat_from_hint_text()and reads an alias from itssqltextis out of scope, even if the statement compiled on the merge base: its output there put the hint after the alias, which Athena rejects.SQLCompiler.visit_table()/visit_alias(), which caches names in the dialect's identifier preparer exactly as SQLAlchemy does when it renders that element, one of its columns, or any same-named table in any statement. What a later rendering gets back from that cache, including itsstrsubclass, is out of scope.Review stop rule (maintainer decision after consulting Codex and Claude Fable 5.2). The next independent round is the final one. After it, only these are actionable:
strorquoted_name.Findings that need a subclass hook, another name or hint type, or shared preparer state are recorded on the PR and not fixed. Repairs are checked by one round limited to the repair diff.
Not changed:
/* c */ FOR VERSION AS OF 1) is not recognized, as before..params()and.unique_params()still drop the hint of a directly selected alias. That is an upstream defect, tracked in Track upstream: SQLAlchemy 2.0 params()/unique_params() drop the FROM hint of a selected alias #1576.WHY
Fixes #1575 (part of #1494). Both cases rendered the hint after the alias, which Athena rejects with a syntax error. Before #1547, the generated-alias case raised
AttributeError.This is a compatible fix for
4.xtoo. The4.xbackport of #1503 (#1578) has been merged, so this PR needs its own4.xbackport. The patch applies cleanly to the current4.x(a23d009), and the differential check gives the same output there.TEST
Tested commit: 6dcc562 (rebased onto master 244632e; the patch series is unchanged by
git range-diff, apart from the context of one test helper).just lintandjust docs lint: passed.just test offline: 4811 passed, 2 skipped (after the rebase).tests/pyathena/sqlalchemy/test_compiler.py -k "time_travel or hint", offline:4.x(a23d009, which supports SQLAlchemy 2.0.23 or later): 36 passed on 2.0.23 and 2.1.9, under Python 3.12. SQLAlchemy 2.0.23 does not import on Python 3.15, the project's default.New tests:
asand a comment that reads the alias name (1). Fails on the merge base.schema_translate_map; an empty name; an int name; andASwithout a name.UserStringor by a proxy that reportsstras its class, next to a table namedevents(2). Passes on the merge base. It checks that the comparison leaves the identifier preparer's quoting cache alone.intname and aUserStringname), which also checks that the name is not left in the identifier cache. Fails on the merge base, which raised there.update(t).with_hint(None)renders no hint (1). Passes on the merge base.UserStringorbyteshint on a table renders no hint (2). Passes on the merge base.isinstance(x, str)(a mock whoseupper()raises) is not read (1). Fails on the merge base, which read it.str(1). Fails without the fix.UPDATEtarget inside a CTE, which SQLAlchemy gives a generated alias, keeps the default placement (1). Passes on the merge base.Mutation check of
format_from_hint_text(). Each mutant fails at least one test:not iscrudstr, or checking it withisinstance()stragain, or checking it withisinstance()get_render_as_alias_suffix("")AScheckASAS.upper()endswith()check withTrueFour mutants are not caught by a test.
endswith()changes only the output for a name that is not astr, which the scope excludes.except ExceptiontoCompileError,IndexErrorandAttributeErrorsurvives, because thestrchecks now stop the tested non-string names first; the broadexceptstays as decided.ASpre-check and the lookbehind change only the running time and were measured instead. Dropping the lookbehind of theASpattern: a hook returningeventsplus 8192 spaces compiles in 0.2 ms, and without the lookbehind in 132 ms (36 ms at 4096 spaces). Dropping theASpre-check: it only skips a needless rendering.Live,
-n 1:tests/pyathena/sqlalchemy/test_base.py -k temporal: 3 passed (at eb46fa4). These three tests only compile statements and do not query AWS. No live query runs a time-travel clause. That Athena rejects a hint after an alias, and accepts the moved form, follows from Render the time-travel hint of an aliased table before its alias #1547 and Trino's grammar.Differential check (
/tmp/pyathena-1575/harness.py, not committed). It covers 9193 cases (rebuilt after a machine restart wiped/tmp). Each case gives the SQL, or an exception, for 10 dialects (5 sync, 5 aio), and all dialects agree in every case.db.events, no schema,"My Schema"."Weird Table",BASIC,"my AS t","AS"} × aliases {none,a, anonymous,"My Alias","x AS y", nested} × 35 hints × compile-timeschema_translate_map{none, translate, toNone}. The hints are:OF(1)FORVERSION,ASOF,OFFICE,OF1,VERSIONS, leading comments, NBSP,ſ,İ, …)WITH (NOLOCK),TABLESAMPLE, empty, blank and%(name)sAS,events_1) × 2 schemas × hint target {schemaless, qualified, both} × order {schemaless first, qualified first,JOIN} × 18 hints × 3 maps.schema_translate_map, through the offline recording engine.tablesample, dialect-specific hints,UPDATE/DELETE, anUPDATEinside a CTE, ORMaliased()(nested, anonymous, in a pair), an ORM pair,table().visit_table()orvisit_alias()in SELECT,UPDATEandDELETE, and avisit_table()hook that renders the table under another name.4.x(a23d009) gives the same output as master, both without and with this patch.events AS events_1 ... AS a, on both the base and the branch. In that one case, the comparison script also moved the hint of the alias half, which the branch correctly leaves as on the base.Not run:
just test sqla/just test sqla-asyncand the full live suite (left to CI when the PR is marked Ready).🤖 Generated with Claude Code