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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -1368,11 +1369,21 @@ class Analyzer(
     private def lookupTableOrView(
         identifier: Seq[String],
         viewOnly: Boolean = false): Option[LogicalPlan] = {
+      val sessionOverlay =
+        if (identifier.length == 1 || 
CatalogManager.isSessionQualifiedViewName(identifier)) {
+          relationResolution.lookupSuppliedTempRelation(
+            identifier, 
SuppliedRelationRegistry.sessionIdentity(identifier.last))
+        } else {
+          None
+        }
+      sessionOverlay.orElse {
       relationResolution.lookupTempView(identifier).map { tempView =>
         ResolvedTempView(identifier.asIdentifier, tempView.tableMeta)
       }.orElse {
         relationResolution.expandIdentifier(identifier) match {
           case CatalogAndIdentifier(catalog, ident) =>
+            val nameParts = ident.toQualifiedNameParts(catalog)
+            relationResolution.lookupSuppliedRelation(nameParts).orElse {

Review Comment:
   Fixed in a9e48aeef77. lookupTableOrView no longer consults caller-supplied 
relations, so the DDL lookups (UnresolvedTable, UnresolvedView, 
UnresolvedTableOrView) act on the catalog's own objects. A supplied relation 
can no longer turn an ALTER TABLE into a ClassCastException. Supplied relations 
still apply to query sources and DML targets, and the existing overlay tests 
still pass. New regression tests in ParseSqlAnalyzeSuite cover ALTER TABLE on a 
supplied name with no catalog table (per-statement TABLE_OR_VIEW_NOT_FOUND, 
later statements still analyzed) and on a real table with a same-named supplied 
relation.



##########
sql/core/src/main/scala/org/apache/spark/sql/catalyst/parser/ParseSqlResult.scala:
##########
@@ -64,68 +127,629 @@ object ParseSqlResult {
     ThreadLocal.withInitial(() => new SparkSqlParser())
 
   /** Parse `sql` as a batch and render the JSON result array. */
-  def fromSql(sql: String): String = {
+  def fromSql(
+      sql: String,
+      mode: String = ParseSqlMode.Parse,
+      context: ParseSqlAnalyzeContext = ParseSqlAnalyzeContext.empty): String 
= {
     val split = parser.get().splitStatementsWithPositions(sql)
     val statements = split.completeStatements ++ split.partialStatement
-    compact(render(JArray(statements.map(parseStatement).toList)))
+    val json = if (mode == ParseSqlMode.Analyze) {
+      analyzeBatch(sql, statements, context)
+    } else {
+      JArray(statements.map { segment =>
+        parsePlanOrError(sql, segment) match {
+          case ParseFailed(errorObj) => errorObj
+          case Parsed(seg, plan) =>
+            successJson(plan, analyzed = None, analyzeError = None, None, 
segmentSpan(sql, seg))
+        }
+      }.toList)
+    }
+    compact(render(json))
+  }
+
+  private sealed trait ParsedStatement
+  private case class Parsed(segment: PositionedSqlStatement, plan: LogicalPlan)
+    extends ParsedStatement
+  private case class ParseFailed(errorObj: JObject) extends ParsedStatement
+
+  /**
+   * Parse every statement, then analyze with optional context overrides.
+   * Statements are analyzed in order without being executed: each sees the
+   * variables, tables, and views declared or created by earlier statements
+   * (see [[AnalyzeState]]).
+   * Analysis / context failures stay JSON (`analyze_success` false) with
+   * whatever parse and catalog qualification is already known.
+   */
+  private def analyzeBatch(
+      batch: String,
+      statements: Seq[PositionedSqlStatement],
+      context: ParseSqlAnalyzeContext): JArray = {
+    val parsed = statements.map(parsePlanOrError(batch, _))
+    val session = ClassicSparkSession.getActiveSession
+      .getOrElse(throw QueryExecutionErrors.parseSqlAnalyzeRequiresSession())
+    // The batch is analyzed on its own: a SQL script that calls parse_sql does
+    // not lend it its locals, and CALL is not run.
+    SqlScriptingContextManager.create(null).runWith {
+      InvokeProcedures.withoutInvocation {
+        try {
+          withAnalyzeContext(session, context) { env =>
+            val state = new AnalyzeState(env)
+            JArray(parsed.map {
+              case ParseFailed(errorObj) => errorObj
+              case Parsed(segment, plan) =>
+                state.statement(plan, segmentSpan(batch, segment))
+            }.toList)
+          }
+        } catch {
+          case e: SparkThrowable with Throwable if !isInternalError(e) =>
+            JArray(parsed.map {
+              case ParseFailed(errorObj) => errorObj
+              case Parsed(segment, plan) =>
+                successJson(plan, None, Some(e), Some(session), 
segmentSpan(batch, segment))
+            }.toList)
+        }
+      }
+    }
+  }
+
+  /** INTERNAL_ERROR is a Spark bug, not an analysis result: it fails the 
call. */
+  private def isInternalError(e: SparkThrowable): Boolean =
+    Option(e.getCondition).exists(_.startsWith("INTERNAL_ERROR"))
+
+  /**
+   * Character span of a statement object; `text` is the statement's own text,
+   * which its error indexes are relative to.
+   */
+  private case class StatementSpan(start: Int, length: Int, text: String)
+
+  private def segmentSpan(batch: String, segment: PositionedSqlStatement): 
StatementSpan =
+    StatementSpan(charStart(batch, segment), charLength(segment), 
segment.statement)
+
+  /** Code points `[from, until)` of `text`, clamped to its bounds. */
+  private def codePointSlice(text: String, from: Int, until: Int): String = {
+    val count = text.codePointCount(0, text.length)
+    val begin = math.max(0, math.min(from, count))
+    val end = math.max(begin, math.min(until, count))
+    text.substring(text.offsetByCodePoints(0, begin), 
text.offsetByCodePoints(0, end))
+  }
+
+  /**
+   * Analysis state carried across the statements of one ANALYZE batch. It
+   * starts from the caller-supplied variables and relations and records the
+   * effect of each analyzed statement on later ones, without executing
+   * anything:
+   *  - DECLARE VARIABLE adds a session variable. DROP TEMPORARY VARIABLE
+   *    removes it.
+   *  - CREATE [OR REPLACE] TABLE / VIEW / TEMP VIEW (column list, AS query,
+   *    LIKE, or a temp view USING with a schema) adds a schema-only relation 
of
+   *    that identity. DROP TABLE / VIEW removes a relation known this way.
+   * Objects dropped that exist in the catalog stay visible, and statements 
that
+   * change a schema in place (for example ALTER TABLE) are not tracked.
+   */
+  private final class AnalyzeState(env: AnalyzeEnv) {
+    private val session = env.session
+    private def mgr: CatalogManager = session.sessionState.catalogManager
+    private def resolver: (String, String) => Boolean = 
session.sessionState.conf.resolver
+
+    private var variables: List[(Seq[String], DataType)] = env.variables.map {
+      case (name, dataType) => SuppliedVariableRegistry.canonicalize(name) -> 
dataType
+    }.toList
+    private var relations: List[(Seq[String], StructType)] = env.relations.map 
{
+      case (name, schema) => SuppliedRelationRegistry.canonicalize(mgr, name) 
-> schema
+    }.toList
+
+    /**
+     * Analyze one statement with the known objects, render its JSON, then
+     * record its effect.
+     */
+    def statement(plan: LogicalPlan, span: StatementSpan): JObject = {
+      SuppliedVariableRegistry.create(variables).runWith {
+        SuppliedRelationRegistry.create(relations).runWith {
+          val (analyzed, error) = analyze(plan)
+          val json = successJson(plan, analyzed, error, Some(session), span)
+          record(plan, analyzed)
+          json
+        }
+      }
+    }
+
+    private def analyze(
+        plan: LogicalPlan,
+        markers: Seq[(String, DataType)] = env.parameterMarkers)
+        : (Option[LogicalPlan], Option[SparkThrowable with Throwable]) = {
+      try {
+        val toAnalyze = bindSuppliedParameterMarkers(plan, markers)
+        val analyzed =
+          session.sessionState.executePlan(toAnalyze, 
CommandExecutionMode.SKIP).analyzed
+        (Some(analyzed), None)
+      } catch {
+        case e: SparkThrowable with Throwable if !isInternalError(e) => (None, 
Some(e))
+      }
+    }
+
+    private def record(plan: LogicalPlan, analyzed: Option[LogicalPlan]): Unit 
= plan match {
+      case c: CreateVariable =>
+        variableType(c, analyzed).foreach { dataType =>
+          c.names.foreach {
+            case UnresolvedIdentifier(nameParts, _) => 
declareVariable(nameParts, dataType)
+            case _ =>
+          }
+        }
+      case DropVariable(UnresolvedIdentifier(nameParts, _), _) =>
+        val identity = SuppliedVariableRegistry.canonicalize(nameParts)
+        variables = variables.filterNot { case (name, _) => sameName(name, 
identity) }
+      case c: CreateTable =>
+        nameOf(c.name).filterNot(n => c.ignoreIfExists && 
relationExists(n)).foreach {
+          createRelation(_, StructType(c.columns.map(col =>
+            StructField(col.name, col.dataType, col.nullable))))
+        }
+      case r: ReplaceTable =>
+        nameOf(r.name).foreach {
+          createRelation(_, StructType(r.columns.map(col =>
+            StructField(col.name, col.dataType, col.nullable))))
+        }
+      case c: CreateTableAsSelect =>
+        nameOf(c.name).filterNot(n => c.ignoreIfExists && 
relationExists(n)).foreach { name =>
+          querySchema(c.query).foreach(createRelation(name, _))
+        }
+      case r: ReplaceTableAsSelect =>
+        nameOf(r.name).foreach(name => 
querySchema(r.query).foreach(createRelation(name, _)))
+      case c: CreateTableLike =>
+        for {
+          name <- nameOf(c.name) if !(c.ifNotExists && relationExists(name))
+          source <- nameOf(c.source)
+          schema <- querySchema(UnresolvedRelation(source))
+        } createRelation(name, schema)
+      case v: CreateView =>
+        nameOf(v.child).filterNot(n => v.allowExisting && 
relationExists(n)).foreach { name =>
+          querySchema(v.query).foreach(s =>
+            createRelation(name, withColumnNames(s, v.userSpecifiedColumns)))
+        }
+      case v: CreateViewCommand =>
+        val name = viewIdentity(v.name, v.viewType)
+        if (!(v.allowExisting && relationExists(name))) {
+          querySchema(v.plan).foreach(s =>
+            createRelation(name, withColumnNames(s, v.userSpecifiedColumns)))
+        }
+      case v: CreateTempViewUsing =>
+        val viewType = if (v.global) GlobalTempView else LocalTempView
+        
v.userSpecifiedSchema.foreach(createRelation(viewIdentity(v.tableIdent, 
viewType), _))
+      case d: DropTable => nameOf(d.child).foreach(dropRelation)
+      case d: DropView => nameOf(d.child).foreach(dropRelation)
+      case _ =>
+    }
+
+    /** The declared type, else the type of the analyzed DEFAULT expression. */
+    private def variableType(
+        c: CreateVariable,
+        analyzed: Option[LogicalPlan]): Option[DataType] = c.defaultExpr.child 
match {
+      case cast: Cast => Some(cast.dataType)
+      case Literal(null, dataType) => Some(dataType)
+      case _ =>
+        analyzed.flatMap(_.collectFirst {
+          case v: CreateVariable if v.defaultExpr.child.resolved => 
v.defaultExpr.child.dataType
+        })
+    }
+
+    private def declareVariable(nameParts: Seq[String], dataType: DataType): 
Unit = {
+      val identity = SuppliedVariableRegistry.canonicalize(nameParts)
+      variables = (identity -> dataType) ::
+        variables.filterNot { case (name, _) => sameName(name, identity) }
+    }
+
+    private def nameOf(plan: LogicalPlan): Option[Seq[String]] = plan match {
+      case UnresolvedIdentifier(nameParts, _) => Some(nameParts)
+      case u: UnresolvedTableOrView => Some(u.multipartIdentifier)
+      case u: UnresolvedTable => Some(u.multipartIdentifier)
+      case u: UnresolvedView => Some(u.multipartIdentifier)
+      case u: UnresolvedRelation => Some(u.multipartIdentifier)
+      case _ => None
+    }
+
+    private def viewIdentity(name: TableIdentifier, viewType: ViewType): 
Seq[String] =
+      viewType match {
+        case LocalTempView => 
SuppliedRelationRegistry.sessionIdentity(name.table)
+        case GlobalTempView => 
Seq(session.sessionState.catalog.globalTempDatabase, name.table)
+        case _ => tableIdentifierParts(name)
+      }
+
+    private def withColumnNames(
+        schema: StructType,
+        columns: Seq[(String, Option[String])]): StructType = {
+      if (columns.nonEmpty && columns.length == schema.length) {
+        StructType(schema.fields.zip(columns).map { case (f, (name, _)) => 
f.copy(name = name) })
+      } else {
+        schema
+      }
+    }
+
+    private def querySchema(query: LogicalPlan): Option[StructType] =
+      analyze(query)._1.map(_.schema)
+
+    /**
+     * Whether an object of the identity `nameParts` names already exists, for
+     * IF NOT EXISTS. This checks that identity only, not what the name would
+     * resolve to through the path.
+     */
+    private def relationExists(nameParts: Seq[String]): Boolean = {
+      val identity = SuppliedRelationRegistry.canonicalize(mgr, nameParts)
+      val catalog = session.sessionState.catalog
+      relations.exists(r => sameName(r._1, identity)) || {
+        try {
+          if (CatalogManager.isSessionQualifiedViewName(identity)) {
+            catalog.getRawTempView(identity.last).isDefined
+          } else if (identity.length == 2 && 
catalog.isGlobalTempViewDB(identity.head)) {
+            catalog.getRawGlobalTempView(identity.last).isDefined
+          } else {
+            mgr.catalog(identity.head) match {
+              case tables: TableCatalog =>
+                tables.tableExists(Identifier.of(identity.tail.init.toArray, 
identity.last))
+              case _ => false
+            }
+          }
+        } catch {
+          case NonFatal(_) => false
+        }
+      }
+    }
+
+    private def createRelation(nameParts: Seq[String], schema: StructType): 
Unit = {
+      if (schema.nonEmpty) {
+        val identity = SuppliedRelationRegistry.canonicalize(mgr, nameParts)
+        relations = (identity -> schema) ::
+          relations.filterNot { case (name, _) => sameName(name, identity) }
+      }
+    }
+
+    /** A one-part name drops the temp view of that name first, as DROP does. 
*/
+    private def dropRelation(nameParts: Seq[String]): Unit = {
+      val sessionIdentity = 
SuppliedRelationRegistry.sessionIdentity(nameParts.last)
+      val identity =
+        if (nameParts.length == 1 && relations.exists(r => sameName(r._1, 
sessionIdentity))) {
+          sessionIdentity
+        } else {
+          SuppliedRelationRegistry.canonicalize(mgr, nameParts)
+        }
+      relations = relations.filterNot { case (name, _) => sameName(name, 
identity) }
+    }
+
+    private def sameName(left: Seq[String], right: Seq[String]): Boolean =
+      left.length == right.length && left.zip(right).forall { case (a, b) => 
resolver(a, b) }
   }
 
-  private def parseStatement(segment: PositionedSqlStatement): JObject = {
+  /** Parsed plan, or parse-failure JSON for this statement. */
+  private def parsePlanOrError(
+      batch: String,
+      segment: PositionedSqlStatement): ParsedStatement = {
     val sql = segment.statement
     try {
       // Do not inherit the outer query's origin from the parse_sql expression.
       // Errors and parsed nodes refer to the individual statement.
       val origin = if (sql.nonEmpty) {
-        Origin(startIndex = Some(0), stopIndex = Some(sql.length - 1), sqlText 
= Some(sql))
+        Origin(
+          startIndex = Some(0),
+          stopIndex = Some(sql.codePointCount(0, sql.length) - 1),
+          sqlText = Some(sql))
       } else {
         Origin(sqlText = Some(sql))
       }
       CurrentOrigin.withOrigin(origin) {
-        val plan = parser.get().parsePlan(sql)
-        successJson(plan, segment)
+        Parsed(segment, parser.get().parsePlan(sql))
       }
     } catch {
-      // User-facing parse / scripting failures become JSON; everything else 
fails.
       case e: ParseException =>
-        errorJson(e, segment)
+        ParseFailed(errorJson(e, segmentSpan(batch, segment)))
       case e: SqlScriptingException =>
-        errorJson(e, segment)
+        ParseFailed(errorJson(e, segmentSpan(batch, segment)))
+    }
+  }
+
+  /** Session and caller-supplied objects for one ANALYZE batch. */
+  private case class AnalyzeEnv(
+      session: ClassicSparkSession,
+      parameterMarkers: Seq[(String, DataType)],
+      variables: Seq[(Seq[String], DataType)],
+      relations: Seq[(Seq[String], StructType)])
+
+  /**
+   * Run `f` with optional catalog / schema / SQL path overrides, then restore
+   * the invoker session. `None` on a field keeps the current value. Supplied
+   * variables and relations are validated here and overlaid per statement.
+   */
+  private def withAnalyzeContext[T](
+      session: ClassicSparkSession,
+      context: ParseSqlAnalyzeContext)(f: AnalyzeEnv => T): T = {
+    val parsedVars = context.variables.map(parseKnownVariable)
+    val parsedRels = context.relations.map(parseKnownRelation)
+    val parsedMarkers = context.parameterMarkers.map(parseKnownParameterMarker)
+    val env = AnalyzeEnv(session, parsedMarkers, parsedVars, parsedRels)
+    val needsSessionOverride =
+      context.catalog.nonEmpty || context.schema.nonEmpty || 
context.path.nonEmpty
+    if (!needsSessionOverride) {
+      f(env)
+    } else {
+      val mgr = session.sessionState.catalogManager
+      val conf = session.sessionState.conf
+      val prevCatalog = mgr.currentCatalog.name()
+      val prevNamespace = mgr.currentNamespace.clone()
+      val prevPath = mgr.storedSessionPathEntries
+      val prevPathEnabled = conf.getConf(SQLConf.PATH_ENABLED)
+      try {
+        context.catalog.foreach { catalog =>
+          if (catalog.trim.isEmpty) {
+            throw 
QueryExecutionErrors.invalidParseSqlContext("current_catalog", catalog)
+          }
+          mgr.setCurrentCatalog(catalog)
+        }
+        context.schema.foreach { schema =>
+          val parts = try {
+            parser.get().parseMultipartIdentifier(schema)
+          } catch {
+            case _: ParseException =>
+              throw 
QueryExecutionErrors.invalidParseSqlContext("current_schema", schema)
+          }
+          if (parts.isEmpty) {
+            throw 
QueryExecutionErrors.invalidParseSqlContext("current_schema", schema)
+          }
+          mgr.setCurrentNamespace(parts.toArray)
+        }
+        context.path.foreach { path =>
+          if (!prevPathEnabled) {
+            conf.setConf(SQLConf.PATH_ENABLED, true)
+          }
+          applyPathOverride(mgr, conf, path)
+        }
+        f(env)
+      } finally {
+        mgr.setCurrentCatalog(prevCatalog)
+        mgr.setCurrentNamespace(prevNamespace)
+        prevPath match {
+          case Some(entries) => mgr.setSessionPath(entries)
+          case None => mgr.clearSessionPath()
+        }
+        if (conf.getConf(SQLConf.PATH_ENABLED) != prevPathEnabled) {
+          conf.setConf(SQLConf.PATH_ENABLED, prevPathEnabled)
+        }
+      }
+    }
+  }
+
+  private def applyPathOverride(
+      mgr: CatalogManager,
+      conf: SQLConf,
+      path: String): Unit = {
+    if (path.trim.isEmpty) {
+      mgr.clearSessionPath()
+    } 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) {
+        mgr.clearSessionPath()
+      } else {
+        mgr.setSessionPath(expanded)
+      }
+    }
+  }
+
+  private def parseKnownVariable(
+      spec: (String, String)): (Seq[String], DataType) = {
+    val (name, typeDdl) = spec
+    val parts = parseKnownName(name, "variables")
+    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 _ =>
+        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 using the same [[BindParameters]] rule 
as
+   * `sql(..., args)`, then analyze the bound plan.
+   */
+  private def bindSuppliedParameterMarkers(
+      plan: LogicalPlan,
+      markers: Seq[(String, DataType)]): LogicalPlan = {
+    // Markers may sit in subqueries and CTE definitions, so look deep.
+    val used = if (markers.isEmpty) None else 
collectPlanReferences(plan).parameterMarkers
+    if (used.isEmpty) {
+      plan
+    } else {
+      val namedArgs = markers.collect {
+        case (name, dataType) if name != "?" =>
+          name -> Literal.create(null, dataType)
+      }
+      val posArgs = markers.collect {
+        case ("?", dataType) => Literal.create(null, dataType)
+      }
+      val usesNamed = used.exists(_.obj.exists(_._1 == "named"))
+      val usesPos = used.exists(_.obj.exists(_._1 == "unnamed_count"))
+      val wrapped = if (usesNamed && namedArgs.nonEmpty) {
+        NameParameterizedQuery(plan, namedArgs.toMap)
+      } else if (usesPos && posArgs.nonEmpty) {
+        PosParameterizedQuery(plan, posArgs)
+      } else {
+        plan
+      }
+      BindParameters(wrapped)
     }
   }
 
   /** Build success JSON from an already-parsed unresolved plan. */
-  private def successJson(plan: LogicalPlan, segment: PositionedSqlStatement): 
JObject = {
+  private def successJson(
+      plan: LogicalPlan,
+      analyzed: Option[LogicalPlan],
+      analyzeError: Option[SparkThrowable with Throwable],
+      session: Option[ClassicSparkSession],
+      span: StatementSpan): JObject = {
     val classification = SqlStatementCodes.classify(plan)
     val fields = mutable.ListBuffer.empty[JField]
-    fields += "start" -> JInt(segment.start + 1)
-    fields += "length" -> JInt(segment.length)
+    fields += "start" -> JInt(span.start)
+    fields += "length" -> JInt(span.length)
     fields += "parse_success" -> JBool(true)
     fields += "statement_identifier" -> 
JString(classification.statementIdentifier)
     fields += "statement_code" -> JInt(classification.statementCode)
+    if (session.nonEmpty) {
+      fields += "analyze_success" -> JBool(analyzed.isDefined)
+    }
     // Omit unused collections / markers so consumers can treat absence as 
empty.
     val refs = collectPlanReferences(plan)
-    if (refs.targetTables.nonEmpty) {
+    // Qualify from the ANALYZE session even when analysis failed: names and
+    // builtins are known from parse plus current catalog / schema / path.
+    // A DML target is the existing object its name resolves to; a DDL target
+    // is named in the current schema.
+    val dmlTarget = plan match {
+      case _: InsertIntoStatement | _: UnresolvedInsert | _: UpdateTable | _: 
DeleteFromTable |
+          _: MergeIntoTable => true
+      case _ => false
+    }
+    val targetTables = session.map(s => 
refs.targetTables.map(qualifyRelation(_, s, dmlTarget)))
+      .getOrElse(refs.targetTables)
+    val sourceTables = session.map(s => 
refs.sourceTables.map(qualifyRelation(_, s)))
+      .getOrElse(refs.sourceTables)
+    val functions = session.map(s => refs.functions.map(qualifyRoutine(_, s)))
+      .getOrElse(refs.functions)
+    if (targetTables.nonEmpty) {
       fields += "target_table_references" ->
-        JArray(refs.targetTables.map(partsToJArray).toList)
+        JArray(targetTables.map(partsToJArray).toList)
     }
-    if (refs.sourceTables.nonEmpty) {
+    if (sourceTables.nonEmpty) {
       fields += "source_table_references" ->
-        JArray(refs.sourceTables.map(partsToJArray).toList)
+        JArray(sourceTables.map(partsToJArray).toList)
     }
-    if (refs.functions.nonEmpty) {
-      fields += "function_references" -> 
JArray(refs.functions.map(partsToJArray).toList)
+    if (functions.nonEmpty) {
+      fields += "function_references" -> 
JArray(functions.map(partsToJArray).toList)
     }
-    val selectList = collectSelectList(plan)
+    val selectList = analyzed.map(collectTypedSelectList)
+      .getOrElse(collectSelectList(plan))
     if (selectList.nonEmpty) {
       fields += "select_list" -> JArray(selectList.toList)
     }
     refs.parameterMarkers.foreach(markers => fields += "parameter_markers" -> 
markers)
+    analyzeError.foreach { e =>
+      fields += "error" -> errorObject(e, span.text)
+    }
     JObject(fields.toList)
   }
 
-  private def errorJson(
-      e: SparkThrowable with Throwable,
-      segment: PositionedSqlStatement): JObject = {
+  /** 1-based Unicode code-point offset of `segment` in `batch`. */
+  private def charStart(batch: String, segment: PositionedSqlStatement): Int = 
{
+    val utf16 = math.max(0, math.min(segment.start, batch.length))
+    batch.codePointCount(0, utf16) + 1

Review Comment:
   Fixed in the current branch. statementSpans now computes the code-point 
start of each statement in one forward pass over the batch (lastUtf16/lastCp 
are carried between statements), so statement i no longer rescans the prefix 
from 0. The batch is walked a bounded number of times rather than once per 
statement.



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