dtenedor commented on code in PR #60367: URL: https://github.com/apache/spark/pull/60367#discussion_r4579536415
########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/OptionalReferenceValidation.scala: ########## @@ -0,0 +1,108 @@ +/* + * 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.parser + +import org.antlr.v4.runtime.ParserRuleContext +import org.antlr.v4.runtime.tree.ParseTree + +import org.apache.spark.sql.catalyst.parser.SqlBaseParser._ +import org.apache.spark.sql.catalyst.util.SparkParserUtils +import org.apache.spark.sql.errors.QueryParsingErrors + +/** Checks where the `?` optional-reference operator can appear in a SQL statement. */ +object OptionalReferenceValidation { + + /** + * Throws an error for the optional reference `ctx`, i.e. the parse tree of a reference with a + * `?` after one of its name parts, if `ctx` is part of an UPDATE, DELETE, MERGE, or AUTO CDC + * statement, of the condition of INSERT ... REPLACE, of a partition specification, or of an + * expression that defines a table object. + * + * The query of an INSERT, including INSERT OVERWRITE, and of a CREATE OR REPLACE TABLE AS + * SELECT is allowed to have optional references: like any query, it only reads data, and the + * rows that these statements replace do not depend on it. Review Comment: Resolving this thread: the follow-up review accepted the statement-kind boundary, and the validator doc now also says that CREATE OR REPLACE TABLE AS SELECT has no REPLACE condition and accepts `?` in its query like any INSERT. ########## 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" : [ + "Definitions of tables and functions must not contain optional references." Review Comment: Done. `IN_DDL` now reads "Column and parameter defaults, generation expressions, CHECK constraints, and table options must not contain optional references.", the conf doc lists "the DEFAULT, GENERATED ALWAYS AS, CHECK, and OPTIONS clauses of table and function definitions", and the validator doc names the same clauses and no longer attributes a REPLACE condition to CREATE OR REPLACE TABLE AS SELECT. The PR description says that SQL function bodies, view queries, and CTAS queries accept `?`. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/OptionalReferenceValidation.scala: ########## @@ -0,0 +1,115 @@ +/* + * 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.parser + +import org.antlr.v4.runtime.ParserRuleContext +import org.antlr.v4.runtime.tree.ParseTree + +import org.apache.spark.sql.catalyst.parser.SqlBaseParser._ +import org.apache.spark.sql.catalyst.util.SparkParserUtils +import org.apache.spark.sql.errors.QueryParsingErrors + +/** Checks where the `?` optional-reference operator can appear in a SQL statement. */ +object OptionalReferenceValidation { + + /** + * Throws an error for the optional reference `ctx`, i.e. the parse tree of a reference with a + * `?` after one of its name parts, if `ctx` is part of an UPDATE, DELETE, MERGE, or AUTO CDC + * statement, of the condition of INSERT ... REPLACE, of a partition specification, or of an + * expression that is stored in the definition of a table or a function. + * + * The boundary is the kind of statement. UPDATE, DELETE, MERGE, and AUTO CDC exist to modify + * existing rows, so they reject optional references everywhere, including in the source query of + * MERGE and in common table expressions. INSERT and CREATE OR REPLACE TABLE AS SELECT reject them + * only in the REPLACE condition, a predicate on the target table: their queries produce the rows + * to write, and a missing column in such a query makes the written rows differ in the same way as + * in any other query. This holds where the written rows also decide which existing rows are + * replaced: an INSERT OVERWRITE with dynamic partition overwrite replaces the partitions of the + * written rows, and INSERT ... REPLACE ON or REPLACE USING deletes the target rows that match + * them. + * + * {{{ + * UPDATE t SET a = b?; -- IN_DML + * WITH s AS (SELECT a? FROM u) DELETE FROM t WHERE ...; -- IN_DML + * INSERT INTO t REPLACE WHERE a? IS NULL SELECT ...; -- IN_DML + * TRUNCATE TABLE t PARTITION (p = :p?); -- IN_PARTITION_SPEC + * CREATE TABLE t (a INT, b INT DEFAULT a?); -- IN_DDL + * INSERT OVERWRITE t SELECT a? FROM s; -- allowed + * }}} + */ + def validate(ctx: ParserRuleContext): Unit = { + Iterator + .iterate(ctx.getParent)(_.getParent) + .takeWhile(_ != null) + .flatMap(unsupportedContextError(_, ctx)) + .nextOption() + .foreach(error => throw error) + } + + /** + * Validates the optional named parameter markers in the parse tree `tree` with [[validate]]. + * This is for the markers that are substituted in `sqlText`, the text that `tree` was parsed + * from, before the statement is parsed into a plan. + */ + def validateNamedParameterMarkers(tree: ParseTree, sqlText: String): Unit = tree match { + case namedParameter: NamedParameterLiteralContext if namedParameter.optionalMarker != null => + SparkParserUtils.withOrigin(namedParameter, Some(sqlText)) { + validate(namedParameter) + } + case _ => + (0 until tree.getChildCount).foreach { index => + validateNamedParameterMarkers(tree.getChild(index), sqlText) + } + } + + /** + * Returns the error for the optional reference `ctx` if its ancestor `ancestor` is a statement + * or a clause that does not support optional references. + */ + private def unsupportedContextError( + ancestor: ParserRuleContext, + ctx: ParserRuleContext): Option[Throwable] = ancestor match { + case _: DeleteFromTableContext => + Some(QueryParsingErrors.optionalReferenceInDmlNotSupportedError("DELETE", ctx)) + case _: UpdateTableContext => + Some(QueryParsingErrors.optionalReferenceInDmlNotSupportedError("UPDATE", ctx)) + case _: MergeIntoTableContext => + Some(QueryParsingErrors.optionalReferenceInDmlNotSupportedError("MERGE", ctx)) + case _: InsertIntoReplaceBooleanCondContext => + Some(QueryParsingErrors.optionalReferenceInDmlNotSupportedError("INSERT", ctx)) Review Comment: Done. The REPLACE condition now has the context `INSERT ... REPLACE`, both in the parser (`InsertIntoReplaceBooleanCondContext`) and in `CheckOptionalReferencesInDml` for `OverwriteByExpression`, which is the plan of `INSERT ... REPLACE WHERE` and of `DataFrameWriterV2.overwrite(condition)`. The `IN_DML` text now reads "Statements that modify existing rows, and conditions that select the rows to replace, must not contain optional references." `OptionalReferencesParserSuite`, `DataFrameWriterV2Suite`, and the golden file expect the new context; `INSERT INTO target SELECT missing? FROM people` still runs. On the CALL question from the review body: I kept `?` allowed in CALL arguments and documented why in the validator doc and the PR description. The arguments of CALL are values, like the arguments of a function in a query; the rejection in UPDATE, DELETE, and MERGE targets a predicate that selects existing rows, which a missing column turns into `NULL IS NULL` or `NULL = x` for every row, while a procedure receives the NULL as an argument that its own code sees and can validate. `CALL p(cutoff => :cutoff?)` is also the natural way to pass an argument only when it is bound. Spark ships no procedures, so this reaches connector implementations only, and rejecting later would be the smaller change if a committer prefers it: a `CallContext` case in `OptionalReferenceValidation` and a `Call` case in `CheckOptionalReferencesInDml`. ########## sql/core/src/main/scala/org/apache/spark/sql/classic/SparkSession.scala: ########## @@ -552,7 +552,10 @@ class SparkSession private( } // In legacy mode, wrap with PosParameterizedQuery for analyzer binding if (args.nonEmpty && sessionState.conf.legacyParameterSubstitutionConstantsOnly) { - PosParameterizedQuery(parsed, paramContext.params) + PosParameterizedQuery( + parsed, + paramContext.params, + hasOptionalReferences = OptionalReferences.hasOptionalReferences(parsed)) Review Comment: Done, both sites compute `sessionState.conf.optionalReferencesEnabled && OptionalReferences.hasOptionalReferences(parsed)`. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/SubstituteParamsParser.scala: ########## @@ -73,12 +73,39 @@ class SubstituteParamsParser extends Logging { // Use shared parser configuration to ensure consistency with main parser. AbstractParser.configureParser(parser, sqlText, tokenStream, SQLConf.get) - val astBuilder = new SubstituteParmsAstBuilder() - // Use shared two-stage parsing strategy for consistent error handling. - val ctx = AbstractParser.executeWithTwoStageStrategy(parser, tokenStream, - _.compoundOrSingleStatement()) - val parameterLocations = astBuilder.extractParameterLocations(ctx) + def parseParameterLocations(): (ParserRuleContext, ParameterLocationInfo) = { + val ctx = AbstractParser.executeWithTwoStageStrategy(parser, tokenStream, + _.compoundOrSingleStatement()) + (ctx, new SubstituteParmsAstBuilder().extractParameterLocations(ctx)) + } + val (ctx, parameterLocations) = parseParameterLocations() match { + // A rule that accepts any tokens, such as `SET .*?`, parses a statement such as + // `SET VAR v = :p?`, which is not valid without optional references. Only the parser that + // builds the plan can tell, so parse a statement with a `?` that is not a parameter marker + // again with optional references. + case (_, locations) + if parser.optional_references_enabled && + AbstractParser.questions(tokenStream).length > + locations.positionalParameterLocations.length && + AbstractParser.restartWithOptionalReferences(parser, tokenStream) => + parseParameterLocations() + case parsed => + parsed + } + // In a statement with optional references, a `?` after an identifier or a non-reserved keyword + // is an optional reference where the syntax allows a reference. The remaining markers must + // not take the values of such a `?` silently, so a value without a marker is an error. + val numPositionalMarkers = parameterLocations.positionalParameterLocations.length + if (parameterLocations.hasOptionalReferences && Review Comment: Done. The check now applies only to statements without named markers, with a comment on why: with named markers every value binds by name, and `ParameterHandler.handleHybridParameters` passes the named USING values as positional values too. New golden cases: `EXECUTE IMMEDIATE 'SELECT id FROM people WHERE id = :x AND deleted? IS NULL' USING 1 AS x` returns the row with id 1, and `EXECUTE IMMEDIATE 'SELECT missing?, ? AS g FROM people' USING 5 AS a, 6 AS b`, named values for a statement with one `?` marker and an optional reference, still fails with `UNUSED_SQL_PARAMETER_VALUES` for 1 marker and 2 values. -- 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]
