RussellSpitzer commented on a change in pull request #1473: URL: https://github.com/apache/iceberg/pull/1473#discussion_r494429284
########## File path: spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveIcebergProcedures.scala ########## @@ -0,0 +1,132 @@ +/* + * 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 +import org.apache.spark.sql.catalyst.CatalystTypeConverters +import org.apache.spark.sql.catalyst.expressions.{Expression, Literal} +import org.apache.spark.sql.catalyst.plans.logical.{Call, CallArgument, LogicalPlan} +import org.apache.spark.sql.catalyst.procedures.{IcebergProcedureRegistry, OptionalParameter, Parameter, Procedure} +import org.apache.spark.sql.catalyst.rules.Rule +import scala.collection.mutable + +// TODO: case sensitivity? +object ResolveIcebergProcedures extends Rule[LogicalPlan] { + + override def apply(plan: LogicalPlan): LogicalPlan = plan resolveOperators { + case Call(nameParts, args) => + val procedure = IcebergProcedureRegistry.resolve(nameParts) + val values = buildProcedureValues(procedure, args) + procedure.createRunnableCommand(values) + } + + private def buildProcedureValues(procedure: Procedure, args: Seq[CallArgument]): Array[Any] = { + // build a map of declared parameter names to their positions + val params = procedure.parameters + val nameToPositionMap = params.map(_.name).zipWithIndex.toMap + + // verify named and positional args are not mixed + val containsNamedArg = args.exists(arg => arg.name.isDefined) + val containsPositionalArg = args.exists(arg => arg.name.isEmpty) + if (containsNamedArg && containsPositionalArg) { + throw new AnalysisException("Named and positional arguments cannot be mixed") + } + + // build a map of parameter names to args + val nameToArgMap = if (containsNamedArg) { + buildNameToArgMapUsingNames(args, nameToPositionMap) + } else { + buildNameToArgMapUsingPositions(args, params) + } + + // verify all required parameters are provided + params.filter(_.required) + .find(param => !nameToArgMap.contains(param.name)) + .foreach { missingArg => + throw new AnalysisException(s"Required procedure argument '${missingArg.name}' is missing") + } + + val values = new Array[Any](params.size) + + // convert provided args from internal Spark representation to Scala + 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) { + throw new AnalysisException(s"Wrong arg type for '${param.name}': expected $paramType but got $argType") + } + values(position) = toScalaValue(arg.expr) + } + + // assign default values for optional params + params.foreach { + case p: OptionalParameter if !nameToArgMap.contains(p.name) => + val position = nameToPositionMap(p.name) + values(position) = p.defaultValue + case _ => + } + + values + } + + private def buildNameToArgMapUsingNames( + args: Seq[CallArgument], + nameToPositionMap: Map[String, Int]): Map[String, CallArgument] = { + + val nameToArgMap = mutable.LinkedHashMap.empty[String, CallArgument] + args.foreach { arg => + val name = arg.name.get + + if (nameToArgMap.contains(name)) { + throw new AnalysisException(s"Duplicate procedure argument: '$name'") + } + + if (!nameToPositionMap.contains(name)) { + throw new AnalysisException(s"Unknown argument name: '$name'") + } + + nameToArgMap.put(name, arg) + } + nameToArgMap.toMap + } + + private def buildNameToArgMapUsingPositions( + args: Seq[CallArgument], + params: Seq[Parameter]): Map[String, CallArgument] = { + + val nameToArgMap = mutable.LinkedHashMap.empty[String, CallArgument] + args.zipWithIndex.foreach { case (arg, position) => Review comment: If order is a concern we should just keep it as a list of tuples ########## File path: spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveIcebergProcedures.scala ########## @@ -0,0 +1,132 @@ +/* + * 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 +import org.apache.spark.sql.catalyst.CatalystTypeConverters +import org.apache.spark.sql.catalyst.expressions.{Expression, Literal} +import org.apache.spark.sql.catalyst.plans.logical.{Call, CallArgument, LogicalPlan} +import org.apache.spark.sql.catalyst.procedures.{IcebergProcedureRegistry, OptionalParameter, Parameter, Procedure} +import org.apache.spark.sql.catalyst.rules.Rule +import scala.collection.mutable + +// TODO: case sensitivity? +object ResolveIcebergProcedures extends Rule[LogicalPlan] { + + override def apply(plan: LogicalPlan): LogicalPlan = plan resolveOperators { + case Call(nameParts, args) => + val procedure = IcebergProcedureRegistry.resolve(nameParts) + val values = buildProcedureValues(procedure, args) + procedure.createRunnableCommand(values) + } + + private def buildProcedureValues(procedure: Procedure, args: Seq[CallArgument]): Array[Any] = { + // build a map of declared parameter names to their positions + val params = procedure.parameters + val nameToPositionMap = params.map(_.name).zipWithIndex.toMap + + // verify named and positional args are not mixed + val containsNamedArg = args.exists(arg => arg.name.isDefined) + val containsPositionalArg = args.exists(arg => arg.name.isEmpty) + if (containsNamedArg && containsPositionalArg) { + throw new AnalysisException("Named and positional arguments cannot be mixed") + } + + // build a map of parameter names to args + val nameToArgMap = if (containsNamedArg) { + buildNameToArgMapUsingNames(args, nameToPositionMap) + } else { + buildNameToArgMapUsingPositions(args, params) + } + + // verify all required parameters are provided + params.filter(_.required) + .find(param => !nameToArgMap.contains(param.name)) + .foreach { missingArg => + throw new AnalysisException(s"Required procedure argument '${missingArg.name}' is missing") + } + + val values = new Array[Any](params.size) + + // convert provided args from internal Spark representation to Scala + 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) { + throw new AnalysisException(s"Wrong arg type for '${param.name}': expected $paramType but got $argType") + } + values(position) = toScalaValue(arg.expr) + } + + // assign default values for optional params + params.foreach { + case p: OptionalParameter if !nameToArgMap.contains(p.name) => + val position = nameToPositionMap(p.name) + values(position) = p.defaultValue + case _ => + } + + values + } + + private def buildNameToArgMapUsingNames( + args: Seq[CallArgument], + nameToPositionMap: Map[String, Int]): Map[String, CallArgument] = { + + val nameToArgMap = mutable.LinkedHashMap.empty[String, CallArgument] + args.foreach { arg => Review comment: Mostly I don't want us to make our own maps explicitly, I think the above is fine, but I think if we want to be really friendly, we gather up all the validation errors at once. Perhaps something like ```scala val validationErrors = NamedArgs.groupBy(_.name).collect { case (name, matchingArgs) if matchinArgs.size >1 => s"Duplicate Procedure argument: '$name'") // May want to add values here as well case (name, matchingArgs) if !nameToPositionMap.contains(name) => s"Unknown argument name: '$name'") if (validationErrors.nonEmpty) { throw new AnalysisException(s"Found the following parameter violations: validationErrors.join) } ``` Also I love having my if statements in my case statements :) ########## File path: spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveIcebergProcedures.scala ########## @@ -0,0 +1,132 @@ +/* + * 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 +import org.apache.spark.sql.catalyst.CatalystTypeConverters +import org.apache.spark.sql.catalyst.expressions.{Expression, Literal} +import org.apache.spark.sql.catalyst.plans.logical.{Call, CallArgument, LogicalPlan} +import org.apache.spark.sql.catalyst.procedures.{IcebergProcedureRegistry, OptionalParameter, Parameter, Procedure} +import org.apache.spark.sql.catalyst.rules.Rule +import scala.collection.mutable + +// TODO: case sensitivity? +object ResolveIcebergProcedures extends Rule[LogicalPlan] { + + override def apply(plan: LogicalPlan): LogicalPlan = plan resolveOperators { + case Call(nameParts, args) => + val procedure = IcebergProcedureRegistry.resolve(nameParts) + val values = buildProcedureValues(procedure, args) + procedure.createRunnableCommand(values) + } + + private def buildProcedureValues(procedure: Procedure, args: Seq[CallArgument]): Array[Any] = { + // build a map of declared parameter names to their positions + val params = procedure.parameters + val nameToPositionMap = params.map(_.name).zipWithIndex.toMap + + // verify named and positional args are not mixed + val containsNamedArg = args.exists(arg => arg.name.isDefined) + val containsPositionalArg = args.exists(arg => arg.name.isEmpty) + if (containsNamedArg && containsPositionalArg) { + throw new AnalysisException("Named and positional arguments cannot be mixed") + } + + // build a map of parameter names to args + val nameToArgMap = if (containsNamedArg) { + buildNameToArgMapUsingNames(args, nameToPositionMap) + } else { + buildNameToArgMapUsingPositions(args, params) + } + + // verify all required parameters are provided + params.filter(_.required) + .find(param => !nameToArgMap.contains(param.name)) + .foreach { missingArg => + throw new AnalysisException(s"Required procedure argument '${missingArg.name}' is missing") + } + + val values = new Array[Any](params.size) + + // convert provided args from internal Spark representation to Scala + 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) { + throw new AnalysisException(s"Wrong arg type for '${param.name}': expected $paramType but got $argType") + } + values(position) = toScalaValue(arg.expr) + } + + // assign default values for optional params + params.foreach { + case p: OptionalParameter if !nameToArgMap.contains(p.name) => + val position = nameToPositionMap(p.name) + values(position) = p.defaultValue + case _ => + } + + values + } + + private def buildNameToArgMapUsingNames( + args: Seq[CallArgument], + nameToPositionMap: Map[String, Int]): Map[String, CallArgument] = { + + val nameToArgMap = mutable.LinkedHashMap.empty[String, CallArgument] + args.foreach { arg => Review comment: Mostly I don't want us to make our own maps explicitly, I think the above is fine, but I think if we want to be really friendly, we gather up all the validation errors at once. Perhaps something like ```scala val validationErrors = NamedArgs.groupBy(_.name).collect { case (name, matchingArgs) if matchinArgs.size >1 => s"Duplicate Procedure argument: '$name'") // May want to add values here as well case (name, _) if !nameToPositionMap.contains(name) => s"Unknown argument name: '$name'") if (validationErrors.nonEmpty) { throw new AnalysisException(s"Found the following parameter violations: validationErrors.join) } ``` Also I love having my if statements in my case statements :) ########## File path: spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/IcebergSparkSqlExtensionsParser.scala ########## @@ -0,0 +1,364 @@ +/* + * 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.extensions + +import org.antlr.v4.runtime._ +import org.antlr.v4.runtime.atn.PredictionMode +import org.antlr.v4.runtime.misc.{Interval, ParseCancellationException} +import org.antlr.v4.runtime.tree.{ParseTree, TerminalNodeImpl} +import org.apache.spark.sql.AnalysisException +import org.apache.spark.sql.catalyst.{FunctionIdentifier, TableIdentifier} +import org.apache.spark.sql.catalyst.expressions.{Expression, Literal} +import org.apache.spark.sql.catalyst.parser.{ParseErrorListener, ParseException, ParserInterface} +import org.apache.spark.sql.catalyst.parser.ParserUtils._ +import org.apache.spark.sql.catalyst.parser.extensions.IcebergSqlExtensionsParser._ +import org.apache.spark.sql.catalyst.plans.logical.{Call, CallArgument, LogicalPlan} +import org.apache.spark.sql.catalyst.trees.Origin +import org.apache.spark.sql.types.{ByteType, DataType, DoubleType, FloatType, LongType, ShortType, StructType} +import scala.collection.JavaConverters._ + +class IcebergSparkSqlExtensionsParser(delegate: ParserInterface) extends ParserInterface { + + private val astBuilder = new IcebergSqlExtensionsAstBuilder() + + /** + * Parse a string to a DataType. + */ + override def parseDataType(sqlText: String): DataType = { + delegate.parseDataType(sqlText) + } + + /** + * Parse a string to a raw DataType without CHAR/VARCHAR replacement. + */ + override def parseRawDataType(sqlText: String): DataType = { + delegate.parseRawDataType(sqlText) + } + + /** + * Parse a string to an Expression. + */ + override def parseExpression(sqlText: String): Expression = { + delegate.parseExpression(sqlText) + } + + /** + * Parse a string to a TableIdentifier. + */ + override def parseTableIdentifier(sqlText: String): TableIdentifier = { + delegate.parseTableIdentifier(sqlText) + } + + /** + * Parse a string to a FunctionIdentifier. + */ + override def parseFunctionIdentifier(sqlText: String): FunctionIdentifier = { + delegate.parseFunctionIdentifier(sqlText) + } + + /** + * Parse a string to a multi-part identifier. + */ + override def parseMultipartIdentifier(sqlText: String): Seq[String] = { + delegate.parseMultipartIdentifier(sqlText) + } + + /** + * Creates StructType for a given SQL string, which is a comma separated list of field + * definitions which will preserve the correct Hive metadata. + */ + override def parseTableSchema(sqlText: String): StructType = { + delegate.parseTableSchema(sqlText) + } + + /** + * Parse a string to a LogicalPlan. + */ + override def parsePlan(sqlText: String): LogicalPlan = parse(sqlText) { parser => + astBuilder.visit(parser.singleStatement()) match { + case plan: LogicalPlan => plan + case _ => delegate.parsePlan(sqlText) + } + } + + protected def parse[T](command: String)(toResult: IcebergSqlExtensionsParser => T): T = { + val lexer = new IcebergSqlExtensionsLexer(new UpperCaseCharStream(CharStreams.fromString(command))) + lexer.removeErrorListeners() + lexer.addErrorListener(ParseErrorListener) Review comment: Good enough for me, I'll look into Lexer classes later but If we aren't changing what already is in Spark then it's fine ########## File path: .baseline/checkstyle/checkstyle.xml ########## @@ -250,7 +250,6 @@ <property name="tokens" value="BAND, BOR, BSR, BXOR, DIV, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR, LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR "/> </module> <module name="OuterTypeFilename"/> <!-- Java Style Guide: File name --> - <module name="OverloadMethodsDeclarationOrder"/> <!-- Java Style Guide: Overloads: never split --> Review comment: I never really understood this rule :/ ---------------------------------------------------------------- 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: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org For additional commands, e-mail: issues-h...@iceberg.apache.org