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


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

Review Comment:
   Obsolete in this PR. The carry-forward of DECLARE/CREATE/DROP across 
statements (AnalyzeState) was removed from this PR during the clean-slate 
rebuild and is planned as a separate PR. This branch has no carried-forward 
schemas. Caller-supplied relations do go through 
CharVarcharUtils.replaceCharVarcharWithStringInSchema in parseKnownRelation, so 
VARCHAR and CHAR are normalized the same way as for real tables under the 
default configuration. Resolving as obsolete; the carry-forward concern moves 
with that PR.



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