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


##########
sql/core/src/main/scala/org/apache/spark/sql/catalyst/parser/ParseSqlResult.scala:
##########
@@ -173,13 +236,142 @@ 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) =>

Review Comment:
   **Non-blocking (P2):** This existence check also runs on a namespace the 
call derived rather than one the caller named: the named catalog's 
defaultNamespace() when current_schema is omitted, and the invoker's current 
namespace when only current_path is given. CatalogPlugin.defaultNamespace 
documents that the namespace it returns need not exist, and USE CATALOG checks 
none. Reading the code, with a JDBC catalog h2, parse_sql('SELECT 1', 
'ANALYZE', current_catalog => 'h2') fails the outer query with 
SCHEMA_NOT_FOUND, because JDBCTableCatalog's default namespace is empty and its 
namespaceExists accepts only a one-part namespace, although USE CATALOG h2 
succeeds. After USE CATALOG h2, parse_sql('SELECT 1', 'ANALYZE', current_path 
=> 'system.builtin') fails the same way, although it names no catalog or 
schema. Checking existence only when the caller gives current_schema would 
match USE CATALOG and keep the check where a schema is named.
   
   **Verification:**
   - **Regression:** parse_sql ANALYZE with current_catalog naming a 
namespace-capable catalog whose default namespace it does not report as 
existing, and no current_schema, returns one result per statement instead of 
failing the query with SCHEMA_NOT_FOUND.
   - **Regression:** After USE CATALOG of such a catalog, parse_sql ANALYZE 
with only current_path returns one result per statement.
   - **Behavior:** current_schema naming a namespace that does not exist in a 
