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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala:
##########
@@ -446,14 +561,28 @@ case class CreateSQLFunctionCommand(
       identifier: FunctionIdentifier,
       plan: LogicalPlan): Unit = {
 
+    // Returns `functionIdentifierForLookup`'s result when `nameParts` names a 
SQL function, and
+    // None otherwise. A missing function outside the system namespace makes 
the lookup throw.
+    def sqlFunctionIdentifier(
+        nameParts: Seq[String],
+        tableFunction: Boolean): Option[(FunctionIdentifier, Boolean)] =
+      functionIdentifierForLookup(catalog, nameParts).filter {

Review Comment:
   **Non-blocking (P2):** With 
`spark.sql.legacy.allowTempFunctionInPersistedSQLFunction` set, the 
temporary-function check reads a two-part `session.f` call as the persistent 
`spark_catalog.session.f` whenever that function exists 
(CreateSQLFunctionCommand.scala:471-474). The cyclic check maps the same call 
through `functionIdentifierForLookup`, which has no legacy branch: with a 
temporary `f` present it returns the `system.session` identifier 
(CreateSQLFunctionCommand.scala:499-503), so the check walks the temporary 
function's body. The base branch's cyclic check looked up 
`FunctionIdentifier(f, Some("session"))`, which finds only the persistent 
function. Reading the code:
   
   ```sql
   CREATE DATABASE session;
   CREATE FUNCTION session.sf() RETURNS INT RETURN 3;
   CREATE TEMPORARY FUNCTION sf() RETURNS INT RETURN 7;
   SET spark.sql.legacy.allowTempFunctionInPersistedSQLFunction=true;
   -- base branch: CYCLIC_FUNCTION_REFERENCE; this PR: created
   CREATE OR REPLACE FUNCTION session.sf() RETURNS INT RETURN session.sf();
   ```
   
   In a session without the temporary `sf`, the stored `session.sf()` then 
calls itself. The table form over a persistent `session.pt` and a temporary 
`pt` behaves the same, and so do indirect cycles, such as replacing `perm_x` 
with a body that calls `session.sf()` while the persistent `session.sf` calls 
`perm_x`. So the flag accepts a body the base branch rejected, although the PR 
describes it as accepting what the base branch accepted, and none of the 
legacy-mode tests creates a cycle.
   
   Applying the same legacy rule when the cyclic check maps a `session.f` call 
while a persistent function is created, for example inside 
`functionIdentifierForLookup` so that both checks share it, would make the two 
checks agree. Temporary function creation and the default mode can keep the 
current mapping, which follows what function resolution binds.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60214#discussion_r4562533446).
   
   **Verification:**
   - **Regression:** With the legacy flag set, a schema named session holding a 
scalar function sf and a table function pt, and temporary functions sf and pt, 
CREATE OR REPLACE FUNCTION session.sf() RETURNS INT RETURN session.sf(), the 
table form over session.pt(), and an indirect cycle in which session.sf calls 
perm_x and perm_x is replaced to call session.sf() each fail with 
CYCLIC_FUNCTION_REFERENCE.
   - **Compatibility:** With the flag set, persistent bodies that call 
session.sf() and SELECT * FROM session.pt() without a cycle are still created; 
without the flag they still fail with INVALID_TEMP_OBJ_REFERENCE; under 
spark.sql.legacy.persistentCatalogFirst the existing outcomes hold; and with 
the flag set, CREATE OR REPLACE TEMPORARY FUNCTION pt() RETURNS TABLE (a INT) 
RETURN SELECT * FROM session.pt() still fails with CYCLIC_FUNCTION_REFERENCE.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/SQLFunctionSuite.scala:
##########
@@ -534,4 +534,353 @@ class SQLFunctionSuite extends SharedSparkSession {
       checkAnswer(sql("SELECT * FROM tvf(null_udf(1))"), Row(null))
     }
   }
+
+  test("SPARK-60805: a SQL function body can call system-qualified functions") 
{
+    withUserDefinedFunction("perm_q" -> false, "perm_q_tbl" -> false) {
+      Seq("builtin.abs(-1)", "system.builtin.abs(-1)", 
"SYSTEM.Builtin.abs(-1)").foreach { call =>
+        sql(s"CREATE OR REPLACE FUNCTION perm_q() RETURNS INT RETURN $call")
+        checkAnswer(sql("SELECT perm_q()"), Row(1))
+        sql(s"CREATE OR REPLACE FUNCTION perm_q_tbl() RETURNS TABLE (a INT) 
RETURN SELECT $call")
+        checkAnswer(sql("SELECT * FROM perm_q_tbl()"), Row(1))
+      }
+      // A builtin.-qualified name that exists nowhere is an unresolved 
routine.
+      val e = intercept[AnalysisException] {
+        sql("CREATE OR REPLACE FUNCTION perm_q() RETURNS INT RETURN 
builtin.nope()")
+      }
+      assert(e.getCondition == "UNRESOLVED_ROUTINE", e.getMessage)
+      // A system-qualified built-in table function, too.
+      Seq("builtin.range(3)", "system.builtin.range(3)").foreach { call =>
+        sql(s"CREATE OR REPLACE FUNCTION perm_q_tbl() RETURNS TABLE (id 
BIGINT) " +
+          s"RETURN SELECT * FROM $call")
+        checkAnswer(sql("SELECT * FROM perm_q_tbl()"), Seq(Row(0), Row(1), 
Row(2)))
+      }
+    }
+    // A catalog-qualified persistent call works too, and is checked for 
cyclic references.
+    withUserDefinedFunction("perm_in" -> false, "perm_out" -> false) {
+      sql("CREATE FUNCTION perm_in() RETURNS INT RETURN 5")
+      sql("CREATE FUNCTION perm_out() RETURNS INT RETURN 
spark_catalog.default.perm_in()")
+      checkAnswer(sql("SELECT perm_out()"), Row(5))
+      val e = intercept[AnalysisException] {
+        sql("CREATE OR REPLACE FUNCTION perm_in() RETURNS INT " +
+          "RETURN spark_catalog.default.perm_out()")
+      }
+      assert(e.getCondition == "CYCLIC_FUNCTION_REFERENCE", e.getMessage)
+    }
+    withUserDefinedFunction("tbl_in" -> false, "tbl_out" -> false) {
+      sql("CREATE FUNCTION tbl_in() RETURNS TABLE (a INT) RETURN SELECT 1")
+      sql("CREATE FUNCTION tbl_out() RETURNS TABLE (a INT) " +
+        "RETURN SELECT * FROM SPARK_CATALOG.default.tbl_in()")
+      checkAnswer(sql("SELECT * FROM tbl_out()"), Row(1))
+      val e = intercept[AnalysisException] {
+        sql("CREATE OR REPLACE FUNCTION tbl_in() RETURNS TABLE (a INT) " +
+          "RETURN SELECT * FROM spark_catalog.default.tbl_out()")
+      }
+      assert(e.getCondition == "CYCLIC_FUNCTION_REFERENCE", e.getMessage)
+    }
+    // A session-qualified call is checked for cyclic references like an 
unqualified one.
+    withUserDefinedFunction("temp_c" -> true, "temp_c_tbl" -> true) {
+      sql("CREATE TEMPORARY FUNCTION temp_c() RETURNS INT RETURN 1")
+      sql("CREATE TEMPORARY FUNCTION temp_c_tbl() RETURNS TABLE (a INT) RETURN 
SELECT 1")
+      Seq(
+        "CREATE OR REPLACE TEMPORARY FUNCTION temp_c() RETURNS INT RETURN 
session.temp_c()",
+        "CREATE OR REPLACE TEMPORARY FUNCTION temp_c() RETURNS INT " +
+          "RETURN system.session.temp_c()",
+        "CREATE OR REPLACE TEMPORARY FUNCTION temp_c_tbl() RETURNS TABLE (a 
INT) " +
+          "RETURN SELECT * FROM session.temp_c_tbl()"
+      ).foreach { ddl =>
+        val e = intercept[AnalysisException](sql(ddl))
+        assert(e.getCondition == "CYCLIC_FUNCTION_REFERENCE", s"$ddl: 
${e.getMessage}")
+      }
+    }
+  }
+
+  test("SPARK-60805: a permanent function cannot reference a temp function or 
temp TVF") {
+    withUserDefinedFunction("temp_fn" -> true, "temp_caller" -> true, 
"temp_tbl" -> true,
+        "temp_tbl_caller" -> true) {
+      sql("CREATE TEMPORARY FUNCTION temp_fn() RETURNS INT RETURN 1")
+      sql("CREATE TEMPORARY FUNCTION temp_tbl() RETURNS TABLE (a INT) RETURN 
SELECT 1")
+      // A temporary function may call another temporary function through 
`system.session.`.
+      sql("CREATE TEMPORARY FUNCTION temp_caller() RETURNS INT RETURN 
system.session.temp_fn()")
+      checkAnswer(sql("SELECT temp_caller()"), Row(1))
+      sql("CREATE TEMPORARY FUNCTION temp_tbl_caller() RETURNS TABLE (a INT) " 
+
+        "RETURN SELECT * FROM system.session.temp_tbl()")
+      checkAnswer(sql("SELECT * FROM temp_tbl_caller()"), Row(1))
+      Seq(
+        "CREATE FUNCTION perm_fn() RETURNS INT RETURN session.temp_fn()",
+        "CREATE FUNCTION perm_fn() RETURNS INT RETURN 
system.session.temp_fn()",
+        "CREATE FUNCTION perm_fn() RETURNS INT RETURN IDENTIFIER('temp_fn')()",
+        "CREATE FUNCTION perm_fn() RETURNS INT RETURN 
IDENTIFIER('session.temp_fn')() + 1",
+        "CREATE FUNCTION perm_fn() RETURNS INT RETURN 
IDENTIFIER(concat('temp', '_fn'))()",
+        "CREATE FUNCTION perm_fn() RETURNS INT RETURN 
IDENTIFIER(lower('TEMP_FN'))()",
+        "CREATE FUNCTION perm_fn() RETURNS INT RETURN (SELECT a FROM 
temp_tbl())",
+        "CREATE FUNCTION perm_fn() RETURNS INT RETURN (SELECT a FROM 
IDENTIFIER('temp_tbl')())",
+        "CREATE FUNCTION perm_fn() RETURNS TABLE (a INT) RETURN SELECT * FROM 
temp_tbl()",
+        "CREATE FUNCTION perm_fn() RETURNS TABLE (a INT) RETURN SELECT * FROM 
session.temp_tbl()",
+        "CREATE FUNCTION perm_fn() RETURNS TABLE (a INT) " +
+          "RETURN SELECT * FROM system.session.temp_tbl()",
+        "CREATE FUNCTION perm_fn() RETURNS INT RETURN (SELECT a FROM 
session.temp_tbl())"
+      ).foreach { ddl =>
+        val e = intercept[AnalysisException](sql(ddl))
+        assert(e.getCondition == "INVALID_TEMP_OBJ_REFERENCE", s"$ddl: 
${e.getMessage}")
+      }
+      withUserDefinedFunction("temp_built" -> true, "perm_built" -> false) {
+        sql("CREATE TEMPORARY FUNCTION temp_built() RETURNS INT " +
+          "RETURN IDENTIFIER(concat('temp', '_fn'))()")
+        checkAnswer(sql("SELECT temp_built()"), Row(1))
+        sql("CREATE FUNCTION perm_built() RETURNS INT RETURN 
IDENTIFIER(concat('ab', 's'))(-1)")
+        checkAnswer(sql("SELECT perm_built()"), Row(1))
+      }
+      // The legacy flag re-allows only the forms earlier versions accepted at 
creation.
+      val legacyKey = 
SQLConf.LEGACY_ALLOW_TEMP_FUNCTION_IN_PERSISTED_SQL_FUNCTION.key
+      withUserDefinedFunction("perm_legacy" -> false, "perm_legacy_tbl" -> 
false,
+          "perm_outer" -> false) {
+        withSQLConf(legacyKey -> "true") {
+          Seq("temp_tbl()", "IDENTIFIER('temp_tbl')()").foreach { call =>
+            sql("CREATE OR REPLACE FUNCTION perm_legacy_tbl() RETURNS TABLE (a 
INT) " +
+              s"RETURN SELECT * FROM $call")
+            checkAnswer(sql("SELECT * FROM perm_legacy_tbl()"), Row(1))
+          }
+          Seq("IDENTIFIER('temp_fn')()", "IDENTIFIER(concat('temp', 
'_fn'))()").foreach { call =>
+            sql(s"CREATE OR REPLACE FUNCTION perm_legacy() RETURNS INT RETURN 
$call")
+            checkAnswer(sql("SELECT perm_legacy()"), Row(1))
+          }
+          Seq(
+            "RETURNS INT RETURN temp_fn()",
+            "RETURNS INT RETURN session.temp_fn()",
+            "RETURNS INT RETURN system.session.temp_fn()",
+            "RETURNS TABLE (a INT) RETURN SELECT * FROM session.temp_tbl()",
+            "RETURNS TABLE (a INT) RETURN SELECT * FROM 
system.session.temp_tbl()"
+          ).foreach { body =>
+            val e = intercept[AnalysisException] {
+              sql(s"CREATE OR REPLACE FUNCTION perm_legacy_rej() $body")
+            }
+            assert(e.getCondition == "INVALID_TEMP_OBJ_REFERENCE", s"$body: 
${e.getMessage}")
+          }
+        }
+        // Without the flag, calling a function that depends on a temp TVF is 
rejected too.

Review Comment:
   **Nit (P3):** Both cases below reach `temp_tbl` through `perm_legacy_tbl`, a 
table SQL function, so only the table-function expansion in the analyzer 
carries the recorded name to the body under creation. A called scalar SQL 
function is expanded by a separate rule, `ResolveSQLFunctions.resolve` 
(Analyzer.scala:2864-2879), which shares the recorded set only because 
`AnalysisContext.withAnalysisContext(function)` keeps the caller's set. If that 
call site started from a fresh set, as `withAnalysisContext(viewDesc)` does for 
views, a persistent function whose scalar SQL callee reads a temporary table 
function would be created again and would fail in other sessions, and no test 
here would fail. A case whose intermediate is a scalar SQL function would close 
that gap.
   
   **Verification:**
   - **Regression:** After creating, under the legacy flag, a persistent scalar 
function perm_mid whose body is (SELECT a FROM temp_tbl()), creating without 
the flag a persistent scalar function that returns perm_mid() and a persistent 
table function that selects perm_mid() each fail with 
INVALID_TEMP_OBJ_REFERENCE naming temp_tbl.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala:
##########
@@ -374,24 +376,42 @@ case class CreateSQLFunctionCommand(
       }.distinct
     }
 
+    def collectInExpression(expr: Expression): Seq[String] = expr.flatMap {
+      case e: SubqueryExpression => collectTempFunctions(e.plan)
+      case e: UnresolvedFunction if isTemporaryScalarFunctionName(catalog, 
e.nameParts) =>
+        Seq(e.nameParts.last)
+      // An IDENTIFIER-clause call: check the call it builds from its constant 
name. An unqualified
+      // name counts only when the SQL PATH resolves it to the temp function.
+      case e: ExpressionWithUnresolvedIdentifier if !legacyTempFunctionCheck =>
+        identifierNameParts(analyzer, e.identifierExpr).map(e.exprBuilder(_, 
e.otherExprs)) match {
+          case Some(f: UnresolvedFunction) if 
isTemporaryScalarFunctionName(catalog, f.nameParts) &&
+              (f.nameParts.length > 1 ||
+                analyzer.unqualifiedFunctionResolvesToTemp(f.nameParts.head)) 
=>
+            Seq(f.nameParts.last)
+          case _ => Seq.empty
+        }
+      // A routed JSON constructor is a temporary-function reference only when 
the
+      // temporary function owns it, not the built-in or a persistent function 
before it.
+      case j: UnresolvedJsonConstructor
+        if j.routeThroughResolution &&
+          catalog.isTemporaryFunction(FunctionIdentifier(j.prettyName)) &&
+          analyzer.unqualifiedFunctionResolvesToTemp(j.prettyName) =>
+        Seq(j.prettyName)
+      case _ => Seq.empty
+    }
+
     def collectTempFunctions(child: LogicalPlan): Seq[String] = {
       child.flatMap {
         case w: UnresolvedWith if !w.resolved => 
w.innerChildren.flatMap(collectTempFunctions)
-        case plan if !plan.resolved =>
-          plan.expressions.flatMap(_.flatMap {
-            case e: SubqueryExpression => collectTempFunctions(e.plan)
-            case e: UnresolvedFunction
-              if catalog.isTemporaryFunction(e.nameParts.asFunctionIdentifier) 
=>
-              Seq(e.nameParts.asFunctionIdentifier.funcName)
-            // A routed JSON constructor is a temporary-function reference 
only when the
-            // temporary function owns it, not the built-in or a persistent 
function before it.
-            case j: UnresolvedJsonConstructor
-              if j.routeThroughResolution &&
-                catalog.isTemporaryFunction(FunctionIdentifier(j.prettyName)) 
&&
-                analyzer.unqualifiedFunctionResolvesToTemp(j.prettyName) =>
-              Seq(j.prettyName)
-            case _ => Seq.empty
-          })
+        // A qualified temp table function call. Resolution's recorded names 
cover the others.
+        case u: UnresolvedTableValuedFunction =>
+          val qualified = if (u.name.length > 1 && 
isTemporaryTableFunctionName(catalog, u.name)) {
+            Seq(u.name.last)
+          } else {
+            Nil
+          }
+          qualified ++ u.functionArgs.flatMap(collectInExpression)
+        case plan if !plan.resolved => 
plan.expressions.flatMap(collectInExpression)

Review Comment:
   **Non-blocking (P2):** This arm reads only `plan.expressions`, and for a 
table function named through IDENTIFIER that is just the name. 
`AstBuilder.withFuncIdentClause` wraps the call in a 
`PlanWithUnresolvedIdentifier` with no children, and 
`buildTvfFromTableFunctionCall` builds the `UnresolvedTableValuedFunction` and 
its arguments inside the node's `planBuilder` closure, so a temporary call 
among those arguments never reaches `collectInExpression`. Analysis later 
builds the call and binds the temporary function, but the recorded names are 
filtered to temporary table functions (CreateSQLFunctionCommand.scala:536-542), 
so nothing rejects it.
   
   Reading the code, after `CREATE TEMPORARY FUNCTION temp_fn() RETURNS INT 
RETURN 2` and `CREATE FUNCTION tbl_fn(x INT) RETURNS TABLE (a INT) RETURN 
SELECT x`:
   
   ```sql
   -- INVALID_TEMP_OBJ_REFERENCE, as the new test at 
SQLFunctionSuite.scala:731-745 asserts
   CREATE FUNCTION p() RETURNS TABLE (a INT) RETURN SELECT * FROM 
tbl_fn(session.temp_fn());
   -- created, as on the base branch
   CREATE FUNCTION p() RETURNS TABLE (a INT) RETURN SELECT * FROM 
IDENTIFIER('tbl_fn')(temp_fn());
   ```
   
   The stored `p` then fails in any session without `temp_fn`, or calls that 
session's own `temp_fn`. The same holds for every temporary scalar reference 
among those arguments: unqualified, `session.`- or `system.session.`-qualified, 
IDENTIFIER-built, or inside a scalar subquery. The PR rejects these calls when 
an expression-position IDENTIFIER clause hides them or when the table function 
is named directly, so only the spelling with an IDENTIFIER-named table function 
still gets through.
   
   Outside legacy mode, a `PlanWithUnresolvedIdentifier` case here could 
evaluate the name with `identifierNameParts`, build the plan with 
`planBuilder`, and scan that plan, counting an unqualified call only when the 
SQL PATH resolves it to the temporary function, as the expression-position 
IDENTIFIER arm does, so that a call a built-in or persistent function owns is 
not newly rejected. The Spark 4.4 migration-guide entry would then name this 
form among the ones that now fail.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60214#discussion_r4562533434).
   
   **Verification:**
   - **Regression:** After creating a temporary scalar function temp_fn and a 
persistent table function tbl_fn(x INT), persistent bodies SELECT * FROM 
IDENTIFIER('tbl_fn')(temp_fn()), SELECT * FROM IDENTIFIER(concat('tbl', 
'_fn'))(session.temp_fn()) and a scalar body that reads such a call in a scalar 
subquery each fail with INVALID_TEMP_OBJ_REFERENCE naming temp_fn.
   - **Compatibility:** With 
spark.sql.legacy.allowTempFunctionInPersistedSQLFunction set, those persistent 
bodies are created; a temporary function with the same body is created and 
returns temp_fn's result; and under a SQL PATH that lists a schema holding a 
persistent function of the same name before system.session, a persistent body 
that passes the unqualified call to an IDENTIFIER-named table function is 
created and returns the persistent function's result.
   - **Inspection:** The Spark 4.4 migration-guide entry for 
spark.sql.legacy.allowTempFunctionInPersistedSQLFunction names a temporary 
scalar function passed to a table function called through an IDENTIFIER clause 
among the forms that now fail and that the flag restores.



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