dtenedor commented on code in PR #60367:
URL: https://github.com/apache/spark/pull/60367#discussion_r4593849723


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckOptionalReferencesInDml.scala:
##########
@@ -0,0 +1,122 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import org.apache.spark.sql.catalyst.expressions.{Expression, 
SubqueryExpression}
+import org.apache.spark.sql.catalyst.plans.logical.{
+  DeleteFromTable,
+  LogicalPlan,
+  MergeIntoTable,
+  OverwriteByExpression,
+  UpdateTable,
+  View
+}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.COMMAND
+import org.apache.spark.sql.errors.QueryCompilationErrors
+
+/**
+ * Rejects optional references in the expressions of a statement that modifies 
table data and
+ * that was built without the SQL parser, which rejects them in SQL text (see
+ * `OptionalReferenceValidation`). A missing column must not silently change 
which rows a
+ * statement deletes or updates.
+ *
+ * The source of a MERGE is checked too, like the source query of the SQL 
statement.
+ * `Dataset.mergeInto` and the Spark Connect MERGE command put the plan of the 
source DataFrame
+ * there, in which only the last operation is sure to be unanalyzed: a Dataset 
operation builds on
+ * the analyzed plan of the one before, and Spark Connect analyzes some 
relations, such as
+ * `withColumns`, when it plans them. In an analyzed operation, an optional 
reference that matched
+ * nothing is the NULL that it resolved to, which is rejected as well.
+ *
+ * {{{
+ *   df.writeTo("t").overwrite(expr("deleted_at? IS NULL"))
+ *   spark.table("s").selectExpr("pk", "archived? AS 
archived").as("s").mergeInto("t", ...)
+ * }}}
+ */
+object CheckOptionalReferencesInDml extends Rule[LogicalPlan] {
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    if (plan.containsPattern(COMMAND)) {
+      plan.foreach { operator =>
+        statementName(operator).foreach { statement =>
+          operator.expressions.foreach(checkExpression(_, statement))
+        }
+        operator match {
+          case merge: MergeIntoTable =>
+            OptionalReferences
+              .unresolvedOptionalReference(merge.sourceTable)
+              .orElse(firstNullReference(merge.sourceTable))
+              .foreach { reference =>
+                throw 
QueryCompilationErrors.optionalReferenceInDmlNotSupportedError(
+                  "MERGE",
+                  reference.origin
+                )
+              }
+          case _ =>
+        }
+      }
+    }
+    plan
+  }
+
+  private def statementName(operator: LogicalPlan): Option[String] = operator 
match {
+    case _: DeleteFromTable => Some("DELETE")
+    case _: UpdateTable => Some("UPDATE")
+    case _: MergeIntoTable => Some("MERGE")
+    // The plan of INSERT ... REPLACE WHERE and of 
`DataFrameWriterV2.overwrite(condition)`.
+    case _: OverwriteByExpression => Some("INSERT ... REPLACE")
+    case _ => None
+  }
+
+  /**
+   * Returns the first NULL that an optional reference of `plan` resolved to 
in an analysis of an
+   * operation of `plan`, see [[OptionalReferences.isNullReference]], or None. 
Views and SQL
+   * functions resolve their own optional references, so the search does not 
enter a view, a SQL
+   * table function, or the body of a SQL scalar function.
+   */
+  private def firstNullReference(plan: LogicalPlan): Option[Expression] = plan 
match {

Review Comment:
   Done, along the lines of the recommended change. The decision now also lives 
on the plan that the analysis returns, so the check no longer depends on the 
NULL surviving the rest of that analysis:
   
   - `OptionalReferences.nullReference`, which both analyzers use, records the 
origin of each NULL it creates in `AnalysisContext.nullReferenceOrigins`. The 
contexts of subqueries share that record. A view body 
(`withAnalysisContext(viewDesc)`) and a SQL function body 
(`withAnalysisContext(function)`) each get their own.
   - At the end of `Analyzer.execute` and of `ResolverRunner.resolve`, 
`markResolvedNullReference` sets the new tag `RESOLVED_NULL_REFERENCE`, with 
the first of those origins, on the root of the returned plan. It skips the root 
when it is the plan the analyzer received.
   - In a MERGE source, `CheckOptionalReferencesInDml` first looks for a NULL 
that is still there, which keeps every existing fragment (`missing?:a`, for 
example), and falls back to the marks. It still skips views and SQL function 
bodies. The NULL of a SQL table function argument counts, because the caller's 
analysis creates it.
   
   Tests in `MergeIntoDataFrameSuite`:
   - Each of these sources fails with IN_DML/MERGE at the fragment of the 
reference, and the target keeps its row:
     - a `selectExpr` with `attrs?['active']`, `tags?[0]`, `items?[0].sku`, or 
`IF(is_active?, true, false)`, followed by `.as("s")`;
     - `SELECT * FROM VALUES (1, flag?) AS t(pk, archived)`;
     - `LATERAL flag_rows(archived?)`, a SQL table function.
   - A source built while optional references were enabled still fails a MERGE 
that runs after they are disabled.
   - The sources that read a view, a SQL scalar function, or a SQL table 
function whose body uses `?` still merge.
   
   `OptionalReferencesConnectSuite` adds `withColumn("archived", 
expr("attrs?['archived']"))`. With the mark turned off locally, the new 
DataFrame and Connect cases fail.
   
   I also applied the same search to the expressions of every checked 
statement. A subquery built from a Dataset (`Dataset.scalar`, `Dataset.exists`, 
`Column.isin(Dataset)`) holds an analyzed plan too. New tests: 
`overwrite(col("id").isin(spark.table("source").where("tags?[0] IS 
NULL").select("id")))` and a MERGE assignment from 
`selectExpr("coalesce(max(bonus?[0]), 0)").scalar()` both fail with IN_DML.
   
   As the review excludes, an unbound `:p?` in the SQL text of a source 
DataFrame (now a TODO at the check) and a materialized source such as a 
checkpoint are not covered.



##########
sql/core/src/test/resources/sql-tests/inputs/optional-references.sql:
##########
@@ -0,0 +1,575 @@
+-- Tests for optional column, field, variable, and named parameter references: 
a `?` after an
+-- identifier makes that identifier optional, so that a reference that cannot 
be resolved
+-- evaluates to a static NULL of type VOID instead of raising a not-found 
error.
+
+--SET spark.sql.optionalReferences.enabled=true
+
+CREATE TEMPORARY VIEW people AS SELECT * FROM VALUES
+  (1, named_struct('city', 'SF', 'zip', '94105')),
+  (2, named_struct('city', 'NYC', 'zip', '10001'))
+  AS t(id, addr);
+
+CREATE TEMPORARY VIEW orgs AS SELECT * FROM VALUES
+  (1, named_struct('addr', named_struct('city', 'SF', 'zip', '94105')))
+  AS t(id, info);
+
+CREATE TEMPORARY VIEW orders AS SELECT * FROM VALUES
+  (1, array(named_struct('sku', 'a', 'qty', 5))),
+  (2, array(named_struct('sku', 'b', 'qty', 9)))
+  AS t(id, items);
+
+-- A missing column resolves to NULL and an existing column resolves normally. 
Either way, the
+-- output column keeps the name of the reference.
+SELECT id?, name? FROM people;
+SELECT typeof(id?), typeof(name?) FROM people LIMIT 1;
+SELECT * FROM (SELECT id?, name? FROM people);
+
+-- Whitespace and comments between the identifier and `?` are insignificant.
+SELECT id ?, name /* comment */ ? FROM people;
+
+-- Optional references in expressions, predicates, grouping, ordering, and 
function arguments.
+SELECT id, bonus? + 1 AS b FROM people;
+SELECT coalesce(archived?, false) AS archived, count(*) AS cnt
+FROM people
+WHERE archived? IS NULL
+GROUP BY archived?;
+SELECT id FROM people WHERE coalesce(archived?, false) = false ORDER BY id;
+SELECT id FROM people ORDER BY missing?, id DESC;
+SELECT id, sum(id) OVER (PARTITION BY region? ORDER BY id) AS running FROM 
people;
+SELECT id FROM people GROUP BY id HAVING max(missing?) IS NULL ORDER BY id;
+SELECT id FROM people GROUP BY id HAVING max(addr.state?) IS NULL ORDER BY id;
+SELECT id FROM people GROUP BY id ORDER BY max(addr.state?), id;
+SELECT id, CASE WHEN missing? IS NULL THEN 'none' ELSE 'some' END AS c FROM 
people;
+SELECT a.id FROM people a JOIN people b ON a.id = b.id AND a.missing? IS NULL 
ORDER BY a.id;
+SELECT a.id, b.missing?, b.addr.state? FROM people a JOIN people b USING (id) 
ORDER BY a.id;
+SELECT id, missing?, count(*) FROM people GROUP BY ALL ORDER BY id;
+SELECT count(*) + missing? AS c FROM people GROUP BY ALL;
+SELECT missing?, count(*) FROM people;
+SELECT count(missing?), max(id?) FROM people;
+SELECT DISTINCT missing?, addr?.city FROM people ORDER BY city;
+SELECT id, row_number() OVER (ORDER BY id) AS rn FROM people QUALIFY rn = 1 
AND missing? IS NULL;
+
+-- GROUP BY, HAVING, and ORDER BY can reference aliases of the SELECT list as 
usual.
+SELECT coalesce(region?, 'none') AS region, count(*) AS cnt FROM people GROUP 
BY region?;
+SELECT coalesce(region?, 'none') AS region, count(*) AS cnt FROM people
+GROUP BY 1 HAVING region? = 'none';
+SELECT coalesce(rank?, id) AS rank FROM people ORDER BY rank? DESC;
+
+-- Where a name can resolve in more than one way, an optional reference 
resolves like the same
+-- reference without `?`: ORDER BY falls back from the SELECT list to the 
columns of the FROM
+-- clause, and HAVING falls back from those columns to the SELECT list.
+SELECT id, named_struct('city', addr.city) AS addr FROM people ORDER BY 
addr.zip?;
+SELECT id, named_struct('city', addr.city) AS addr FROM people ORDER BY 
addr.state?, id DESC;
+SELECT id, named_struct('city', addr.city) AS addr FROM people ORDER BY 
addr?.state;
+SELECT named_struct('city', 'x') AS addr FROM people GROUP BY id ORDER BY 
addr.zip?;
+SELECT named_struct('state', 'CA') AS addr FROM people GROUP BY addr HAVING 
addr.state? = 'CA';
+SELECT named_struct('state', 'CA') AS addr FROM people GROUP BY addr
+HAVING addr.country? IS NULL;
+-- `addr.city` exists below the SELECT list but is not grouped, so HAVING 
falls back to the alias
+-- `addr` of the SELECT list, which has no `city`.
+SELECT named_struct('state', 'CA') AS addr FROM people GROUP BY id HAVING 
addr.city? IS NULL;
+-- A column that is out of scope is not found.
+SELECT DISTINCT id FROM people ORDER BY addr?, id DESC;
+-- ORDER BY and WHERE do not reach below an aliased subquery or a pipe 
operator, like without `?`.
+SELECT id FROM (SELECT id FROM people) s ORDER BY addr?, id;
+SELECT id FROM (SELECT id FROM people) s ORDER BY addr, id;
+FROM people |> SELECT id |> WHERE addr? IS NULL;
+FROM people |> SELECT id |> WHERE addr IS NULL;
+
+-- Common table expressions and set operations.
+WITH cte AS (SELECT id, missing? AS m FROM people) SELECT id, m, other? FROM 
cte ORDER BY id;
+SELECT id?, missing? FROM people UNION ALL SELECT missing?, id? FROM people
+ORDER BY id NULLS FIRST, missing NULLS FIRST;
+
+-- An optional reference that resolves keeps its type and nullability.
+SELECT id? + 1 AS next_id, addr?.city AS city FROM people;
+
+-- Qualified and nested references: `?` guards only the identifier that it 
follows.
+SELECT p.name? FROM people AS p;
+SELECT people.name?, people.addr.state? FROM people;
+SELECT addr?.city FROM people;
+SELECT addr?.state FROM people;
+SELECT addr.state? FROM people;
+SELECT ghost?.city FROM people;
+SELECT ghost.city? FROM people;
+SELECT ghost?.city? FROM people;
+SELECT t.name? FROM people;
+SELECT people?, p? FROM people AS p;
+-- The qualifier of a table can include its namespace and catalog, like 
without `?`.
+CREATE TABLE qualified_t (id INT) USING parquet;
+INSERT INTO qualified_t VALUES (1);
+SELECT qualified_t.missing? AS a, default.qualified_t.missing? AS b,
+  spark_catalog.default.qualified_t.missing? AS c
+FROM qualified_t;
+SELECT other.qualified_t.missing? FROM qualified_t;
+DROP TABLE qualified_t;
+
+-- Three-part names: `?` binds to the immediately preceding identifier only.
+SELECT info.addr.zip? FROM orgs;
+SELECT info.addr.geo? FROM orgs;
+SELECT info.loc?.city FROM orgs;
+SELECT info.loc.city? FROM orgs;
+SELECT info?.addr.zip FROM orgs;
+SELECT a?.b?.c? FROM orgs;
+SELECT missing?.a.b, info.addr.geo?.x FROM orgs;
+-- The fields of a column of type VOID are NULL, like without `?`.
+SELECT n.a, n.a? FROM VALUES (NULL) AS t(n);
+SELECT struct(id?, missing?) AS s FROM orgs;
+
+-- Errors other than not-found are still raised.
+SELECT x? FROM (SELECT 1 AS x) a JOIN (SELECT 2 AS x) b;
+SELECT addr.state? FROM people a JOIN people b ON a.id = b.id;
+SELECT id.missing? FROM people;
+SELECT missing? FROM people GROUP BY id;
+SELECT 1 AS c FROM (SELECT 1 AS x) a JOIN (SELECT 2 AS x) b ORDER BY x?;
+
+-- An optional reference to an existing column is still subject to the usual 
rules, also where
+-- the column is below the operator that references it, and in a subquery.
+SELECT addr.zip? FROM people GROUP BY id;
+SELECT id FROM people GROUP BY id DISTRIBUTE BY addr?;
+SELECT (SELECT max(v) FROM VALUES (1, 2, 3) AS t(k, v, x) GROUP BY k HAVING x? 
> 0) AS m
+FROM people;
+SELECT (SELECT max(v) FROM VALUES (1, 2, 3) AS t(k, v, x) GROUP BY k ORDER BY 
x? LIMIT 1) AS m
+FROM people;
+
+-- Lateral column aliases resolve as usual.
+SELECT id AS a, a? + 1 AS b, c? FROM people;
+SELECT named_struct('x', 1) AS s, s.x?, s.y? FROM people;
+SELECT missing? AS a, a? AS b FROM people;
+SELECT missing? AS a, a + 1 AS b FROM people;
+SELECT id AS a, a? + 1 AS b FROM people WHERE missing? IS NULL;
+-- A missing optional reference is NULL under its own name, but unlike the 
name of `addr.city`,
+-- that name is not a lateral column alias and not a GROUP BY alias, so a 
reference to it
+-- without `?` is not found. ORDER BY and HAVING can reference it as a column 
of the SELECT list.
+SELECT missing?, missing? IS NULL AS m, addr.city, upper(city) AS c FROM 
people;
+SELECT missing?, missing + 1 AS m FROM people;
+SELECT missing + 1 AS m, missing? FROM people;
+SELECT addr.state?, upper(state) AS s FROM people;
+SELECT missing?, count(*) AS c FROM people GROUP BY missing;
+SELECT addr.state?, count(*) AS c FROM people GROUP BY state;
+SELECT addr.city, count(*) AS c FROM people GROUP BY city ORDER BY city;
+SELECT missing?, count(*) AS c FROM people GROUP BY missing?;
+SELECT missing? AS m, count(*) AS c FROM people GROUP BY m;
+SELECT missing?, id FROM people ORDER BY missing, id;
+SELECT missing?, count(*) AS c FROM people GROUP BY ALL HAVING missing IS NULL;
+-- A field that the column does not have is not looked up in a lateral column 
alias of the same
+-- name, like without `?`.
+SELECT named_struct('state', 'CA') AS addr, addr.state? FROM people;
+
+-- Session variables resolve as usual.
+DECLARE OR REPLACE VARIABLE known INT DEFAULT 7;
+SELECT known?, unknown?;
+SELECT known? FROM people WHERE missing? IS NULL LIMIT 1;
+DECLARE OR REPLACE VARIABLE known_struct STRUCT<a: INT> DEFAULT 
named_struct('a', 1);
+SELECT known_struct.a?, known_struct.b?;
+SELECT session.known?, session.unknown?, system.session.unknown?;
+SELECT session?, system.session?;
+SELECT known_struct.b;
+-- The name of a missing field of a variable is not a lateral column alias 
either.
+SELECT known_struct.b?, b + 1;
+-- The fields of a variable of type VOID are an error, like without `?`, 
unlike those of a column.
+DECLARE OR REPLACE VARIABLE void_var DEFAULT NULL;

Review Comment:
   Done: `void_var` is dropped with the other session variables. In the 
regenerated golden files, the only change after that point is the DROP 
statement itself, and both analyzers agree on every query that follows. To 
confirm those queries now reach the single-pass resolver, I removed the outer 
scopes from `NameScope.tryResolveOptionalReferenceAsNull` locally. The golden 
run then failed with `SINGLE_PASS_FAILED_FIXED_POINT_SUCCEEDED` on the 
correlated scalar, EXISTS, and HAVING subquery cases.



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