Skip to content

Use parameterized queries in HiveStatsCollectionOperator - #66751

Merged
potiuk merged 6 commits into
apache:mainfrom
Har1sh-k:parameterize-hive-stats-sql
Aug 19, 2026
Merged

potiuk merged 6 commits into
apache:mainfrom
Har1sh-k:parameterize-hive-stats-sql

Conversation

@Har1sh-k

@Har1sh-k Har1sh-k commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

HiveStatsCollectionOperator builds its SQL by f-string-interpolating template-rendered fields (table, partition, dttm) directly into raw SQL strings: the SELECT and DELETE against hive_stats in the MySQL metastore, and the SELECT ... FROM <table> WHERE <partition_key> = '<value>' against Presto.

This is a robustness and correctness fix, not a security fix. Under Airflow's security model the Dag author is a trusted party who can already execute arbitrary code, so operator arguments are not an untrusted input boundary and there is no vulnerability here. Please do not route this through the security process or read the merge as a silent CVE fix.

What the current code does get wrong is ordinary correctness. Any table or column name that is not a plain word identifier is interpolated bare and produces invalid SQL, so a Dag over a table with a hyphenated or spaced column name fails outright with a Presto parse error rather than collecting stats. Binding the values as parameters and quoting the identifiers fixes that, and as a side effect retires the string-concatenation pattern that sql.rst discourages.

What changed

  • The MySQL SELECT and DELETE use %s placeholders with the parameters= kwarg of MySqlHook.get_records / .run, so values are bound by the driver instead of interpolated.
  • For the Presto SELECT, partition values are passed as bound parameters using the hook's declared placeholder (PrestoHook overrides DbApiHook's default %s to ?), rather than hardcoding ?, so a connection that overrides placeholder still works.
  • Identifiers cannot be parameterized in standard SQL, so the table name, the partition column names, and the projected column names and aliases are quoted instead. Plain word identifiers are emitted unchanged, correctly pre-quoted identifiers are passed through untouched, and anything else is double-quoted with embedded quotes doubled. A column named weird-col now renders as COUNT("weird-col") where it previously emitted invalid SQL.
  • The table name is split into catalog/schema/table components only on the dots outside a quoted identifier, so a quoted name containing a dot ("my.table", db."odd.name") stays a single identifier instead of being split and re-escaped.

extra_exprs and assignment_func still accept Dag-authored SQL expressions by design and are intentionally unchanged.

Test plan

  • test_quote_presto_identifier pins the identifier helper: plain, special-character, pre-quoted, embedded-doubled-quote, dotted-and-quoted, and malformed-quote inputs.
  • test_quote_presto_table pins the qualified-name assembly: bare, dotted-plain, special-character-per-component, pre-quoted, embedded-quote, and quoted-containing-a-dot names, plus a trailing-SQL input that stays one inert component.
  • test_execute_quotes_table_identifier, test_execute_quotes_partition_column and test_execute_quotes_special_char_projection_column assert the quoting reaches the emitted Presto SQL, and that the quoting does not leak into the values written to hive_stats.col.
  • test_execute_parameterizes_mysql_bookkeeping_queries and test_execute_parameterizes_presto_partition_values verify the SQL is parameterized (no interpolation of table / partition values into the SQL body) and that the Presto query uses the hook's ? placeholder.
  • test_execute_delete_previous_runs_rows and test_runs_for_hive_stats updated to assert the parameterized form.
  • Full test_hive_stats.py module passes locally.

Was generative AI tooling used to co-author this PR?
  • Yes (Claude Opus 4.7, and Claude Opus 5 for the later review rounds)

I used Claude to assist with this PR, following the Gen-AI Assisted contributions guidelines:

  • I reviewed and understand the generated code. The quoting rules, the qualified-name splitting, the move to presto.placeholder, the MySQL parameterization, and the tests were iterated against the Presto/Trino identifier grammar and the Airflow security docs rather than blindly accepted.
  • Ruff lint and format checks (pinned ruff==0.15.12) pass on both changed files.
  • The diff is scoped to two files under providers/apache/hive/ with no unrelated changes.
  • The added unit tests are part of the diff and will run in CI.
  • I take final responsibility for the change.

@boring-cyborg

boring-cyborg Bot commented May 12, 2026

Copy link
Copy Markdown

Congratulations on your first Pull Request and welcome to the Apache Airflow community! If you have any issues or are unsure about any anything please check our Contributors' Guide
Here are some useful points:

  • Pay attention to the quality of your code (ruff, mypy and type annotations). Our prek-hooks will help you with that.
  • In case of a new feature add useful documentation (in docstrings or in docs/ directory). Adding a new operator? Check this short guide Consider adding an example Dag that shows how users should use it.
  • Consider using Breeze environment for testing locally, it's a heavy docker but it ships with a working Airflow and a lot of integrations.
  • Be patient and persistent. It might take some time to get a review or get the final approval from Committers.
  • Please follow ASF Code of Conduct for all communication including (but not limited to) comments on Pull Requests, Mailing list and Slack.
  • Be sure to read the Airflow Coding style.
  • Always keep your Pull Requests rebased, otherwise your build might fail due to changes not related to your commits.
    Apache Airflow is a community-driven project and together we are making it better 🚀.
    In case of doubts contact the developers at:
    Mailing List: dev@airflow.apache.org
    Slack: https://s.apache.org/airflow-slack

