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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckOptionalReferencesInDml.scala:
##########
@@ -0,0 +1,72 @@
+/*
+ * 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
+import org.apache.spark.sql.catalyst.plans.logical.{
+  DeleteFromTable,
+  LogicalPlan,
+  MergeIntoTable,
+  OverwriteByExpression,
+  UpdateTable
+}
+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.
+ *
+ * {{{
+ *   df.writeTo("t").overwrite(expr("deleted_at? IS NULL"))
+ * }}}
+ */
+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))

Review Comment:
   Done. `CheckOptionalReferencesInDml` now also walks the source plan of a 
`MergeIntoTable` and raises `IN_DML` with the `MERGE` context, with a doc note 
on why: `Dataset.mergeInto` and the Connect MERGE command put the unanalyzed 
plan of the source DataFrame there. New test in `MergeIntoDataFrameSuite`: a 
source built with `spark.sql("SELECT pk, is_deleted? AS is_deleted FROM 
source")` and one built with `selectExpr` fail with `IN_DML`/`MERGE` and the 
fragment of the reference; a source that reads a view created from the same 
query still runs, since the view resolves its own `?`.



##########
sql/api/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseParser.g4:
##########
@@ -1727,16 +1778,28 @@ primaryExpression
     | identifier ARROW expression                                              
                #lambda
     | LEFT_PAREN identifier (COMMA identifier)+ RIGHT_PAREN ARROW expression   
                #lambda
     | value=primaryExpression LEFT_BRACKET index=valueExpression RIGHT_BRACKET 
                #subscript
-    | identifier                                                               
                #columnReference
-    | base=primaryExpression DOT fieldName=identifier                          
                #dereference
+    | identifier optionalMarker=QUESTION_WITH_OPTIONAL_REFERENCES?             
               #columnReference

Review Comment:
   Done. The comment above `overlayExpression` now states the measured cost 
with the conf off (about 2% of the parse time of the TPC-DS queries to about 9% 
for a statement with 1,000 nested field references) and why it stays in the 
shared parser: `AstBuilder` visits the same generated contexts in both parse 
stages, and keeping the syntax out of first-stage and conf-off parses would 
need a second generated parser whose contexts `AstBuilder` cannot visit and 
whose grammar would have to accept every statement without `?` exactly as this 
one does.



##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -7039,6 +7039,29 @@
     ],
     "sqlState" : "HY008"
   },
