srielau commented on code in PR #59874:
URL: https://github.com/apache/spark/pull/59874#discussion_r4632729424


##########
sql/core/src/main/scala/org/apache/spark/sql/catalyst/parser/ParseSqlResult.scala:
##########
@@ -682,6 +984,9 @@ object ParseSqlResult {
           add(tempViewParts(r.identifier))
         case r: ResolvedIdentifier if role == TableRefRole.Target =>
           add(catalogIdentParts(r.catalog.name(), r.identifier))
+        case l: LocalRelation =>

Review Comment:
   Fixed in 4c69a8a9caf. `visitChildPlans` has an `InsertIntoSuppliedRelation` 
case that visits the non-child `table` slot as the target and the query as the 
source, so the target is reported. Covered by 'ANALYZE reports an INSERT target 
on a supplied relation'.



##########
sql/core/src/main/scala/org/apache/spark/sql/catalyst/parser/ParseSqlResult.scala:
##########
@@ -238,28 +426,142 @@ object ParseSqlResult {
     }
   }
 
-  /** Analyze `plan` without executing it. Scripts never reach QueryExecution. 
*/
+  /**
+   * Analyze `plan` without executing it. Scripts never reach QueryExecution, 
which runs
+   * a script when analysis starts; [[analyzePlan]] refuses them before that.
+   */
   private def analyze(
       session: ClassicSparkSession,
-      plan: LogicalPlan): (Option[LogicalPlan], Option[SparkThrowable with 
Throwable]) = {
-    plan match {
-      case _: CompoundBody =>
-        (None, Some(QueryExecutionErrors.parseSqlAnalyzeUnsupportedScript()))
+      analyzerOpt: Option[Analyzer],
+      plan: LogicalPlan,
+      markers: Seq[(String, DataType)])
+      : (Option[LogicalPlan], Option[SparkThrowable with Throwable]) = {
+    try {
+      // Refuse a script before any binding wraps it, as [[analyzePlan]] does 
after.
+      if (QueryExecution.isUnresolvedPlanSqlScript(plan)) {
+        throw QueryExecutionErrors.parseSqlAnalyzeUnsupportedScript()
+      }
+      val toAnalyze = bindSuppliedParameterMarkers(plan, markers)
+      (Some(analyzePlan(session, analyzerOpt, toAnalyze)), None)
+    } catch {
+      case e: SparkThrowable with Throwable if !isInternalError(e) => (None, 
Some(e))
+    }
+  }
+
+  private def parseKnownVariable(spec: (String, String)): (Seq[String], 
DataType) = {
+    val (name, typeDdl) = spec
+    val parts = parseKnownName(name, "variables")
+    // A session variable has at most three parts (system.session.v), a local 
two (proc.p).
+    val maxParts = if (SuppliedVariableRegistry.isSessionName(parts)) 3 else 2
+    if (parts.length > maxParts) {
+      throw QueryExecutionErrors.invalidParseSqlContext("variables", name)
+    }
+    val dataType = try {
+      DataType.fromDDL(typeDdl)
+    } catch {
+      case _: ParseException | _: AnalysisException =>
+        throw QueryExecutionErrors.invalidParseSqlContext("variables", typeDdl)
+    }
+    (parts, dataType)
+  }
+
+  private def parseKnownRelation(spec: (String, String)): (Seq[String], 
StructType) = {
+    val (name, schemaDdl) = spec
+    val parts = parseKnownName(name, "relations")
+    val dataType = try {
+      DataType.fromDDL(schemaDdl)
+    } catch {
+      case _: ParseException | _: AnalysisException =>
+        throw QueryExecutionErrors.invalidParseSqlContext("relations", 
schemaDdl)
+    }
+    dataType match {
+      case schema: StructType if schema.nonEmpty =>
+        (parts, CharVarcharUtils.replaceCharVarcharWithStringInSchema(schema))
       case _ =>
-        try {
-          (Some(analyzePlan(session, plan)), None)
-        } catch {
-          case e: SparkThrowable with Throwable if !isInternalError(e) => 
(None, Some(e))
-        }
+        throw QueryExecutionErrors.invalidParseSqlContext("relations", 
schemaDdl)
+    }
+  }
+
+  private def parseKnownName(name: String, parameter: String): Seq[String] = {
+    val parts = try {
+      parser.get().parseMultipartIdentifier(name)
+    } catch {
+      case _: ParseException =>
+        throw QueryExecutionErrors.invalidParseSqlContext(parameter, name)
+    }
+    if (parts.isEmpty) {
+      throw QueryExecutionErrors.invalidParseSqlContext(parameter, name)
+    }
+    parts
+  }
+
+  private def parseKnownParameterMarker(spec: (String, String)): (String, 
DataType) = {
+    val (name, typeDdl) = spec
+    val dataType = try {
+      DataType.fromDDL(typeDdl)
+    } catch {
+      case _: ParseException | _: AnalysisException =>
+        throw QueryExecutionErrors.invalidParseSqlContext("parameter_markers", 
typeDdl)
     }
+    val trimmed = name.trim
+    if (trimmed == "?") {
+      ("?", dataType)
+    } else {
+      val parts = parseKnownName(trimmed, "parameter_markers")
+      if (parts.length != 1) {
+        throw QueryExecutionErrors.invalidParseSqlContext("parameter_markers", 
name)
+      }
+      (parts.head, dataType)
+    }
+  }
+
+  /**
+   * Bind caller-supplied marker types with the [[BindParameters]] rule that
+   * `sql(..., args)` uses, so the plan is typed the way a real query with 
those
+   * arguments would be. Markers the plan does not use leave it unchanged.
+   */
+  private def bindSuppliedParameterMarkers(
+      plan: LogicalPlan,
+      markers: Seq[(String, DataType)]): LogicalPlan = {
+    val used = if (markers.isEmpty) None else 
collectPlanReferences(plan).parameterMarkers
+    if (used.isEmpty) {
+      plan
+    } else {
+      // The bound values are built during constant folding of parse_sql, so 
they would
+      // otherwise inherit the outer call's origin. Build them without one, so 
an error on a
+      // marker does not report the outer query text as its context.
+      def nullValue(dataType: DataType): Literal =
+        CurrentOrigin.withOrigin(Origin()) { Literal.create(null, dataType) }
+      val namedArgs = markers.collect {
+        case (name, dataType) if name != "?" => name -> nullValue(dataType)
+      }
+      val posArgs = markers.collect {
+        case ("?", dataType) => nullValue(dataType)
+      }
+      val usesNamed = used.exists(m => (m \ "named") != JNothing)
+      val usesPos = used.exists(m => (m \ "unnamed_count") != JNothing)
+      val wrapped = if (usesNamed && namedArgs.nonEmpty) {
+        NameParameterizedQuery(plan, namedArgs.toMap)
+      } else if (usesPos && posArgs.nonEmpty) {
+        PosParameterizedQuery(plan, posArgs)
+      } else {
+        plan
+      }
+      BindParameters(wrapped)

Review Comment:
   Fixed in 4c69a8a9caf. `bindSuppliedParameterMarkers` recurses into a 
`SupervisingCommand` first, and binds the markers of its supervised plan. 
Covered by 'ANALYZE binds markers inside EXPLAIN and DESCRIBE QUERY'.



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