HiveStatsCollectionOperator builds its bookkeeping SQL (the SELECT
and DELETE against hive_stats in the MySQL metastore, and the
SELECT ... FROM <table> WHERE <partition_key> = '<value>' against
Presto) by f-string-interpolating template-rendered fields (table,
partition, dttm) directly into raw SQL strings.

Per the security model in airflow-core/docs/security/security_model.rst
and airflow-core/docs/security/sql.rst, Dag authors are trusted users
responsible for sanitizing input before passing it to operators. The
change here is defense-in-depth so that the operator does not rely on
each Dag author to sanitize.

The MySQL bookkeeping SELECT and DELETE now use %s placeholders with
the parameters= kwarg of MySqlHook.get_records / .run, so the values
are bound by the driver instead of interpolated.

For the Presto SELECT, partition values are passed as bound parameters
using the hook's declared placeholder (PrestoHook overrides the
DbApiHook default to "?"). Identifiers (table name and partition
column names) cannot be parameterized in standard SQL — they are
validated against ^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?$
for the table and ^[A-Za-z_][A-Za-z0-9_]*$ for partition keys, raising
AirflowException on mismatch.
@Har1sh-k
Har1sh-k force-pushed the parameterize-hive-stats-sql branch from 7ed5db6 to 4bb0946 Compare May 12, 2026 03:59
@Har1sh-k
Har1sh-k marked this pull request as ready for review May 12, 2026 04:04
…nOperator

The static check `check-no-new-airflow-exceptions` flagged the two new
`raise AirflowException` calls added in this PR (the table-identifier
allowlist and the partition-column allowlist).

Switch both to `raise ValueError`, matching the existing input-validation
pattern in the same provider (sensors/named_hive_partition.py:81 raises
`ValueError` for an invalid partition string).

This keeps the pre-existing `raise AirflowException("The query returned
None")` at line 161 untouched (that one is in the allowlist already) and
restores the AirflowException count for this file to its prior value.
@potiuk potiuk added the ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green. label May 18, 2026

@Nataneljpwd Nataneljpwd left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looks good overall yet it won't work for all cases such as columns with special chars which is a breaking change, in presto it uses " and in MySQL it uses backticks, I think that it needs to be fixed before it can be merged

…jecting them

The previous approach rejected any table or column identifier that was not a
plain word, which broke valid Hive identifiers containing dashes or spaces.
Instead, quote every identifier interpolated into the Presto stats query -- the
table in FROM (per dotted component, so database.table still works), the
partition columns in WHERE, and the metastore columns and their aliases
projected in the SELECT -- using double quotes with embedded quotes doubled.
Plain identifiers are still emitted bare, so existing Dags are unaffected.
Partition values and the MySQL bookkeeping values stay bound as query parameters.
@Har1sh-k

Har1sh-k commented Jun 3, 2026

Copy link
Copy Markdown
Contributor Author

Pushed a fix. I dropped the reject-regex and instead quote the identifiers that get interpolated into the Presto SELECT: the table in FROM (quoting each component of a db.table name), the partition columns in WHERE, and the column names and their aliases in the projection (COUNT(col), SUM(col), and so on). Plain identifiers are still emitted unquoted like before, and anything with dashes or spaces is double-quoted with embedded quotes doubled, so a column like weird-col now renders as COUNT("weird-col") instead of failing. Added a unit test covering the special-character column.

@Nataneljpwd Nataneljpwd left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

looks better, one last edge case and we are done

An identifier the caller already double-quoted (e.g. "weird-col") was
re-escaped into """weird-col""", breaking the Presto stats query for users
who quoted identifiers themselves. Recognize a well-formed double-quoted
identifier and pass it through unchanged; anything else is still
double-quoted with embedded quotes doubled, so injection payloads stay
inert as a single identifier.

@Nataneljpwd Nataneljpwd left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looks great!

Now there is no SQL injection nor will it break old queries, unless I missed something which I don't think so
Great job!

@Har1sh-k

Har1sh-k commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor Author

CI failed once here on a transient Docker Hub issue, not on this change. The Build documentation (--spellcheck-only) job died on its very first step — the runner workspace-cleanup that pulls bash:latest to rm -rf the workspace:

docker: Error response from daemon: Get "https://registry-1.docker.io/v2/": net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)
Error: Process completed with exit code 125.

That's a Docker Hub registry timeout on the runner (exit 125 = docker run couldn't pull the image), unrelated to the diff — every other check on the PR was green. Re-triggered with a fresh commit.