+  "OPTIONAL_REFERENCE_NOT_SUPPORTED" : {
+    "message" : [
+      "The `?` optional-reference operator is not supported in <context>."
+    ],
+    "subClass" : {
+      "IN_DDL" : {
+        "message" : [
+          "Table definitions must not contain optional references."

Review Comment:
   Done. `IN_DDL` now reads "Definitions of tables and functions must not 
contain optional references.", the validator's doc has the same scope (an 
expression stored in the definition of a table or a function), and 
`UNUSED_SQL_PARAMETER_VALUES` limits the reading to a `?` that follows an 
identifier or a non-reserved keyword "where the syntax allows a reference". 
`OptionalReferencesParserSuite` gained `CREATE TEMPORARY FUNCTION f(x INT 
DEFAULT a?) RETURNS INT RETURN x` as an `IN_DDL` case with the `DEFAULT` 
context.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/parameters.scala:
##########
@@ -174,6 +174,22 @@ object MoveParameterizedQueriesDown extends 
Rule[LogicalPlan] {
  */
 object BindParameters extends Rule[LogicalPlan] with QueryErrorsBase {
 
+  /**
+   * Fails if a statement with optional references has fewer positional 
parameter markers than
+   * values. In such a statement, a `?` after an identifier or a non-reserved 
keyword is an
+   * optional reference where the syntax allows a reference, and the remaining 
markers must not
+   * take its value silently. See `SubstituteParamsParser` for the statements 
that are not bound
+   * here.
+   */
+  private def checkUnusedPositionalArgs(plan: LogicalPlan, numMarkers: Int, 
numArgs: Int): Unit = {
+    def hasOptionalReferences: Boolean = plan.exists { operator =>
+      
operator.expressions.exists(OptionalReferences.unresolvedOptionalReference(_).isDefined)

Review Comment:
   Done. `PosParameterizedQuery` and `GeneralParameterizedQuery` now carry 
`hasOptionalReferences`, which `SparkSession` computes from the parsed plan 
with the new `OptionalReferences.hasOptionalReferences` before any analysis; it 
looks into the plans of subquery expressions and into common table expressions 
(the `innerChildren` of `UnresolvedWith`). `checkUnusedPositionalArgs` goes by 
that fact instead of searching for references that are still unresolved. New 
`ParametersSuite` test in the legacy binding mode, over a view with columns 
`id` and `distinct`: `SELECT id?, first(DISTINCT ?) AS f, ? AS g FROM v` with 
two values fails with `UNUSED_SQL_PARAMETER_VALUES` (1 marker, 2 values) 
through `spark.sql(text, args)` and through `EXECUTE IMMEDIATE ... USING`, and 
runs with one value; `SELECT ? AS a FROM v` with two values still runs and 
ignores the extra value in both paths. The existing legacy case with references 
that stay unresolved is unchanged.



##########
docs/sql-migration-guide.md:
##########
@@ -99,6 +99,7 @@ license: |
 - Since Spark 4.4, a CHECK constraint that `ALTER TABLE ... ADD CONSTRAINT` 
adds to a Data Source V2 table, and whose condition reads the current time, 
date, catalog, user and the like, such as `ts <= current_timestamp()` or `db = 
current_database()`, is checked against their values at the time of each write. 
Previously, it was checked against their values at the time of the `ALTER 
TABLE`, unless a write could not read back a predicate for its condition, such 
as one with a lambda function or one that passes a column to `datediff`, `year` 
or `upper` (SPARK-60032). Such a constraint is stored without a predicate, so 
each write parses and analyzes its SQL text under the session of the write, as 
it does for a constraint without a predicate that `CREATE TABLE` adds. A 
setting of the write such as `spark.sql.ansi.enforceReservedKeywords`, which 
reserves `TIME`, or `spark.sql.ansi.doubleQuotedIdentifiers` can then make it 
fail to parse the text or read it differently. A row-level operation
  that copies unchanged rows, such as a `DELETE` or `UPDATE` on a copy-on-write 
table, fails with `CHECK_CONSTRAINT_VIOLATION` on a copied row that no longer 
satisfies the condition. For example, `ts >= current_timestamp() - INTERVAL 30 
DAYS` now fails such a `DELETE` once a copied row is older than 30 days. A 
condition that Spark detects a write could resolve differently is stored as 
before, so a write accepts and rejects the same rows for it as before. Examples 
are conditions that also read a variable, a `CHAR` column, a name with more 
than one part such as a column qualified by the table name, or a constant that 
depends on the session time zone, such as `'2024-01-01 00:00:00'` cast to a 
timestamp. So are conditions with a name such as `current_date` or `user` 
without parentheses, which a write can read as a column name, and conditions 
whose text the parser settings of the `ALTER TABLE`, such as 
`spark.sql.ansi.doubleQuotedIdentifiers` or 
`spark.sql.parser.escapedStringLiterals`, r
 ead differently from their default values. ANSI mode, 
`spark.sql.timestampType` and the session time zone are taken from the session 
for this comparison, as for a generation expression. A condition that reads the 
current date or time only through a typed literal such as `DATE 'today'` is 
also stored as before. An existing constraint keeps its stored predicate until 
it is dropped and added again. `Check.predicate()` is null for a constraint 
stored without a predicate, so a connector that validates or enforces it itself 
has to evaluate `Check.predicateSql()`. To restore the previous behavior, set 
`spark.sql.legacy.freezeCurrentValuesInCheckConstraint` to `true` before adding 
the constraint. A constraint added without it is not changed.
 - 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 name in the body of a SQL function that is called in a 
subquery no longer resolves to a column of the query around the subquery. It 
resolves like a name in the body of a function that is called directly: to a 
parameter or a column of the body, or else to a session variable. For example, 
after `DECLARE VARIABLE v INT DEFAULT 100` and `CREATE FUNCTION f() RETURNS INT 
RETURN v`, `SELECT (SELECT f()) FROM VALUES (5) AS t(v)` returns 100 instead of 
5. To restore the previous behavior, set 
`spark.sql.legacy.sqlFunctionBodyResolvesOuterReferences` to `true`.

Review Comment:
   Done, the example now creates a temporary function.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/OptionalReferences.scala:
##########
@@ -0,0 +1,410 @@
+/*
+ * 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 java.util.Locale
+
+import scala.annotation.tailrec
+import scala.util.{Left => EitherLeft, Right => EitherRight}
+
+import org.apache.spark.SparkThrowable
+import org.apache.spark.sql.catalyst.SqlScriptingContextManager
+import org.apache.spark.sql.catalyst.expressions.{
+  Alias,
+  Attribute,
+  Expression,
+  ExtractValue,
+  Literal,
+  NonNullLiteral,
+  SubqueryExpression
+}
+import org.apache.spark.sql.catalyst.trees.TreeNodeTag
+import org.apache.spark.sql.catalyst.util.{toPrettySQL, MetadataColumnHelper}
+import org.apache.spark.sql.connector.catalog.CatalogManager
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{NullType, StringType}
+
+/**
+ * Optional references: a `?` after an identifier of a column, field, or 
variable reference, or
+ * after a named parameter marker, makes that identifier optional. When name 
resolution finds no
+ * match for an optional identifier, the reference resolves to a static NULL 
of type VOID instead
+ * of raising a not-found error. Ambiguity and type errors are still raised.
+ *
+ * {{{
+ *   -- `t` has a column `id` but no column `name`:
+ *   SELECT id?, name? FROM t;
+ *   -- Project [id#1, null AS name#2]
+ * }}}
+ */
+object OptionalReferences {
+
+  /**
+   * Indices of the name parts of an unresolved multipart name (an 
`UnresolvedAttribute` or an
+   * `UnresolvedNamedLambdaVariable`) that are followed by `?`.
+   */
+  val OPTIONAL_NAME_PART_INDICES: TreeNodeTag[Set[Int]] =
+    TreeNodeTag[Set[Int]]("optionalNamePartIndices")
+
+  /**
+   * Marks an [[UnresolvedExtractValue]] field, a named parameter marker, or 
an IDENTIFIER clause
+   * followed by `?`.
+   */
+  val OPTIONAL_REFERENCE: TreeNodeTag[Unit] = 
TreeNodeTag[Unit]("optionalReference")
+
+  /**
+   * Marks the NULL that an unresolvable optional reference resolves to, see 
[[nullReference]], and
+   * the alias that names it, see [[implicitAlias]].
+   *
+   * The three tags describe the statement: they are facts about the reference 
as written, which

Review Comment:
   Done. The doc of `NULL_REFERENCE` now separates the two parser tags, which 
are facts about the reference as written and stay true in every analysis, from 
this tag, which records a decision of one analysis (the reference matched 
nothing) on the NULL and the alias that this analysis creates: only the 
analyzer sets it, only on these nodes, and never on the nodes of the plan that 
it receives. The PR description's Tags paragraph says the same.



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