cloud-fan commented on code in PR #60213:
URL: https://github.com/apache/spark/pull/60213#discussion_r4562670668
##########
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:
**Blocking (P1):** `lookupIdentifier` computes each call's owner inside
`AnalysisContext.withNewAnalysisContext`, so it reads the creating session's
SQL path and settings. The check also calls it for every call inside the bodies
of existing SQL functions it expands (`checkFunction` and the table-function
case, lines 428-442 and 459-473), without installing that function's context.
Analysis expands the same bodies under `Analyzer.buildSQLFunctionConf(function,
...)` and `AnalysisContext.withAnalysisContext(function)`, which apply the
function's captured configs and pin its stored path (`Analyzer.scala:298-304`
and `2900-2905`). At nested depths the check can therefore follow a different
function from the one that actually runs.
Reading the code, with `spark.sql.path.enabled=true`, the default path, and
current schema `default`:
```sql
CREATE FUNCTION default.a() RETURNS INT RETURN 1;
CREATE FUNCTION default.h() RETURNS INT RETURN 1;
CREATE FUNCTION default.g() RETURNS INT RETURN h(); -- g's stored path
resolves h to default.h
CREATE DATABASE db1;
CREATE FUNCTION db1.h() RETURNS INT RETURN a();
SET PATH = spark_catalog.db1, spark_catalog.default, system.builtin,
system.session;
CREATE OR REPLACE FUNCTION default.a() RETURNS INT RETURN g();
```
The check looks `h` up under the session path, reaches `db1.h`, and fails
with CYCLIC_FUNCTION_REFERENCE (`spark_catalog.default.a ->
spark_catalog.default.g -> spark_catalog.db1.h -> spark_catalog.default.a`).
But analysis and every later call bind `default.h` inside `g`, so there is no
cycle. The base branch, like v4.3.0, looked `h` up in the current schema and
created the function. In the mirrored setup, where `default.h` calls `a()` and
`db1.h` does not, the check follows `db1.h`, finds no cycle, and replaces the
working `a` with the cycle `a -> g -> default.h -> a`. The base branch rejected
that statement.
The same divergence exists with the path disabled. A nested body analyzes
under the `spark.sql.functionResolution.sessionOrder` its function captured, or
the default, while the check uses the session's value. Under
`sessionOrder=last`, for example, the check follows a persistent function where
a nested body created under the default order binds a same-named temporary one.
The body being created is handled correctly.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60213#discussion_r4537919943).
**Recommended change:** When the cycle check expands an existing SQL
function's body, in checkFunction and in the table-function case of checkPlan,
walk that body under the configuration and analysis context analysis uses for
it. That is SQLConf.withExistingConf(Analyzer.buildSQLFunctionConf(function,
applySessionOverrides = true, alwaysSetAnsiValue = false)) around
AnalysisContext.withAnalysisContext(function), as ResolveSQLFunctions does at
Analyzer.scala:2900-2905. Enter one fresh analysis context for the whole check
of the body being created, instead of one per call at
CreateSQLFunctionCommand.scala:414, and let lookupIdentifier read the owner
from whichever context is in effect. Commit 099b81b2e4e added lookupIdentifier
reading the ambient context. Commit 18b9cf1a7fd moved it into a fresh context
per call so that a CREATE FUNCTION issued inside a procedure reads the current
SQL path rather than the CALL's cached one. A single fresh context at the top
keeps that reason. Look a
n owner in system.builtin or system.session up by that exact identifier rather
than by bare name, because the bare-name lookup orders built-in and temporary
functions by the live session path. Add SQL function tests with
spark.sql.path.enabled covering nested functions created under a different path.
**Why this works:** Each nested body then resolves its one-part calls
against its own stored path and captured configs, exactly as analysis and later
invocations do, so the chain the check follows is the chain the stored
functions will execute. The top-level body keeps the creating session's current
path, read once in a fresh context.
**Compatibility:** The body being created keeps following the creating
session's current SQL path, session order and persistentCatalogFirst, read in a
fresh analysis context, and analysis itself resolves every function body
exactly as before.
**Risks:** Applying a nested function's captured configs during the walk can
change which owner the check follows when those configs differ from the
session's. This includes runs with spark.sql.path.enabled off, where a nested
body keeps the spark.sql.functionResolution.sessionOrder it captured, or the
default, rather than the session's. The new owner is the one analysis binds, so
a statement that passed only because the check used the session's settings may
now be reported as a real cycle. Rolling back is a revert of the check's
context handling; nothing persisted changes.
**Constraints:** Keep a fresh analysis context for the body being created,
so a CREATE FUNCTION issued inside a procedure CALL still reads the current SQL
path. Inside a nested body, look up an owner in system.builtin or
system.session by its exact identifier, because SessionCatalog's bare-name
lookup orders built-in and temporary functions by the live session path, not
the pinned one. Restore the original analysis context and SQL configuration
after each nested body, as the analyzer's own helpers do, and leave how
analysis itself resolves function bodies unchanged.
**Exclusions:**
- Qualified calls such as session.f() or system.session.f() in a function
body keep the base branch's lookup, since the PR defers them to SPARK-60805.
- One-part calls whose owner lives in a catalog other than spark_catalog
keep falling back to the base branch's bare-name lookup.
**Verification:**
- **Regression:** With the SQL path enabled, create a function g under the
default path whose body calls h, then create functions named h in two schemas,
where only the copy in a schema the session path later lists first calls back
the function being replaced. After setting that path, replacing the function so
its body calls g succeeds, and calling it returns the value from g's own
resolution.
- **Regression:** In the mirrored setup, only the h that g's stored path
resolves to calls back the function being replaced. Replacing the function
fails with CYCLIC_FUNCTION_REFERENCE through that h, and the previous
definition still returns its old value.
- **Regression:** With the SQL path enabled, a persistent function g is
created under a path that puts system.builtin first and calls a built-in name.
The session path later puts system.session first, with a same-named temporary
SQL function that calls back the function being replaced. Replacing that
function with a body that calls g is not reported as a cycle.
- **Regression:** With the SQL path disabled, create g under the default
function resolution order with a body that calls h while only a persistent h
that returns a constant exists, then create a temporary h that calls the
function being replaced. With spark.sql.functionResolution.sessionOrder=last in
the session, replacing that function with a body that calls g fails with
CYCLIC_FUNCTION_REFERENCE through the temporary h, which g's body binds, and
the previous definition still works.
- **Compatibility:** Under sessionOrder=last, under a persistent-first SQL
path, and inside a procedure that sets the path before creating the function,
replacing a function so that its body calls a persistent function that calls it
back, while a same-named temporary function shadows the callee, still fails
with CYCLIC_FUNCTION_REFERENCE for scalar and table functions.
##########
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:
**Nit (P3):** The previous review asked to apply the same rule to
IDENTIFIER-clause variables read inside the default, but there is nothing for
that rule to act on here. While `ResolveFunctions` handles a tagged default,
this wrapper installs a fresh `referredTempVariableNamesUnderIdentifier` set,
and nothing can write to it. The only writer is
`ResolveIdentifierClause.recordTemporaryVariablesUnderIdentifier`
(`ResolveIdentifierClause.scala:169-172`), a separate rule that never runs
inside this wrapper. A parameter default also cannot read a session variable at
all. CREATE FUNCTION rejects a default containing an `UnresolvedAttribute`
(`CreateSQLFunctionCommand.scala:137-143`), and `IDENTIFIER(v)` keeps `v` as
one. So the set is allocated and discarded. Meanwhile, this wrapper's doc and
the `SQLFunction.INSERTED_PARAMETER_DEFAULT` doc tell readers that variables
read by an inserted default are isolated too.
Drop the variable reset and narrow both docs to temporary functions, noting
that a parameter default cannot read a session variable. The temporary-function
half works and should stay.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60213#discussion_r4537919916).
**Verification:**
- **Inspection:** withTempReferencesOfInsertedDefault no longer creates or
installs an IDENTIFIER-variable set, and the documentation of both the wrapper
and the inserted-default tag describes isolation of temporary functions only,
stating that parameter defaults cannot read session variables.
##########
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:
**Non-blocking (P2):** For every one-part call the check visits,
`lookupIdentifier` runs `unqualifiedFunctionOwner` in a new context, which also
discards the per-pass path memo. When no built-in or temporary function owns
the name, which under the default configuration is every call to a persistent
function, the walk ends in `persistentFunctionExists`. For `spark_catalog` that
calls `V2SessionCatalog.functionExists`, then
`SessionCatalog.isPersistentFunction`, which issues
`externalCatalog.databaseExists` and `externalCatalog.functionExists` without
consulting the function registry (`SessionCatalog.scala:2523-2528`). The check
re-expands a nested function body at every call site, so the probes repeat for
each occurrence across the whole transitive call tree.
For example, take loaded persistent functions `p(x INT) RETURN r(x) + r(x +
1)` and `r(x INT) RETURN x`. Then `CREATE FUNCTION f(x INT) RETURNS INT RETURN
p(x) + p(x + 1)` makes six owner walks, about twelve metastore round trips. The
base branch's lookups answered these loaded functions from the registry cache.
Under the default configuration every probe returns the owner that the
bare-name lookup already picks.
Caching the owner for the duration of one `checkCyclicFunctionReference`
call gives the same result with at most one probe per distinct name. Key the
cache by the name and the body being walked, so that an owner computed under
one body's path is never reused for a body that resolves under another.
**Verification:**
- **Behavior:** Creating a function whose body calls persistent SQL
functions several times, directly and through nested functions that repeat
their own calls, issues at most one external-catalog existence check per
distinct called name per body context, observed through a counting external
catalog, and the function is created as before.
- **Compatibility:** With the cache in place, the scalar and table cycle
cases under sessionOrder=last and a persistent-first SQL path, and a nested
body whose stored path differs from the session path, still report the same
CYCLIC_FUNCTION_REFERENCE outcomes.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -306,13 +309,20 @@ object AnalysisContext {
// and must be recorded there. Sharing the caller's set records it; a
nested view, by
// contrast, stores its own and so is reset. The exception is a SQL
function body under
// creation, which must not inherit the dependencies of the functions it
calls; see
- // `shareIdentifierVariablesWithNestedSQLFunctions`.
+ // `shareTempReferencesWithNestedSQLFunctions`.
referredTempVariableNamesUnderIdentifier =
- if (originContext.shareIdentifierVariablesWithNestedSQLFunctions) {
+ if (originContext.shareTempReferencesWithNestedSQLFunctions) {
originContext.referredTempVariableNamesUnderIdentifier
} else {
mutable.LinkedHashSet.empty
},
+ // The same holds for the temporary functions the body binds.
+ referredTempFunctionNames =
+ if (originContext.shareTempReferencesWithNestedSQLFunctions) {
+ originContext.referredTempFunctionNames
Review Comment:
**Nit (P3):** This branch now shares or resets `referredTempFunctionNames`
depending on `shareTempReferencesWithNestedSQLFunctions`. The PR's tests cover
only the reset side, during function creation ('a temp function bound in a
called function's body is not a reference'). The share side, which views and
CACHE TABLE rely on, has no test. No test in the PR, `SQLViewSuite`,
`SQLViewTestSuite`, `create-view.sql` or `sql-udf.sql` creates a view over a
SQL function whose own body binds a temporary function. The view cases in the
named-argument default test exercise the other site,
`withTempReferencesOfInsertedDefault`.
If this condition were inverted or always reset, `CREATE VIEW v AS SELECT
inner_fn()` would be accepted when `inner_fn`'s body calls a name that a
temporary function shadows. The view would then silently depend on whatever
temporary function a later session defines. Add a view case next to that callee
test: a persistent view selecting `inner_fn()` fails with
INVALID_TEMP_OBJ_REFERENCE naming the temporary function, and a temporary view
over the same call lists it in its referred temporary functions.
**Verification:**
- **Regression:** A persistent view that selects a SQL function whose body
binds a temporary function is rejected with INVALID_TEMP_OBJ_REFERENCE naming
that temporary function, a temporary view over the same call lists it among its
referred temporary functions, and a persistent SQL function with the same call
is still created.
##########
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:
**Nit (P3):** Both new cycle tests, this one and 'the cycle check reads the
path the body resolves under', create the persistent functions in `default`,
which is also the current schema. That includes the `SET PATH =
spark_catalog.default, ...` variants. `lookupIdentifier` builds the identifier
from the owning path entry's schema (`CreateSQLFunctionCommand.scala:419-421`),
so a regression that used the current database instead would pass both tests.
Add a path variant: keep `default` as the current schema, run `SET PATH =
spark_catalog.other_db, system.session, system.builtin`, and then create the
persistent functions as `other_db.a` and `other_db.pf`, plus the table-function
pair and same-named temporary functions. Expect CYCLIC_FUNCTION_REFERENCE
naming the `other_db` functions. Creating them after the `SET PATH` stores that
path with them, so the expected cycle holds whether the check reads the session
path or each function's stored path.
**Verification:**
- **Regression:** With the persistent functions created in a schema other
than the current one, under a SQL path that lists that schema first, replacing
a function so that its body calls a persistent function that calls it back,
while a same-named temporary function exists, fails with
CYCLIC_FUNCTION_REFERENCE whose path names the functions in that schema, and
the previous definition still works.
##########
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:
**Nit (P3):** This test covers only the scalar `pf()`. The only persistent
and temporary `pf_tvf` pair is in the cycle test, which fails before the body
is analyzed. Now that CREATE FUNCTION rejects the temporary table functions
that analysis records, accepting `SELECT * FROM pf_tvf()` when a persistent
`pf_tvf` owns the call depends on the table-function candidate walk recording
only the candidate it binds. Suppose that walk, or a future quick check for
table functions, recorded the temporary `pf_tvf` first, which is the problem
this PR fixes in `LookupFunctions` for scalar calls. A valid function would
then fail with INVALID_TEMP_OBJ_REFERENCE, and no test would catch it.
Add a persistent table function and a same-named temporary one here. Under
both `sessionOrder=last` and the persistent-first path, create a persistent
function and a view that select from it, and check that both return the
persistent function's rows.
**Verification:**
- **Regression:** Under sessionOrder=last and under a persistent-first SQL
path, with a persistent table function and a same-named temporary one, a
persistent function and a persistent view that select from the table function
are created and return the persistent function's rows.
--
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]