@Har1sh-k

Copy link
Copy Markdown
Contributor Author

@potiuk , following up...Any more checks pending?

@potiuk potiuk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks — this is a solid hardening pass. Moving the Presto WHERE values and the MySQL statements onto bound parameters is exactly right, and using presto.placeholder rather than hardcoding ? is a nice touch for connections that override it.

I tried to break _quote_presto_identifier and couldn't — "a" OR 1=1 --" comes back as """a"" OR 1=1 --""", a single correctly-escaped identifier, and the _QUOTED_IDENT_RE pass-through can't be fooled into leaving an unbalanced quote. The escaping logic itself is sound.

One genuine bug in how the table name is assembled, plus a note on the helper — both inline.

On framing: worth being explicit in the PR description that this is a robustness/correctness fix rather than a security vulnerability. Under Airflow's security model the Dag author is a trusted party who can already execute arbitrary code, so operator arguments aren't an untrusted input boundary. Saying so plainly avoids anyone routing this through the security process or reading the merge as a silent CVE fix.


Drafted-by: Claude Code (Opus 5); reviewed by @potiuk before posting

Quoting the table name per `self.table.split(".")` component treated a dot
inside a quoted identifier as a catalog/schema separator, so each fragment
matched neither the plain-identifier nor the quoted-identifier regex and both
halves were re-escaped: `"my.table"` became `"""my"."table"""` and
`db."odd.name"` became `db."""odd"."name"""`. Plain `db.tbl` and bare `tbl`
were unaffected, so this only hit the quoted-with-dot case, which is exactly
the case the quoting support exists for.

Move the assembly into `_quote_presto_table`, which splits on the dots
*outside* a quoted identifier, leaving a quoted component that contains a dot
intact.

Add `test_quote_presto_table` pinning the pass-through behaviour (bare,
qualified-plain, special-character, pre-quoted, embedded doubled quote, and
quoted-containing-a-dot), so a future refactor cannot quietly reintroduce the
double-escaping, plus the dotted cases at the emitted-SQL level in
`test_execute_quotes_table_identifier`.
@Har1sh-k

Har1sh-k commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @potiuk , both addressed, and I rewrote the PR description along the lines you suggested.

The table-name split. You're right, and both examples reproduce exactly as you posted them. The assembly now lives in _quote_presto_table, splitting only on the dots outside a quoted identifier with the regex you proposed:

_QUALIFIED_NAME_PART_RE = re.compile(r'"(?:[^"]|"")*"|[^.]+')

def _quote_presto_table(table: str) -> str:
    return ".".join(_quote_presto_identifier(part) for part in _QUALIFIED_NAME_PART_RE.findall(table))

"my.table" now stays "my.table" and db."odd.name" stays db."odd.name"; plain db.tbl and bare tbl are byte-identical to before.

The helper note. Added test_quote_presto_table covering the four cases you named (bare, pre-quoted, embedded doubled quote, and the dotted case), plus per-component special characters and a trailing-SQL input that stays one inert component. I also added the dotted cases to test_execute_quotes_table_identifier so the behaviour is pinned at the emitted-SQL level and not only at the helper. As a negative control I reverted the helper body to the old split(".") and confirmed 6 of the new assertions fail, so they discriminate rather than pass vacuously. Full module is 41 passed, 1 skipped (the pre-existing AIRFLOW_RUNALL_TESTS skip).

One thing worth flagging, which I have deliberately left out of this diff. The quoted-dotted case cannot actually reach the FROM clause today, because HiveMetastoreHook.get_table raw-splits the same string three lines before the SQL is built:

# providers/apache/hive/src/airflow/providers/apache/hive/hooks/hive.py:703-704
if db == "default" and "." in table_name:
    db, table_name = table_name.split(".")[:2]

So table='"my.table"' resolves to db "my / table table", and db."odd.name" resolves to db db / table "odd. Both fail at the metastore lookup on line 164 of the operator before any SQL is generated. Running the full matrix, the only inputs where this diff changes SQL that a real run would actually emit are trailing-dot names: db.tbl. previously produced FROM db.tbl."" and now produces FROM db.tbl.

I still think the helper should be correct on its own terms, since it is the identifier-quoting primitive and the tests now pin it. But if you want the quoted-dotted case to be genuinely reachable end to end, that means changing how HiveMetastoreHook parses a qualified name, which affects every caller of that hook and feels like a separate PR. Happy to open one if you would like it.

@Har1sh-k
Har1sh-k requested a review from potiuk August 19, 2026 00:56
@potiuk
potiuk merged commit 2e30d73 into apache:main Aug 19, 2026
83 checks passed
@boring-cyborg

boring-cyborg Bot commented Aug 19, 2026

Copy link
Copy Markdown

Awesome work, congrats on your first merged pull request! You are invited to check our Issue Tracker for additional contributions.

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

Labels

area:providers provider:apache-hive ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants