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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -159,44 +159,142 @@ class AstBuilder extends DataTypeAstBuilder
     script
   }
 
-  private def visitCompoundBodyImpl(
-      ctx: CompoundBodyContext,
-      label: Option[String],
-      allowVarDeclare: Boolean,
-      labelCtx: SqlScriptingLabelContext,
-      isScope: Boolean): CompoundBody = {
-    val buff = ListBuffer[CompoundPlanStatement]()
-    ctx.compoundStatements.forEach(
-      compoundStatement => buff += 
visitCompoundStatementImpl(compoundStatement, labelCtx))
+  private def assertSqlState(sqlState: String): Unit = {
+    val sqlStateRegex = "^[A-Za-z0-9]{5}$".r
+    if (sqlStateRegex.findFirstIn(sqlState).isEmpty
+      || sqlState.startsWith("00")
+      || sqlState.startsWith("01")
+      || sqlState.startsWith("XX")) {
+      throw SqlScriptingErrors.invalidSqlStateValue(CurrentOrigin.get, 
sqlState)
+    }
+  }
+
+  private def visitConditionValueImpl(
+      ctx: ConditionValueContext,
+      handlerTriggers: HandlerTriggers): Unit = {
+    // Current element is SQLSTATE.
+    Option(ctx.sqlStateValue())
+      .foreach { sqlStateValueContext =>
+        val sqlState = sqlStateValueContext.getText.replace("'", "")
+        assertSqlState(sqlState)
+        handlerTriggers.addUniqueSqlState(sqlState)
+      }
 
-    val compoundStatements = buff.toList
+    // Current element is condition.
+    Option(ctx.multipartIdentifier())
+      .foreach { conditionContext =>
+        handlerTriggers.addUniqueCondition(conditionContext.getText)
+      }
 
-    val candidates = if (allowVarDeclare) {
-      compoundStatements.dropWhile {
-        case SingleStatement(_: CreateVariable) => true
-        case _ => false
+    Option(ctx.SQLEXCEPTION())
+      .foreach { _ =>
+        handlerTriggers.addUniqueSqlException()
       }
-    } else {
-      compoundStatements
+
+    // It is sufficient to check only NOT for NOT FOUND handler.
+    Option(ctx.NOT()).foreach { _ =>
+      handlerTriggers.addUniqueNotFound()
     }
+  }
 
-    val declareVarStatement = candidates.collectFirst {
-      case SingleStatement(c: CreateVariable) => c
+  /**
+   * Visit list of condition/sqlstate values in handler declaration.
+   */
+  private def visitConditionValuesImpl(
+      ctx: ConditionValuesContext): HandlerTriggers = {
+
+    val handlerTriggers: HandlerTriggers = new HandlerTriggers()
+
+    ctx.cvList.forEach { cvContext =>
+      visitConditionValueImpl(cvContext, handlerTriggers)
     }
 
-    declareVarStatement match {
-      case Some(c: CreateVariable) =>
-        if (allowVarDeclare) {
-          throw SqlScriptingErrors.variableDeclarationOnlyAtBeginning(
-            c.origin, c.name.asInstanceOf[UnresolvedIdentifier].nameParts)
-        } else {
-          throw SqlScriptingErrors.variableDeclarationNotAllowedInScope(
-            c.origin, c.name.asInstanceOf[UnresolvedIdentifier].nameParts)
+    handlerTriggers
+  }
+
+  private def visitDeclareConditionStatementImpl(
+      ctx: DeclareConditionStatementContext): ErrorCondition = {
+    val conditionName = ctx.multipartIdentifier().getText
+
+    // Qualified user defined condition name is not allowed.
+    if (ctx.multipartIdentifier().parts.size() > 1) {
+      throw SqlScriptingErrors
+        .conditionCannotBeQualified(CurrentOrigin.get, conditionName)
+    }
+
+    // If SQLSTATE is not provided, default to 45000.
+    val sqlState = Option(ctx.sqlStateValue())
+      .map(_.getText.replace("'", "")).getOrElse("45000")
+
+    assertSqlState(sqlState)
+    ErrorCondition(conditionName, sqlState)
+  }
+
+  private def visitDeclareHandlerStatementImpl(
+      ctx: DeclareHandlerStatementContext,
+      labelCtx: SqlScriptingLabelContext): ErrorHandler = {
+    val handlerTriggers = visitConditionValuesImpl(ctx.conditionValues())
+
+    if (Option(ctx.CONTINUE()).isDefined) {
+      throw SqlScriptingErrors.continueHandlerNotSupported(CurrentOrigin.get)
+    }
+
+    val handlerType = HandlerType.EXIT
+    val body = if (Option(ctx.beginEndCompoundBlock()).isDefined) {
+      visitBeginEndCompoundBlockImpl(
+        ctx.beginEndCompoundBlock(),
+        labelCtx)
+    } else {
+      // If there is no compound body, then there must be a statement or set 
statement.
+      val statement = Option(ctx.statement().asInstanceOf[ParserRuleContext])
+        
.orElse(Option(ctx.setStatementWithOptionalVarKeyword().asInstanceOf[ParserRuleContext]))
+        .map { s =>
+          SingleStatement(parsedPlan = visit(s).asInstanceOf[LogicalPlan])
         }
-      case _ =>
+      CompoundBody(Seq(statement.get), None, isScope = false)
     }
 
-    CompoundBody(buff.toSeq, label, isScope)
+    ErrorHandler(handlerTriggers, body, handlerType)
+  }
+
+  private def visitCompoundBodyImpl(
+      ctx: CompoundBodyContext,
+      label: Option[String],
+      allowVarDeclare: Boolean,
+      labelCtx: SqlScriptingLabelContext,
+      isScope: Boolean): CompoundBody = {
+    val buff = ListBuffer[CompoundPlanStatement]()
+
+    val handlers = ListBuffer[ErrorHandler]()
+    val conditions = HashMap[String, String]()
+
+    val scriptingParserContext = new SqlScriptingParsingContext()
+
+    ctx.compoundStatements.forEach(compoundStatement => {
+      val stmt = visitCompoundStatementImpl(compoundStatement, labelCtx)
+      stmt match {
+        case handler: ErrorHandler =>
+          scriptingParserContext.handler()
+          handlers += handler
+        case condition: ErrorCondition =>
+          scriptingParserContext.condition(condition)
+          // Check for duplicate condition names in each scope.
+          if (conditions.contains(condition.conditionName)) {

Review Comment:
   shall we consider case sensitivity?



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