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


##########
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:
   A clause after a call gets split from its call. `SELECT sum(a) OVER 
(PARTITION BY b)::int FROM t` becomes `SELECT sum(a) CAST(OVER (PARTITION BY b) 
AS int) FROM t`, because `OVER (...)` is read as a call to a function named 
`OVER`. Spark 4.2 parses the original as a cast of the window function, since 
`OVER`, `FILTER`, `WITHIN GROUP`, and `IGNORE NULLS` are all part of the 
[`functionCall` primary 
expression](https://github.com/apache/spark/blob/32f7299601108917fb01920a54e084595b7b3bf8/sql/api/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseParser.g4#L1345-L1349).
 Spark 3.5.9 raises `PARSE_SYNTAX_ERROR` on the rewrite, so the record is 
skipped on 3.5 with nothing reported, as with [the `exists` 
case](https://github.com/apache/datafusion-spark/pull/391#discussion_r4645349578).
   
   Could we step over those clauses before looking for the call?
   
   ```suggestion
       k = _significant_before(tokens, len(tokens))
       if k < 0:
           raise Skip(_UNTRANSLATABLE)
       tail = _call_clause_start(tokens, k)
       if tail is not None:
           # A clause of the call before it, such as OVER (...)
           return _operand_start(tokens[:tail])
       kind, text = tokens[k]
   ```
   
   with this next to `_name_start`:
   
   ```python
   def _call_clause_start(tokens: list[tuple[str, str]], k: int) -> 
Optional[int]:
       """The start of the clause that ends at tokens[k] and follows a call, 
such
       as `OVER (...)`, `OVER w`, `FILTER (...)`, `WITHIN GROUP (...)` or
       `IGNORE NULLS`, or None if tokens[k] does not end one."""
   
       def word_before(j: int) -> tuple[int, str]:
           j = _significant_before(tokens, j)
           return j, tokens[j][1].upper() if j >= 0 and tokens[j][0] == "word" 
else ""
   
       if tokens[k][1] == ")":
           j, word = word_before(_matching_open(tokens, k))
           if word in ("OVER", "FILTER"):
               return j
           if word == "GROUP":
               i, before = word_before(j)
               return i if before == "WITHIN" else None
       elif tokens[k][0] == "word":
           j, word = word_before(k)
           if word == "OVER" or (tokens[k][1].upper() == "NULLS" and word in 
("IGNORE", "RESPECT")):
               return j
       return None
   ```
   
   Could you add these to `test_double_colon_casts_for_spark_3`?
   
   ```python
               "SELECT sum(a) OVER (PARTITION BY b)::int FROM t": "SELECT 
CAST(sum(a) OVER (PARTITION BY b) AS int) FROM t",
               "SELECT sum(a) OVER w::int FROM t": "SELECT CAST(sum(a) OVER w 
AS int) FROM t",
               "SELECT count(*) FILTER (WHERE a > 1)::string FROM t": "SELECT 
CAST(count(*) FILTER (WHERE a > 1) AS string) FROM t",
               "SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY a)::string 
FROM t": "SELECT CAST(percentile_cont(0.5) WITHIN GROUP (ORDER BY a) AS string) 
FROM t",
               "SELECT first_value(a) IGNORE NULLS::string FROM t": "SELECT 
CAST(first_value(a) IGNORE NULLS AS string) FROM t",
   ```



##########
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]
+    if kind == "other" and text in (")", "]"):
+        k = _matching_open(tokens, k)
+        before = _significant_before(tokens, k)
+        prev = tokens[before] if before >= 0 else ("", "")
+        if text == ")" and prev[0] == "word" and prev[1].upper() not in 
_KEYWORDS:
+            # A call, f(...)
+            return _name_start(tokens, before)
+        if text == "]" and (prev[0] in ("word", "quoted", "string") or prev[1] 
in (")", "]")):
+            # A subscript, a[...], of the operand that ends before it
+            return _operand_start(tokens[: before + 1])
+        return k
+    if kind == "string":
+        before = _significant_before(tokens, k)
+        if before >= 0 and tokens[before][0] == "word" and 
tokens[before][1].upper() in _TYPED_LITERALS:
+            # A typed literal, such as DATE '2024-01-01'.
+            return before
+        return k
+    if kind == "number":
+        before = _significant_before(tokens, k)
+        if before >= 0 and tokens[before][1] == "-":
+            sign_of = _significant_before(tokens, before)
+            prev = tokens[sign_of] if sign_of >= 0 else None
+            if (
+                prev is None
+                or (prev[0] == "other" and prev[1] not in (")", "]"))
+                or (prev[0] == "word" and prev[1].upper() in _KEYWORDS)
+            ):
+                return before
+        return k
+    if kind in ("word", "quoted"):
+        return _name_start(tokens, k)

Review Comment:
   Two more operands end in a word that `_name_start` treats as a column:
   
   - A `CASE` expression, which Spark parses as [one primary 
expression](https://github.com/apache/spark/blob/32f7299601108917fb01920a54e084595b7b3bf8/sql/api/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseParser.g4#L1329-L1330).
 `SELECT CASE WHEN a THEN 1 END::string FROM t` becomes `SELECT CASE WHEN a 
THEN 1 CAST(END AS string) FROM t`.
   - An [interval 
literal](https://github.com/apache/spark/blob/32f7299601108917fb01920a54e084595b7b3bf8/sql/api/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseParser.g4#L1430-L1463)
 with units. `SELECT INTERVAL '1' DAY::string` becomes `SELECT INTERVAL '1' 
CAST(DAY AS string)`. The commented-out records in `try_add.slt`, 
`try_subtract.slt`, `try_divide.slt`, `try_multiply.slt`, `sign.slt`, and 
`signum.slt` use this form, for example [`try_add.slt` line 
29](https://github.com/apache/datafusion-spark/blob/f4b912895dc356b37c8f92822716fa95f6771dc0/crates/sqllogictest/test_files/math/try_add.slt#L29),
 so they'd be skipped on 3.5 once they're enabled.
   
   Spark 3.5.9 raises `PARSE_SYNTAX_ERROR` on both rewrites. Could we match 
`END` to its `CASE`, and walk back over the value and unit pairs of an interval?
   
   ```suggestion
       if kind == "word" and text.upper() == "END":
           # A CASE expression, whose END matches the CASE that starts it
           depth = 0
           for j in range(k, -1, -1):
               word = tokens[j][1].upper() if tokens[j][0] == "word" else ""
               depth += (word == "END") - (word == "CASE")
               if depth == 0:
                   return j
           raise Skip(_UNTRANSLATABLE)
       if kind == "word" and text.upper() in _INTERVAL_UNITS:
           start = _interval_start(tokens, k)
           if start is not None:
               return start
       if kind in ("word", "quoted"):
           return _name_start(tokens, k)
   ```
   
   with this next to `_name_start`:
   
   ```python
   _INTERVAL_UNITS = {
       unit + plural
       for unit in ("YEAR", "MONTH", "WEEK", "DAY", "HOUR", "MINUTE", "SECOND", 
"MILLISECOND", "MICROSECOND", "NANOSECOND")
       for plural in ("", "S")
   }
   
   
   def _interval_start(tokens: list[tuple[str, str]], k: int) -> Optional[int]:
       """The index of INTERVAL in an interval literal with units, such as
       `INTERVAL '1' DAY` or `INTERVAL '1-2' YEAR TO MONTH`, that ends at
       tokens[k], or None if tokens[k] does not end one."""
       while k >= 0 and tokens[k][0] == "word" and tokens[k][1].upper() in 
_INTERVAL_UNITS:
           k = _significant_before(tokens, k)
           if k >= 0 and tokens[k][1].upper() == "TO":
               k = _significant_before(tokens, k)
               continue
           if k < 0 or tokens[k][0] not in ("string", "number"):
               return None
           k = _significant_before(tokens, k)
           if k >= 0 and tokens[k][1] in ("+", "-"):
               k = _significant_before(tokens, k)
           if k >= 0 and tokens[k][1].upper() == "INTERVAL":
               return k
       return None
   ```
   
   `_interval_start` needs a value before each unit, so a column named `day` 
still works: `INTERVAL '1' DAY - day::int` becomes `INTERVAL '1' DAY - CAST(day 
AS int)`. Could you add these cases to `test_double_colon_casts_for_spark_3`?
   
   ```python
               "SELECT CASE WHEN a THEN CASE b WHEN 1 THEN 2 END END::string 
FROM t": "SELECT CAST(CASE WHEN a THEN CASE b WHEN 1 THEN 2 END END AS string) 
FROM t",
               "SELECT INTERVAL '1-2' YEAR TO MONTH::string": "SELECT 
CAST(INTERVAL '1-2' YEAR TO MONTH AS string)",
               "SELECT INTERVAL -1 DAY 2 HOURS::string": "SELECT CAST(INTERVAL 
-1 DAY 2 HOURS AS string)",
               "SELECT INTERVAL '1' DAY - day::int FROM t": "SELECT INTERVAL 
'1' DAY - CAST(day AS int) FROM t",
   ```



##########
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]
+    if kind == "other" and text in (")", "]"):
+        k = _matching_open(tokens, k)
+        before = _significant_before(tokens, k)
+        prev = tokens[before] if before >= 0 else ("", "")
+        if text == ")" and prev[0] == "word" and prev[1].upper() not in 
_KEYWORDS:
+            # A call, f(...)
+            return _name_start(tokens, before)
+        if text == "]" and (prev[0] in ("word", "quoted", "string") or prev[1] 
in (")", "]")):
+            # A subscript, a[...], of the operand that ends before it
+            return _operand_start(tokens[: before + 1])
+        return k
+    if kind == "string":
+        before = _significant_before(tokens, k)
+        if before >= 0 and tokens[before][0] == "word" and 
tokens[before][1].upper() in _TYPED_LITERALS:
+            # A typed literal, such as DATE '2024-01-01'.
+            return before
+        return k
+    if kind == "number":
+        before = _significant_before(tokens, k)
+        if before >= 0 and tokens[before][1] == "-":
+            sign_of = _significant_before(tokens, before)
+            prev = tokens[sign_of] if sign_of >= 0 else None
+            if (
+                prev is None
+                or (prev[0] == "other" and prev[1] not in (")", "]"))
+                or (prev[0] == "word" and prev[1].upper() in _KEYWORDS)
+            ):
+                return before
+        return k
+    if kind in ("word", "quoted"):
+        return _name_start(tokens, k)
+    if kind == "operand":
+        # A cast that this function already rewrote, as in `x::int::string`.
+        return k
+    raise Skip(_UNTRANSLATABLE)
+
+
+def _name_start(tokens: list[tuple[str, str]], k: int) -> int:
+    """The start of a possibly qualified name, such as `t.a`, that ends at 
tokens[k]."""
+    while k >= 2 and tokens[k - 1][1] == "." and tokens[k - 2][0] in ("word", 
"quoted"):
+        k -= 2
+    if k >= 2 and tokens[k - 1][1] == "." and tokens[k - 2][1] in (")", "]"):
+        # A field of a call or subscript, such as `struct(1 AS x).x`
+        return _operand_start(tokens[: k - 1])
+    return k
+
+
+def _type_end(tokens: list[tuple[str, str]], start: int) -> int:
+    """The index after the type name that starts at tokens[start], such as
+    `int`, `decimal(10, 2)` or `array<map<string, int>>`."""
+    k = _next_significant(tokens, start)
+    if k >= len(tokens) or tokens[k][0] != "word":
+        raise Skip(_UNTRANSLATABLE)
+    name = tokens[k][1].upper()
+    k += 1

Review Comment:
   An interval type loses its fields. `SELECT a::interval day FROM t` becomes 
`SELECT CAST(a AS interval) day FROM t`. Spark 3.5 reads that as a cast to a 
calendar interval with the alias `day`, and the record is skipped as a 
`CalendarIntervalType` value. Inside a call, as in the commented-out 
`try_add(DATE '2021-01-01'::date, INTERVAL '1' YEAR::interval year)`, the 
rewrite is a `PARSE_SYNTAX_ERROR`. Spark's [interval 
type](https://github.com/apache/spark/blob/32f7299601108917fb01920a54e084595b7b3bf8/sql/api/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseParser.g4#L1483-L1485)
 takes an optional field, then an optional `TO` and a second field:
   
   ```suggestion
       name = tokens[k][1].upper()
       k += 1
       if name == "INTERVAL":
           # The fields of an ANSI interval type, such as `interval day to 
second`
           fields = ("YEAR", "MONTH", "DAY", "HOUR", "MINUTE", "SECOND")
           for words in (fields, ("TO",), fields):
               j = _next_significant(tokens, k)
               if j >= len(tokens) or tokens[j][1].upper() not in words:
                   break
               k = j + 1
           return k
   ```
   
   Could you add `a::interval day to second` and a plain `a::interval` to the 
tests?
   
   ```python
               "SELECT a::interval day to second FROM t": "SELECT CAST(a AS 
interval day to second) FROM t",
               "SELECT a::interval FROM t": "SELECT CAST(a AS interval) 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