ganeshashree commented on code in PR #60213:
URL: https://github.com/apache/spark/pull/60213#discussion_r4563769848


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala:
##########
@@ -429,13 +401,32 @@ case class CreateSQLFunctionCommand(
    */
   private def checkCyclicFunctionReference(
       catalog: SessionCatalog,
+      analyzer: Analyzer,
       identifier: FunctionIdentifier,
       plan: LogicalPlan): Unit = {
 
+    // Look up an unqualified call that a persistent function owns by its 
qualified name, since
+    // the unqualified lookup tries built-in and temp functions first. A fresh 
context reads the
+    // current SQL path: a CREATE FUNCTION that a procedure issues runs inside 
the CALL's analysis
+    // pass, whose cached path may predate a SET PATH.
+    def lookupIdentifier(nameParts: Seq[String]): FunctionIdentifier = {
+      val owner = if (nameParts.length == 1) {
+        
AnalysisContext.withNewAnalysisContext(analyzer.unqualifiedFunctionOwner(nameParts.head))

Review Comment:
   Fixed in ebdd2f37a24. The check now walks each nested body under that 
function's own configs and stored path, as analysis does, inside one fresh 
context for the whole check. Built-in and temp owners are looked up by their 
exact identifier. Added tests for the cases you described.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala:
##########
@@ -429,13 +401,32 @@ case class CreateSQLFunctionCommand(
    */
   private def checkCyclicFunctionReference(
       catalog: SessionCatalog,
+      analyzer: Analyzer,
       identifier: FunctionIdentifier,
       plan: LogicalPlan): Unit = {
 
+    // Look up an unqualified call that a persistent function owns by its 
qualified name, since
+    // the unqualified lookup tries built-in and temp functions first. A fresh 
context reads the
+    // current SQL path: a CREATE FUNCTION that a procedure issues runs inside 
the CALL's analysis
+    // pass, whose cached path may predate a SET PATH.
+    def lookupIdentifier(nameParts: Seq[String]): FunctionIdentifier = {
+      val owner = if (nameParts.length == 1) {
+        
AnalysisContext.withNewAnalysisContext(analyzer.unqualifiedFunctionOwner(nameParts.head))

Review Comment:
   Fixed in ebdd2f37a24. Owners are now cached per walked body and name. I 
didn't add a counting-catalog test.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -333,15 +343,42 @@ object AnalysisContext {
   }
 
   /**
-   * Runs `f` with `shareIdentifierVariablesWithNestedSQLFunctions` set to 
`share`; see that field.
+   * Runs `f` with `shareTempReferencesWithNestedSQLFunctions` set to `share`; 
see that field.
    */
-  def withSharingIdentifierVariablesWithNestedSQLFunctions[A](share: 
Boolean)(f: => A): A = {
+  def withSharingTempReferencesWithNestedSQLFunctions[A](share: Boolean)(f: => 
A): A = {
     val originContext = value.get()
-    val context = 
originContext.copy(shareIdentifierVariablesWithNestedSQLFunctions = share)
+    val context = originContext.copy(shareTempReferencesWithNestedSQLFunctions 
= share)
     
context.setSinglePassResolverBridgeState(originContext.getSinglePassResolverBridgeState)
     set(context)
     try f finally { set(originContext) }
   }
+
+  /**
+   * Wraps `rule` so that a parameter default inserted by named-argument 
filling
+   * ([[SQLFunction.INSERTED_PARAMETER_DEFAULT]]) records temp references as 
the called function's
+   * body does: in fresh sets unless 
`shareTempReferencesWithNestedSQLFunctions` is set. Unlike a
+   * default that a positional call omits, which the body pads, it resolves in 
the caller's plan.
+   */
+  def withTempReferencesOfInsertedDefault(
+      rule: PartialFunction[Expression, Expression]): 
PartialFunction[Expression, Expression] =
+    new PartialFunction[Expression, Expression] {
+      override def isDefinedAt(e: Expression): Boolean = rule.isDefinedAt(e)
+      override def apply(e: Expression): Expression = applyOrElse(e, rule)
+      override def applyOrElse[E <: Expression, B >: Expression](e: E, 
default: E => B): B = {
+        lazy val originContext = value.get()
+        if (e.getTagValue(SQLFunction.INSERTED_PARAMETER_DEFAULT).isEmpty ||
+            originContext.shareTempReferencesWithNestedSQLFunctions) {
+          rule.applyOrElse(e, default)
+        } else {
+          val context = originContext.copy(
+            referredTempFunctionNames = mutable.Set.empty,
+            referredTempVariableNamesUnderIdentifier = 
mutable.LinkedHashSet.empty)

Review Comment:
   Done.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/SQLFunctionSuite.scala:
##########
@@ -534,4 +546,303 @@ class SQLFunctionSuite extends SharedSparkSession {
       checkAnswer(sql("SELECT * FROM tvf(null_udf(1))"), Row(null))
     }
   }
+
+  test("SPARK-60806: a temp function counts as a reference only if it owns the 
call") {
+    withUserDefinedFunction("perm_abs" -> false, "perm_abs_tbl" -> false) {
+      sql("CREATE TEMPORARY FUNCTION abs(x INT) RETURNS INT RETURN 42")
+      try {
+        // The built-in precedes a same-named temp function under the default 
resolution order.
+        sql("CREATE FUNCTION perm_abs() RETURNS INT RETURN abs(-1)")
+        checkAnswer(sql("SELECT perm_abs()"), Row(1))
+        sql("CREATE FUNCTION perm_abs_tbl() RETURNS TABLE (a INT) RETURN 
SELECT abs(-1)")
+        checkAnswer(sql("SELECT * FROM perm_abs_tbl()"), Row(1))
+        // With the session first in the path, the temp function owns the call.
+        withSQLConf(SQLConf.PATH_ENABLED.key -> "true") {
+          try {
+            sql("SET PATH = system.session, system.builtin, 
spark_catalog.default")
+            checkAnswer(sql("SELECT abs(-1)"), Row(42))
+            checkError(
+              exception = intercept[AnalysisException] {
+                sql("CREATE FUNCTION perm_abs2() RETURNS INT RETURN abs(-1)")
+              },
+              condition = "INVALID_TEMP_OBJ_REFERENCE",
+              parameters = Map("obj" -> "FUNCTION", "objName" -> 
"`default`.`perm_abs2`",
+                "tempObj" -> "FUNCTION", "tempObjName" -> "`abs`"))
+          } finally {
+            sql("SET PATH = DEFAULT_PATH")
+          }
+        }
+      } finally {
+        sql("DROP TEMPORARY FUNCTION abs")
+      }
+    }
+  }
+
+  test("SPARK-60806: a temp function is not a reference when a persistent one 
owns the call") {
+    withUserDefinedFunction("caller" -> false, "caller2" -> false) {
+      withView("v", "v2") {
+        sql("CREATE FUNCTION pf() RETURNS INT RETURN 7")
+        sql("CREATE TEMPORARY FUNCTION pf() RETURNS INT RETURN 42")
+        try {
+          def check(caller: String, view: String): Unit = {
+            checkAnswer(sql("SELECT pf()"), Row(7))
+            sql(s"CREATE FUNCTION $caller() RETURNS INT RETURN pf()")
+            checkAnswer(sql(s"SELECT $caller()"), Row(7))
+            sql(s"CREATE VIEW $view AS SELECT pf() AS a")
+            checkAnswer(sql(s"SELECT * FROM $view"), Row(7))
+          }
+          withSQLConf(SQLConf.SESSION_FUNCTION_RESOLUTION_ORDER.key -> "last") 
{
+            check("caller", "v")
+          }
+          withSQLConf(SQLConf.PATH_ENABLED.key -> "true") {
+            try {
+              sql("SET PATH = spark_catalog.default, system.session, 
system.builtin")
+              check("caller2", "v2")
+            } finally {
+              sql("SET PATH = DEFAULT_PATH")
+            }
+          }
+        } finally {
+          sql("DROP TEMPORARY FUNCTION IF EXISTS pf")
+          sql("DROP FUNCTION IF EXISTS pf")
+        }
+      }
+    }
+  }
+
+  test("SPARK-60806: a session-qualified call a persistent function owns is 
not a temp reference") {
+    withUserDefinedFunction("caller" -> false, "caller2" -> false, 
"temp_caller" -> true) {
+      withView("v") {
+        withDatabase("session") {
+          sql("CREATE DATABASE session")
+          sql("CREATE FUNCTION session.test_func() RETURNS STRING RETURN 
'persistent'")
+          sql("CREATE TEMPORARY FUNCTION test_func() RETURNS STRING RETURN 
'temp'")
+          try {
+            withSQLConf(SQLConf.PERSISTENT_CATALOG_FIRST.key -> "true") {
+              sql("CREATE FUNCTION caller() RETURNS STRING RETURN 
session.test_func()")
+              checkAnswer(sql("SELECT caller()"), Row("persistent"))
+              sql("CREATE VIEW v AS SELECT session.test_func() AS a")
+              checkAnswer(sql("SELECT * FROM v"), Row("persistent"))
+              sql("CREATE TEMPORARY FUNCTION temp_caller() RETURNS STRING " +
+                "RETURN session.test_func()")
+              assert(lookupTempSQLFunction("temp_caller", Nil)
+                .properties("referredTempFunctionsNames") === "[]")
+            }
+            // By default the temp function owns the session-qualified call.
+            checkError(
+              exception = intercept[AnalysisException] {
+                sql("CREATE FUNCTION caller2() RETURNS STRING RETURN 
session.test_func()")
+              },
+              condition = "INVALID_TEMP_OBJ_REFERENCE",
+              parameters = Map("obj" -> "FUNCTION", "objName" -> 
"`default`.`caller2`",
+                "tempObj" -> "FUNCTION", "tempObjName" -> "`test_func`"))
+          } finally {
+            sql("DROP TEMPORARY FUNCTION IF EXISTS test_func")
+            sql("DROP FUNCTION IF EXISTS session.test_func")
+          }
+        }
+      }
+    }
+  }
+
+  test("SPARK-60806: a temp function bound by an omitted named-argument 
default is not a " +
+    "reference") {
+    withUserDefinedFunction("g" -> false, "inner_fn" -> false, "inner_tvf" -> 
false,
+        "c1" -> false, "c2" -> false, "c3" -> false, "temp_c" -> true) {
+      withView("v", "tv") {
+        sql("CREATE FUNCTION g() RETURNS INT RETURN 1")
+        sql("CREATE FUNCTION inner_fn(x INT, y INT DEFAULT g(), z INT DEFAULT 
IDENTIFIER('g')()) " +
+          "RETURNS INT RETURN x + y + z")
+        sql("CREATE FUNCTION inner_tvf(x INT, y INT DEFAULT g()) RETURNS TABLE 
(a INT) " +
+          "RETURN SELECT x + y")
+        try {
+          sql("CREATE TEMPORARY FUNCTION g() RETURNS INT RETURN 2")
+          // The omitted defaults are the callee's dependencies, however the 
call is written.
+          sql("CREATE FUNCTION c1() RETURNS INT RETURN inner_fn(1)")
+          sql("CREATE FUNCTION c2() RETURNS INT RETURN inner_fn(x => 1)")
+          sql("CREATE FUNCTION c3() RETURNS TABLE (a INT) RETURN SELECT * FROM 
inner_tvf(x => 1)")
+          sql("CREATE TEMPORARY FUNCTION temp_c() RETURNS INT RETURN 
inner_fn(x => 1)")
+          assert(lookupTempSQLFunction("temp_c", Nil)
+            .properties("referredTempFunctionsNames") === "[]")
+          // A view owns the dependencies of the functions it expands.
+          checkError(
+            exception = intercept[AnalysisException] {
+              sql("CREATE VIEW v AS SELECT inner_fn(x => 1) AS a")
+            },
+            condition = "INVALID_TEMP_OBJ_REFERENCE",
+            parameters = Map("obj" -> "VIEW", "objName" -> 
"`spark_catalog`.`default`.`v`",
+              "tempObj" -> "FUNCTION", "tempObjName" -> "`g`"))
+          sql("CREATE TEMPORARY VIEW tv AS SELECT inner_fn(x => 1) AS a")
+          
assert(spark.sessionState.catalog.getTempViewOrPermanentTableMetadata(
+            TableIdentifier("tv")).viewReferredTempFunctionNames === Seq("g"))
+          sql("DROP TEMPORARY FUNCTION g")
+          checkAnswer(sql("SELECT c1(), c2()"), Row(3, 3))
+          checkAnswer(sql("SELECT * FROM c3()"), Row(2))
+        } finally {
+          sql("DROP TEMPORARY FUNCTION IF EXISTS g")
+        }
+      }
+    }
+  }
+
+  test("SPARK-60806: the cycle check follows the owner a temp function shadows 
by name") {

Review Comment:
   Done.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/SQLFunctionSuite.scala:
##########
@@ -534,4 +546,303 @@ class SQLFunctionSuite extends SharedSparkSession {
       checkAnswer(sql("SELECT * FROM tvf(null_udf(1))"), Row(null))
     }
   }
+
+  test("SPARK-60806: a temp function counts as a reference only if it owns the 
call") {
+    withUserDefinedFunction("perm_abs" -> false, "perm_abs_tbl" -> false) {
+      sql("CREATE TEMPORARY FUNCTION abs(x INT) RETURNS INT RETURN 42")
+      try {
+        // The built-in precedes a same-named temp function under the default 
resolution order.
+        sql("CREATE FUNCTION perm_abs() RETURNS INT RETURN abs(-1)")
+        checkAnswer(sql("SELECT perm_abs()"), Row(1))
+        sql("CREATE FUNCTION perm_abs_tbl() RETURNS TABLE (a INT) RETURN 
SELECT abs(-1)")
+        checkAnswer(sql("SELECT * FROM perm_abs_tbl()"), Row(1))
+        // With the session first in the path, the temp function owns the call.
+        withSQLConf(SQLConf.PATH_ENABLED.key -> "true") {
+          try {
+            sql("SET PATH = system.session, system.builtin, 
spark_catalog.default")
+            checkAnswer(sql("SELECT abs(-1)"), Row(42))
+            checkError(
+              exception = intercept[AnalysisException] {
+                sql("CREATE FUNCTION perm_abs2() RETURNS INT RETURN abs(-1)")
+              },
+              condition = "INVALID_TEMP_OBJ_REFERENCE",
+              parameters = Map("obj" -> "FUNCTION", "objName" -> 
"`default`.`perm_abs2`",
+                "tempObj" -> "FUNCTION", "tempObjName" -> "`abs`"))
+          } finally {
+            sql("SET PATH = DEFAULT_PATH")
+          }
+        }
+      } finally {
+        sql("DROP TEMPORARY FUNCTION abs")
+      }
+    }
+  }
+
+  test("SPARK-60806: a temp function is not a reference when a persistent one 
owns the call") {

Review Comment:
   Done.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to