You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "allisonwang-db (via GitHub)" <gi...@apache.org> on 2024/12/10 05:50:30 UTC

[PR] [SPARK-48730][SQL] Implement CreateSQLFunctionCommand for SQL Scalar and Table Functions [spark]

allisonwang-db opened a new pull request, #49126:
URL: https://github.com/apache/spark/pull/49126

   <!--
   Thanks for sending a pull request!  Here are some tips for you:
     1. If this is your first time, please read our contributor guidelines: https://spark.apache.org/contributing.html
     2. Ensure you have added or run the appropriate tests for your PR: https://spark.apache.org/developer-tools.html
     3. If the PR is unfinished, add '[WIP]' in your PR title, e.g., '[WIP][SPARK-XXXX] Your PR title ...'.
     4. Be sure to keep the PR description updated to reflect all changes.
     5. Please write your PR title to summarize what this PR proposes.
     6. If possible, provide a concise example to reproduce the issue for a faster review.
     7. If you want to add a new configuration, please read the guideline first for naming configurations in
        'core/src/main/scala/org/apache/spark/internal/config/ConfigEntry.scala'.
     8. If you want to add or modify an error type or message, please read the guideline first in
        'common/utils/src/main/resources/error/README.md'.
   -->
   
   ### What changes were proposed in this pull request?
   <!--
   Please clarify what changes you are proposing. The purpose of this section is to outline the changes and how this PR fixes the issue. 
   If possible, please consider writing useful notes for better and faster reviews in your PR. See the examples below.
     1. If you refactor some codes with changing classes, showing the class hierarchy will help reviewers.
     2. If you fix some SQL features, you can provide some references of other DBMSes.
     3. If there is design documentation, please add the link.
     4. If there is a discussion in the mailing list, please add the link.
   -->
   This PR implements the `CreateSQLFunctionCommand` to support the creation of SQL scalar and table functions.
   
   Note that the logic for storing and resolving SQL UDFs will be implemented in subsequent PRs. And more SQL tests will be added once it can work E2E.
   
   ### Why are the changes needed?
   <!--
   Please clarify why the changes are needed. For instance,
     1. If you propose a new API, clarify the use case for a new API.
     2. If you fix a bug, you can clarify why it is a bug.
   -->
   To support SQL UDFs.
   
   ### Does this PR introduce _any_ user-facing change?
   <!--
   Note that it means *any* user-facing change including all aspects such as the documentation fix.
   If yes, please clarify the previous behavior and the change this PR proposes - provide the console output, description and/or an example to show the behavior difference if possible.
   If possible, please also clarify if this is a user-facing change compared to the released Spark versions or within the unreleased branches such as master.
   If no, write 'No'.
   -->
   Yes. After this PR, users can create persistent SQL UDFs.
   
   ### How was this patch tested?
   <!--
   If tests were added, say they were added here. Please make sure to add some test cases that check the changes thoroughly including negative and positive cases if possible.
   If it was tested in a way different from regular unit tests, please clarify how you tested step by step, ideally copy and paste-able, so that other reviewers can test and check, and descendants can verify in the future.
   If tests were not added, please describe why they were not added and/or why it was difficult to add.
   If benchmark tests were added, please run the benchmarks in GitHub Actions for the consistent environment, and the instructions could accord to: https://spark.apache.org/developer-tools.html#github-workflow-benchmarks.
   -->
   New UTs.
   
   ### Was this patch authored or co-authored using generative AI tooling?
   <!--
   If generative AI tooling has been used in the process of authoring this patch, please include the
   phrase: 'Generated-by: ' followed by the name of the tool and its version.
   If no, write 'No'.
   Please refer to the [ASF Generative Tooling Guidance](https://www.apache.org/legal/generative-tooling.html) for details.
   -->
   No


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-48730][SQL] Implement CreateSQLFunctionCommand for SQL Scalar and Table Functions [spark]

