codeant-ai-for-open-source[bot] commented on code in PR #41803: URL: https://github.com/apache/superset/pull/41803#discussion_r3618977908
########## superset/sql/dialects/trino.py: ########## @@ -0,0 +1,310 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from __future__ import annotations + +import typing as t + +from sqlglot import exp +from sqlglot.dialects.trino import Trino as SqlglotTrino +from sqlglot.tokens import Token, TokenType + +# Keywords that open a block terminated by ``END`` in Trino SQL routines +# (https://trino.io/docs/current/udf/sql.html). ``CASE`` is included because +# both the ``CASE`` statement and the ``CASE`` expression are terminated by +# ``END``, so counting them keeps the depth balanced either way. +BLOCK_OPENERS: set[str] = {"BEGIN", "CASE", "IF", "LOOP", "REPEAT", "WHILE"} + +# Keywords that are also scalar functions in Trino (e.g. ``IF(a, b, c)`` and +# ``REPEAT('a', 3)``). When immediately followed by ``(`` they are function +# calls, not block openers, unless the token stream shows otherwise (see +# ``_is_paren_condition_block``). +AMBIGUOUS_OPENERS: set[str] = {"IF", "REPEAT"} + +BODY_KEYWORDS: tuple[str, str] = ("RETURN", "BEGIN") + + +def _is_paren_condition_block(tokens: t.Sequence[Token], paren_index: int) -> bool: + """ + Determine whether the parenthesized group starting at ``tokens[paren_index]`` + (an ``L_PAREN``) is a procedural block condition, e.g. ``IF (a > b) THEN``, + as opposed to a scalar function call argument list, e.g. ``IF(a, b, c)``. + + Only ``IF`` has this ambiguity: a parenthesized condition is followed by + ``THEN``, while a scalar function call's closing paren never is. + """ + depth = 0 + for i in range(paren_index, len(tokens)): + token_type = tokens[i].token_type + if token_type == TokenType.L_PAREN: + depth += 1 + elif token_type == TokenType.R_PAREN: + depth -= 1 + if depth == 0: + next_token = tokens[i + 1] if i + 1 < len(tokens) else None + return ( + next_token is not None and next_token.token_type == TokenType.THEN + ) + return False + + +class InlineUDF(exp.CTE): + """ + An inline SQL user-defined function declared in a ``WITH`` clause. + + Trino supports declaring UDFs inline as part of a query:: + + WITH FUNCTION meaning_of_life() + RETURNS tinyint + BEGIN + DECLARE a tinyint DEFAULT CAST(6 AS tinyint); + DECLARE b tinyint DEFAULT CAST(7 AS tinyint); + RETURN a * b; + END + SELECT meaning_of_life() + + The function definition is stored verbatim as an opaque string (wrapped + in an ``exp.Var`` so that AST traversal helpers see an expression), since + sqlglot has no representation for SQL routine bodies. Trino does not + allow queries inside SQL UDF bodies, so no table references are hidden + by the opaque representation. + + This subclasses ``exp.CTE`` because ``sqlglot.parser.Parser._parse_with`` + only collects ``exp.CTE`` instances into the ``WITH`` clause. + """ + + arg_types = {"this": True} + + +class Trino(SqlglotTrino): + """ + Custom Trino dialect with support for inline SQL UDFs. + + sqlglot cannot parse Trino SQL routine syntax; see + https://github.com/tobymao/sqlglot/issues/5178. There are two separate + problems: + + 1. The parser splits statements on every semicolon, including the ones + inside a ``BEGIN ... END`` routine body. + 2. The ``FUNCTION`` specification in a ``WITH`` clause is not valid CTE + syntax. + + This dialect keeps routine bodies intact when splitting statements, and + parses inline function specifications into opaque `InlineUDF` nodes that + regenerate verbatim. + + Note that sqlglot's ``Dialect`` metaclass registers subclasses by class + name, so once this module is imported this class also replaces the + built-in dialect for string-based lookups (``dialect="trino"``). This is + intentional, and consistent with how other Superset dialects (e.g. + ``Dremio``) shadow their sqlglot counterparts: the extensions are purely + additive, only activating on syntax that fails to parse upstream. + """ + + class Parser(SqlglotTrino.Parser): + @staticmethod + def _block_depth_delta( + tokens: list[Token], + index: int, + prev_text: str, + ) -> int: + """ + Compute the block nesting change contributed by the routine token + at ``tokens[index]``. + """ + text = tokens[index].text.upper() + if text in BLOCK_OPENERS: + if prev_text == "END": + return 0 # block terminator, e.g. `END IF`, `END CASE` + next_token = tokens[index + 1] if index + 1 < len(tokens) else None + if ( + text in AMBIGUOUS_OPENERS + and next_token + and next_token.token_type == TokenType.L_PAREN + ): + if text == "IF" and _is_paren_condition_block(tokens, index + 1): + return 1 # procedural `IF (...) THEN`, not a call + return 0 # scalar function call, e.g. `IF(a, b, c)` + return 1 + if text == "END": + return -1 + return 0 + + def _parse( + self, + parse_method: t.Callable[..., exp.Expression | None], + raw_tokens: list[Token], + sql: str | None = None, + ) -> list[exp.Expression | None]: + """ + Split tokens into statements, keeping routine bodies intact. + + This is a copy of ``sqlglot.parser.Parser._parse`` (as of + sqlglot 30.8.0, the version pinned in ``requirements/base.txt``) + with one change: when a statement starts with ``WITH FUNCTION``, + ``CREATE FUNCTION``, or ``CREATE OR REPLACE FUNCTION``, semicolons + inside ``BEGIN ... END`` blocks do not split the statement. If + sqlglot's own ``_parse`` changes on a future upgrade, this copy + will silently drift from it and should be re-diffed against the + new version. + """ + self.reset() + self.sql = sql or "" + + total = len(raw_tokens) + chunks: list[list[Token]] = [[]] + routine_mode: bool = False + depth: int = 0 + prev_text: str = "" + + for i, token in enumerate(raw_tokens): + if token.token_type == TokenType.SEMICOLON and depth <= 0: + if token.comments: + chunks.append([token]) + if i < total - 1: + chunks.append([]) + routine_mode = False + depth = 0 + prev_text = "" + continue + + chunk = chunks[-1] + chunk.append(token) + + if token.token_type == TokenType.FUNCTION and not routine_mode: + heads = [tok.token_type for tok in chunk[:-1]] + routine_mode = heads in ( + [TokenType.WITH], + [TokenType.CREATE], + [TokenType.CREATE, TokenType.OR, TokenType.REPLACE], + ) + elif routine_mode: + depth += self._block_depth_delta(raw_tokens, i, prev_text) Review Comment: **Suggestion:** `routine_mode` is only enabled when `FUNCTION` appears immediately after `WITH`, so valid `WITH` clauses that define a normal CTE first and an inline function later will not enter routine mode. In that case, semicolons inside the later function body are treated as statement separators and the query is split incorrectly. Update the detection so `FUNCTION` inside an active `WITH` clause is recognized even when it is not the first entry. [logic error] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ❌ Trino queries with CTE before inline UDF fail parsing. - ⚠️ SQL Lab cannot run affected Trino queries. - ⚠️ Security checks may mis-handle incorrectly split statements. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Import the custom Trino dialect class from `superset/sql/dialects/trino.py` and use it as the active sqlglot dialect (this happens automatically for `dialect="trino"` because `Trino` at line 94 shadows `SqlglotTrino`). 2. Execute a Trino query that mixes a normal CTE and an inline SQL UDF, for example: `WITH cte AS (SELECT 1), FUNCTION meaning_of_life() RETURNS tinyint BEGIN DECLARE a tinyint DEFAULT 6; DECLARE b tinyint DEFAULT 7; RETURN a * b; END SELECT meaning_of_life();` via Superset’s SQL parsing (which calls sqlglot with the Trino dialect), causing `Parser._parse` in `superset/sql/dialects/trino.py:148-205` to process the token stream. 3. In `_parse`, when the `FUNCTION` token inside the `WITH` clause is visited, `chunk` already contains tokens for `WITH cte AS (SELECT 1),`, so `heads = [tok.token_type for tok in chunk[:-1]]` at line 191 produces a longer list like `[WITH, IDENTIFIER, AS, L_PAREN, ...]` which does not equal any of `([WITH], [CREATE], [CREATE, OR, REPLACE])`. As a result, `routine_mode` remains `False` and the subsequent inline UDF body is never tracked for block depth. 4. Later in the same `_parse` loop, each semicolon inside the UDF body is processed while `routine_mode` is `False` and `depth <= 0`, so the condition at line 175 (`token.token_type == TokenType.SEMICOLON and depth <= 0`) treats these semicolons as statement separators, splitting the query into multiple chunks mid-function. When `self._parse_batch_statements` is called at line 199, some chunks represent incomplete routine fragments and fail to parse, leading to a SQL parse error or incorrect multi-statement splitting for the original query in SQL Lab. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=6b6054e113844441bc41f4b14a8d6c55&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=6b6054e113844441bc41f4b14a8d6c55&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/sql/dialects/trino.py **Line:** 190:196 **Comment:** *Logic Error: `routine_mode` is only enabled when `FUNCTION` appears immediately after `WITH`, so valid `WITH` clauses that define a normal CTE first and an inline function later will not enter routine mode. In that case, semicolons inside the later function body are treated as statement separators and the query is split incorrectly. Update the detection so `FUNCTION` inside an active `WITH` clause is recognized even when it is not the first entry. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41803&comment_hash=062f85b9ee2154583dff2f7b55d764da8cbce00264e5a775d34fdd2b050b834c&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41803&comment_hash=062f85b9ee2154583dff2f7b55d764da8cbce00264e5a775d34fdd2b050b834c&reaction=dislike'>👎</a> -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
