cloud-fan commented on code in PR #59874:
URL: https://github.com/apache/spark/pull/59874#discussion_r4627287609


##########
sql/core/src/main/scala/org/apache/spark/sql/catalyst/parser/ParseSqlResult.scala:
##########
@@ -926,30 +1231,33 @@ object ParseSqlResult {
         sessionIdent(last)
       }
     } else {
-      qualifyWithCurrentNamespace(parts, session)
+      qualifyWithCurrentNamespace(parts, scope)
     }
   }
 
   private def qualifyRoutine(
       parts: Seq[String],
-      session: ClassicSparkSession): Seq[String] = {
-    val catalog = session.sessionState.catalog
-    // Same order as FunctionResolution: `first` is session, builtin, 
persistent;
-    // `second` (default) is builtin, session, persistent; `last` is builtin, 
persistent, session.
-    val sessionOrder =
-      
session.sessionState.conf.getConf(SQLConf.SESSION_FUNCTION_RESOLUTION_ORDER)
+      scope: AnalysisScope): Seq[String] = {
+    val catalog = scope.catalog
     def isTemp(name: String): Boolean =
       catalog.isTemporaryFunction(FunctionIdentifier(name))
-    // Persistent in the catalog the statement resolves names in, as 
FunctionResolution does.
-    def isPersistent(name: String): Boolean = {
-      val mgr = session.sessionState.catalogManager
-      mgr.currentCatalog match {
-        case _ if 
mgr.currentCatalog.name().equalsIgnoreCase(CatalogManager.SESSION_CATALOG_NAME) 
=>
-          catalog.isPersistentFunction(FunctionIdentifier(name))
-        case fc: FunctionCatalog =>
-          Try(fc.functionExists(Identifier.of(mgr.currentNamespace, 
name))).getOrElse(false)
-        case _ => false
-      }
+    // The identity of routine `name` in path entry `entry`, spelled as the 
catalog spells it.
+    def persistentIn(entry: Seq[String], name: String): Option[Seq[String]] = 
entry match {
+      case Seq(cat, db) if 
cat.equalsIgnoreCase(CatalogManager.SESSION_CATALOG_NAME) =>
+        val ident = FunctionIdentifier(name, Some(db))
+        if (Try(catalog.isPersistentFunction(ident)).getOrElse(false)) {

Review Comment:
   **Nit (P3):** Without SET PATH or current_path, the path this walk iterates 
ends with the current catalog and schema under the default and 'first' function 
resolution orders. For an unqualified name that is neither builtin nor temp, a 
hit reports catalog.schema.name, and a miss falls back to 
qualifyWithCurrentNamespace, which reports the same parts. Each such name in 
each statement still pays isPersistentFunction's databaseExists and 
functionExists metastore calls, which the base branch did not make under these 
orders. Skipping the probe for a last path entry whose identity equals the 
fallback removes the calls without changing any reported name. Under 'last', 
system.session follows the persistent entry, so that probe still matters and 
stays.
   
   **Verification:**
   - **Inspection:** qualifyRoutine makes no persistent-function existence call 
for a path entry that is last on the path and whose identity equals the 
fallback identity.
   - **Compatibility:** function_references for a persistent function, an 
unknown function, a temp function shadowing a builtin, and a function found on 
an explicit path are the same as before under the default, 'first' and 'last' 
session orders.



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

Review Comment:
   **Non-blocking (P2):** This clone reuses the session's 
extendedResolutionRules (Analyzer.scala:544), including 
ResolveExecuteImmediate, which the session state builds over the session's 
catalog manager and which analyzes the payload with 
session.sessionState.analyzer (ResolveExecuteImmediate.scala:195). So within 
one call, direct statements resolve under the requested context and EXECUTE 
IMMEDIATE payloads under the invoker's. Reading the code, with tables s.t (a 
INT) and default.t (a STRING) and the session on default, parse_sql('SELECT a 
FROM t; EXECUTE IMMEDIATE ''SELECT a FROM t''', 'ANALYZE', current_schema => 
's') types a as INT in the first statement and as STRING in the payload. A 
supplied relation t given with current_schema => 's' is stored as 
spark_catalog.s.t, so the payload's lookup of spark_catalog.default.t misses 
it. The usage text states this exception, but these arguments are defined to 
act as USE and SET PATH would, and after USE a payload does resolve in the ne
 w schema. SQL written for another schema that contains dynamic SQL therefore 
still fails in the payload as it does on the base branch.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59874#discussion_r4405911386).
   
   **Recommended change:** While ParseSqlResult analyzes a statement with a 
per-call analyzer, publish that analyzer through a lexical thread-local scope, 
as the supplied-relation and supplied-variable registries are published, and 
have ResolveExecuteImmediate analyze the payload with the published analyzer 
when one is installed, falling back to the session's analyzer otherwise. Update 
the parse_sql usage text and the PR description, which say the payload is 
analyzed with the invoker's catalog, schema and path (wording added in commits 
a71727224ae and 61f0657bf5b), and add parse_sql ANALYZE tests for EXECUTE 
IMMEDIATE under current_schema and current_path.
   
   **Why this works:** The payload then resolves through the call's 
AnalysisCatalogManager, so unqualified relation and routine names use the 
call's catalog, schema and path, supplied relations canonicalized with the 
call's schema match the payload's lookups, and the call's path-enabled conf is 
paired with the call's own path rather than the invoker's catalog manager.
   
   **Compatibility:** EXECUTE IMMEDIATE outside a parse_sql ANALYZE call keeps 
analyzing its payload with the session's analyzer.
   
   **Risks:** The published analyzer must be removed when the statement's 
analysis ends, including on failure, or a later ordinary EXECUTE IMMEDIATE on 
the same thread would use a stale per-call analyzer; scoping it with runWith, 
as the registries are, avoids this.
   
   **Constraints:** Outside a parse_sql ANALYZE call, EXECUTE IMMEDIATE keeps 
analyzing with the session's analyzer. The payload's local-variable hiding and 
USING parameter binding stay as they are.
   
   **Exclusions:**
   - Transaction-aware analyzer clones created by QueryExecution keep analyzing 
EXECUTE IMMEDIATE payloads with the session's analyzer; changing them is 
outside this PR.
   
   **Verification:**
   - **Regression:** With tables s.t (a INT) and default.t (a STRING) and the 
session on default, ANALYZE of SELECT a FROM t followed by EXECUTE IMMEDIATE 
'SELECT a FROM t' with current_schema set to s types a as INT in both 
statements.
   - **Regression:** With a supplied relation t (b INT) and current_schema set 
to s, an EXECUTE IMMEDIATE payload SELECT b FROM t analyzes successfully 
against the supplied relation.
   - **Behavior:** With current_path naming a schema that holds a SQL function, 
an EXECUTE IMMEDIATE payload that calls the function unqualified resolves it, 
and the session's path and spark.sql.path.enabled are unchanged afterwards.
   - **Compatibility:** An EXECUTE IMMEDIATE statement run directly, outside 
parse_sql, still resolves against the session's current schema.



##########
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 =>
+          // A caller-supplied relation (relations overlay) is named by its 
canonical identity.
+          l.getTagValue(SuppliedRelationRegistry.IDENTITY_TAG).foreach(add)

Review Comment:
   **Non-blocking (P2):** This reports the tag verbatim, and 
SuppliedRelationRegistry.canonicalize stores a global temp entry as the 
two-part [global_temp, v] (SuppliedRelationRegistry.scala:94-96), while 
viewParts and tempViewParts report a real global temp view as 
spark_catalog.global_temp.v. So SELECT a FROM global_temp.v with relations => 
array(named_struct('name', 'global_temp.v', 'schema', 'a INT')) reports 
source_table_references [["global_temp", "v"]], unlike the same query over a 
real global temp view, and lineage consumers see two objects. Reporting a 
two-part tag headed by the global temp database with the session catalog in 
front, as globalTempIdent does, fixes this without changing the registry key.
   
   **Verification:**
   - **Regression:** With a supplied relation global_temp.v (a INT), ANALYZE of 
SELECT a FROM global_temp.v reports the source spark_catalog.global_temp.v.
   - **Regression:** With the same relation, ANALYZE of INSERT INTO 
global_temp.v SELECT 1 reports the target spark_catalog.global_temp.v.
   - **Compatibility:** Real global temp views and other supplied relations 
keep their reported identities.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/VariableResolution.scala:
##########
@@ -153,23 +161,51 @@ class VariableResolution(
           varDef
         )
       }
-      .orElse(
-        if (maybeTempVariableName(nameParts) &&
-            allowUnqualifiedSessionTempVariableLookup(nameParts)) {
-          tempVariableManager
-            .get(namePartsCaseAdjusted)
-            .map { varDef =>
-              VariableReference(
-                nameParts,
-                FakeSystemCatalog,
-                Identifier.of(Array(CatalogManager.SESSION_NAMESPACE), 
namePartsCaseAdjusted.last),
-                varDef
-              )
-            }
-        } else {
-          None
+  }
+
+  private def lookupSuppliedLocal(
+      nameParts: Seq[String],
+      namePartsCaseAdjusted: Seq[String]): Option[VariableReference] = {
+    if (SuppliedVariableRegistry.isSessionName(nameParts)) {
+      None
+    } else {
+      SuppliedVariableRegistry.lookup(nameParts, conf.resolver).map { dataType 
=>

Review Comment:
   **Blocking (P1):** withHiddenLocalVariables 
(ResolveExecuteImmediate.scala:249-261) hides locals from a payload only by 
replacing the SQL scripting variable manager. The SuppliedVariableRegistry 
installed for the statement stays in effect, so this lookup still resolves a 
supplied two-part local inside the payload. Reading the code, 
parse_sql('EXECUTE IMMEDIATE ''SELECT proc.p AS x''', 'ANALYZE', variables => 
array(named_struct('name', 'proc.p', 'type', 'INT'))) reports analyze_success 
true with x typed INT, while the same payload inside proc: BEGIN DECLARE p INT; 
... END fails, because EXECUTE IMMEDIATE cannot see locals. A caller that uses 
ANALYZE to check a procedure body gets a wrong verdict with no error. Supplied 
session variables are unaffected, since payloads do see session variables. 
Installing a registry that keeps only the session-shaped entries inside 
withHiddenLocalVariables would hide supplied locals exactly where script locals 
are hidden; the usage text that says pay
 loads see the call's variables would then say session variables.
   
   **Verification:**
   - **Regression:** ANALYZE of EXECUTE IMMEDIATE 'SELECT proc.p AS x' with a 
supplied variable proc.p of type INT reports analyze_success false with an 
unresolved-name error.
   - **Behavior:** With supplied variables v INT and proc.p INT, an EXECUTE 
IMMEDIATE payload SELECT v AS x reports x as INT, and the direct statement 
SELECT proc.p AS x reports x as INT.
   - **Compatibility:** After a payload is analyzed, the next statement of the 
same batch still sees every supplied variable, locals included.



##########
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:
   **Nit (P3):** All six context arguments default to NULL literals in 
functionSignature (ParseSql.scala:413-419), so with null propagation every call 
that omits any of them, including a plain parse_sql(sql, 'ANALYZE'), would fold 
to NULL, not only a call that passes a NULL catalog or schema. As written, a 
reader could conclude that null intolerance could return once those two 
arguments are handled.
   
   ```suggestion
     // Every context argument defaults to a NULL literal, so null propagation 
would fold every
     // call that omits one to NULL. eval returns NULL itself for a NULL 
statement or mode.
   ```
   
   **Verification:**
   - **Inspection:** The comment above ParseSql's nullIntolerant setting 
explains it by the NULL defaults of all six context arguments, not only 
current_catalog and current_schema.



##########
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:
   **Non-blocking (P2):** This copy shares state.functionRegistry and 
state.tableFunctionRegistry with the session but locks on its own instance. 
resolvePersistentTableFunction is synchronized on the SessionCatalog it is 
called on, checks the registry, fetches from the external catalog and registers 
with overrideIfExists = false (SessionCatalog.scala:2837-2858), and the 
per-call analyzer's FunctionResolution calls it on this copy 
(FunctionResolution.scala:270). Before this change one SessionCatalog per 
session guarded each registry. Now a parse_sql call with current_schema and an 
ordinary query on the same session (Spark Connect runs a session's operations 
concurrently) that first resolve the same persistent SQL table function can 
both miss, and whichever registers second fails with ROUTINE_ALREADY_EXISTS. 
The failure is transient and a retry succeeds, but it can hit the invoker's 
unrelated query too.
   
   **Recommended change:** Make the per-call catalog load and register 
persistent functions through the session's SessionCatalog, for example by 
building it as a SessionCatalog subclass whose persistent table and scalar 
function loading delegates to the session catalog after qualifying the name 
with the call's current database, so one monitor guards each shared registry 
again. Add a test that interleaves first uses of a persistent SQL table 
function by a context call and by an ordinary query on the same session.
   
   **Why this works:** Check-then-register on each shared registry again runs 
under a single SessionCatalog lock, so two first uses of one persistent 
function cannot both pass the existence check.
   
   **Risks:** Delegated calls must qualify names with the call's current 
database before reaching the session catalog, whose current database is the 
invoker's; an unqualified delegated name would load from the wrong schema.
   
   **Constraints:** The call does not change the session catalog's current 
database or temp views. Lock order stays one way: the copy may wait on the 
session catalog, never the reverse.
   
   **Verification:**
   - **Regression:** With the metastore lookup of a not yet registered 
persistent SQL table function paused for a parse_sql ANALYZE call that gives 
current_schema, an ordinary query on the same session that first resolves the 
same function and the resumed call both succeed.
   - **Behavior:** A parse_sql ANALYZE call with current_schema resolves an 
unqualified persistent table function from the call's schema and reports it 
there.
   - **Compatibility:** The session's current database is unchanged after such 
a call.



##########
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:
   **Blocking (P1):** This builds the command from the target and the aligned 
query only, so the INSERT's replaceCriteriaOpt is discarded, and the new node 
has no expressions, so CheckAnalysis never sees an unresolved condition. 
Reading the code, with relations t (a INT, b STRING), INSERT INTO t REPLACE 
WHERE missing_col = 1 SELECT 1, 'x' reports analyze_success true although no 
table with that schema accepts the condition, and INSERT INTO t REPLACE USING 
(a) SELECT 1, 'x' succeeds too, while ResolveInsertInto rejects REPLACE 
ON/USING for every DSv2 target (Analyzer.scala:1631-1635) and 
PreprocessTableInsertion rejects all REPLACE criteria for v1 targets 
(rules.scala:341-345). Rejecting REPLACE ON and REPLACE USING with the DSv2 
error, and keeping a REPLACE WHERE condition resolved against the supplied 
relation's columns on the command, would make these statements fail as they do 
against a real table.
   
   **Verification:**
   - **Regression:** With a supplied relation t (a INT, b STRING), ANALYZE of 
INSERT INTO t REPLACE WHERE missing_col = 1 SELECT 1, 'x' reports 
analyze_success false with an unresolved-column error.
   - **Regression:** With the same relation, ANALYZE of INSERT INTO t REPLACE 
USING (a) SELECT 1, 'x' reports analyze_success false with the REPLACE ON/USING 
error.
   - **Behavior:** With the same relation, ANALYZE of INSERT INTO t REPLACE 
WHERE a = 1 SELECT 1, 'x' reports analyze_success true.
   - **Compatibility:** INSERT into a supplied relation without REPLACE 
criteria, with VALUES, a column list, static partitions or BY NAME, analyzes as 
before.



##########
sql/core/src/test/scala/org/apache/spark/sql/catalyst/expressions/ParseSqlAnalyzeSuite.scala:
##########
@@ -921,6 +1202,767 @@ class ParseSqlAnalyzeSuite extends QueryTest with 
SharedSparkSession {
     }
   }
 
+  test("ANALYZE current_schema applies to one call and leaves the session 
unchanged") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      sql("CREATE DATABASE parse_sql_per_call_a")
+      sql("CREATE DATABASE parse_sql_per_call_b")
+      try {
+        sql("CREATE TABLE parse_sql_per_call_a.t (a INT) USING parquet")
+        sql("CREATE TABLE parse_sql_per_call_b.t (a STRING) USING parquet")
+        val before = spark.catalog.currentDatabase
+        val inA = evalCall(
+          "SELECT parse_sql('SELECT a FROM t', 'ANALYZE', NULL, 
'parse_sql_per_call_a')")
+        val inB = evalCall(
+          "SELECT parse_sql('SELECT a FROM t', 'ANALYZE', NULL, 
'parse_sql_per_call_b')")
+        assert(inA.head \ "analyze_success" === JBool(true))
+        assert(inA.head \ "source_table_references" === JArray(List(
+          ref("spark_catalog", "parse_sql_per_call_a", "t"))))
+        assert(inA.head \ "select_list" === typedColumns("a" -> jsonInt))
+        assert(inB.head \ "analyze_success" === JBool(true))
+        assert(inB.head \ "source_table_references" === JArray(List(
+          ref("spark_catalog", "parse_sql_per_call_b", "t"))))
+        assert(inB.head \ "select_list" === typedColumns("a" -> jsonString))
+        assert(spark.catalog.currentDatabase === before)
+      } finally {
+        sql("DROP DATABASE IF EXISTS parse_sql_per_call_a CASCADE")
+        sql("DROP DATABASE IF EXISTS parse_sql_per_call_b CASCADE")
+      }
+    }
+  }
+
+  test("ANALYZE of a missing current_schema is an error and keeps the 
session") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      val before = spark.catalog.currentDatabase
+      intercept[NoSuchNamespaceException] {
+        spark.sql("SELECT parse_sql('SELECT a FROM t', 'ANALYZE', NULL, " +
+          "'parse_sql_per_call_missing')").collect()
+      }
+      assert(spark.catalog.currentDatabase === before)
+    }
+  }
+
+  test("ANALYZE current_schema does not change the invoker's later 
resolution") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      sql("CREATE DATABASE parse_sql_per_call_c")
+      try {
+        sql("CREATE TABLE parse_sql_per_call_c.t (a INT) USING parquet")
+        val overridden = evalCall(
+          "SELECT parse_sql('SELECT a FROM t', 'ANALYZE', NULL, 
'parse_sql_per_call_c')")
+        assert(overridden.head \ "analyze_success" === JBool(true))
+        // A later call with no context still resolves against the invoker's 
database.
+        val inherited = evalStatement("SELECT a FROM t")
+        assert(inherited \ "analyze_success" === JBool(false))
+      } finally {
+        sql("DROP DATABASE IF EXISTS parse_sql_per_call_c CASCADE")
+      }
+    }
+  }
+
+  test("ANALYZE current_catalog matches the session catalog in any case") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      sql("CREATE DATABASE parse_sql_per_call_d")
+      try {
+        sql("CREATE TABLE parse_sql_per_call_d.t (a INT) USING parquet")
+        val result = evalCall(
+          "SELECT parse_sql('SELECT a FROM t; SELECT a FROM 
parse_sql_missing_t', " +
+            "'ANALYZE', 'SPARK_CATALOG', 'parse_sql_per_call_d')")
+        assert(result.head \ "analyze_success" === JBool(true))
+        assert(result.head \ "source_table_references" === JArray(List(
+          ref("spark_catalog", "parse_sql_per_call_d", "t"))))
+        // A statement that fails analysis is still qualified with the call's 
schema.
+        assert(result(1) \ "analyze_success" === JBool(false))
+        assert(result(1) \ "source_table_references" === JArray(List(
+          ref("spark_catalog", "parse_sql_per_call_d", 
"parse_sql_missing_t"))))
+      } finally {
+        sql("DROP DATABASE IF EXISTS parse_sql_per_call_d CASCADE")
+      }
+    }
+  }
+
+  test("ANALYZE current_schema qualifies persistent function references with 
the call") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      sql("CREATE DATABASE parse_sql_per_call_e")
+      try {
+        sql("CREATE FUNCTION parse_sql_per_call_e.parse_sql_f() RETURNS INT 
RETURN 1")
+        val result = evalCall(
+          "SELECT parse_sql('SELECT parse_sql_f() AS x', 'ANALYZE', NULL, " +
+            "'parse_sql_per_call_e')")
+        assert(result.head \ "analyze_success" === JBool(true), result)
+        assert(result.head \ "function_references" === JArray(List(
+          ref("spark_catalog", "parse_sql_per_call_e", "parse_sql_f"))))
+      } finally {
+        sql("DROP DATABASE IF EXISTS parse_sql_per_call_e CASCADE")
+      }
+    }
+  }
+
+  test("ANALYZE current_path expands PATH to the invoker's path") {
+    withSQLConf(
+        SQLConf.PARSE_SQL_ENABLED.key -> "true",
+        SQLConf.PATH_ENABLED.key -> "true") {
+      sql("CREATE DATABASE parse_sql_per_call_f")
+      try {
+        sql("CREATE TABLE parse_sql_per_call_f.parse_sql_path_t (a INT) USING 
parquet")
+        sql("SET PATH = spark_catalog.parse_sql_per_call_f, system.builtin")
+        val result = evalCall(
+          "SELECT parse_sql('SELECT a FROM parse_sql_path_t', 'ANALYZE', " +
+            "current_path => 'PATH, system.session')")
+        assert(result.head \ "analyze_success" === JBool(true), result)
+        assert(result.head \ "source_table_references" === JArray(List(
+          ref("spark_catalog", "parse_sql_per_call_f", "parse_sql_path_t"))))
+      } finally {
+        sql("SET PATH = DEFAULT_PATH")
+        sql("DROP DATABASE IF EXISTS parse_sql_per_call_f CASCADE")
+      }
+    }
+  }
+
+  test("ANALYZE current_path qualifies a persistent function found on the 
path") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      sql("CREATE DATABASE parse_sql_per_call_g")
+      try {
+        sql("CREATE FUNCTION parse_sql_per_call_g.parse_sql_g() RETURNS INT 
RETURN 1")
+        val result = evalCall(
+          "SELECT parse_sql('SELECT parse_sql_g() AS x', 'ANALYZE', " +
+            "current_path => 'system.builtin, 
SPARK_CATALOG.PARSE_SQL_PER_CALL_G')")
+        assert(result.head \ "analyze_success" === JBool(true), result)
+        assert(result.head \ "function_references" === JArray(List(
+          ref("spark_catalog", "parse_sql_per_call_g", "parse_sql_g"))))
+      } finally {
+        sql("DROP DATABASE IF EXISTS parse_sql_per_call_g CASCADE")
+      }
+    }
+  }
+
+  test("ANALYZE current_path orders a temp function before a builtin of the 
same name") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      spark.udf.register("upper", (s: String) => s.length)
+      try {
+        val builtinFirst = evalCall(
+          "SELECT parse_sql('SELECT upper(''a'') AS x', 'ANALYZE', " +
+            "current_path => 'system.builtin, system.session')")
+        assert(builtinFirst.head \ "select_list" === typedColumns("x" -> 
jsonString),
+          builtinFirst)
+        assert(builtinFirst.head \ "function_references" === JArray(List(
+          ref("system", "builtin", "upper"))))
+        val sessionFirst = evalCall(
+          "SELECT parse_sql('SELECT upper(''a'') AS x', 'ANALYZE', " +
+            "current_path => 'system.session, system.builtin')")
+        assert(sessionFirst.head \ "select_list" === typedColumns("x" -> 
jsonInt),
+          sessionFirst)
+        assert(sessionFirst.head \ "function_references" === JArray(List(
+          ref("system", "session", "upper"))))
+      } finally {
+        spark.sessionState.catalog.dropTempFunction("upper", ignoreIfNotExists 
= true)
+      }
+    }
+  }
+
+  test("ANALYZE overlays do not replace a temp view read by a temp view") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      withTempView("parse_sql_tv_base", "parse_sql_tv_outer") {
+        sql("CREATE TEMPORARY VIEW parse_sql_tv_base AS SELECT 1 AS a")
+        sql("CREATE TEMPORARY VIEW parse_sql_tv_outer AS SELECT * FROM 
parse_sql_tv_base")
+        val result = evalCall(
+          "SELECT parse_sql('SELECT * FROM parse_sql_tv_outer; SELECT * FROM 
parse_sql_tv_base', " +
+            "'ANALYZE', relations => array(named_struct(" +
+            "'name', 'system.session.parse_sql_tv_base', 'schema', 'b 
STRING')))")
+        assert(result.head \ "select_list" === typedColumns("a" -> jsonInt), 
result)
+        assert(result(1) \ "select_list" === typedColumns("b" -> jsonString), 
result)
+      }
+    }
+  }
+
+  test("ANALYZE overlays do not replace a session variable read by a temp 
view") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      sql("DECLARE VARIABLE parse_sql_view_var INT DEFAULT 1")
+      try {
+        withTempView("parse_sql_var_v") {
+          sql("CREATE TEMPORARY VIEW parse_sql_var_v AS SELECT 
parse_sql_view_var AS x")
+          val result = evalCall(
+            "SELECT parse_sql('SELECT x FROM parse_sql_var_v; SELECT 
parse_sql_view_var AS y', " +
+              "'ANALYZE', variables => array(named_struct(" +
+              "'name', 'parse_sql_view_var', 'type', 'STRING')))")
+          assert(result.head \ "select_list" === typedColumns("x" -> jsonInt), 
result)
+          assert(result(1) \ "select_list" === typedColumns("y" -> 
jsonString), result)
+        }
+      } finally {
+        sql("DROP TEMPORARY VARIABLE IF EXISTS parse_sql_view_var")
+      }
+    }
+  }
+
+  test("ANALYZE overlays do not replace a table read by a SQL function body") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      withTable("parse_sql_fn_base") {
+        withUserDefinedFunction("parse_sql_fn" -> false) {
+          sql("CREATE TABLE parse_sql_fn_base (a INT) USING parquet")
+          sql("CREATE FUNCTION parse_sql_fn() RETURNS TABLE (a INT) " +
+            "RETURN SELECT a FROM parse_sql_fn_base")
+          val result = evalCall(
+            "SELECT parse_sql('SELECT a FROM parse_sql_fn()', 'ANALYZE', " +
+              "relations => array(named_struct(" +
+              "'name', 'spark_catalog.default.parse_sql_fn_base', 'schema', 'b 
STRING')))")
+          assert(result.head \ "analyze_success" === JBool(true), result)
+          assert(result.head \ "select_list" === typedColumns("a" -> jsonInt), 
result)
+        }
+      }
+    }
+  }
+
+  test("ANALYZE overlays do not replace a table read by a scalar SQL function 
body") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      withTable("parse_sql_sfn_base") {
+        withUserDefinedFunction("parse_sql_sfn" -> false) {
+          sql("CREATE TABLE parse_sql_sfn_base (a INT) USING parquet")
+          sql("CREATE FUNCTION parse_sql_sfn() RETURNS INT " +
+            "RETURN (SELECT max(a) FROM parse_sql_sfn_base)")
+          val result = evalCall(
+            "SELECT parse_sql('SELECT parse_sql_sfn() AS x', 'ANALYZE', " +
+              "relations => array(named_struct(" +
+              "'name', 'spark_catalog.default.parse_sql_sfn_base', 'schema', 
'b STRING')))")
+          assert(result.head \ "analyze_success" === JBool(true), result)
+          assert(result.head \ "select_list" === typedColumns("x" -> jsonInt), 
result)
+        }
+      }
+    }
+  }
+
+  test("ANALYZE overlays apply to the statement an EXECUTE IMMEDIATE runs") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      val result = evalCall(
+        "SELECT parse_sql('EXECUTE IMMEDIATE ''SELECT b FROM 
parse_sql_ei_t''', 'ANALYZE', " +
+          "relations => array(named_struct(" +
+          "'name', 'spark_catalog.default.parse_sql_ei_t', 'schema', 'b 
STRING')))")
+      assert(result.head \ "analyze_success" === JBool(true), result)
+    }
+  }
+
+  test("ANALYZE overlays do not replace a table read by a persistent view") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      withTable("parse_sql_view_base") {
+        withView("parse_sql_evolving_v") {
+          sql("CREATE TABLE parse_sql_view_base (a INT) USING parquet")
+          sql("CREATE VIEW parse_sql_evolving_v WITH SCHEMA EVOLUTION AS " +
+            "SELECT * FROM parse_sql_view_base")
+          val result = evalCall(
+            "SELECT parse_sql('SELECT * FROM parse_sql_evolving_v', 'ANALYZE', 
" +
+              "relations => array(named_struct(" +
+              "'name', 'spark_catalog.default.parse_sql_view_base', " +
+              "'schema', 'b STRING')))")
+          assert(result.head \ "analyze_success" === JBool(true), result)
+          assert(result.head \ "select_list" === typedColumns("a" -> jsonInt), 
result)
+          // A view WITH SCHEMA EVOLUTION would write an overlay's schema to 
the catalog.
+          val stored = spark.sessionState.catalog.getTableMetadata(
+            TableIdentifier("parse_sql_evolving_v"))
+          assert(stored.schema.fieldNames.toSeq === Seq("a"))
+        }
+      }
+    }
+  }
+
+  test("supplied relation identities are canonical under case-sensitive 
analysis") {
+    withSQLConf(
+        SQLConf.PARSE_SQL_ENABLED.key -> "true",
+        SQLConf.CASE_SENSITIVE.key -> "true") {
+      val mgr = spark.sessionState.catalogManager
+      val globalDb = spark.conf.get(StaticSQLConf.GLOBAL_TEMP_DATABASE)
+      assert(SuppliedRelationRegistry.canonicalize(mgr, Seq("SYSTEM", 
"SESSION", "v")) ===
+        Seq("system", "session", "v"))
+      assert(SuppliedRelationRegistry.canonicalize(mgr, Seq("System", 
"Session", "v")) ===
+        SuppliedRelationRegistry.sessionIdentity("v"))
+      assert(SuppliedRelationRegistry.canonicalize(mgr, Seq("SPARK_CATALOG", 
"default", "t")) ===
+        Seq("spark_catalog", "default", "t"))
+      assert(SuppliedRelationRegistry.canonicalize(mgr, Seq("GLOBAL_TEMP", 
"v")) ===
+        Seq(globalDb, "v"))
+      // Idempotent, so a stored identity and a looked-up identity agree.
+      val once = SuppliedRelationRegistry.canonicalize(mgr, 
Seq("SPARK_CATALOG", "default", "t"))
+      assert(SuppliedRelationRegistry.canonicalize(mgr, once) === once)
+    }
+  }
+
+  test("ANALYZE resolves injected session variables and restores the invoker") 
{
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      sql("DECLARE VARIABLE parse_sql_existing_v INT DEFAULT 1")
+      try {
+        val json = spark.sql(
+          """SELECT parse_sql(
+            |  'SELECT system.session.v AS x',
+            |  'ANALYZE',
+            |  variables => array(named_struct('name', 'system.session.v', 
'type', 'INT')))
+            |""".stripMargin).head().getString(0)
+        val analyzed = parse(json) match {
+          case JArray(List(value: JObject)) => value
+          case other => fail(s"expected one statement object, got: $other")
+        }
+        assert(analyzed \ "analyze_success" === JBool(true), json)
+        assert(analyzed \ "select_list" === JArray(List(
+          JObject("name" -> JArray(List(JString("x"))), "type" -> jsonInt))))
+        assert(spark.sql("SELECT parse_sql_existing_v").head().getInt(0) === 1)

Review Comment:
   **Nit (P3):** This assertion reads parse_sql_existing_v, but the call 
supplies system.session.v, so it cannot fail if the supplied v stayed installed 
after the call. Asserting afterwards that SELECT v fails to resolve, or 
supplying parse_sql_existing_v itself and reading it back as 1, would check 
what the test name promises.
   
   **Verification:**
   - **Behavior:** After an ANALYZE call that supplies system.session.v, a 
query on the session that references v fails to resolve it.



##########
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:
   **Blocking (P1):** This case reads a supplied relation's identity only from 
a LocalRelation the walk visits, but InsertIntoSuppliedRelation keeps its 
target in the non-child field table (LocalRelation.scala:131-139), and neither 
visitChildPlans nor visitNonChildSlots has a case for the node 
(ParseSqlResult.scala:750-866), so only its query is walked and the parse-side 
target goes to qualifyTarget, which knows only real temp views. Reading the 
code, with relations => array(named_struct('name', 'system.session.t', 
'schema', 'a INT')) and no temp view t, INSERT INTO t VALUES (1) resolves its 
target to the supplied relation but reports target_table_references 
[spark_catalog, default, t], and an entry spark_catalog.s2.t reached through 
current_path is reported under the current schema. Lineage consumers then 
record a write target the statement does not write to. The suite's 
INSERT-target test passes only because a real temp view of the same name 
exists. Visiting the node's table in the
  target role and its query in the source role, as the walker does for 
V2WriteCommand, reports the supplied identity.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59874#discussion_r4405911415).
   
   See **Shared repair plan 1** in the review body.



##########
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:
   **Non-blocking (P2):** For EXPLAIN and DESCRIBE QUERY the wrapped child is a 
SupervisingCommand whose query sits in a non-child slot, so BindParameters' 
PARAMETER-pattern pruning finds nothing to bind and the rule returns the child 
with the wrapper removed. The analyzer avoids this by running 
MoveParameterizedQueriesDown before BindParameters (Analyzer.scala:813-814). 
analyzePlan then analyzes the supervised query with its markers unbound, so, 
reading the code, parse_sql('EXPLAIN SELECT ? AS x', 'ANALYZE', 
parameter_markers => array(named_struct('name', '?', 'type', 'INT'))) reports 
UNBOUND_SQL_PARAMETER while SELECT ? AS x succeeds with the same argument, and 
DESCRIBE QUERY with a named marker fails the same way. The scaladoc says this 
uses the BindParameters rule that sql(..., args) uses, but classic sql(text, 
args) substitutes markers at parse time unless the legacy constants-only mode 
is on. Applying MoveParameterizedQueriesDown before binding, or binding inside 
analyzePlan's 
 supervised-plan recursion, binds these markers too.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59874#discussion_r4405911477).
   
   **Verification:**
   - **Regression:** ANALYZE of EXPLAIN SELECT ? AS x with a supplied 
positional marker of type INT reports analyze_success true.
   - **Regression:** ANALYZE of DESCRIBE QUERY SELECT :p AS x with a supplied 
marker p of type STRING reports analyze_success true.
   - **Compatibility:** A BEGIN ... END script wrapped by supplied named 
markers still reports PARSE_SQL_ANALYZE_UNSUPPORTED_SCRIPT and is not executed.
   - **Behavior:** Supplied markers in subqueries and CTEs of a direct 
statement are still bound.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RelationResolution.scala:
##########
@@ -235,13 +246,27 @@ class RelationResolution(
     None
   }
 
+  /**
+   * Schema-only stand-in for a caller-supplied relation identity. Eclipses the
+   * real object of that identity for this analysis.
+   */
+  private def lookupSuppliedRelation(identity: Seq[String]): 
Option[LogicalPlan] = {
+    SuppliedRelationRegistry.lookup(identity, conf.resolver).map { schema =>
+      val local = LocalRelation(schema)
+      local.setTagValue(SuppliedRelationRegistry.IDENTITY_TAG, identity)
+      SubqueryAlias(identity, local)
+    }
+  }
+
   /**
    * Try to resolve the identifier as a persistent table/view (current 
catalog/namespace).
    */
   private def tryResolvePersistent(
       u: UnresolvedRelation,
       identifier: Seq[String],
       finalTimeTravelSpec: Option[TimeTravelSpec]): Option[LogicalPlan] = {
+    val supplied = lookupSuppliedPersistentRelation(identifier)

Review Comment:
   **Non-blocking (P2):** This persistent step, like the session steps above 
it, returns a supplied relation before any catalog lookup, and some commands 
that name a table reach it: ALTER TABLE ... ADD CONSTRAINT ... CHECK builds 
AddCheckConstraint(Filter(Not(cond), UnresolvedRelation)) 
(AstBuilder.scala:7338-7341), and CACHE TABLE and UNCACHE TABLE build their 
target as an UnresolvedRelation (AstBuilder.scala:7616-7617 and 7670). Reading 
the code, with relations t (a INT) and no catalog table t, ALTER TABLE t ADD 
CONSTRAINT c CHECK (a > 0) reports analyze_success true instead of 
TABLE_OR_VIEW_NOT_FOUND; over a real v1 table t, the LocalRelation child hides 
ResolveSessionCatalog's rejection of ADD CONSTRAINT for v1 tables; and CACHE 
TABLE t and UNCACHE TABLE t succeed against a supplied relation with no catalog 
table. The usage text and the lookupTableOrView comment 
(Analyzer.scala:1477-1478) say such commands act on the catalog's own objects, 
so their verdicts should not depend on a
  supplied relation.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59874#discussion_r4405911430).
   
   **Recommended change:** Resolve the target relation of ALTER TABLE ... ADD 
CONSTRAINT ... CHECK, CACHE TABLE and UNCACHE TABLE with the supplied 
registries cleared, for example in a Resolution-batch step that handles those 
command shapes before the generic UnresolvedRelation case reaches their target, 
matching the bypass commit a9e48aeef77 gave lookupTableOrView. Add parse_sql 
ANALYZE tests for these commands with a same-named supplied relation.
   
   **Why this works:** These command targets then resolve to the catalog's own 
object or fail as on the base branch, so a supplied relation cannot change 
their outcome, while every query source and DML target keeps resolving to the 
supplied entry.
   
   **Compatibility:** Supplied relations keep eclipsing real objects for query 
sources and DML targets.
   
   **Risks:** ALTER TABLE ... ADD CONSTRAINT ... CHECK can then no longer be 
analyzed against a table that exists only as a supplied relation, which is the 
documented behavior for DDL.
   
   **Constraints:** CACHE TABLE ... AS SELECT and the query sources of every 
other statement keep resolving against supplied relations. Outside a parse_sql 
call nothing changes, because the registries are empty.
   
   **Verification:**
   - **Regression:** With a supplied relation t (a INT) and no catalog table t, 
ANALYZE of ALTER TABLE t ADD CONSTRAINT c CHECK (a > 0) reports 
TABLE_OR_VIEW_NOT_FOUND.
   - **Regression:** With a real table t (a INT) and a supplied relation t (b 
INT), the CHECK (a > 0) is validated against the real table's column a.
   - **Regression:** With a supplied relation t and no catalog table t, CACHE 
TABLE t and UNCACHE TABLE t report TABLE_OR_VIEW_NOT_FOUND.
   - **Compatibility:** Query sources and INSERT, UPDATE, DELETE and MERGE 
targets still resolve to supplied relations, and DDL built on UnresolvedTable 
still ignores them.



##########
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:
   **Non-blocking (P2):** This command's output is empty, and 
ParseSqlResult.primaryQueryPlan (ParseSqlResult.scala:1338-1371) no longer has 
the `case i: InsertIntoSuppliedRelation => primaryQueryPlan(i.query)` that the 
previously reviewed revision had, so collectTypedSelectList finds a resolved 
plan with no output and falls back to the parse-time list. Reading the code, 
with relations t (a INT, b STRING), INSERT INTO t SELECT 1 AS x, 'y' AS z 
reports select_list x and z without types, and INSERT INTO t VALUES (1, 'y') 
reports none, while an INSERT into a real table reports the target columns a 
INT and b STRING, as collectTypedSelectList's own doc promises. Restoring that 
case lets the walker read the typed projection already in query.
   
   See **Shared repair plan 1** in the review body.



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