Skip to content

End a hint's trailing line comment with a line break - #1644

Merged
laughingman7743 merged 5 commits into
masterfrom
fix/1598-line-comment-hint
Dec 1, 2026
Merged

laughingman7743 merged 5 commits into
masterfrom
fix/1598-line-comment-hint

Conversation

@laughingman7743

@laughingman7743 laughingman7743 commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

WHAT

A FROM hint (with_hint()) or a statement hint (with_statement_hint()) whose last line contains -- now ends with a line break ("\n"), so a trailing line comment ends with the hint.

  • FROM hints: AthenaStatementCompiler.format_from_hint_text() passes the hint with the line break to SQLAlchemy's placement. The time-travel recognition still reads the hint as given. Every FROM element and placement is covered: SQLAlchemy's default placement after the element (tables, subquery aliases, DML targets) and PyAthena's placement of a time-travel hint before an alias (explicit and generated aliases, Render the time-travel hint of an aliased table before its alias #1547 / Place a time-travel hint before a generated alias and accept irregular whitespace (GH-1575) #1582).
    • FROM events FOR VERSION AS OF 1 -- audit\n, other
    • FROM events FOR VERSION AS OF 1 -- audit\n JOIN other ON ...
    • FROM events FOR VERSION AS OF 1 -- audit\n AS a, other
    • DELETE FROM events -- audit\n WHERE events.id = 1
  • Statement hints: get_statement_hint_text() (new override) appends the line break to each statement hint before SQLAlchemy joins them: FROM events -- first\n -- second\n UNION ALL SELECT ....
  • Rule: "--" in hint.rpartition("\n")[2], for a hint whose type is str or a subclass (checked with type(), as Place a time-travel hint before a generated alias and accept irregular whitespace (GH-1575) #1582 does). The check splits at "\n" only. A comment followed by a bare "\r", where Trino already ends it, gets a redundant line break.
    • A -- that is not a comment, such as one in a string literal, a quoted identifier substituted for %(name)s, or a block comment, adds only the line break. A line break between tokens does not change what the statement does, so no SQL is lexed.
    • A hint that already ends with a line break, or whose comment is on an earlier line, is unchanged.
    • A hint that is not a string is passed through unchanged.
  • The design of Place a time-travel hint before a generated alias and accept irregular whitespace (GH-1575) #1582 is unchanged. The time-travel recognition reads the hint as given, so a quoted_name with quote=True keeps its own upper(). _split_alias() does not read the hint.
  • Also: the comment of the test_time_travel_hint_of_table_renamed_by_hook parameters now scopes the empty-name case to SQLAlchemy 2.0 (2.1 renders ""), with the same wording as the 4.x commit 286b3b0 ([4.x] Backport #1582 and #1633 #1640).

Compatibility. The SQL string changes only for a hint whose last line contains --. Such a statement was either rejected or ran a different query, except when the hint's line ended anyway, as before the \nWHERE of a SELECT. That statement now has one more line break, so a result cache keyed by the query string sees a new string once. Candidate for a 4.x backport after merge.

Scope (carried over from #1582). Compiler hooks are best effort: a subclass get_from_hint_text(), or a format_from_hint_text() later in the MRO, receives the hint with the line break. Text from prefix_with(), suffix_with(), text() and literal_column() is the caller's SQL and is not changed. No public hook renders prefixes or suffixes; they go through the private SQLCompiler._generate_prefixes(). For hints and names that are not strings, PyAthena guarantees only that it adds no exception. Rejected design options (consulted with Codex and Claude Fable 5.2, decided by the maintainer): documentation only (leaves silent wrong results, including a DELETE without its WHERE), a CompileError (rejects statements that work today), checking the rendered result instead of the hint, and treating a bare "\r" as a line end.

WHY

Closes #1598.

SQLAlchemy renders what follows a hint on the hint's line: another FROM element, a JOIN, the alias that PyAthena places after a time-travel hint, the SET or WHERE of an UPDATE or DELETE target, a UNION, or a closing parenthesis. A hint that ended with a line comment turned that text into a comment. Athena then rejected the statement or ran a different one: a count(*) over two FROM elements counted only the first, a JOIN disappeared, and delete(t).where(...).with_hint("-- audit") rendered DELETE FROM t -- audit WHERE ..., which Athena reads as a DELETE without a WHERE clause.

TEST

Tested commit: 7301e92 (on master 72c955e; master's changes since the harness base edb54b7 touch only the filesystem and one filesystem test stub).

  • just lint: passed.
  • just test offline: 5157 passed, 12 skipped.
  • just benchmark test (on d5e9dce; later commits change only the hint path and tests): 363 passed, 1 skipped.
  • New tests in tests/pyathena/sqlalchemy/test_compiler.py compare exact strings (no whitespace normalization): test_hint_ending_with_line_comment_ends_its_line (two FROM elements with a comment on the hint's second line, JOIN, alias, generated alias, subquery, DELETE, UPDATE, a quoted_name time-travel hint that is not recognized, \r, already-terminated, comment on an earlier line) and test_statement_hint_ending_with_line_comment_ends_its_line. The proxy test test_hint_that_only_passes_isinstance_is_not_read also traps rpartition(). Mutation check: removing either call, recognizing the hint with the line break, always appending, a \r-aware rule, checking the whole hint, skipping multiline hints, and an isinstance() guard each fail at least one test.
  • Differential check (offline, /tmp/pyathena-1598/diff, built on the SQLAlchemy time-travel hint follows a SQLAlchemy-generated alias and misses hints with irregular whitespace #1575 harness; merge base edb54b7 run twice per SQLAlchemy version, identical): 13,503 cases × 10 dialects (sync and aio rest/pandas/arrow/polars/s3fs) on SQLAlchemy 2.0.52 and 2.1.9. The matrix covers tables, aliases, generated aliases, ORM, DML targets, schema_translate_map at compile and execution time, compiler hooks, and the shapes of A SQLAlchemy FROM hint that ends with a line comment swallows the rest of its line #1598 (two FROM elements with a comment on the hint's second line, JOIN, outer join, subquery, CTE, EXISTS, UNION, DELETE/UPDATE with WHERE, dialect-specific hints), with 12 line-comment hints, 4 quoted_name hints and statement hints (*, awsathena, mysql). Expected: every rendered occurrence of a hint whose last line contains -- gains "\n", nothing else changes, and no new exception. Result: 2,745 expected changes, 2,745 differences, 0 problems on both versions.
  • Not run: live AWS tests (no live test renders a hint with a line comment; the existing time-travel tests in test_base.py compile only) and just test sqla / sqla-async, which run in AWS CI when the PR is marked Ready.

laughingman7743 and others added 2 commits December 1, 2026 22:28
GH-1575)

SQLAlchemy 2.0 raises IndexError for an empty table name, but 2.1
renders it as "", so on 2.1 the empty-name case keeps the default
placement because the hooked text does not start with the rendering.
Comment only; same wording as 4.x commit 286b3b0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SQLAlchemy renders what follows a FROM hint or a statement hint on the
hint's line: another FROM element, a JOIN, the alias that PyAthena
places after a time-travel hint, the WHERE or SET of an UPDATE or
DELETE target, a UNION, or a closing parenthesis. A hint that ended with
a line comment turned that text into a comment, so Athena rejected the
statement or ran a different one; a DELETE lost its WHERE clause.

A hint whose last line contains "--" now ends with a line break, in
format_from_hint_text() for every FROM element and placement, and in
get_statement_hint_text() for each statement hint. Only "\n" ends a
line, and a "--" that is not a comment adds only the line break, which
does not change what the statement does. Hints that are not strings are
passed through as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@laughingman7743 laughingman7743 added this to the 5.0.0 milestone Dec 1, 2026
Look the statement up by its shape, so a new or misspelled shape fails
instead of compiling an UPDATE. Give the earlier-line case a hint that
does not start with a comment, since a time-travel hint is recognized
only after whitespace. Name the "\r" case for what it shows, and say
that the line break does not change what the statement does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread pyathena/sqlalchemy/compiler.py Outdated
Returns:
The FROM element with the hint.
"""
hint = self._end_line_comment(hint)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Self-review round 1 (behavior and implementation): FINDINGS → repaired in 6390d41

Scope: git diff 72c955e52ea25eedfb898fe6684edfabd312ef3c..d5e9dce3d8ca9fc8301ec340ee0276b8bb149465, frozen in a detached snapshot. Inventory: format_from_hint_text() (line break before both placements), the new get_statement_hint_text() and _end_line_comment(), the two new tests, and the scoped test comment from 4.x 286b3b0. Run with /code-review high and /simplify (4 angles: reuse, simplification, efficiency, altitude), plus the differential check (/tmp/pyathena-1598/diff: 13,027 cases × 10 dialects, SQLAlchemy 2.0.52 and 2.1.9; base run twice, stable; 2,394 expected changes, 0 problems, rerun on 6390d41) and a mutation check (5 mutants, all killed).

Repaired in 6390d41:

  • test_compiler.py comment_on_earlier_line: the hint -- audit\nFOR VERSION AS OF 1 read as support for a time-travel hint that starts with a comment, which Place a time-travel hint before a generated alias and accept irregular whitespace (GH-1575) #1582 does not recognize: on an alias it lands after the alias. Replaced with FOR VERSION AS OF 1 -- audit\n/* note */.
  • Test id carriage_return_is_not_a_line_end → comment_before_carriage_return: Trino ends a line comment at \r. The check splits at \n only, so the line break it adds there is redundant but harmless.
  • The shape dispatch ended in a bare else (UPDATE), so a misspelled shape would have tested UPDATE. It is now a dict lookup (KeyError).
  • _end_line_comment() docstring: Returns shortened; "does not change what the statement does" instead of "does not change the statement".

Not adopted:

  • Removing the issubclass(type(hint), str) check of the recognition as a duplicate: it is still needed. _end_line_comment() returns a non-str hint unchanged, and the recognition then calls hint.upper().
  • An INSERT test: INSERT goes through the same iscrud path as DELETE/UPDATE (_setup_crud_hints), so the test would add no new evidence. No docs change: the maintainer decided this.
  • Merging the two "type itself" comments: the one in the recognition is Place a time-travel hint before a generated alias and accept irregular whitespace (GH-1575) #1582's code, which this PR does not change.
  • Efficiency, reuse: no findings.

Open, asked of the maintainer (consulting Codex and Claude Fable 5.2 first): moving the FROM-hint line break into the existing get_from_hint_text() override (altitude), and prefix_with()/suffix_with() text that ends with -- (same defect, rendered through private SQLCompiler._generate_prefixes() / visit_select).

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.

Open items of round 1, after consulting Codex and Claude Fable 5.2 (both agree): neither changes the approved design.

  • Move the FROM-hint line break into get_from_hint_text(): not adopted. SQLAlchemy's own paths (visit_table, visit_alias, _setup_crud_hints, the only callers of format_from_hint_text(), 2.0.52 and 2.1.9) render the same SQL either way. Compiler hooks do not. Today, a subclass that overrides get_from_hint_text() without super(), or a format_from_hint_text() later in the MRO that appends hint itself, receives the hint with its line break. After the move it would not. The move would also go beyond the methods that the maintainer named.
  • prefix_with() / suffix_with() text that ends with --: no action. No public hook renders that text. SELECT/DML prefixes and SELECT suffixes go through the private SQLCompiler._generate_prefixes() from inside visit_select/DML visitors (2.0.52 sql/compiler.py:5156, 2.1.9 :5560). post_process_text() would rewrite every text(), which means lexing the caller's raw SQL. Like text() and literal_column(), the fragment is the caller's SQL, and PyAthena adds nothing to it. .suffix_with("-- x\n") works as is.

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>
"""
# The time-travel recognition reads the hint as given: a quoted_name
# keeps its own upper().
ended = self._end_line_comment(hint)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Self-review round 2 (claims, compatibility, operational effects): FINDINGS → repaired in a639d72

Scope: git diff 72c955e52ea25eedfb898fe6684edfabd312ef3c..6390d419171a77e7cf3c18dc455d10a5972f91cb (full pass over the PR body, docstrings, comments, commit messages and the issue premises). Covered: existing callers (str, str subclasses incl. quoted_name and StrEnum, non-str hints, SQLAlchemy 2.0.52 and 2.1.9, all 10 sync/aio dialects), hooks (MRO-next formatter, get_from_hint_text override, @compiles), statement hints (*/awsathena/mysql, subquery, CTE, UNION, LIMIT), DML targets, and AWS effects (no new requests; query-string-keyed result cache sees a new string once for an affected statement).

Finding (regression, repaired):

  • The line break was appended before the time-travel recognition. quoted_name + "\n" is a plain str, so quoted_name("for version as of 1 -- q", True), which Place a time-travel hint before a generated alias and accept irregular whitespace (GH-1575) #1582 leaves unrecognized (its upper() keeps the case), was upper-cased, recognized, and moved before the alias: FROM db.events for version as of 1 -- q\n AS a instead of FROM db.events AS a for version as of 1 -- q\n. The differential check had no quoted_name hint; 4 were added (78 mismatches before the repair). Repair: recognition reads the hint as given; only the text passed to super().format_from_hint_text() ends with the line break. New test case quoted_name_keeps_recognition; mutation "recognize the hint with the line break" is killed. Harness rerun (base twice per version, stable): 13,503 cases, 2,745 expected changes, 0 problems on 2.0.52 and 2.1.9.

Claim corrections (PR body):

  • "Only \n ends a line" → the check splits at \n only; a comment before a bare \r (which Trino already ends) gets a redundant break.
  • "recognition and _split_alias() see the same hint plus the line break" → recognition reads the hint as given; _split_alias() does not read the hint.
  • DELETE example: "deletes every row" → "which Athena reads as a DELETE without a WHERE clause" (not run live).
  • Scope now names the hooks that receive the line break and the raw-SQL fragments that are not changed.

Checked, holds: rendered examples in the body (harness output); DML SET/WHERE on the hint's line (SQLAlchemy visit_update/visit_delete); statement hints only on SELECT (_render_select/_compose_select_body); 4.x has the same hooks in 2.0.44 (checked at backport). The d5e9dce commit message's "Only "\n" ends a line" defines the rule's notion of a line and is kept.

…1598)

The two-FROM case now uses a hint whose comment is on its second line,
so a rule that skipped multiline hints fails. The proxy test also traps
rpartition(), so the new type check cannot fall back to isinstance().
The docstring limits "does not change what the statement does" to a
literal that the hint closes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
a closing parenthesis. A line comment at the end of the hint would turn
that text into a comment. A hint whose last line contains ``--`` gets a
line break, even when the ``--`` is not a comment, such as one in a
string literal that the hint closes; a line break between tokens does

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Independent review (relayed): Codex CLI (codex exec -s read-only, fresh session 01a231df-75e8-7f60-99da-e0d619c45320), static review with offline compilation and offline tests run by the reviewer; FINDINGS (3 × Low) → repaired in 7301e92

Package: detached snapshot of a639d72f21ae601bb624057174e024169edba061, diff 72c955e52ea25eedfb898fe6684edfabd312ef3c..a639d72f21ae601bb624057174e024169edba061, the differential harness (read-only), the maintainer-decided constraints; no PR text, commit messages or prior findings. Snapshot and PR worktree verified unchanged afterwards.

Reviewer coverage: tables, explicit and generated aliases, JOINs, subqueries, CTEs, INSERT/UPDATE/DELETE targets, statement-hint sequences, UNION, quoted_name(..., True) time-travel placement; the hint tests on SQLAlchemy 2.0.52–2.0.58 and 2.1.0–2.1.9 (49 passed on each); all 11 added cases that expect changed SQL fail on the merge base; harness: exactly the 2,745 expected differences per version. The renamed-table comment is accurate on 2.0 (IndexError) and 2.1 ("").

Findings and repairs:

  1. Low — no added case had a hint with an existing \n: a rule that skipped multiline hints passed all tests (FOR VERSION AS OF 1\n--audit → --audit, other). Repair: the two-FROM case uses FOR VERSION AS OF 1\n-- audit.
  2. Low — replacing the new issubclass(type(hint), str) with isinstance() passed all tests; a str-spec proxy would then hit rpartition(). Repair: test_hint_that_only_passes_isinstance_is_not_read also traps rpartition().
  3. Low — docstring: two statement hints that split one literal ("WHERE length('x--", "y') = 5") change meaning ('x-- y' → 'x--\n y'). Repair: the claim is limited to a literal that the hint closes. The behavior stays: a literal split across hints is a lexing case left to the caller (PyAthena does not lex SQL).

Validation of the repair: just lint ok; just test offline 5157 passed, 12 skipped; mutation check (8 mutants incl. isinstance() guard and skip-multiline) all killed; compiler code unchanged except the docstring, so the harness result stands. Both self-review perspectives on the repair: tests and wording only, no contract change. A narrow independent follow-up on the repair is running.

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 follow-up (relayed): Codex CLI (codex exec -s read-only, fresh session 01a231f0-5820-74d3-ae10-8bd2eb18008a), narrow review of git diff a639d72f21ae601bb624057174e024169edba061..7301e929 against the three findings: CLEAN.

  • The two-FROM case requires FROM events FOR VERSION AS OF 1\n-- audit\n, other; it passes, and fails when multiline hints are skipped.
  • The proxy test passes on the merge-base compiler and on the head; changing only _end_line_comment() to isinstance() makes it fail on rpartition().
  • The docstring limits its claim to a line break between tokens; a literal split across two hints is outside it.

Snapshot and PR worktree verified unchanged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A SQLAlchemy FROM hint that ends with a line comment swallows the rest of its line

1 participant