rdblue commented on a change in pull request #1743:
URL: https://github.com/apache/iceberg/pull/1743#discussion_r520966189



##########
File path: 
spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveProcedures.scala
##########
@@ -0,0 +1,165 @@
+/*
+ * 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.analysis
+
+import org.apache.spark.sql.{AnalysisException, SparkSession}
+import org.apache.spark.sql.catalyst.expressions.{Cast, Expression, Literal}
+import org.apache.spark.sql.catalyst.plans.logical.{Call, CallArgument, 
CallStatement, LogicalPlan, NamedArgument, PositionalArgument}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.connector.catalog.{CatalogManager, CatalogPlugin, 
LookupCatalog, Procedure, ProcedureCatalog, ProcedureParameter}
+import scala.collection.Seq
+
+case class ResolveProcedures(spark: SparkSession) extends Rule[LogicalPlan] 
with LookupCatalog {
+
+  protected lazy val catalogManager: CatalogManager = 
spark.sessionState.catalogManager
+
+  override def apply(plan: LogicalPlan): LogicalPlan = plan resolveOperators {
+    case CallStatement(CatalogAndIdentifier(catalog, ident), args) =>
+      val procedure = catalog.asProcedureCatalog.loadProcedure(ident)
+      validateParams(procedure)
+      Call(procedure, args = buildArgExprs(procedure, args))
+  }
+
+  private def validateParams(procedure: Procedure): Unit = {
+    // should not be any duplicate param names
+    val duplicateParamNames = procedure.parameters.groupBy(_.name).collect {
+      case (name, matchingParams) if matchingParams.length > 1 => name
+    }
+
+    if (duplicateParamNames.nonEmpty) {
+      throw new AnalysisException(s"Duplicate parameter names: 
${duplicateParamNames.mkString("[", ",", "]")}")
+    }
+
+    // optional params should be at the end
+    procedure.parameters.sliding(2).foreach {
+      case Array(previousParam, currentParam) if previousParam.required && 
!currentParam.required =>
+        throw new AnalysisException("Optional parameters must be after 
required ones")
+      case _ =>
+    }
+  }
+
+  private def buildArgExprs(procedure: Procedure, args: Seq[CallArgument]): 
Seq[Expression] = {
+    val params = procedure.parameters
+
+    // build a map of declared parameter names to their positions
+    val nameToPositionMap = params.map(_.name).zipWithIndex.toMap
+
+    // build a map of parameter names to args
+    val nameToArgMap = buildNameToArgMap(params, args, nameToPositionMap)
+
+    // verify all required parameters are provided
+    val missingParamNames = params.filter(_.required).collect {
+      case param if !nameToArgMap.contains(param.name) => param.name
+    }
+
+    if (missingParamNames.nonEmpty) {
+      throw new AnalysisException(s"Missing required parameters: 
${missingParamNames.mkString("[", ",", "]")}")
+    }
+
+    val argExprs = new Array[Expression](params.size)
+
+    nameToArgMap.foreach { case (name, arg) =>
+      val position = nameToPositionMap(name)
+      val param = params(position)
+      val paramType = param.dataType
+      val argType = arg.expr.dataType
+
+      if (paramType != argType && !Cast.canUpCast(argType, paramType)) {
+        throw new AnalysisException(s"Wrong arg type for ${param.name}: 
expected $paramType but got $argType")
+      }
+
+      if (paramType != argType) {
+        argExprs(position) = Cast(arg.expr, paramType)
+      } else {
+        argExprs(position) = arg.expr
+      }
+    }
+
+    // assign nulls to optional params that were not set
+    params.foreach {
+      case p if !p.required && !nameToArgMap.contains(p.name) =>

Review comment:
       We know from validation above that if the map doesn't contain an 
argument, that it must be required. Not a big deal to have the additional 
check, though.




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

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