codeant-ai-for-open-source[bot] commented on code in PR #41803: URL: https://github.com/apache/superset/pull/41803#discussion_r3531226110
########## superset/sql/dialects/trino.py: ########## @@ -0,0 +1,273 @@ +# 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 = {"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. +AMBIGUOUS_OPENERS = {"IF", "REPEAT"} + +BODY_KEYWORDS = ("RETURN", "BEGIN") + + +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( + text: str, + prev_text: str, + next_token: Token | None, + ) -> int: + """ + Compute the block nesting change contributed by a routine token. + """ + if text in BLOCK_OPENERS: + if prev_text == "END": + return 0 # block terminator, e.g. `END IF`, `END CASE` + if ( + text in AMBIGUOUS_OPENERS + and next_token + and next_token.token_type == TokenType.L_PAREN + ): + return 0 # scalar function call, e.g. `IF(a, b, c)` Review Comment: **Suggestion:** The parser treats any `IF` followed by `(` as a scalar function call, which misclassifies valid procedural `IF (...) THEN ... END IF` blocks and breaks block-depth tracking. This causes valid inline UDFs to fail parsing or split incorrectly when the IF condition is parenthesized. Update the opener detection to distinguish statement-form `IF ... THEN` from scalar `IF(...)` calls (and apply the same rule in both block-depth paths). [logic error] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ❌ Trino inline UDFs with IF(...) bodies fail parsing. - ⚠️ SQL Lab parsing fails for such Trino UDF scripts. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Note that the custom Trino dialect is wired into Superset's parser via `SQLGLOT_DIALECTS["trino"] = Trino` in `superset/sql/parse.py:106-169`, so any `SQLScript(..., "trino")` or `SQLStatement(..., "trino")` uses `superset/sql/dialects/trino.py:68-269`. 2. Inside this dialect, `Parser._parse` at `superset/sql/dialects/trino.py:117-172` walks `raw_tokens` in `routine_mode` and uses `_block_depth_delta` (defined at lines 95-115) to maintain `depth`, treating any semicolon with `depth <= 0` as a statement splitter at lines 140-149. 3. `_block_depth_delta`'s ambiguous-opener logic at `superset/sql/dialects/trino.py:103-111` returns `0` (no new block) whenever an `IF` token is immediately followed by a `(` token, classifying it as a scalar `IF()` call rather than a procedural block opener, and the same pattern is used in `_consume_block` at lines 235-267. 4. Construct a Trino inline UDF similar to the existing nested-block test at `superset/tests/unit_tests/sql/dialects/trino_tests.py:110-119`, but change the condition to be parenthesized, for example: `WITH FUNCTION classify(a bigint) RETURNS varchar BEGIN IF (a > 100) THEN RETURN 'big'; ELSEIF a > 0 THEN RETURN 'small'; END IF; RETURN 'negative'; END SELECT classify(x) FROM some_table`. When this SQL is passed to `sqlglot.parse(sql, dialect=Trino)` (as in `test_inline_udf_nested_blocks` at lines 93-141) or through `SQLScript(sql, "trino")` as in `test_sqlscript_inline_udf` at lines 172-181, the `IF` token inside the body is misclassified as scalar because the next token is `(` (lines 106-111), so the `depth` counter is not incremented for that nested block; when the corresponding `END` of the `IF` is processed, `depth` is decremented to zero and the following semicolon is treated as a statement terminator in `_parse` (lines 140-149), causing the inline UDF body to be split prematurely or parsed as multiple statements, and the overall inline UDF fails to parse correctly. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=92ac1f8a63834d5bb6f682290367f3ce&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=92ac1f8a63834d5bb6f682290367f3ce&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:** 106:111 **Comment:** *Logic Error: The parser treats any `IF` followed by `(` as a scalar function call, which misclassifies valid procedural `IF (...) THEN ... END IF` blocks and breaks block-depth tracking. This causes valid inline UDFs to fail parsing or split incorrectly when the IF condition is parenthesized. Update the opener detection to distinguish statement-form `IF ... THEN` from scalar `IF(...)` calls (and apply the same rule in both block-depth paths). 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=76e8662d9f9b689cdd370badfd53e30278aeafd7388c87bd9ab5cadecb3858a7&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41803&comment_hash=76e8662d9f9b689cdd370badfd53e30278aeafd7388c87bd9ab5cadecb3858a7&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]
