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


##########
sql/core/src/main/scala/org/apache/spark/sql/catalyst/expressions/ParseSql.scala:
##########
@@ -146,12 +218,15 @@ case class ParseSql(
 
   override val nodePatterns: Seq[TreePattern] = Seq(PARSE_SQL)
 
-  override def nullIntolerant: Boolean = true
+  // A NULL current_catalog or current_schema is valid, so null propagation 
must not
+  // rewrite the call. eval returns NULL itself for a NULL statement or mode.

Review Comment:
   Applied the suggested comment in 4c69a8a9caf.



##########
sql/core/src/main/scala/org/apache/spark/sql/catalyst/parser/ParseSqlResult.scala:
##########
@@ -173,13 +234,140 @@ object ParseSqlResult {
   /** Analyze `plan`, including nested EXPLAIN / DESCRIBE QUERY payloads. */
   private def analyzePlan(
       session: ClassicSparkSession,
+      analyzerOpt: Option[Analyzer],
       plan: LogicalPlan): LogicalPlan = {
+    // Checked here, before QueryExecution, because QueryExecution executes a 
script (also
+    // when named parameter markers wrap it) as soon as analysis starts. A 
script under a
+    // supervising command is refused by the recursive call below.
+    if (QueryExecution.isUnresolvedPlanSqlScript(plan)) {
+      throw QueryExecutionErrors.parseSqlAnalyzeUnsupportedScript()
+    }
     val toAnalyze = plan match {
       case s: SupervisingCommand =>
-        s.withTransformedSupervisedPlan(inner => analyzePlan(session, inner))
+        s.withTransformedSupervisedPlan(inner => analyzePlan(session, 
analyzerOpt, inner))
       case other => other
     }
-    session.sessionState.executePlan(toAnalyze, 
CommandExecutionMode.SKIP).analyzed
+    new QueryExecution(
+      session,
+      toAnalyze,
+      mode = CommandExecutionMode.SKIP,
+      analyzerOpt = analyzerOpt).analyzed
+  }
+
+  /**
+   * Run `f` under the call's conf when the call gives its own SQL path. The 
copy enables the
+   * path feature for this call only; the invoker's conf is not changed.
+   */
+  private def inCallConf[T](conf: Option[SQLConf])(f: => T): T = conf match {
+    case Some(c) => SQLConf.withExistingConf(c)(f)
+    case None => f
+  }
+
+  /**
+   * The analyzer for one ANALYZE call with `current_catalog` / 
`current_schema` /
+   * `current_path` overrides, and the conf to run it under when the call 
gives a path.
+   * The session is not changed: the call gets its own catalog manager, v1 
catalog and conf.
+   */
+  private def contextAnalyzer(
+      session: ClassicSparkSession,
+      context: ParseSqlAnalyzeContext): (Analyzer, Option[SQLConf]) = {
+    val state = session.sessionState
+    val mgr = state.catalogManager
+    val invokerCatalog = mgr.currentCatalog.name()
+    val target = context.catalog.map(checkedContextValue("current_catalog", _))
+      .map(mgr.catalog)
+      .getOrElse(mgr.currentCatalog)
+    val catalogName = target.name()
+    val isSession = CatalogV2Util.isSessionCatalog(target)
+    val switched = catalogName != invokerCatalog
+    val namespace: Array[String] = context.schema match {
+      case Some(schema) => checkedNamespace(schema, isSession)
+      case None if switched =>
+        if (isSession) Array(state.conf.defaultDatabase) else 
target.defaultNamespace()
+      case None => mgr.currentNamespace
+    }
+    target match {
+      case ns: SupportsNamespaces if !isSession && 
!ns.namespaceExists(namespace) =>
+        throw QueryCompilationErrors.noSuchNamespaceError(catalogName +: 
namespace)
+      case _ =>
+    }
+    val v1 = perCallSessionCatalog(session)
+    if (isSession) v1.setCurrentDatabase(namespace.head)
+    val callConf = context.path.map { _ =>
+      val copy = state.conf.clone()
+      copy.setConf(SQLConf.PATH_ENABLED, true)
+      copy
+    }
+    // PATH in the call's path means the invoker's path, as in SET PATH. 
CURRENT_SCHEMA
+    // stays a marker that resolves against the call's schema.
+    val pathOverride = (context.path, callConf) match {
+      case (Some(path), Some(conf)) => callPathOverride(path, conf, mgr)
+      case _ => None
+    }
+    val analyzer = state.analyzer.withCatalogManager(
+      new AnalysisCatalogManager(mgr, catalogName, namespace, v1, 
pathOverride))
+    (analyzer, callConf)
+  }
+
+  /**
+   * The SQL path of one call. A blank path clears it to the conf default, as 
`SET PATH`
+   * does. A path that expands to nothing does the same.
+   */
+  private def callPathOverride(
+      path: String,
+      conf: SQLConf,
+      mgr: CatalogManager): 
Option[Option[Seq[CatalogManager.SessionPathEntry]]] = {
+    if (path.trim.isEmpty) {
+      Some(None)
+    } else {
+      val elements = try {
+        parser.get().parsePathElements(path)
+      } catch {
+        case _: ParseException =>
+          throw QueryExecutionErrors.invalidParseSqlContext("current_path", 
path)
+      }
+      val expanded = PathElement.validateNoStaticDuplicates(
+        PathElement.expand(elements, conf, mgr),
+        conf.caseSensitiveAnalysis)
+      if (expanded.isEmpty) Some(None) else Some(Some(expanded))
+    }
+  }
+
+  private def checkedContextValue(parameter: String, value: String): String = {
+    if (value.trim.isEmpty) {
+      throw QueryExecutionErrors.invalidParseSqlContext(parameter, value)
+    }
+    value
+  }
+
+  /** A `current_schema` value as a namespace. The session catalog takes one 
part. */
+  private def checkedNamespace(schema: String, isSession: Boolean): 
Array[String] = {
+    val parts = try {
+      
parser.get().parseMultipartIdentifier(checkedContextValue("current_schema", 
schema))
+    } catch {
+      case _: ParseException =>
+        throw QueryExecutionErrors.invalidParseSqlContext("current_schema", 
schema)
+    }
+    if (parts.isEmpty || (isSession && parts.length != 1)) {
+      throw QueryExecutionErrors.invalidParseSqlContext("current_schema", 
schema)
+    }
+    parts.toArray
+  }
+
+  /** A v1 catalog copy with the invoker's temp views and current database. */
+  private def perCallSessionCatalog(session: ClassicSparkSession): 
SessionCatalog = {
+    val state = session.sessionState
+    val catalog = new SessionCatalog(
+      () => session.sharedState.externalCatalog,
+      () => session.sharedState.globalTempViewManager,
+      state.functionRegistry,

Review Comment:
   Fixed in 4c69a8a9caf. `SessionCatalog` has a `registryMonitor` that defaults 
to the catalog itself. A per-call copy points it at the session catalog, and 
`resolvePersistentTableFunction` and the lazy builder lock on it, so the copy 
and the session serialize their loads on one monitor.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -1557,6 +1569,60 @@ class Analyzer(
     }
   }
 
+  /**
+   * Resolve an INSERT whose target is a caller-supplied relation into
+   * [[InsertIntoSuppliedRelation]]. No other rule resolves 
[[InsertIntoStatement]] for such a
+   * target, so without this rule the statement would stay unresolved.
+   */
+  object ResolveInsertIntoSuppliedRelation extends ResolveInsertionBase {
+    override def apply(plan: LogicalPlan): LogicalPlan = {
+      if (SuppliedRelationRegistry.get().isEmpty) {
+        plan
+      } else {
+        plan.resolveOperatorsUp {
+          case i: InsertIntoStatement
+              if i.query.resolved && 
SuppliedRelationRegistry.isSupplied(i.table) =>
+            EliminateSubqueryAliases(i.table) match {
+              case local: LocalRelation => resolveInsert(i, local)
+              case _ => i
+            }
+        }
+      }
+    }
+
+    private def resolveInsert(
+        i: InsertIntoStatement,
+        local: LocalRelation): LogicalPlan = {
+      val name = 
local.getTagValue(SuppliedRelationRegistry.IDENTITY_TAG).getOrElse(Nil).quoted
+      val byName = i.byName || i.userSpecifiedCols.nonEmpty
+      val query =
+        if (i.userSpecifiedCols.nonEmpty) createProjectForByNameQuery(name, i) 
else i.query
+      val staticPartitions = i.partitionSpec.collect { case (col, Some(value)) 
=>
+        val attr = local.resolve(Seq(col), this.resolver).getOrElse(
+          throw QueryCompilationErrors.unresolvedAttributeError(
+            "UNRESOLVED_COLUMN", col, local.output.map(_.name), i.origin))
+        attr.name -> Alias(Cast(Literal(value), attr.dataType), attr.name)()
+      }
+      val withPartitions = if (staticPartitions.isEmpty) {
+        query
+      } else if (byName) {
+        Project(query.output ++ staticPartitions.values, query)
+      } else {
+        val dynamic = query.output.iterator
+        val columns = local.output.flatMap { attr =>
+          staticPartitions.collectFirst {
+            case (col, value) if this.resolver(col, attr.name) => value
+          }.orElse(if (dynamic.hasNext) Some(dynamic.next()) else None)
+        }
+        Project(columns ++ dynamic, query)
+      }
+      val newQuery = TableOutputResolver.resolveOutputColumns(
+        name, local.output, withPartitions, byName, conf,
+        TableOutputResolver.DefaultValueFillMode.FILL)
+      InsertIntoSuppliedRelation(local, newQuery)

Review Comment:
   Fixed in 4c69a8a9caf. REPLACE ON/USING now throws the DSv2 error 
`unsupportedInsertReplaceOnOrUsing` with the target name. REPLACE WHERE 
resolves against the supplied relation's output and must be boolean 
(`DATATYPE_MISMATCH.FILTER_NOT_BOOLEAN`, as for a DSv2 table). The condition is 
validated but not carried into `InsertIntoSuppliedRelation`: a supplied 
relation has no rows to delete, so the node is analysis-only. Covered by 
'ANALYZE checks the REPLACE forms of an INSERT into a supplied relation'.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/LocalRelation.scala:
##########
@@ -123,3 +123,17 @@ case class LocalRelation(
 
   override val nodePatterns: Seq[TreePattern] = Seq(LOCAL_RELATION)
 }
+
+/**
+ * INSERT whose target resolved to a caller-supplied overlay relation. Analysis
+ * only: the statement is not executed.
+ */
+case class InsertIntoSuppliedRelation(

Review Comment:
   Fixed in 4c69a8a9caf. `primaryQueryPlan` now looks through 
`InsertIntoSuppliedRelation` to its query, so the select list is reported. The 
INSERT target test checks the select list too.



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