cloud-fan commented on code in PR #57962: URL: https://github.com/apache/spark/pull/57962#discussion_r3797669762
########## sql/core/src/main/scala/org/apache/spark/sql/catalyst/parser/ParseSqlResult.scala: ########## @@ -0,0 +1,371 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.catalyst.parser + +import scala.collection.mutable + +import org.json4s._ +import org.json4s.jackson.JsonMethods.{compact, parse => parseJson, render} + +import org.apache.spark.{ErrorMessageFormat, SparkThrowable, SparkThrowableHelper} +import org.apache.spark.sql.catalyst.analysis._ +import org.apache.spark.sql.catalyst.expressions._ +import org.apache.spark.sql.catalyst.plans.logical._ +import org.apache.spark.sql.catalyst.trees.{CurrentOrigin, Origin, SQLQueryContext} +import org.apache.spark.sql.exceptions.SqlScriptingException +import org.apache.spark.sql.execution.SparkSqlParser +import org.apache.spark.sql.execution.command.{CreateViewCommand, DescribeQueryCommand, ExplainCommand} +import org.apache.spark.sql.execution.datasources.CreateTempViewUsing + +/** + * Parses a SQL statement string and returns a compact JSON description of the + * unresolved plan (parse-only; no catalog resolution). + * + * Uses a stock [[SparkSqlParser]] (ThreadLocal) so statement coverage matches + * the default production parser (EXPLAIN / SET / ADD JAR / temp views / etc.). + * Session-specific [[org.apache.spark.sql.SparkSessionExtensions]] parser + * wrappers are intentionally not applied: `parse_sql` must evaluate on + * executors without a session, so only the stock parser is available under + * distributed eval. + * + * On success the JSON always includes `parse_success`, the statement + * identifier/code (ISO/IEC 9075-2:2023 Table 39), and omits unused optional + * fields (`table_references`, `function_references`, `select_list`, + * `parameter_markers`) when empty. On parse failure it returns + * `parse_success: false` with source location and a nested STANDARD-format + * error object, and does not throw. Only [[ParseException]] / + * [[SqlScriptingException]] are converted to JSON; unexpected / internal + * failures propagate so the function fails. + */ +object ParseSqlResult { + + private val parser: ThreadLocal[SparkSqlParser] = + ThreadLocal.withInitial(() => new SparkSqlParser()) + + /** Parse `sql` and render the JSON result string. */ + def fromSql(sql: String): String = { + try { + // Do not inherit the outer query's origin from the parse_sql expression. + // Errors and parsed nodes must refer to the SQL string passed to this function. + val origin = if (sql.nonEmpty) { + Origin(startIndex = Some(0), stopIndex = Some(sql.length - 1), sqlText = Some(sql)) + } else { + Origin(sqlText = Some(sql)) + } + CurrentOrigin.withOrigin(origin) { + val plan = parser.get().parsePlan(sql) + fromPlan(plan) + } + } catch { + // User-facing parse / scripting failures become JSON; everything else fails. + case e: ParseException => + errorJson(e) + case e: SqlScriptingException => + errorJson(e) + } + } + + /** Build success JSON from an already-parsed unresolved plan. */ + def fromPlan(plan: LogicalPlan): String = { + val classification = SqlStatementCodes.classify(plan) + val fields = mutable.ListBuffer.empty[JField] + fields += "parse_success" -> JBool(true) + fields += "statement_identifier" -> JString(classification.statementIdentifier) + fields += "statement_code" -> JInt(classification.statementCode) + // Omit unused collections / markers so consumers can treat absence as empty. + val tables = collectTableReferences(plan) + if (tables.nonEmpty) { + fields += "table_references" -> JArray(tables.map(partsToJArray).toList) + } + val functions = collectFunctionReferences(plan) + if (functions.nonEmpty) { + fields += "function_references" -> JArray(functions.map(partsToJArray).toList) + } + val selectList = collectSelectList(plan) + if (selectList.nonEmpty) { + fields += "select_list" -> JArray(selectList.toList) + } + parameterMarkersJson(plan).foreach(markers => fields += "parameter_markers" -> markers) + compact(render(JObject(fields.toList))) + } + + private def errorJson(e: SparkThrowable with Throwable): String = { + val errorObj = parseJson( + SparkThrowableHelper.getMessage(e, ErrorMessageFormat.STANDARD)).asInstanceOf[JObject] + val origin = e match { + case p: ParseException => Some(p.start) + case s: SqlScriptingException => Some(s.origin) + case _ => None + } + val locationFields = origin.toSeq.flatMap(originFields) + val contextFields = if (errorObj.obj.exists(_._1 == "queryContext")) { + Nil + } else { + origin.toSeq.flatMap(queryContextField) + } + compact(render(JObject( + "parse_success" -> JBool(false), + "error" -> JObject(errorObj.obj ++ contextFields ++ locationFields) + ))) + } + + private def queryContextField(origin: Origin): Option[JField] = origin.context match { + case context: SQLQueryContext if context.isValid => + Some("queryContext" -> JArray(List(JObject( + "objectType" -> JString(context.objectType), + "objectName" -> JString(context.objectName), + "startIndex" -> JInt(context.startIndex + 1), + "stopIndex" -> JInt(context.stopIndex + 1), + "fragment" -> JString(context.fragment) + )))) + case _ => None + } + + private def originFields(origin: Origin): Seq[JField] = Seq( + origin.line.map(line => "line" -> JInt(line)), + origin.startPosition.map(position => "position" -> JInt(position))).flatten + + private def partsToJArray(parts: Seq[String]): JArray = + JArray(parts.map(JString).toList) + + /** + * Walk expressions in all product fields, including wrappers such as column + * definitions that [[LogicalPlan.expressions]] does not descend into. + */ + private def foreachExpressionDeep(plan: LogicalPlan)(f: Expression => Unit): Unit = { + def visit(value: Any): Unit = value match { + case e: Expression => f(e) + case _: LogicalPlan => + case values: Iterable[_] => values.foreach(visit) + case value: Product => value.productIterator.foreach(visit) + case _ => + } + plan.productIterator.foreach(visit) + } + + /** + * Deep plan walk covering tree slots that standard `collect` / + * `collectWithSubqueries` miss: + * - [[UnresolvedWith]] CTE definitions (`innerChildren`, not `children`) + * - [[InsertIntoStatement]].table (non-child plan slot) + * - [[SingleStatement]].parsedPlan (children expose only nested children) + * - [[CompoundBody]].handlers (not in `children`) + * - [[SimpleCaseStatement]].elseBody (not in `children`) + * Nested expression subqueries are still covered by `foreachWithSubqueries`. + */ + private def foreachPlanDeep(plan: LogicalPlan)(f: LogicalPlan => Unit): Unit = { + plan.foreachWithSubqueries { p => + f(p) + p match { + case w: UnresolvedWith => + w.cteRelations.foreach { case (_, ctePlan, _) => + foreachPlanDeep(ctePlan)(f) + } + case InsertIntoStatement(table, _, _, _, _, _, _, _, _) => + foreachPlanDeep(table)(f) + case s: SingleStatement => + // Root of the wrapped statement is skipped by SingleStatement.children. + foreachPlanDeep(s.parsedPlan)(f) Review Comment: Thanks, the root-only traversal and focused positional-marker coverage address this. ########## sql/core/src/main/scala/org/apache/spark/sql/catalyst/parser/ParseSqlResult.scala: ########## @@ -0,0 +1,371 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.catalyst.parser + +import scala.collection.mutable + +import org.json4s._ +import org.json4s.jackson.JsonMethods.{compact, parse => parseJson, render} + +import org.apache.spark.{ErrorMessageFormat, SparkThrowable, SparkThrowableHelper} +import org.apache.spark.sql.catalyst.analysis._ +import org.apache.spark.sql.catalyst.expressions._ +import org.apache.spark.sql.catalyst.plans.logical._ +import org.apache.spark.sql.catalyst.trees.{CurrentOrigin, Origin, SQLQueryContext} +import org.apache.spark.sql.exceptions.SqlScriptingException +import org.apache.spark.sql.execution.SparkSqlParser +import org.apache.spark.sql.execution.command.{CreateViewCommand, DescribeQueryCommand, ExplainCommand} +import org.apache.spark.sql.execution.datasources.CreateTempViewUsing + +/** + * Parses a SQL statement string and returns a compact JSON description of the + * unresolved plan (parse-only; no catalog resolution). + * + * Uses a stock [[SparkSqlParser]] (ThreadLocal) so statement coverage matches + * the default production parser (EXPLAIN / SET / ADD JAR / temp views / etc.). + * Session-specific [[org.apache.spark.sql.SparkSessionExtensions]] parser + * wrappers are intentionally not applied: `parse_sql` must evaluate on + * executors without a session, so only the stock parser is available under + * distributed eval. + * + * On success the JSON always includes `parse_success`, the statement + * identifier/code (ISO/IEC 9075-2:2023 Table 39), and omits unused optional + * fields (`table_references`, `function_references`, `select_list`, + * `parameter_markers`) when empty. On parse failure it returns + * `parse_success: false` with source location and a nested STANDARD-format + * error object, and does not throw. Only [[ParseException]] / + * [[SqlScriptingException]] are converted to JSON; unexpected / internal + * failures propagate so the function fails. + */ +object ParseSqlResult { + + private val parser: ThreadLocal[SparkSqlParser] = + ThreadLocal.withInitial(() => new SparkSqlParser()) + + /** Parse `sql` and render the JSON result string. */ + def fromSql(sql: String): String = { + try { + // Do not inherit the outer query's origin from the parse_sql expression. + // Errors and parsed nodes must refer to the SQL string passed to this function. + val origin = if (sql.nonEmpty) { + Origin(startIndex = Some(0), stopIndex = Some(sql.length - 1), sqlText = Some(sql)) + } else { + Origin(sqlText = Some(sql)) + } + CurrentOrigin.withOrigin(origin) { + val plan = parser.get().parsePlan(sql) + fromPlan(plan) + } + } catch { + // User-facing parse / scripting failures become JSON; everything else fails. + case e: ParseException => + errorJson(e) + case e: SqlScriptingException => + errorJson(e) + } + } + + /** Build success JSON from an already-parsed unresolved plan. */ + def fromPlan(plan: LogicalPlan): String = { + val classification = SqlStatementCodes.classify(plan) + val fields = mutable.ListBuffer.empty[JField] + fields += "parse_success" -> JBool(true) + fields += "statement_identifier" -> JString(classification.statementIdentifier) + fields += "statement_code" -> JInt(classification.statementCode) + // Omit unused collections / markers so consumers can treat absence as empty. + val tables = collectTableReferences(plan) + if (tables.nonEmpty) { + fields += "table_references" -> JArray(tables.map(partsToJArray).toList) + } + val functions = collectFunctionReferences(plan) + if (functions.nonEmpty) { + fields += "function_references" -> JArray(functions.map(partsToJArray).toList) + } + val selectList = collectSelectList(plan) + if (selectList.nonEmpty) { + fields += "select_list" -> JArray(selectList.toList) + } + parameterMarkersJson(plan).foreach(markers => fields += "parameter_markers" -> markers) Review Comment: Thanks, the combined reference walk resolves the per-row traversal concern. -- 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]