non-session catalog still fails the query with SCHEMA_NOT_FOUND.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -1557,6 +1574,77 @@ 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
+      i.replaceCriteriaOpt.foreach {
+        case criteria if criteria.isReplaceOnOrUsing =>
+          throw QueryCompilationErrors.unsupportedInsertReplaceOnOrUsing(name)
+        case InsertReplaceWhere(cond) =>
+          // Same check as a DSv2 table's REPLACE WHERE: the condition 
resolves against the
+          // target's columns and must be boolean.
+          val condition = resolveExpressionByPlanOutput(cond, local, throws = 
true)

Review Comment:
   **Blocking (P1):** This resolves the condition only against the supplied 
relation's column names: an unknown column stays unresolved, and a function 
applied to the relation's columns is still unresolved too, because function 
resolution skipped it while its arguments were unresolved. The boolean check 
that follows passes for any predicate, since a predicate reports BooleanType 
without resolving its children, and the condition is dropped when the command 
is built, so no later rule or CheckAnalysis sees it. Reading the code, with a 
supplied relation t (a INT, b STRING), INSERT INTO t REPLACE WHERE missing_col 
= 1 SELECT 1, 'x' and INSERT INTO t REPLACE WHERE no_such_fn(b) = 1 SELECT 1, 
'x' both report analyze_success true, although a real table with that schema 
rejects both. When the top node itself is still unresolved, as in REPLACE WHERE 
missing_col or the valid REPLACE WHERE starts_with(b, 'x'), condition.dataType 
throws an INTERNAL_ERROR that ParseSqlResult rethrows, so the outer
  query fails and every statement's result is lost. REPLACE ON and REPLACE 
USING now fail with the DSv2 error, as intended.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59874#discussion_r4627287687).
   
   **Recommended change:** Keep the REPLACE WHERE condition on 
InsertIntoSuppliedRelation as an optional expression field instead of 
discarding it, and have the command report the supplied relation's columns as 
its input set and count the condition in its resolved state, as 
OverwriteByExpression does for its table. Resolve the condition against the 
supplied relation's columns with an explicit ResolveReferences case, the way 
the delete condition of a DSv2 overwrite is resolved, and check it only once it 
is resolved: an unknown column or function then fails with the analyzer's 
unresolved-column or unresolved-routine error, a resolved non-boolean condition 
fails with DATATYPE_MISMATCH.FILTER_NOT_BOOLEAN, and a subquery fails with 
UNSUPPORTED_FEATURE.OVERWRITE_BY_SUBQUERY through a CheckAnalysis case for the 
new command like the one for OverwriteByExpression. Remove the one-shot 
dataType call on the unresolved condition, so an unresolved function or column 
at the top of the condition can
  no longer raise INTERNAL_ERROR. Commit 4c69a8a9caf added the current check; 
no earlier commit of this PR kept the condition on the command.
   
   **Why this works:** With the condition among the command's expressions, 
ResolveReferences resolves its columns against the supplied relation each 
iteration and ResolveFunctions resolves its functions once their arguments are 
resolved. Because the command's input set is the supplied relation's output, as 
OverwriteByExpression's is its table's (v2Commands.scala:257), CheckAnalysis's 
missing-input check accepts a resolved condition, and because the condition 
counts toward the command's resolved state, CheckAnalysis reports anything that 
stays unresolved instead of the rule calling dataType on it; the boolean and 
subquery checks then run on a resolved expression.
   
   **Compatibility:** INSERT into a supplied relation without REPLACE criteria, 
with VALUES, a column list, static partitions or BY NAME, analyzes and reports 
as before.
   
   **Risks:** The analyzed plan now carries the condition, so anything that 
walks the analyzed command's expressions, such as routine reporting, sees the 
condition's resolved routines where it saw none before.
   
   **Constraints:** The condition must resolve against the supplied relation's 
columns, never against the INSERT query's output, which the generic resolution 
case would use. REPLACE ON and REPLACE USING keep failing with the DSv2 error 
before the condition is kept. The command's input set must include the supplied 
relation's output, or CheckAnalysis reports the columns of every valid 
condition as missing attributes.
   
   **Exclusions:**
   - Modeling which rows REPLACE WHERE would delete stays out of scope; the 
command remains analysis-only.
   
   **Verification:**
   - **Regression:** With a supplied relation t (a INT, b STRING), ANALYZE of 
INSERT INTO t REPLACE WHERE missing_col = 1 SELECT 1, 'x', of INSERT INTO t 
REPLACE WHERE no_such_fn(b) = 1 SELECT 1, 'x', and of INSERT INTO t REPLACE 
WHERE missing_col SELECT 1, 'x' each report analyze_success false with an 
unresolved-column or unresolved-routine error, and the outer query succeeds.
   - **Regression:** With the same supplied relation, ANALYZE of INSERT INTO t 
REPLACE WHERE starts_with(b, 'x') SELECT 1, 'x' reports analyze_success true 
and the outer query succeeds.
   - **Behavior:** With the same supplied relation, REPLACE WHERE a > 0 still 
reports analyze_success true, REPLACE WHERE a still reports 
DATATYPE_MISMATCH.FILTER_NOT_BOOLEAN, and REPLACE WHERE a IN (SELECT 1) reports 
the same error class a DSv2 table reports for a subquery condition.
   - **Compatibility:** REPLACE ON and REPLACE USING into a supplied relation 
keep failing with the DSv2 error, and an INSERT into a supplied relation 
without REPLACE criteria keeps its reported target, select list and verdict.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -315,9 +315,18 @@ object AnalysisContext {
         },
       collation = function.collation)
     set(context)
-    try f finally { set(originContext) }
+    try withoutSuppliedObjects(f) finally { set(originContext) }
   }
 
