spark-test commented on code in PR #60662:
URL: https://github.com/apache/spark/pull/60662#discussion_r4624951370


##########
sql/core/src/test/scala/org/apache/spark/sql/connector/DeleteFromTableSuiteBase.scala:
##########
@@ -1066,6 +1066,97 @@ abstract class DeleteFromTableSuiteBase extends 
RowLevelOperationSuiteBase {
         Row(3, 300, "hr")))      // unchanged (pk 3 not in source)
   }
 
+  test("delete target is not replaced by a same-named CTE") {

Review Comment:
   **Nit (P3):** This test and its counterparts at 
UpdateTableSuiteBase.scala:1341 and MergeIntoTableSuiteBase.scala:1317 check 
which table each statement modifies, but not that the named target is loaded 
with the statement's write privileges. That load is part of what the change 
fixes: before it, the CTE's table was loaded as a plain read, so the catalog 
never authorized the write. The transactional test catalog returns one pinned 
table for read and write loads alike 
(sql/catalyst/src/test/scala/org/apache/spark/sql/connector/catalog/txns.scala:193-199),
 so if a later change let the target lose its write-privilege marker after the 
CTE check in `CTESubstitution`, the rows would change the same way and every 
new test would still pass. The existing 
`assertLastTransactionWriteLoadOptions()` helper would catch that; calling it 
right after each statement whose literal target is shadowed by a CTE would pin 
the load, for example:
   
   ```scala
   withSQLConf(SQLConf.LEGACY_CTE_PRECEDENCE_POLICY.key -> policy) {
     sql(...)
   }
   assertLastTransactionWriteLoadOptions()
   ```
   
   Leave out the `UPDATE IDENTIFIER(concat(...))` statement: Spark starts a 
transaction only for a target it can name before analysis, so that statement 
runs outside one and the helper would re-check the previous statement's 
transaction.
   
   **Verification:**
   - **Regression:** With a temporary change that makes CTESubstitution's new 
write-target exemption return the target without its write-privilege marker, 
the new assertion fails for DELETE, UPDATE and MERGE while the existing row 
checks still pass.
   - **Behavior:** In every group-based and delta-based variant of the DELETE, 
UPDATE and MERGE suites, the tests that run a CTE-shadowed statement with a 
literal target against the named table assert that the table was loaded with 
the statement's write privileges, and they pass.



##########
docs/sql-migration-guide.md:
##########
@@ -104,6 +104,7 @@ license: |
 - Since Spark 4.4, a function created by `CREATE FUNCTION ... AS 'class'` 
whose class implements 
`org.apache.spark.sql.connector.catalog.functions.UnboundFunction` and extends 
either a Hive UDF class (such as `UDF` or `GenericUDF`) or 
`org.apache.spark.sql.expressions.UserDefinedAggregateFunction` runs as a 
DataSource V2 function instead of a Hive UDF or Spark UDAF, including functions 
created in earlier versions. Its result type, argument coercion, and null 
handling are defined by the V2 implementation selected by 
`UnboundFunction.bind`. Hive's `@UDFType` and Spark UDAF's `deterministic` 
property do not control the V2 path. For scalar functions, determinism uses 
`BoundFunction.isDeterministic()` (default `true`) and the arguments' 
determinism. A call with constant arguments can therefore become eligible for 
constant folding during query planning instead of being evaluated per row.
 - Since Spark 4.4, `next_day` and `last_day` fail with `DATETIME_OVERFLOW` 
when the result is later than the maximum `DATE`, `+5881580-07-11`, and `trunc` 
fails with it when the result is earlier than the minimum `DATE`, 
`-5877641-06-23`, regardless of `spark.sql.ansi.enabled`. Previously, these 
functions silently returned a wrong date, in most cases one at the other end of 
the `DATE` range; for example, `last_day(DATE'+5881580-07-11')` returned 
`-5877641-07-12` and `trunc(DATE'-5877641-06-23', 'MONTH')` returned 
`+5881580-06-20`, while `trunc` to `QUARTER` failed with `ARITHMETIC_OVERFLOW`. 
`next_day` and `trunc` to `WEEK` also returned a wrong date for the first days 
of the `DATE` range; for example, `next_day(DATE'-5877641-06-23', 'MO')` and 
`trunc(DATE'-5877641-07-01', 'WEEK')` returned `-5877641-06-25`, a Thursday, 
and now return `-5877641-06-29`.
 - Since Spark 4.4, a Variant `TIMESTAMP` value is rendered in the session time 
zone (`spark.sql.session.timeZone`) when it is nested in an array, map, or 
struct that is cast to `STRING`, in `Dataset.show()`, and in the output of the 
spark-sql CLI and the Thrift server, as a top-level `CAST(v AS STRING)` already 
does. Previously, these paths rendered it in UTC. For example, with 
`spark.sql.session.timeZone` set to `America/Los_Angeles`, 
`CAST(named_struct('a', CAST(TIMESTAMP'2020-01-01 00:00:00Z' AS VARIANT)) AS 
STRING)` returns `{"2019-12-31 16:00:00-08:00"}` instead of `{"2020-01-01 
00:00:00+00:00"}`. The rendered text carries an explicit offset, so it still 
denotes the same instant. Sessions in UTC are not affected.
+- Since Spark 4.4, a CTE no longer replaces a `DELETE`, `UPDATE` or `MERGE` 
target that has the same unqualified name, as it already did not replace an 
`INSERT` target. Such a statement modifies the table or view that it names, or 
fails with `TABLE_OR_VIEW_NOT_FOUND` when none exists, and other references to 
the name in the statement, such as in a `WHERE` subquery or the `MERGE` source, 
still read the CTE. Previously, a CTE whose body is a bare table reference made 
the statement modify the table that the CTE reads: for example, `WITH o AS 
(TABLE cat.db.orders) DELETE FROM o WHERE id = 1` deleted rows from 
`cat.db.orders`. Any other CTE body made the statement fail with 
`INTERNAL_ERROR` or `UNSUPPORTED_FEATURE.TABLE_OPERATION`. To modify the table 
that the CTE reads, name that table as the target. To restore the previous 
behavior, set `spark.sql.legacy.cteSubstituteDmlTarget` to `true`; such a 
statement then again modifies the table that the CTE reads, which Spark loads 
without the w
 rite privileges of the statement.

Review Comment:
   **Non-blocking (P2):** The sentence "Any other CTE body made the statement 
fail ..." holds for `UPDATE` and `MERGE`, but not for `DELETE`. From reading 
the analyzer and planner, under the old resolution (which the legacy flag 
restores) the CTEs of a `DELETE` are inlined, so the CTE body replaces the 
target, and `RewriteDeleteFromTable` leaves a target that is not a relation 
unchanged. For a body such as `SELECT * FROM cat.db.orders`, the optimizer then 
removes the aliases and the no-op projection, and V2 scan push-down drops a CTE 
filter that the source applies in full, so the target becomes a plain scan. 
`DataSourceV2Strategy` then plans `DeleteFromTableExec` or `TruncateTableExec` 
on the CTE's table, using only the `DELETE` condition 
(sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/DataSourceV2Strategy.scala:648-679),
 so a filtered body can also delete rows the CTE does not return. The `DELETE` 
statements that do fail also raise more than the two listed err
 ors, for example `_LEGACY_ERROR_TEMP_1108` when such a body meets a `WHERE pk 
IN (SELECT ...)` condition.
   
   A user who reads this entry to find the statements that modified the CTE's 
table will miss these `DELETE` statements, which now silently target a 
same-named table when one exists, and setting the flag brings those deletions 
back without warning. The doc of `spark.sql.legacy.cteSubstituteDmlTarget` 
makes the same claim ("Any other CTE body makes the statement fail.", 
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:7608-7609)
 and needs the same correction. One possible wording for this entry:
   
   ```suggestion
   - Since Spark 4.4, a CTE no longer replaces a `DELETE`, `UPDATE` or `MERGE` 
target that has the same unqualified name, as it already did not replace an 
`INSERT` target. Such a statement modifies the table or view that it names, or 
fails with `TABLE_OR_VIEW_NOT_FOUND` when none exists, and other references to 
the name in the statement, such as in a `WHERE` subquery or the `MERGE` source, 
still read the CTE. Previously, a CTE whose body is a bare table reference made 
the statement modify the table that the CTE reads: for example, `WITH o AS 
(TABLE cat.db.orders) DELETE FROM o WHERE id = 1` deleted rows from 
`cat.db.orders`. With any other CTE body, `UPDATE` and `MERGE` failed. So did 
`DELETE`, unless Spark reduced the body to a plain scan of a table that 
supports deletes by filter or truncation, such as `SELECT * FROM 
cat.db.orders`: it then deleted from or truncated that table by the `DELETE` 
condition alone, which could also remove rows that a filter in the CTE body 
excludes. To m
 odify the table that the CTE reads, name that table as the target. To restore 
the previous behavior, set `spark.sql.legacy.cteSubstituteDmlTarget` to `true`; 
such a statement then again modifies the table that the CTE reads, which Spark 
loads without the write privileges of the statement.
   ```
   
   **Verification:**
   - **Inspection:** The Spark 4.4 migration-guide entry and the doc of 
spark.sql.legacy.cteSubstituteDmlTarget no longer say that every CTE body other 
than a bare table reference makes the statement fail; both say that UPDATE and 
MERGE fail while a DELETE can delete from or truncate the table the CTE reads, 
using only its own condition, when the body reduces to a plain scan of a table 
that supports deletes by filter or truncation.



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