Posted by "allisonwang-db (via GitHub)" <gi...@apache.org>.
allisonwang-db commented on PR #49126:
URL: https://github.com/apache/spark/pull/49126#issuecomment-2574260661

   Thanks, merging to master


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-48730][SQL] Implement CreateSQLFunctionCommand for SQL Scalar and Table Functions [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #49126:
URL: https://github.com/apache/spark/pull/49126#discussion_r1890214852


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2Commands.scala:
##########
@@ -1066,6 +1066,26 @@ case class CreateFunction(
     copy(child = newChild)
 }
 
+/**
+ * The logical plan of the CREATE FUNCTION command for SQL Functions.
+ */
+case class CreateUserDefinedFunction(

Review Comment:
   shall we follow `UnsetNamespacePropertiesCommand`? i.e. extends `UnaryRunnableCommand` and implement `def run`, so that we only need one logical plan: the command itself.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-48730][SQL] Implement CreateSQLFunctionCommand for SQL Scalar and Table Functions [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #49126:
URL: https://github.com/apache/spark/pull/49126#discussion_r1900525249


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala:
##########
@@ -72,8 +85,312 @@ case class CreateSQLFunctionCommand(
       isTableFunc,
       Map.empty)
 
-    // TODO: Implement the rest of the method.
+    val newFunction = {
+      val (expression, query) = function.getExpressionAndQuery(parser, isTableFunc)
+      assert(query.nonEmpty || expression.nonEmpty)
+
+      // Check if the function can be replaced.
+      if (replace && catalog.functionExists(name)) {
+        checkFunctionSignatures(catalog, name)
+      }
+
+      // Build function input.
+      val inputPlan = if (inputParam.isDefined) {
+        val param = inputParam.get
+        checkParameterNotNull(param, inputParamText.get)
+        checkParameterNameDuplication(param, conf, name)
+        checkDefaultsTrailing(param, name)
+
+        // Qualify the input parameters with the function name so that attributes referencing
+        // the function input parameters can be resolved correctly.
+        val qualifier = Seq(name.funcName)
+        val input = param.map(p => Alias(
+          {
+            val defaultExpr = p.getDefault()
+            if (defaultExpr.isEmpty) {
+              Literal.create(null, p.dataType)
+            } else {
+              val defaultPlan = parseDefault(defaultExpr.get, parser)
+              if (SubqueryExpression.hasSubquery(defaultPlan)) {
+                throw new AnalysisException(
+                  errorClass = "USER_DEFINED_FUNCTIONS.NOT_A_VALID_DEFAULT_EXPRESSION",
+                  messageParameters =
+                    Map("functionName" -> name.funcName, "parameterName" -> p.name))
+              } else if (defaultPlan.containsPattern(UNRESOLVED_ATTRIBUTE)) {

Review Comment:
   We can improve it together with https://github.com/apache/spark/pull/49126/files#r1899305732



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-48730][SQL] Implement CreateSQLFunctionCommand for SQL Scalar and Table Functions [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #49126:
URL: https://github.com/apache/spark/pull/49126#discussion_r1890228720


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala:
##########
@@ -72,8 +85,312 @@ case class CreateSQLFunctionCommand(
       isTableFunc,
       Map.empty)
 
-    // TODO: Implement the rest of the method.
+    val newFunction = {
+      val (expression, query) = function.getExpressionAndQuery(parser, isTableFunc)
+      assert(query.nonEmpty || expression.nonEmpty)
+
+      // Check if the function can be replaced.
+      if (replace && catalog.functionExists(name)) {
+        checkFunctionSignatures(catalog, name)
+      }
+
+      // Build function input.
+      val inputPlan = if (inputParam.isDefined) {
+        val param = inputParam.get
+        checkParameterNotNull(param, inputParamText.get, function.language)
+        checkParameterNameDuplication(param, conf, name)
+        checkDefaultsTrailing(param, name)
+
+        // Qualify the input parameters with the function name so that attributes referencing
+        // the function input parameters can be resolved correctly.
+        val qualifier = Seq(name.funcName)
+        val input = param.map(p => Alias(
+          {
+            val defaultExpr = p.getDefault()
+            if (defaultExpr.isEmpty) {
+              Literal.create(null, p.dataType)
+            } else {
+              val defaultPlan = parseDefault(defaultExpr.get, parser)
+              if (SubqueryExpression.hasSubquery(defaultPlan)) {
+                throw new AnalysisException(
+                  errorClass = "USER_DEFINED_FUNCTIONS.NOT_A_VALID_DEFAULT_EXPRESSION",
+                  messageParameters =
+                    Map("functionName" -> name.funcName, "parameterName" -> p.name))
+              } else if (defaultPlan.containsPattern(UNRESOLVED_ATTRIBUTE)) {
+                defaultPlan.collect {
+                  case a: UnresolvedAttribute =>
+                    throw QueryCompilationErrors.unresolvedAttributeError(
+                      "UNRESOLVED_COLUMN", a.sql, Seq.empty, a.origin)
+                }
+              }
+              Cast(defaultPlan, p.dataType)
+            }
+          }, p.name)(qualifier = qualifier))
+        Project(input, OneRowRelation())
+      } else {
+        OneRowRelation()
+      }
+
+      // Build the function body and check if the function body can be analyzed successfully.
+      val (unresolvedPlan, analyzedPlan, inferredReturnType) = if (!isTableFunc) {
+        // Build SQL scalar function plan.
+        val outputExpr = if (query.isDefined) ScalarSubquery(query.get) else expression.get
+        val plan: LogicalPlan = returnType.map { t =>
+          val retType: DataType = t match {
+            case Left(t) => t
+            case _ => throw SparkException.internalError(
+              "Unexpected return type for a scalar SQL UDF.")
+          }
+          val outputCast = Seq(Alias(Cast(outputExpr, retType), name.funcName)())
+          Project(outputCast, inputPlan)
+        }.getOrElse {
+          // If no explicit RETURNS clause is present, infer the result type from the function body.
+          val outputAlias = Seq(Alias(outputExpr, name.funcName)())
+          Project(outputAlias, inputPlan)
+        }
+
+        // Check the function body can be analyzed correctly.
+        val analyzed = analyzer.execute(plan)
+        val (resolved, resolvedReturnType) = analyzed match {
+          case p @ Project(expr :: Nil, _) if expr.resolved =>
+            (p, Left(expr.dataType))
+          case other =>
+            (other, function.returnType)
+        }
+
+        // Check if the SQL function body contains aggregate/window functions.
+        // This check needs to be performed before checkAnalysis to provide better error messages.
+        checkAggOrWindowOrGeneratorExpr(resolved)
+
+        // Check if the SQL function body can be analyzed.
+        checkFunctionBodyAnalysis(analyzer, function, resolved)
+
+        (plan, resolved, resolvedReturnType)
+      } else {
+        // Build SQL table function plan.
+        if (query.isEmpty) {
+          throw UserDefinedFunctionErrors.bodyIsNotAQueryForSqlTableUdf(name.funcName)
+        }
+
+        // Construct a lateral join to analyze the function body.
+        val plan = LateralJoin(inputPlan, LateralSubquery(query.get), Inner, None)
+        val analyzed = analyzer.execute(plan)
+        val newPlan = analyzed match {
+          case Project(_, j: LateralJoin) => j
+          case j: LateralJoin => j
+          case _ => throw SparkException.internalError("Unexpected plan returned when " +
+            s"creating a SQL TVF: ${analyzed.getClass.getSimpleName}.")
+        }
+        val maybeResolved = newPlan.asInstanceOf[LateralJoin].right.plan
+
+        // Check if the function body can be analyzed.
+        checkFunctionBodyAnalysis(analyzer, function, maybeResolved)
+
+        // Get the function's return schema.
+        val returnParam: StructType = returnType.map {
+          case Right(t) => t
+          case Left(_) => throw SparkException.internalError(
+            "Unexpected return schema for a SQL table function.")
+        }.getOrElse {
+          // If no explicit RETURNS clause is present, infer the result type from the function body.
+          // To detect this, we search for instances of the UnresolvedAlias expression. Examples:
+          // CREATE TABLE t USING PARQUET AS VALUES (0, 1), (1, 2) AS tab(c1, c2);
+          // SELECT c1 FROM t           -->  UnresolvedAttribute: 'c1
+          // SELECT c1 + 1 FROM t       -->  UnresolvedAlias: unresolvedalias(('c1 + 1), None)
+          // SELECT c1 + 1 AS a FROM t  -->  Alias: ('c1 + 1) AS a#2
+          query.get match {
+            case Project(projectList, _) if projectList.exists(_.isInstanceOf[UnresolvedAlias]) =>
+              throw UserDefinedFunctionErrors.missingColumnNamesForSqlTableUdf(name.funcName)
+            case _ =>
+              StructType(analyzed.asInstanceOf[LateralJoin].right.plan.output.map { col =>
+                StructField(col.name, col.dataType)
+              })
+          }
+        }
+
+        // Check the return columns cannot have NOT NULL specified.
+        checkParameterNotNull(returnParam, returnTypeText, function.language)
+
+        // Check duplicated return column names.
+        checkReturnsColumnDuplication(returnParam, conf, name)
+
+        // Check if the actual output size equals to the number of return parameters.
+        val outputSize = maybeResolved.output.size
+        if (outputSize != returnParam.size) {
+          throw new AnalysisException(
+            errorClass = "USER_DEFINED_FUNCTIONS.RETURN_COLUMN_COUNT_MISMATCH",
+            messageParameters = Map(
+              "outputSize" -> s"$outputSize",
+              "returnParamSize" -> s"${returnParam.size}",
+              "name" -> s"$name"
+            )
+          )
+        }
+
+        (plan, analyzed, Right(returnParam))
+      }
+
+      // A permanent function is not allowed to reference temporary objects.
+      // This should be called after `qe.assertAnalyzed()` (i.e., `plan` can be resolved)
+      verifyTemporaryObjectsNotExists(catalog, isTemp, name, unresolvedPlan, analyzedPlan)
+
+      // Generate function properties.
+      val properties = generateFunctionProperties(sparkSession, unresolvedPlan, analyzedPlan)
+
+      // Derive determinism of the SQL function.
+      val deterministic = analyzedPlan.deterministic
+
+      function.copy(
+        // Assign the return type, inferring from the function body if needed.
+        returnType = inferredReturnType,
+        deterministic = Some(function.deterministic.getOrElse(deterministic)),
+        properties = properties
+      )
+    }
+
+    // TODO: create/register sql functions in catalog
 
     Seq.empty
   }
+
+  /**
+   * Check if the function body can be analyzed.
+   */
+  private def checkFunctionBodyAnalysis(
+      analyzer: Analyzer,
+      function: SQLFunction,
+      body: LogicalPlan): Unit = {
+    analyzer.checkAnalysis(SQLFunctionNode(function, body))

Review Comment:
   Does it work if we just use a `Project` here to combine the `body` and `function` into a logical plan?



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-48730][SQL] Implement CreateSQLFunctionCommand for SQL Scalar and Table Functions [spark]

Posted by "allisonwang-db (via GitHub)" <gi...@apache.org>.
allisonwang-db commented on PR #49126:
URL: https://github.com/apache/spark/pull/49126#issuecomment-2538704743

   cc @cloud-fan 


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-48730][SQL] Implement CreateSQLFunctionCommand for SQL Scalar and Table Functions [spark]

Posted by "allisonwang-db (via GitHub)" <gi...@apache.org>.
allisonwang-db commented on code in PR #49126:
URL: https://github.com/apache/spark/pull/49126#discussion_r1903203274


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala:
##########
@@ -72,8 +85,312 @@ case class CreateSQLFunctionCommand(
       isTableFunc,
       Map.empty)
 
-    // TODO: Implement the rest of the method.
+    val newFunction = {
+      val (expression, query) = function.getExpressionAndQuery(parser, isTableFunc)
+      assert(query.nonEmpty || expression.nonEmpty)
+
+      // Check if the function can be replaced.
+      if (replace && catalog.functionExists(name)) {
+        checkFunctionSignatures(catalog, name)
+      }
+
+      // Build function input.
+      val inputPlan = if (inputParam.isDefined) {
+        val param = inputParam.get
+        checkParameterNotNull(param, inputParamText.get)
+        checkParameterNameDuplication(param, conf, name)
+        checkDefaultsTrailing(param, name)
+
+        // Qualify the input parameters with the function name so that attributes referencing
+        // the function input parameters can be resolved correctly.
+        val qualifier = Seq(name.funcName)
+        val input = param.map(p => Alias(
+          {
+            val defaultExpr = p.getDefault()
+            if (defaultExpr.isEmpty) {
+              Literal.create(null, p.dataType)
+            } else {
+              val defaultPlan = parseDefault(defaultExpr.get, parser)
+              if (SubqueryExpression.hasSubquery(defaultPlan)) {
+                throw new AnalysisException(
+                  errorClass = "USER_DEFINED_FUNCTIONS.NOT_A_VALID_DEFAULT_EXPRESSION",
+                  messageParameters =
+                    Map("functionName" -> name.funcName, "parameterName" -> p.name))
+              } else if (defaultPlan.containsPattern(UNRESOLVED_ATTRIBUTE)) {

Review Comment:
   Sounds good. Added a comment here.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-48730][SQL] Implement CreateSQLFunctionCommand for SQL Scalar and Table Functions [spark]

Posted by "allisonwang-db (via GitHub)" <gi...@apache.org>.
allisonwang-db commented on code in PR #49126:
URL: https://github.com/apache/spark/pull/49126#discussion_r1899307458


##########
sql/core/src/main/scala/org/apache/spark/sql/catalyst/catalog/SQLFunction.scala:
##########
@@ -56,10 +63,48 @@ case class SQLFunction(
   assert((isTableFunc && returnType.isRight) || (!isTableFunc && returnType.isLeft))
 
   override val language: RoutineLanguage = LanguageSQL
+
+  /**
+   * Optionally get the function body as an expression or query using the given parser.
+   */
+  def getExpressionAndQuery(
+      parser: ParserInterface,
+      isTableFunc: Boolean): (Option[Expression], Option[LogicalPlan]) = {

Review Comment:
   Either approach works since this is only used in one place. I prefer the current way since it's simpler and more readable :) 



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2Commands.scala:
##########
@@ -1066,6 +1066,26 @@ case class CreateFunction(
     copy(child = newChild)
 }
 
+/**
+ * The logical plan of the CREATE FUNCTION command for SQL Functions.
+ */
+case class CreateUserDefinedFunction(

Review Comment:
   This is a good suggestion. I've created a follow up ticket here: [SPARK-50698](https://issues.apache.org/jira/browse/SPARK-50698)



##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -5592,6 +5610,54 @@
     ],
     "sqlState" : "42K0E"
   },
+  "USER_DEFINED_FUNCTIONS" : {
+    "message" : [
+      "User defined function is invalid:"
+    ],
+    "subClass" : {
+      "CANNOT_CONTAIN_COMPLEX_FUNCTIONS" : {
+        "message" : [
+          "SQL scalar function cannot contain aggregate/window/generate functions: <queryText>"
+        ]
+      },
+      "CANNOT_REPLACE_NON_SQL_UDF_WITH_SQL_UDF" : {
+        "message" : [
+          "Cannot replace the non-SQL function <name> with a SQL function."
+        ]
+      },
+      "NOT_A_VALID_DEFAULT_EXPRESSION" : {
+        "message" : [
+          "The DEFAULT expression of `<functionName>`.`<parameterName>` is not supported because it contains a subquery."
+        ]
+      },
+      "NOT_A_VALID_DEFAULT_PARAMETER_POSITION" : {
+        "message" : [
+          "In routine `<functionName>` parameter `<parameterName>` with DEFAULT must not be followed by parameter `<nextParameterName>` without DEFAULT."
+        ]
+      },
+      "NOT_NULL_ON_FUNCTION_PARAMETERS" : {
+        "message" : [
+          "Cannot specify NOT NULL on <languageName> function parameters: <input>"

Review Comment:
   Good point. This should hold regardless of the function language.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala:
##########
@@ -72,8 +85,312 @@ case class CreateSQLFunctionCommand(
       isTableFunc,
       Map.empty)
 
-    // TODO: Implement the rest of the method.
+    val newFunction = {
+      val (expression, query) = function.getExpressionAndQuery(parser, isTableFunc)
+      assert(query.nonEmpty || expression.nonEmpty)
+
+      // Check if the function can be replaced.
+      if (replace && catalog.functionExists(name)) {
+        checkFunctionSignatures(catalog, name)
+      }
+
+      // Build function input.
+      val inputPlan = if (inputParam.isDefined) {
+        val param = inputParam.get
+        checkParameterNotNull(param, inputParamText.get, function.language)
+        checkParameterNameDuplication(param, conf, name)
+        checkDefaultsTrailing(param, name)
+
+        // Qualify the input parameters with the function name so that attributes referencing
+        // the function input parameters can be resolved correctly.
+        val qualifier = Seq(name.funcName)
+        val input = param.map(p => Alias(
+          {
+            val defaultExpr = p.getDefault()
+            if (defaultExpr.isEmpty) {
+              Literal.create(null, p.dataType)
+            } else {
+              val defaultPlan = parseDefault(defaultExpr.get, parser)
+              if (SubqueryExpression.hasSubquery(defaultPlan)) {
+                throw new AnalysisException(
+                  errorClass = "USER_DEFINED_FUNCTIONS.NOT_A_VALID_DEFAULT_EXPRESSION",
+                  messageParameters =
+                    Map("functionName" -> name.funcName, "parameterName" -> p.name))
+              } else if (defaultPlan.containsPattern(UNRESOLVED_ATTRIBUTE)) {
+                defaultPlan.collect {
+                  case a: UnresolvedAttribute =>
+                    throw QueryCompilationErrors.unresolvedAttributeError(
+                      "UNRESOLVED_COLUMN", a.sql, Seq.empty, a.origin)
+                }
+              }
+              Cast(defaultPlan, p.dataType)
+            }
+          }, p.name)(qualifier = qualifier))
+        Project(input, OneRowRelation())
+      } else {
+        OneRowRelation()
+      }
+
+      // Build the function body and check if the function body can be analyzed successfully.
+      val (unresolvedPlan, analyzedPlan, inferredReturnType) = if (!isTableFunc) {
+        // Build SQL scalar function plan.
+        val outputExpr = if (query.isDefined) ScalarSubquery(query.get) else expression.get
+        val plan: LogicalPlan = returnType.map { t =>
+          val retType: DataType = t match {
+            case Left(t) => t
+            case _ => throw SparkException.internalError(
+              "Unexpected return type for a scalar SQL UDF.")
+          }
+          val outputCast = Seq(Alias(Cast(outputExpr, retType), name.funcName)())
+          Project(outputCast, inputPlan)
+        }.getOrElse {
+          // If no explicit RETURNS clause is present, infer the result type from the function body.
+          val outputAlias = Seq(Alias(outputExpr, name.funcName)())
+          Project(outputAlias, inputPlan)
+        }
+
+        // Check the function body can be analyzed correctly.
+        val analyzed = analyzer.execute(plan)
+        val (resolved, resolvedReturnType) = analyzed match {
+          case p @ Project(expr :: Nil, _) if expr.resolved =>
+            (p, Left(expr.dataType))
+          case other =>
+            (other, function.returnType)
+        }
+
+        // Check if the SQL function body contains aggregate/window functions.
+        // This check needs to be performed before checkAnalysis to provide better error messages.
+        checkAggOrWindowOrGeneratorExpr(resolved)
+
+        // Check if the SQL function body can be analyzed.
+        checkFunctionBodyAnalysis(analyzer, function, resolved)
+
+        (plan, resolved, resolvedReturnType)
+      } else {
+        // Build SQL table function plan.
+        if (query.isEmpty) {
+          throw UserDefinedFunctionErrors.bodyIsNotAQueryForSqlTableUdf(name.funcName)
+        }
+
+        // Construct a lateral join to analyze the function body.
+        val plan = LateralJoin(inputPlan, LateralSubquery(query.get), Inner, None)
+        val analyzed = analyzer.execute(plan)
+        val newPlan = analyzed match {
+          case Project(_, j: LateralJoin) => j
+          case j: LateralJoin => j
+          case _ => throw SparkException.internalError("Unexpected plan returned when " +
+            s"creating a SQL TVF: ${analyzed.getClass.getSimpleName}.")
+        }
+        val maybeResolved = newPlan.asInstanceOf[LateralJoin].right.plan
+
+        // Check if the function body can be analyzed.
+        checkFunctionBodyAnalysis(analyzer, function, maybeResolved)
+
+        // Get the function's return schema.
+        val returnParam: StructType = returnType.map {
+          case Right(t) => t
+          case Left(_) => throw SparkException.internalError(
+            "Unexpected return schema for a SQL table function.")
+        }.getOrElse {
+          // If no explicit RETURNS clause is present, infer the result type from the function body.
+          // To detect this, we search for instances of the UnresolvedAlias expression. Examples:
+          // CREATE TABLE t USING PARQUET AS VALUES (0, 1), (1, 2) AS tab(c1, c2);
+          // SELECT c1 FROM t           -->  UnresolvedAttribute: 'c1
+          // SELECT c1 + 1 FROM t       -->  UnresolvedAlias: unresolvedalias(('c1 + 1), None)
+          // SELECT c1 + 1 AS a FROM t  -->  Alias: ('c1 + 1) AS a#2
+          query.get match {
+            case Project(projectList, _) if projectList.exists(_.isInstanceOf[UnresolvedAlias]) =>
+              throw UserDefinedFunctionErrors.missingColumnNamesForSqlTableUdf(name.funcName)
+            case _ =>
+              StructType(analyzed.asInstanceOf[LateralJoin].right.plan.output.map { col =>
+                StructField(col.name, col.dataType)
+              })
+          }
+        }
+
+        // Check the return columns cannot have NOT NULL specified.
+        checkParameterNotNull(returnParam, returnTypeText, function.language)
+
+        // Check duplicated return column names.
+        checkReturnsColumnDuplication(returnParam, conf, name)
+
+        // Check if the actual output size equals to the number of return parameters.
+        val outputSize = maybeResolved.output.size
+        if (outputSize != returnParam.size) {
+          throw new AnalysisException(
+            errorClass = "USER_DEFINED_FUNCTIONS.RETURN_COLUMN_COUNT_MISMATCH",
+            messageParameters = Map(
+              "outputSize" -> s"$outputSize",
+              "returnParamSize" -> s"${returnParam.size}",
+              "name" -> s"$name"
+            )
+          )
+        }
+
+        (plan, analyzed, Right(returnParam))
+      }
+
+      // A permanent function is not allowed to reference temporary objects.
+      // This should be called after `qe.assertAnalyzed()` (i.e., `plan` can be resolved)
+      verifyTemporaryObjectsNotExists(catalog, isTemp, name, unresolvedPlan, analyzedPlan)
+
+      // Generate function properties.
+      val properties = generateFunctionProperties(sparkSession, unresolvedPlan, analyzedPlan)
+
+      // Derive determinism of the SQL function.
+      val deterministic = analyzedPlan.deterministic
+
+      function.copy(
+        // Assign the return type, inferring from the function body if needed.
+        returnType = inferredReturnType,
+        deterministic = Some(function.deterministic.getOrElse(deterministic)),
+        properties = properties
+      )
+    }
+
+    // TODO: create/register sql functions in catalog
 
     Seq.empty
   }
+
+  /**
+   * Check if the function body can be analyzed.
+   */
+  private def checkFunctionBodyAnalysis(
+      analyzer: Analyzer,
+      function: SQLFunction,
+      body: LogicalPlan): Unit = {
+    analyzer.checkAnalysis(SQLFunctionNode(function, body))

Review Comment:
   Do you mean an empty project list with the plan node as the child? I think we might be able to simply check the function body using: `analyzer.checkAnalysis(body)`. I am wrapping this function body in a SQLFunctionNode in case we want to check additional things later.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-48730][SQL] Implement CreateSQLFunctionCommand for SQL Scalar and Table Functions [spark]

Posted by "allisonwang-db (via GitHub)" <gi...@apache.org>.
allisonwang-db commented on code in PR #49126:
URL: https://github.com/apache/spark/pull/49126#discussion_r1903204479


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala:
##########
@@ -72,8 +85,312 @@ case class CreateSQLFunctionCommand(
       isTableFunc,
       Map.empty)
 
-    // TODO: Implement the rest of the method.
+    val newFunction = {
+      val (expression, query) = function.getExpressionAndQuery(parser, isTableFunc)
+      assert(query.nonEmpty || expression.nonEmpty)
+
+      // Check if the function can be replaced.
+      if (replace && catalog.functionExists(name)) {
+        checkFunctionSignatures(catalog, name)
+      }
+
+      // Build function input.
+      val inputPlan = if (inputParam.isDefined) {
+        val param = inputParam.get
+        checkParameterNotNull(param, inputParamText.get)
+        checkParameterNameDuplication(param, conf, name)
+        checkDefaultsTrailing(param, name)
+
+        // Qualify the input parameters with the function name so that attributes referencing
+        // the function input parameters can be resolved correctly.
+        val qualifier = Seq(name.funcName)
+        val input = param.map(p => Alias(
+          {
+            val defaultExpr = p.getDefault()
+            if (defaultExpr.isEmpty) {
+              Literal.create(null, p.dataType)
+            } else {
+              val defaultPlan = parseDefault(defaultExpr.get, parser)
+              if (SubqueryExpression.hasSubquery(defaultPlan)) {
+                throw new AnalysisException(
+                  errorClass = "USER_DEFINED_FUNCTIONS.NOT_A_VALID_DEFAULT_EXPRESSION",
+                  messageParameters =
+                    Map("functionName" -> name.funcName, "parameterName" -> p.name))
+              } else if (defaultPlan.containsPattern(UNRESOLVED_ATTRIBUTE)) {
+                defaultPlan.collect {
+                  case a: UnresolvedAttribute =>
+                    throw QueryCompilationErrors.unresolvedAttributeError(
+                      "UNRESOLVED_COLUMN", a.sql, Seq.empty, a.origin)
+                }
+              }
+              Cast(defaultPlan, p.dataType)
+            }
+          }, p.name)(qualifier = qualifier))
+        Project(input, OneRowRelation())
+      } else {
+        OneRowRelation()
+      }
+
+      // Build the function body and check if the function body can be analyzed successfully.
+      val (unresolvedPlan, analyzedPlan, inferredReturnType) = if (!isTableFunc) {
+        // Build SQL scalar function plan.
+        val outputExpr = if (query.isDefined) ScalarSubquery(query.get) else expression.get
+        val plan: LogicalPlan = returnType.map { t =>
+          val retType: DataType = t match {
+            case Left(t) => t
+            case _ => throw SparkException.internalError(
+              "Unexpected return type for a scalar SQL UDF.")
+          }
+          val outputCast = Seq(Alias(Cast(outputExpr, retType), name.funcName)())
+          Project(outputCast, inputPlan)
+        }.getOrElse {
+          // If no explicit RETURNS clause is present, infer the result type from the function body.
+          val outputAlias = Seq(Alias(outputExpr, name.funcName)())
+          Project(outputAlias, inputPlan)
+        }
+
+        // Check the function body can be analyzed correctly.
+        val analyzed = analyzer.execute(plan)
+        val (resolved, resolvedReturnType) = analyzed match {
+          case p @ Project(expr :: Nil, _) if expr.resolved =>
+            (p, Left(expr.dataType))
+          case other =>
+            (other, function.returnType)
+        }
+
+        // Check if the SQL function body contains aggregate/window functions.
+        // This check needs to be performed before checkAnalysis to provide better error messages.
+        checkAggOrWindowOrGeneratorExpr(resolved)
+
+        // Check if the SQL function body can be analyzed.
+        checkFunctionBodyAnalysis(analyzer, function, resolved)
+
+        (plan, resolved, resolvedReturnType)
+      } else {
+        // Build SQL table function plan.
+        if (query.isEmpty) {
+          throw UserDefinedFunctionErrors.bodyIsNotAQueryForSqlTableUdf(name.funcName)
+        }
+
+        // Construct a lateral join to analyze the function body.
+        val plan = LateralJoin(inputPlan, LateralSubquery(query.get), Inner, None)
+        val analyzed = analyzer.execute(plan)
+        val newPlan = analyzed match {
+          case Project(_, j: LateralJoin) => j
+          case j: LateralJoin => j
+          case _ => throw SparkException.internalError("Unexpected plan returned when " +
+            s"creating a SQL TVF: ${analyzed.getClass.getSimpleName}.")
+        }
+        val maybeResolved = newPlan.asInstanceOf[LateralJoin].right.plan
+
+        // Check if the function body can be analyzed.
+        checkFunctionBodyAnalysis(analyzer, function, maybeResolved)
+
+        // Get the function's return schema.
+        val returnParam: StructType = returnType.map {
+          case Right(t) => t
+          case Left(_) => throw SparkException.internalError(
+            "Unexpected return schema for a SQL table function.")
+        }.getOrElse {
+          // If no explicit RETURNS clause is present, infer the result type from the function body.
+          // To detect this, we search for instances of the UnresolvedAlias expression. Examples:
+          // CREATE TABLE t USING PARQUET AS VALUES (0, 1), (1, 2) AS tab(c1, c2);
+          // SELECT c1 FROM t           -->  UnresolvedAttribute: 'c1
+          // SELECT c1 + 1 FROM t       -->  UnresolvedAlias: unresolvedalias(('c1 + 1), None)
+          // SELECT c1 + 1 AS a FROM t  -->  Alias: ('c1 + 1) AS a#2

Review Comment:
   Yea this is to support an optional return type for SQL functions. We don't require users to specify this alias unless the return type is missing (inferred from the function body).



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-48730][SQL] Implement CreateSQLFunctionCommand for SQL Scalar and Table Functions [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #49126:
URL: https://github.com/apache/spark/pull/49126#discussion_r1900523254


##########
sql/core/src/main/scala/org/apache/spark/sql/catalyst/catalog/SQLFunction.scala:
##########
@@ -92,4 +137,42 @@ object SQLFunction {
       }
     }
   }
+
+  def isSQLFunction(className: String): Boolean = className == SQL_FUNCTION_PREFIX
+
+  /**
+   * Convert the current catalog and namespace to properties.
+   */
+  def catalogAndNamespaceToProps(
+      currentCatalog: String,
+      currentNamespace: Seq[String]): Map[String, String] = {
+    val props = new mutable.HashMap[String, String]
+    val parts = currentCatalog +: currentNamespace
+    if (parts.nonEmpty) {
+      props.put(FUNCTION_CATALOG_AND_NAMESPACE, parts.length.toString)
+      parts.zipWithIndex.foreach { case (name, index) =>
+        props.put(s"$FUNCTION_CATALOG_AND_NAMESPACE_PART_PREFIX$index", name)
+      }
+    }
+    props.toMap
+  }
+
+  /**
+   * Convert the temporary object names to properties.
+   */
+  def referredTempNamesToProps(
+    viewNames: Seq[Seq[String]], functionsNames: Seq[String],
+    variableNames: Seq[Seq[String]]): Map[String, String] = {

Review Comment:
   ```suggestion
     def referredTempNamesToProps(
         viewNames: Seq[Seq[String]],
         functionsNames: Seq[String],
         variableNames: Seq[Seq[String]]): Map[String, String] = {
   ```



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-48730][SQL] Implement CreateSQLFunctionCommand for SQL Scalar and Table Functions [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #49126:
URL: https://github.com/apache/spark/pull/49126#discussion_r1900521793


##########
sql/api/src/main/scala/org/apache/spark/sql/types/StructField.scala:
##########
@@ -147,6 +147,17 @@ case class StructField(
     if (metadata.contains("comment")) Option(metadata.getString("comment")) else None
   }
 
+  /**
+   * Return the default value of this StructField.

Review Comment:
   we should add more comments here, to highlight the difference between this and the current/existing default values.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-48730][SQL] Implement CreateSQLFunctionCommand for SQL Scalar and Table Functions [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #49126:
URL: https://github.com/apache/spark/pull/49126#discussion_r1890216377


##########
sql/core/src/main/scala/org/apache/spark/sql/catalyst/catalog/SQLFunction.scala:
##########
@@ -56,10 +63,48 @@ case class SQLFunction(
   assert((isTableFunc && returnType.isRight) || (!isTableFunc && returnType.isLeft))
 
   override val language: RoutineLanguage = LanguageSQL
+
+  /**
+   * Optionally get the function body as an expression or query using the given parser.
+   */
+  def getExpressionAndQuery(
+      parser: ParserInterface,
+      isTableFunc: Boolean): (Option[Expression], Option[LogicalPlan]) = {

Review Comment:
   should it return `Either[Expression, LogicalPlan]`?



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-48730][SQL] Implement CreateSQLFunctionCommand for SQL Scalar and Table Functions [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #49126:
URL: https://github.com/apache/spark/pull/49126#discussion_r1900531045


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala:
##########
@@ -72,8 +85,312 @@ case class CreateSQLFunctionCommand(
       isTableFunc,
       Map.empty)
 
-    // TODO: Implement the rest of the method.
+    val newFunction = {
+      val (expression, query) = function.getExpressionAndQuery(parser, isTableFunc)
+      assert(query.nonEmpty || expression.nonEmpty)
+
+      // Check if the function can be replaced.
+      if (replace && catalog.functionExists(name)) {
+        checkFunctionSignatures(catalog, name)
+      }
+
+      // Build function input.
+      val inputPlan = if (inputParam.isDefined) {
+        val param = inputParam.get
+        checkParameterNotNull(param, inputParamText.get)
+        checkParameterNameDuplication(param, conf, name)
+        checkDefaultsTrailing(param, name)
+
+        // Qualify the input parameters with the function name so that attributes referencing
+        // the function input parameters can be resolved correctly.
+        val qualifier = Seq(name.funcName)
+        val input = param.map(p => Alias(
+          {
+            val defaultExpr = p.getDefault()
+            if (defaultExpr.isEmpty) {
+              Literal.create(null, p.dataType)
+            } else {
+              val defaultPlan = parseDefault(defaultExpr.get, parser)
+              if (SubqueryExpression.hasSubquery(defaultPlan)) {
+                throw new AnalysisException(
+                  errorClass = "USER_DEFINED_FUNCTIONS.NOT_A_VALID_DEFAULT_EXPRESSION",
+                  messageParameters =
+                    Map("functionName" -> name.funcName, "parameterName" -> p.name))
+              } else if (defaultPlan.containsPattern(UNRESOLVED_ATTRIBUTE)) {
+                defaultPlan.collect {
+                  case a: UnresolvedAttribute =>
+                    throw QueryCompilationErrors.unresolvedAttributeError(
+                      "UNRESOLVED_COLUMN", a.sql, Seq.empty, a.origin)
+                }
+              }
+              Cast(defaultPlan, p.dataType)
+            }
+          }, p.name)(qualifier = qualifier))
+        Project(input, OneRowRelation())
+      } else {
+        OneRowRelation()
+      }
+
+      // Build the function body and check if the function body can be analyzed successfully.
+      val (unresolvedPlan, analyzedPlan, inferredReturnType) = if (!isTableFunc) {
+        // Build SQL scalar function plan.
+        val outputExpr = if (query.isDefined) ScalarSubquery(query.get) else expression.get
+        val plan: LogicalPlan = returnType.map { t =>
+          val retType: DataType = t match {
+            case Left(t) => t
+            case _ => throw SparkException.internalError(
+              "Unexpected return type for a scalar SQL UDF.")
+          }
+          val outputCast = Seq(Alias(Cast(outputExpr, retType), name.funcName)())
+          Project(outputCast, inputPlan)
+        }.getOrElse {
+          // If no explicit RETURNS clause is present, infer the result type from the function body.
+          val outputAlias = Seq(Alias(outputExpr, name.funcName)())
+          Project(outputAlias, inputPlan)
+        }
+
+        // Check the function body can be analyzed correctly.
+        val analyzed = analyzer.execute(plan)
+        val (resolved, resolvedReturnType) = analyzed match {
+          case p @ Project(expr :: Nil, _) if expr.resolved =>
+            (p, Left(expr.dataType))
+          case other =>
+            (other, function.returnType)
+        }
+
+        // Check if the SQL function body contains aggregate/window functions.
+        // This check needs to be performed before checkAnalysis to provide better error messages.
+        checkAggOrWindowOrGeneratorExpr(resolved)
+
+        // Check if the SQL function body can be analyzed.
+        checkFunctionBodyAnalysis(analyzer, function, resolved)
+
+        (plan, resolved, resolvedReturnType)
+      } else {
+        // Build SQL table function plan.
+        if (query.isEmpty) {
+          throw UserDefinedFunctionErrors.bodyIsNotAQueryForSqlTableUdf(name.funcName)
+        }
+
+        // Construct a lateral join to analyze the function body.
+        val plan = LateralJoin(inputPlan, LateralSubquery(query.get), Inner, None)
+        val analyzed = analyzer.execute(plan)
+        val newPlan = analyzed match {
+          case Project(_, j: LateralJoin) => j
+          case j: LateralJoin => j
+          case _ => throw SparkException.internalError("Unexpected plan returned when " +
+            s"creating a SQL TVF: ${analyzed.getClass.getSimpleName}.")
+        }
+        val maybeResolved = newPlan.asInstanceOf[LateralJoin].right.plan
+
+        // Check if the function body can be analyzed.
+        checkFunctionBodyAnalysis(analyzer, function, maybeResolved)
+
+        // Get the function's return schema.
+        val returnParam: StructType = returnType.map {
+          case Right(t) => t
+          case Left(_) => throw SparkException.internalError(
+            "Unexpected return schema for a SQL table function.")
+        }.getOrElse {
+          // If no explicit RETURNS clause is present, infer the result type from the function body.
+          // To detect this, we search for instances of the UnresolvedAlias expression. Examples:
+          // CREATE TABLE t USING PARQUET AS VALUES (0, 1), (1, 2) AS tab(c1, c2);
+          // SELECT c1 FROM t           -->  UnresolvedAttribute: 'c1
+          // SELECT c1 + 1 FROM t       -->  UnresolvedAlias: unresolvedalias(('c1 + 1), None)
+          // SELECT c1 + 1 AS a FROM t  -->  Alias: ('c1 + 1) AS a#2

Review Comment:
   This reminds me how we require the view query column names to be aliased, which is done with the resolved plan with `ViewHelper.verifyAutoGeneratedAliasesNotExists`



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-48730][SQL] Implement CreateSQLFunctionCommand for SQL Scalar and Table Functions [spark]

Posted by "allisonwang-db (via GitHub)" <gi...@apache.org>.
allisonwang-db closed pull request #49126: [SPARK-48730][SQL] Implement CreateSQLFunctionCommand for SQL Scalar and Table Functions
URL: https://github.com/apache/spark/pull/49126


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-48730][SQL] Implement CreateSQLFunctionCommand for SQL Scalar and Table Functions [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #49126:
URL: https://github.com/apache/spark/pull/49126#discussion_r1890204739


##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -5592,6 +5610,54 @@
     ],
     "sqlState" : "42K0E"
   },
+  "USER_DEFINED_FUNCTIONS" : {
+    "message" : [
+      "User defined function is invalid:"
+    ],
+    "subClass" : {
+      "CANNOT_CONTAIN_COMPLEX_FUNCTIONS" : {
+        "message" : [
+          "SQL scalar function cannot contain aggregate/window/generate functions: <queryText>"
+        ]
+      },
+      "CANNOT_REPLACE_NON_SQL_UDF_WITH_SQL_UDF" : {
+        "message" : [
+          "Cannot replace the non-SQL function <name> with a SQL function."
+        ]
+      },
+      "NOT_A_VALID_DEFAULT_EXPRESSION" : {
+        "message" : [
+          "The DEFAULT expression of `<functionName>`.`<parameterName>` is not supported because it contains a subquery."
+        ]
+      },
+      "NOT_A_VALID_DEFAULT_PARAMETER_POSITION" : {
+        "message" : [
+          "In routine `<functionName>` parameter `<parameterName>` with DEFAULT must not be followed by parameter `<nextParameterName>` without DEFAULT."
+        ]
+      },
+      "NOT_NULL_ON_FUNCTION_PARAMETERS" : {
+        "message" : [
+          "Cannot specify NOT NULL on <languageName> function parameters: <input>"

Review Comment:
   do we really need to call out the language name when reporting error for the function parameters?



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-48730][SQL] Implement CreateSQLFunctionCommand for SQL Scalar and Table Functions [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on PR #49126:
URL: https://github.com/apache/spark/pull/49126#issuecomment-2572568719

   @allisonwang-db can you run `./build/mvn scalafmt:format -Dscalafmt.skip=false -Dscalafmt.validateOnly=false -Dscalafmt.changedOnly=false -pl sql/api -pl sql/connect/common -pl sql/connect/server -pl connector/connect/client/jvm`? Seems the format check failed


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-48730][SQL] Implement CreateSQLFunctionCommand for SQL Scalar and Table Functions [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #49126:
URL: https://github.com/apache/spark/pull/49126#discussion_r1900525129


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala:
##########
@@ -72,8 +85,312 @@ case class CreateSQLFunctionCommand(
       isTableFunc,
       Map.empty)
 
-    // TODO: Implement the rest of the method.
+    val newFunction = {
+      val (expression, query) = function.getExpressionAndQuery(parser, isTableFunc)
+      assert(query.nonEmpty || expression.nonEmpty)
+
+      // Check if the function can be replaced.
+      if (replace && catalog.functionExists(name)) {
+        checkFunctionSignatures(catalog, name)
+      }
+
+      // Build function input.
+      val inputPlan = if (inputParam.isDefined) {
+        val param = inputParam.get
+        checkParameterNotNull(param, inputParamText.get)
+        checkParameterNameDuplication(param, conf, name)
+        checkDefaultsTrailing(param, name)
+
+        // Qualify the input parameters with the function name so that attributes referencing
+        // the function input parameters can be resolved correctly.
+        val qualifier = Seq(name.funcName)
+        val input = param.map(p => Alias(
+          {
+            val defaultExpr = p.getDefault()
+            if (defaultExpr.isEmpty) {
+              Literal.create(null, p.dataType)
+            } else {
+              val defaultPlan = parseDefault(defaultExpr.get, parser)
+              if (SubqueryExpression.hasSubquery(defaultPlan)) {
+                throw new AnalysisException(
+                  errorClass = "USER_DEFINED_FUNCTIONS.NOT_A_VALID_DEFAULT_EXPRESSION",
+                  messageParameters =
+                    Map("functionName" -> name.funcName, "parameterName" -> p.name))
+              } else if (defaultPlan.containsPattern(UNRESOLVED_ATTRIBUTE)) {

Review Comment:
   This reminds me of how we validate column default values for CREATE TABLE. We don't hold the expr string in the command, but the parsed expression (`ColumnDefinition#defaultValue`). Then we validate the resolved expression in `ResolveDefaultColumns.validateDefaultValueExpr`



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-48730][SQL] Implement CreateSQLFunctionCommand for SQL Scalar and Table Functions [spark]

Posted by "tedyu (via GitHub)" <gi...@apache.org>.
tedyu commented on code in PR #49126:
URL: https://github.com/apache/spark/pull/49126#discussion_r1905333183


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala:
##########
@@ -72,8 +85,313 @@ case class CreateSQLFunctionCommand(
       isTableFunc,
       Map.empty)
 
-    // TODO: Implement the rest of the method.
+    val newFunction = {
+      val (expression, query) = function.getExpressionAndQuery(parser, isTableFunc)
+      assert(query.nonEmpty || expression.nonEmpty)
+
+      // Check if the function can be replaced.
+      if (replace && catalog.functionExists(name)) {
+        checkFunctionSignatures(catalog, name)
+      }
+
+      // Build function input.
+      val inputPlan = if (inputParam.isDefined) {
+        val param = inputParam.get
+        checkParameterNotNull(param, inputParamText.get)
+        checkParameterNameDuplication(param, conf, name)
+        checkDefaultsTrailing(param, name)
+
+        // Qualify the input parameters with the function name so that attributes referencing
+        // the function input parameters can be resolved correctly.
+        val qualifier = Seq(name.funcName)
+        val input = param.map(p => Alias(
+          {
+            val defaultExpr = p.getDefault()
+            if (defaultExpr.isEmpty) {
+              Literal.create(null, p.dataType)
+            } else {
+              val defaultPlan = parseDefault(defaultExpr.get, parser)
+              if (SubqueryExpression.hasSubquery(defaultPlan)) {
+                throw new AnalysisException(
+                  errorClass = "USER_DEFINED_FUNCTIONS.NOT_A_VALID_DEFAULT_EXPRESSION",
+                  messageParameters =
+                    Map("functionName" -> name.funcName, "parameterName" -> p.name))
+              } else if (defaultPlan.containsPattern(UNRESOLVED_ATTRIBUTE)) {
+                // TODO(SPARK-50698): use parsed expression instead of expression string.
+                defaultPlan.collect {
+                  case a: UnresolvedAttribute =>
+                    throw QueryCompilationErrors.unresolvedAttributeError(
+                      "UNRESOLVED_COLUMN", a.sql, Seq.empty, a.origin)
+                }
+              }
+              Cast(defaultPlan, p.dataType)
+            }
+          }, p.name)(qualifier = qualifier))
+        Project(input, OneRowRelation())
+      } else {
+        OneRowRelation()
+      }
+
+      // Build the function body and check if the function body can be analyzed successfully.
+      val (unresolvedPlan, analyzedPlan, inferredReturnType) = if (!isTableFunc) {
+        // Build SQL scalar function plan.
+        val outputExpr = if (query.isDefined) ScalarSubquery(query.get) else expression.get
+        val plan: LogicalPlan = returnType.map { t =>
+          val retType: DataType = t match {
+            case Left(t) => t
+            case _ => throw SparkException.internalError(
+              "Unexpected return type for a scalar SQL UDF.")
+          }
+          val outputCast = Seq(Alias(Cast(outputExpr, retType), name.funcName)())
+          Project(outputCast, inputPlan)
+        }.getOrElse {
+          // If no explicit RETURNS clause is present, infer the result type from the function body.
+          val outputAlias = Seq(Alias(outputExpr, name.funcName)())
+          Project(outputAlias, inputPlan)
+        }
+
+        // Check the function body can be analyzed correctly.
+        val analyzed = analyzer.execute(plan)
+        val (resolved, resolvedReturnType) = analyzed match {
+          case p @ Project(expr :: Nil, _) if expr.resolved =>
+            (p, Left(expr.dataType))
+          case other =>
+            (other, function.returnType)
+        }
+
+        // Check if the SQL function body contains aggregate/window functions.
+        // This check needs to be performed before checkAnalysis to provide better error messages.
+        checkAggOrWindowOrGeneratorExpr(resolved)
+
+        // Check if the SQL function body can be analyzed.
+        checkFunctionBodyAnalysis(analyzer, function, resolved)
+
+        (plan, resolved, resolvedReturnType)
+      } else {
+        // Build SQL table function plan.
+        if (query.isEmpty) {
+          throw UserDefinedFunctionErrors.bodyIsNotAQueryForSqlTableUdf(name.funcName)
+        }
+
+        // Construct a lateral join to analyze the function body.
+        val plan = LateralJoin(inputPlan, LateralSubquery(query.get), Inner, None)
+        val analyzed = analyzer.execute(plan)
+        val newPlan = analyzed match {
+          case Project(_, j: LateralJoin) => j
+          case j: LateralJoin => j
+          case _ => throw SparkException.internalError("Unexpected plan returned when " +
+            s"creating a SQL TVF: ${analyzed.getClass.getSimpleName}.")
+        }
+        val maybeResolved = newPlan.asInstanceOf[LateralJoin].right.plan
+
+        // Check if the function body can be analyzed.
+        checkFunctionBodyAnalysis(analyzer, function, maybeResolved)
+
+        // Get the function's return schema.
+        val returnParam: StructType = returnType.map {
+          case Right(t) => t
+          case Left(_) => throw SparkException.internalError(
+            "Unexpected return schema for a SQL table function.")
+        }.getOrElse {
+          // If no explicit RETURNS clause is present, infer the result type from the function body.
+          // To detect this, we search for instances of the UnresolvedAlias expression. Examples:
+          // CREATE TABLE t USING PARQUET AS VALUES (0, 1), (1, 2) AS tab(c1, c2);
+          // SELECT c1 FROM t           -->  UnresolvedAttribute: 'c1
+          // SELECT c1 + 1 FROM t       -->  UnresolvedAlias: unresolvedalias(('c1 + 1), None)
+          // SELECT c1 + 1 AS a FROM t  -->  Alias: ('c1 + 1) AS a#2
+          query.get match {
+            case Project(projectList, _) if projectList.exists(_.isInstanceOf[UnresolvedAlias]) =>
+              throw UserDefinedFunctionErrors.missingColumnNamesForSqlTableUdf(name.funcName)
+            case _ =>
+              StructType(analyzed.asInstanceOf[LateralJoin].right.plan.output.map { col =>
+                StructField(col.name, col.dataType)
+              })
+          }
+        }
+
+        // Check the return columns cannot have NOT NULL specified.
+        checkParameterNotNull(returnParam, returnTypeText)
+
+        // Check duplicated return column names.
+        checkReturnsColumnDuplication(returnParam, conf, name)
+
+        // Check if the actual output size equals to the number of return parameters.
+        val outputSize = maybeResolved.output.size
+        if (outputSize != returnParam.size) {
+          throw new AnalysisException(
+            errorClass = "USER_DEFINED_FUNCTIONS.RETURN_COLUMN_COUNT_MISMATCH",
+            messageParameters = Map(
+              "outputSize" -> s"$outputSize",
+              "returnParamSize" -> s"${returnParam.size}",
+              "name" -> s"$name"
+            )
+          )
+        }
+
+        (plan, analyzed, Right(returnParam))
+      }
+
+      // A permanent function is not allowed to reference temporary objects.
+      // This should be called after `qe.assertAnalyzed()` (i.e., `plan` can be resolved)
+      verifyTemporaryObjectsNotExists(catalog, isTemp, name, unresolvedPlan, analyzedPlan)
+
+      // Generate function properties.
+      val properties = generateFunctionProperties(sparkSession, unresolvedPlan, analyzedPlan)
+
+      // Derive determinism of the SQL function.
+      val deterministic = analyzedPlan.deterministic

Review Comment:
   This call can be delayed since the value is used in `getOrElse` on line 247



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-48730][SQL] Implement CreateSQLFunctionCommand for SQL Scalar and Table Functions [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #49126:
URL: https://github.com/apache/spark/pull/49126#discussion_r1903626780


##########
sql/core/src/test/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionParserSuite.scala:
##########
@@ -0,0 +1,204 @@
+/*
+ * 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.execution.command
+
+import org.apache.spark.sql.catalyst.FunctionIdentifier
+import org.apache.spark.sql.catalyst.analysis.{AnalysisTest, UnresolvedIdentifier}
+import org.apache.spark.sql.catalyst.catalog.LanguageSQL
+import org.apache.spark.sql.catalyst.plans.logical.CreateUserDefinedFunction
+import org.apache.spark.sql.execution.SparkSqlParser
+import org.apache.spark.sql.test.SharedSparkSession
+
+class CreateSQLFunctionParserSuite extends AnalysisTest with SharedSparkSession {

Review Comment:
   do we really need `with SharedSparkSession`? This only tests the parser



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionParserSuite.scala:
##########
@@ -0,0 +1,204 @@
+/*
+ * 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.execution.command
+
+import org.apache.spark.sql.catalyst.FunctionIdentifier
+import org.apache.spark.sql.catalyst.analysis.{AnalysisTest, UnresolvedIdentifier}
+import org.apache.spark.sql.catalyst.catalog.LanguageSQL
+import org.apache.spark.sql.catalyst.plans.logical.CreateUserDefinedFunction
+import org.apache.spark.sql.execution.SparkSqlParser
+import org.apache.spark.sql.test.SharedSparkSession
+
+class CreateSQLFunctionParserSuite extends AnalysisTest with SharedSparkSession {
+  private lazy val parser = new SparkSqlParser()
+
+  private def intercept(sqlCommand: String, messages: String*): Unit =
+    interceptParseException(parser.parsePlan)(sqlCommand, messages: _*)()
+
+  private def checkParseError(
+      sqlCommand: String,
+      errorClass: String,
+      parameters: Map[String, String],
+      queryContext: Array[ExpectedContext] = Array.empty): Unit =
+      assertParseErrorClass(parser.parsePlan, sqlCommand, errorClass, parameters, queryContext)

Review Comment:
   ```suggestion
       assertParseErrorClass(parser.parsePlan, sqlCommand, errorClass, parameters, queryContext)
   ```



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-48730][SQL] Implement CreateSQLFunctionCommand for SQL Scalar and Table Functions [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #49126:
URL: https://github.com/apache/spark/pull/49126#discussion_r1900529242


##########
sql/core/src/test/scala/org/apache/spark/sql/execution/command/DDLParserSuite.scala:
##########
@@ -828,24 +893,90 @@ class DDLParserSuite extends AnalysisTest with SharedSparkSession {
       ShowCatalogsCommand(Some("defau*")))
   }
 
-  test("Create SQL functions") {
+  test("create temporary SQL functions") {

Review Comment:
   shall we create a new `CreateSQLFunctionParserSuite`? similar to `DropTableParserSuite`.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org