+  /**
+   * A stored view or SQL function body reads the objects it was defined over, 
so the relations
+   * and variables a caller supplies for its statement do not apply inside it.
+   */
+  private def withoutSuppliedObjects[A](f: => A): A =
+    SuppliedRelationRegistry.create(Nil).runWith {

Review Comment:
   **Non-blocking (P2):** Clearing the registry here keeps supplied relations 
out of view bodies for the fixed-point analyzer, but the single-pass resolver 
does not ask the registry again for a relation it has already seen. 
MetadataResolver caches resolved relations in one map keyed by RelationId 
(identity, options, streaming and time travel) and skips keys already present, 
and ViewResolver resolves a view body with the same resolver and map. Reading 
the code, with spark.sql.analyzer.singlePassResolver.enabled=true, a table t (a 
INT), a view v defined as SELECT a FROM t and relations => 
array(named_struct('name', 't', 'schema', 'b STRING')), ANALYZE of SELECT * 
FROM t JOIN v caches the supplied stand-in under spark_catalog.default.t, and 
the body of v then reads it, so v is typed with column b instead of a. The 
configuration is internal and off by default, and the fixed-point analyzer 
types v from the real table.
   
   **Recommended change:** Add the supplied-relation scope to the single-pass 
relation key: RelationId gains a component, defaulting to the value used when 
no supplied relations are installed, that records whether supplied relations 
apply where the key is computed, and relationIdFromUnresolvedRelation sets it 
from the supplied relation registry. A statement reference resolved to a 
supplied relation and a view-body reference of the same identity, computed 
inside the view's analysis context where the registry is cleared, then get 
different keys.
   
   **Why this works:** The map keeps one entry per identity and scope, so the 
view body misses the statement's entry, resolves its own relation with the 
registry cleared, and reads the real object, while the statement keeps reading 
the supplied relation.
   
   **Risks:** In a call with supplied relations, a relation read both by the 
statement and by a view body is resolved once per scope; the extra lookup is 
bounded and limited to such calls.
   
   **Constraints:** Every key computed with no supplied relations must equal 
today's key, so ordinary queries keep their cache behavior.
   
   **Verification:**
   - **Regression:** With spark.sql.analyzer.singlePassResolver.enabled=true, a 
table t (a INT), a view v defined as SELECT a FROM t and a supplied relation t 
(b STRING), ANALYZE of SELECT * FROM t JOIN v types the view's column as a INT 
and the statement's t as b STRING, as the fixed-point analyzer does.
   - **Compatibility:** Queries without supplied relations produce the same 
single-pass relation keys and analyzed plans as before.



##########
sql/core/src/main/scala/org/apache/spark/sql/catalyst/parser/ParseSqlResult.scala:
##########
@@ -173,13 +236,142 @@ 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):** Because these registries are shared, a persistent SQL 
function that this copy loads first is registered with a builder the copy 
built: resolvePersistentTableFunction and the lazy builder of 
loadPersistentScalarFunction register makeUserDefinedTableFuncBuilder or 
makeUserDefinedScalarFuncBuilder, and both builders call the instance method 
rearrangeArguments, so they capture the copy. Reading the code, with a 
persistent SQL table function db1.tvf that the session has not used yet, 
parse_sql('SELECT * FROM tvf(1)', 'ANALYZE', current_schema => 'db1') leaves 
the copy, with its snapshot of the invoker's temp views and its 
AnalysisCatalogManager, reachable from the session's tableFunctionRegistry 
until the function is dropped or the session ends. The registryMonitor change 
serializes the loads but does not change which catalog the builders capture. 
The retention is bounded by the number of persistent functions, and the 
builders compute the same results the session
 's would.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59874#discussion_r4627287674).
   
   **Recommended change:** Have the per-call SessionCatalog hand persistent 
function loading to the session catalog: when it serves a per-call analysis, 
resolvePersistentTableFunction and loadPersistentScalarFunction qualify the 
name with the copy's current database and call the session catalog's own 
methods, which build and register the builders under the session catalog's 
lock. This takes the place of the registryMonitor redirect that commit 
4c69a8a9caf added, and keeps its single lock.
   
   **Why this works:** Builders in the shared registries are then created by 
the session catalog and reference only session state; the copy no longer 
registers anything, so nothing per-call stays reachable after the call, and 
check-then-register still runs under one lock.
   
   **Risks:** A persistent function first loaded by a context call stays cached 
in the session's registry, as it would after a session query; only the owner of 
its builder changes.
   
   **Constraints:** The name must be qualified with the call's current database 
before it reaches the session catalog, whose current database is the invoker's. 
Lock order stays one way: the per-call catalog may wait on the session catalog, 
never the reverse.
   
   **Verification:**
   - **Inspection:** The per-call session catalog never registers a builder in 
the session's function registries itself; persistent table and scalar function 
loads it receives are carried out by the session catalog after qualifying the 
name with the call's database.
   - **Behavior:** parse_sql ANALYZE with current_schema resolves an 
