mbutrovich commented on code in PR #391:
URL: https://github.com/apache/datafusion-spark/pull/391#discussion_r4686507950


##########
crates/sqllogictest/scripts/pyspark_slt_runner.py:
##########
@@ -788,6 +873,130 @@ def translate(sql: str, time_zone: str = "UTC") -> str:
     return "".join(out)
 
 
+# Keywords after which a `-` is a sign, not a subtraction, and a `(` does
+# not start the arguments of a call.
+_KEYWORDS = {
+    "ALL", "AND", "AS", "BETWEEN", "BY", "CASE", "DISTINCT", "ELSE",
+    "FROM", "HAVING", "IN", "IS", "JOIN", "LIKE", "LIMIT", "NOT",
+    "ON", "OR", "RETURN", "SELECT", "THEN", "VALUES", "WHEN", "WHERE",
+}
+
+
+# The type names of typed literals, such as DATE '2024-01-01'.
+_TYPED_LITERALS = ("DATE", "TIME", "INTERVAL", "X", *_TIMESTAMP_TYPES)
+
+# Brackets that nest in a type name, such as `array<decimal(10, 2)>`.
+_TYPE_NESTING = {"(": 1, "<": 1, ")": -1, ">": -1}
+
+_UNTRANSLATABLE = "a `::` cast this runner cannot translate"
+
+
+def rewrite_double_colons(sql: str) -> str:
+    """Replace each `expr::type` with `CAST(expr AS type)`.
+
+    Spark 3.5 does not parse `::`. As in Spark 4, `::` applies to the primary
+    expression before it: a literal, a column, a call, a parenthesized
+    expression or a subscript. A sign belongs to a number literal, so
+    `-1::int` is `CAST(-1 AS int)`, but `-(1)::int` is `-CAST((1) AS int)`.
+    """
+    tokens = _tokenize(sql)
+    out: list[tuple[str, str]] = []
+    i = 0
+    while i < len(tokens):
+        if tokens[i][0] != "cast":
+            out.append(tokens[i])
+            i += 1
+            continue
+        start = _operand_start(out)
+        operand = "".join(t for _, t in out[start:]).strip()
+        del out[start:]
+        end = _type_end(tokens, i + 1)
+        type_sql = "".join(t for _, t in tokens[i + 1 : end]).strip()
+        if not operand or not type_sql:
+            raise Skip(_UNTRANSLATABLE)
+        out.append(("operand", f"CAST({operand} AS {type_sql})"))
+        i = end
+    return "".join(t for _, t in out)
+
+
+def _significant_before(tokens: list[tuple[str, str]], end: int) -> int:
+    """The index of the last token before `end` that is not whitespace, or 
-1."""
+    k = end - 1
+    while k >= 0 and tokens[k][0] in ("space", "comment"):
+        k -= 1
+    return k
+
+
+def _operand_start(tokens: list[tuple[str, str]]) -> int:
+    """The index where the primary expression that ends `tokens` starts."""
+    k = _significant_before(tokens, len(tokens))
+    if k < 0:
+        raise Skip(_UNTRANSLATABLE)
+    kind, text = tokens[k]

Review Comment:
   > I added one check to `_call_clause_start`: the clause has to follow a 
call's `)`.
   
   `OVER` can also follow `IGNORE NULLS` or `RESPECT NULLS`, as in the 
[`functionCall` 
rule](https://github.com/apache/spark/blob/32f7299601108917fb01920a54e084595b7b3bf8/sql/api/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseParser.g4#L1349)
 (`(nullsOption=(IGNORE | RESPECT) NULLS)? ( OVER windowSpec)?`). The check in 
[`after_call`](https://github.com/apache/datafusion-spark/blob/160e7c9882adf268cccee07baf809498901e54fb/crates/sqllogictest/scripts/pyspark_slt_runner.py#L999-L1003)
 rejects that, so `SELECT first_value(a) IGNORE NULLS OVER (ORDER BY b)::string 
FROM t` becomes `SELECT first_value(a) IGNORE NULLS CAST(OVER (ORDER BY b) AS 
string) FROM t`, and Spark 3.5.9 raises `PARSE_SYNTAX_ERROR` on it. 
`first_value(a) RESPECT NULLS OVER w::string` becomes `... OVER CAST(w AS 
string)`. Could `after_call` accept `NULLS` as well as `)`?
   
   ```python
       def after_call(j: int) -> Optional[int]:
           # Only a call, or its IGNORE NULLS clause, can come before the 
clause.
           # Without this, the call `filter(arr, x -> x > 1)` would read as a
           # FILTER clause.
           before = _significant_before(tokens, j)
           return j if before >= 0 and tokens[before][1].upper() in (")", 
"NULLS") else None
   ```
   
   `ORDER BY a NULLS FIRST` isn't affected, because a clause is only found when 
`OVER`, `FILTER`, or `WITHIN GROUP` comes right after `NULLS`. Could you add 
both cases to `test_double_colon_casts_for_spark_3`?
   
   ```python
               "SELECT first_value(a) IGNORE NULLS OVER (ORDER BY b)::string 
FROM t": "SELECT CAST(first_value(a) IGNORE NULLS OVER (ORDER BY b) AS string) 
FROM t",
               "SELECT first_value(a) RESPECT NULLS OVER w::string FROM t": 
"SELECT CAST(first_value(a) RESPECT NULLS OVER w AS string) FROM t",
   ```



-- 
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]

Reply via email to