cloud-fan commented on code in PR #60214:
URL: https://github.com/apache/spark/pull/60214#discussion_r4562533434
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala:
##########
@@ -360,24 +362,43 @@ case class CreateSQLFunctionCommand(
}.distinct
}
+ def collectInExpression(expr: Expression): Seq[String] = expr.flatMap {
+ case e: SubqueryExpression => collectTempFunctions(e.plan)
+ case e: UnresolvedFunction if isTemporaryFunctionName(catalog,
e.nameParts) =>
+ Seq(e.nameParts.last)
+ // An IDENTIFIER-clause call with a constant name: check the call it
builds. The body
+ // has already been analyzed, so the name evaluates.
+ case e: ExpressionWithUnresolvedIdentifier
+ if !legacyTempFunctionCheck && e.identifierExpr.resolved =>
Review Comment:
**Non-blocking (P2):** This guard holds only for literal-only names. In the
parsed body this scan reads, `IDENTIFIER(concat('temp', '_fn'))()` still has
`concat(...)` as an `UnresolvedFunction`, so `e.identifierExpr.resolved` is
false and the arm is skipped. Analysis later resolves and evaluates the same
expression (`ResolveIdentifierClause`), and the call binds the temporary scalar
function. The recorded names don't catch it either, because
`verifyTemporaryObjectsNotExists` keeps only temporary table functions.
Reading the code, after `CREATE TEMPORARY FUNCTION temp_fn() RETURNS INT
RETURN 1`, `CREATE FUNCTION perm_fn() RETURNS INT RETURN
IDENTIFIER(concat('temp', '_fn'))()` is created, while the same body written
`IDENTIFIER('temp_fn')()` fails with `INVALID_TEMP_OBJ_REFERENCE`. The stored
function then fails in any session without `temp_fn`, or calls that session's
own `temp_fn`. Function-built IDENTIFIER names are a supported form
(identifier-clause.sql calls `IDENTIFIER(concat('COAL', 'ESCE'))(NULL, 1)`),
and the new tests use only string literals.
**Recommended change:** In the IDENTIFIER arm of collectInExpression
(CreateSQLFunctionCommand.scala:369-378), when the identifier expression is not
resolved in the parsed body, resolve it with the session analyzer before
evaluating it, for example by analyzing a one-column projection of the
expression over a single-row relation. When the result is a foldable string,
evaluate it and check the call it builds with isTemporaryFunctionName, as the
arm already does for literal names. Reword the comment at
CreateSQLFunctionCommand.scala:369-370 to say that the name is resolved and
evaluated as analysis evaluated it. Add SQL function creation tests for
IDENTIFIER names built by a function call.
**Why this works:** The body's own analysis already resolved and evaluated
each IDENTIFIER expression to a constant name, so resolving the same expression
on its own gives the same constant. Evaluating it lets the arm build and check
the same call for every constant IDENTIFIER name, not only literal-only ones.
The legacy flag still skips the arm, so setting it restores the base-branch
acceptance.
**Risks:** A persistent body whose IDENTIFIER name comes from a session
variable, accepted today under
spark.sql.legacy.allowSessionVariableInPersistedView, is rejected when that
name resolves to a temporary scalar function, unless
spark.sql.legacy.allowTempFunctionInPersistedSQLFunction is also set. This
matches the migration-guide statement that such calls fail. Without
spark.sql.legacy.allowSessionVariableInPersistedView, a body that calls a
temporary scalar function through IDENTIFIER(var) still fails with
INVALID_TEMP_OBJ_REFERENCE, but the error now names the temporary function
instead of the variable, because temporary functions are checked first.
**Constraints:** Resolve the identifier expression in a fresh analysis
context, so that names its lookups record do not reach the context of the
statement running CREATE FUNCTION. Call IdentifierResolution.evalIdentifierExpr
only on a resolved, foldable string expression, because it fails on any other
expression.
**Exclusions:**
- The cyclic-reference check still does not follow IDENTIFIER-built calls,
as on the base branch.
- A temporary scalar function reached only through another SQL function the
body calls stays accepted, as on the base branch.
**Verification:**
- **Regression:** After creating a temporary scalar function temp_fn, a
persistent function whose body calls it through IDENTIFIER(concat('temp',
'_fn'))() or IDENTIFIER(lower('TEMP_FN'))() fails with
INVALID_TEMP_OBJ_REFERENCE naming temp_fn, and a temporary function with the
same body is created and returns temp_fn's result.
- **Compatibility:** With
spark.sql.legacy.allowTempFunctionInPersistedSQLFunction set, the same
persistent bodies are created. Literal IDENTIFIER names keep their current
outcomes, and a persistent body whose function-built IDENTIFIER name resolves
to a built-in function, such as IDENTIFIER(concat('ab', 's'))(-1), is created
and returns the built-in's result.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala:
##########
@@ -387,13 +408,56 @@ case class CreateSQLFunctionCommand(
(collectTempViews(child), tempFunctions)
}
+ private def legacyTempFunctionCheck: Boolean =
+ conf.getConf(SQLConf.LEGACY_ALLOW_TEMP_FUNCTION_IN_PERSISTED_SQL_FUNCTION)
+
+ // Whether `nameParts` (unqualified, or `session.` /
`system.session.`-qualified) names a temp
+ // function.
+ private def isTemporaryFunctionName(catalog: SessionCatalog, nameParts:
Seq[String]): Boolean =
+ nameParts match {
+ case Seq(funcName) =>
catalog.isTemporaryFunction(FunctionIdentifier(funcName))
+ // Check the in-memory registry first: the lookup may probe the
metastore.
+ case _ =>
+
catalog.identifierFromSystemNameParts(nameParts).exists(catalog.isTemporaryFunction)
&&
Review Comment:
**Non-blocking (P2):** With the legacy flag set, this case still flags a
`session.<f>` call whenever a temporary `<f>` exists, even when a persistent
`spark_catalog.session.<f>` exists too. The base branch and 4.3.0 accepted that
body: there, `isTemporaryFunction(FunctionIdentifier("sf", Some("session")))`
is false because `isTempFunctionIdentifier` requires the `system` catalog, and
the cyclic check followed the persistent `session.sf`. 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: created; this PR: INVALID_TEMP_OBJ_REFERENCE
CREATE FUNCTION perm_sf() RETURNS INT RETURN session.sf();
```
The table form, `SELECT * FROM session.pt()` with a persistent `session.pt`
and a temporary `pt`, behaves the same. This is the `session.f()` case that the
previous review's decision challenge named: the flag added since re-allows the
other forms but not this one, and the comment at
CreateSQLFunctionCommand.scala:393 says earlier versions rejected it. None of
the legacy-flag tests uses a schema named `session`. Keeping three-part
`system.session.<f>` calls rejected is fine, since the base branch rejected
every three-part name.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60214#issuecomment-6798916093).
**Verification:**
- **Regression:** With
spark.sql.legacy.allowTempFunctionInPersistedSQLFunction set, a schema named
session holding a scalar function sf and a table function pt, and temporary
functions sf and pt, persistent bodies that call session.sf() and SELECT * FROM
session.pt() are created. Without the flag, both fail with
INVALID_TEMP_OBJ_REFERENCE.
- **Compatibility:** With the flag set and no schema named session,
persistent bodies that call session.temp_fn(), system.session.temp_fn(),
session.temp_tbl() and system.session.temp_tbl() still fail with
INVALID_TEMP_OBJ_REFERENCE, and the existing default-mode and
persistentCatalogFirst cases keep their results.
- **Inspection:** The flag's doc, the Spark 4.4 migration-guide entry, and
the comments at CreateSQLFunctionCommand.scala:392-393 and
SQLFunctionSuite.scala:622 no longer say that earlier versions rejected every
qualified call, and each covers the case of a session.<f> call backed by a
same-named persistent function.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -4600,6 +4600,18 @@ object SQLConf {
.booleanConf
.createWithDefault(false)
+ val LEGACY_ALLOW_TEMP_FUNCTION_IN_PERSISTED_SQL_FUNCTION =
+ buildConf("spark.sql.legacy.allowTempFunctionInPersistedSQLFunction")
+ .internal()
+ .doc("When true, CREATE FUNCTION for a persistent SQL function accepts a
body that calls " +
Review Comment:
**Nit (P3):** With the flag set, `tempTableFunctions` is `Nil`
(CreateSQLFunctionCommand.scala:481-482), so names recorded while expanding a
called SQL function are dropped too. A body such as `SELECT * FROM
perm_legacy_tbl()`, where `perm_legacy_tbl` reads a temporary `temp_tbl`, is
rejected without the flag (SQLFunctionSuite.scala:647-653) and accepted with
it. The migration-guide entry lists this case among the forms the flag
restores, but this doc does not, so a reader of the config would conclude that
it stays rejected. Adding a clause such as "or that depends on a temporary
table function through another SQL function it calls" would make the two agree.
**Verification:**
- **Inspection:** The doc of
spark.sql.legacy.allowTempFunctionInPersistedSQLFunction names the transitive
case, a temporary table function reached through another SQL function the body
calls, and describes the same restored forms as the Spark 4.4 migration-guide
entry for the flag.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala:
##########
@@ -387,13 +408,56 @@ case class CreateSQLFunctionCommand(
(collectTempViews(child), tempFunctions)
}
+ private def legacyTempFunctionCheck: Boolean =
+ conf.getConf(SQLConf.LEGACY_ALLOW_TEMP_FUNCTION_IN_PERSISTED_SQL_FUNCTION)
+
+ // Whether `nameParts` (unqualified, or `session.` /
`system.session.`-qualified) names a temp
+ // function.
+ private def isTemporaryFunctionName(catalog: SessionCatalog, nameParts:
Seq[String]): Boolean =
+ nameParts match {
+ case Seq(funcName) =>
catalog.isTemporaryFunction(FunctionIdentifier(funcName))
+ // Check the in-memory registry first: the lookup may probe the
metastore.
+ case _ =>
+
catalog.identifierFromSystemNameParts(nameParts).exists(catalog.isTemporaryFunction)
&&
+ functionIdentifierForLookup(catalog, nameParts).exists(_._2)
+ }
+
+ // The identifier to look up `nameParts` by, and whether it is in a system
namespace. A
+ // `builtin.` / `session.` name follows function resolution's candidate
order. None for another
+ // catalog's function.
+ private def functionIdentifierForLookup(
+ catalog: SessionCatalog,
+ nameParts: Seq[String]): Option[(FunctionIdentifier, Boolean)] = {
+ lazy val persistentIdent = nameParts match {
+ case Seq(_) | Seq(_, _) => Some(nameParts.asFunctionIdentifier)
+ // The session catalog name is case-insensitive even with
spark.sql.caseSensitive=true.
+ case Seq(c, db, f) if
c.equalsIgnoreCase(CatalogManager.SESSION_CATALOG_NAME) =>
+ Some(FunctionIdentifier(f, Some(db),
Some(CatalogManager.SESSION_CATALOG_NAME)))
+ case _ => None
Review Comment:
**Nit (P3):** This arm is what lets a body such as `RETURN testcat.ns.f()`
reach analysis instead of failing with `IDENTIFIER_TOO_MANY_NAME_PARTS`, as it
did on the base branch. The new tests use three-part names only with
`spark_catalog` and `system`, and no SQL function body in `SQLFunctionSuite`,
`DataSourceV2FunctionSuite` or `sql-udf.sql` calls another catalog's function,
so a regression here would go unnoticed. A case with a registered function
catalog, or even a catalog name that does not exist, asserting that CREATE
FUNCTION gets the same outcome as the same call in a query would pin it.
**Verification:**
- **Behavior:** CREATE FUNCTION with a body that calls a function by a
three-part name in a catalog other than spark_catalog either succeeds, when the
same call works in a query, or fails with the error the same query reports, and
never with IDENTIFIER_TOO_MANY_NAME_PARTS.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala:
##########
@@ -174,8 +174,8 @@ case class CreateSQLFunctionCommand(
checkCyclicFunctionReference(catalog, name, plan)
// Check the function body can be analyzed correctly.
- val (analyzed, referredTempVarsUnderIdentifier) =
- analyzer.executeWithReferredTempVariablesUnderIdentifier(plan)
+ val (analyzed, referredTempVarsUnderIdentifier, referredTempFunctions)
=
Review Comment:
**Nit (P3):** This forwarding has no failure signal. Every test that depends
on recorded names creates a `RETURNS TABLE` function
(SQLFunctionSuite.scala:613, the IDENTIFIER loop at
SQLFunctionSuite.scala:689-703, and `perm_outer` at
SQLFunctionSuite.scala:647-653). The only scalar body over a temporary table
function, `RETURN (SELECT a FROM session.temp_tbl())` at
SQLFunctionSuite.scala:617, is caught by the qualified-name arm instead. If
this branch passed `Nil`, `CREATE FUNCTION f() RETURNS INT RETURN (SELECT a
FROM temp_tbl())` would be accepted again without any test failing. Scalar
cases for an unqualified call, for `IDENTIFIER('temp_tbl')()`, and for a call
through a persistent table function that reads `temp_tbl` would cover it.
**Verification:**
- **Regression:** A persistent scalar function whose body reads an
unqualified temporary table function in a scalar subquery fails with
INVALID_TEMP_OBJ_REFERENCE naming that table function, and so do bodies that
reach it through IDENTIFIER('temp_tbl')() or through a called persistent table
function that depends on it. A temporary scalar function with the unqualified
body is created.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala:
##########
@@ -432,14 +506,28 @@ case class CreateSQLFunctionCommand(
identifier: FunctionIdentifier,
plan: LogicalPlan): Unit = {
+ // Returns `functionIdentifierForLookup`'s result when `nameParts` names a
SQL function, and
+ // None otherwise.
Review Comment:
**Nit (P3):** For a name outside the system namespace, line 517 calls
`lookupFunctionInfo`, which assumes the function exists
(SessionCatalog.scala:2882) and throws for a missing name such as `nope()`. So
this helper does not return `None` for every name that is not a SQL function;
only the system branch at lines 515-516 returns `None` for a missing function.
```suggestion
// Returns `functionIdentifierForLookup`'s result when `nameParts` names
a SQL function, and
// None otherwise, except that a missing function outside the system
namespace makes the
// lookup throw.
```
**Verification:**
- **Inspection:** The comment on sqlFunctionIdentifier no longer says it
returns None for every name that is not a SQL function, and states that the
persistent lookup throws for a name that does not exist.
--
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]