unqualified persistent SQL table function from the call's schema, and a later 
session query that calls the same function by its qualified name returns the 
same result as in a session where parse_sql was never called.
   - **Compatibility:** The session's current database and temp views are 
unchanged after such a call.



##########
sql/core/src/main/scala/org/apache/spark/sql/catalyst/parser/ParseSqlResult.scala:
##########
@@ -238,28 +430,151 @@ 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 =>

Review Comment:
   **Nit (P3):** Only parse and analysis errors are converted here, so a type 
that the parser accepts but cannot construct escapes the per-statement report: 
DecimalType throws SparkArithmeticException for a precision above 38, 
parseTypeWithFallback rethrows it, and analyzeBatch catches only 
SparkRuntimeException. Reading the code, parse_sql('SELECT 1; SELECT 2', 
'ANALYZE', variables => array(named_struct('name', 'v', 'type', 'DECIMAL(39, 
0)'))) fails the outer query with DECIMAL_PRECISION_EXCEEDS_MAX_PRECISION 
instead of returning two statement objects with 
INVALID_PARAMETER_VALUE.PARSE_SQL_CONTEXT, as 'type' => '!!!' does. 
parseKnownRelation and parseKnownParameterMarker have the same catch, so a 
parameter_markers type and a relations schema such as STRUCT<a: DECIMAL(39, 0)> 
fail the same way, and so does an out-of-range CHAR length. Converting every 
non-internal Spark error from DataType.fromDDL in these three parsers would 
keep the documented per-statement report.
   
   **Verification:**
   - **Regression:** parse_sql ANALYZE of a two-statement batch with a 
variables entry typed DECIMAL(39, 0), and separately with a parameter_markers 
entry of that type and with a relations entry whose schema is STRUCT<a: 
DECIMAL(39, 0)>, returns two statement objects reporting analyze_success false 
with INVALID_PARAMETER_VALUE.PARSE_SQL_CONTEXT.
   - **Behavior:** An unparsable type such as '!!!' is still reported per 
statement, and a NULL or blank entry still fails the query.



##########
sql/core/src/main/scala/org/apache/spark/sql/catalyst/parser/ParseSqlResult.scala:
##########
@@ -238,28 +430,151 @@ 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.

Review Comment:
   **Nit (P3):** Neither half of this holds: classic SparkSession.sql(text, 
args) substitutes arguments while parsing and wraps the plan for BindParameters 
only in the legacy constants-only mode, and bindOwnParameterMarkers binds every 
marker to a typed NULL literal, so a marker in LIMIT or OFFSET fails analysis 
with INVALID_LIMIT_LIKE_EXPRESSION.IS_NULL, as the new suite test asserts, 
where a real argument passes. Describing the NULL binding and its limit would 
keep readers from expecting sql(..., args) behavior:
   
   ```suggestion
      * Bind each caller-supplied marker to a typed NULL literal through 
[[BindParameters]], for
      * analysis only. A marker in a position that must be a non-null constant, 
such as LIMIT or
      * OFFSET, therefore fails analysis. Markers the plan does not use leave 
it unchanged.
   ```
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59874#discussion_r4405911477).
   
   **Verification:**
   - **Inspection:** The bindSuppliedParameterMarkers comment no longer says 
the binding is the one sql(..., args) uses or that the plan is typed as a real 
query with those arguments would be, and it states the NULL binding and its 
LIMIT and OFFSET limit, or whatever binding the code performs.



##########
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:
   Thanks, REPLACE ON and REPLACE USING now fail with the DSv2 error. REPLACE 
WHERE is not covered yet: the condition is resolved only for columns that exist 
and is then dropped, so INSERT INTO t REPLACE WHERE missing_col = 1 SELECT 1, 
'x' still reports analyze_success true. This review raises the remaining 
REPLACE WHERE problem as a separate finding.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4627287687","thread_id":"inline:4627287687","verdict_sha256":"31e427bd36ac0984798c3ed0ab41f338daa3a05f32ebeb164405bbba8698cada"}
 -->



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