cloud-fan commented on code in PR #60214:
URL: https://github.com/apache/spark/pull/60214#discussion_r4639303859
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -4716,6 +4716,21 @@ 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
the temporary " +
+ "function references that earlier versions did not detect: an
unqualified call to a " +
+ "temporary table function, a temporary function reached through
another SQL function " +
+ "it calls, a call through an IDENTIFIER clause, and a `session.` call
" +
Review Comment:
**Nit (P3):** This list does not match what the flag restores. It leaves out
a temporary function passed to a table function named through IDENTIFIER, such
as `SELECT * FROM IDENTIFIER('tbl_fn')(temp_fn())`, which the Spark 4.4
migration-guide entry names and which the flag accepts again (the test at
SQLFunctionSuite.scala:767-771 asserts it), and it does not say that the forms
also apply to parameter defaults, as the migration note does.
Both this doc and the migration note also leave out a temporary generator
called through LATERAL VIEW. Reading the code, the parser builds an
`UnresolvedGenerator`, which neither the base nor the new scan matches, and
`ResolveFunctions` resolves it through `SessionCatalog.lookupFunction`
(Analyzer.scala:2585-2592), which now records the temporary function. So with
Hive support, once a temporary Hive UDTF `my_udtf` exists, `CREATE FUNCTION f()
RETURNS TABLE (c INT) RETURN SELECT c FROM t LATERAL VIEW my_udtf(arr) tv AS c`
was created on the base branch, now fails with `INVALID_TEMP_OBJ_REFERENCE`
naming `my_udtf`, and is created again with the flag set, yet neither text
names that form.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60214#discussion_r4562533455).
**Verification:**
- **Inspection:** The doc of
spark.sql.legacy.allowTempFunctionInPersistedSQLFunction and the Spark 4.4
migration-guide entry for it list the same newly rejected forms, including a
temporary function passed to a table function named through IDENTIFIER, a
temporary generator called through LATERAL VIEW, and `session.`-qualified
temporary references in table-function arguments, CTE definitions, and
table-function parameter defaults, and both state that the forms apply in
parameter defaults.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala:
##########
@@ -401,13 +432,97 @@ case class CreateSQLFunctionCommand(
(collectTempViews(child), tempFunctions)
}
+ private def legacyTempFunctionCheck: Boolean =
+ conf.getConf(SQLConf.LEGACY_ALLOW_TEMP_FUNCTION_IN_PERSISTED_SQL_FUNCTION)
+
+ // The name an IDENTIFIER clause evaluates to, resolved and evaluated as the
body's analysis
+ // did. None when it is not a constant string.
+ private def identifierNameParts(analyzer: Analyzer, expr: Expression):
Option[Seq[String]] =
+ try {
+ val resolved = if (expr.resolved) {
+ Some(expr)
+ } else {
+ // A fresh context keeps the names its lookups record out of this
statement's context.
+ AnalysisContext.withNewAnalysisContext {
+ analyzer.execute(Project(Seq(Alias(expr, "name")()),
OneRowRelation()))
+ } match {
+ case Project(Seq(a: Alias), _) if a.resolved => Some(a.child)
+ case _ => None
+ }
+ }
+ resolved.map(IdentifierResolution.evalIdentifierExpr)
+ } catch {
+ case _: AnalysisException => None
+ }
+
+ // A same-named temp table function does not count: the scalar call then
reaches a built-in or
+ // persistent function, or fails analysis.
+ private def isTemporaryScalarFunctionName(
+ catalog: SessionCatalog,
+ nameParts: Seq[String]): Boolean =
+ isTemporaryFunctionName(catalog, nameParts,
catalog.isTemporaryScalarFunctionVisible)
+
+ private def isTemporaryTableFunctionName(
+ catalog: SessionCatalog,
+ nameParts: Seq[String]): Boolean =
+ isTemporaryFunctionName(catalog, nameParts,
catalog.isTemporaryTableFunctionVisible)
+
+ // Whether `nameParts` (unqualified, or `session.` /
`system.session.`-qualified) names a temp
+ // function that `isTemp` accepts.
+ private def isTemporaryFunctionName(
+ catalog: SessionCatalog,
+ nameParts: Seq[String],
+ isTemp: FunctionIdentifier => Boolean): Boolean =
+ nameParts match {
+ case Seq(funcName) => isTemp(FunctionIdentifier(funcName))
+ // Check the in-memory registry first: the lookup may probe the
metastore.
+ case _ =>
+ catalog.identifierFromSystemNameParts(nameParts).exists(isTemp) &&
Review Comment:
**Non-blocking (P2):** With
`spark.sql.legacy.allowTempFunctionInPersistedSQLFunction` set, this qualified
check still runs wherever the scan walks, so the flag does not restore some
bodies the base branch created. 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`, with no schema named `session` and the
flag set:
```sql
-- base branch and 4.3.0: created; this PR with the flag set:
INVALID_TEMP_OBJ_REFERENCE
CREATE FUNCTION p() RETURNS TABLE (a INT) RETURN SELECT * FROM
tbl_fn(session.temp_fn());
CREATE FUNCTION q() RETURNS INT
RETURN (WITH c AS (SELECT session.temp_fn() AS a) SELECT a FROM c);
CREATE FUNCTION r(x INT DEFAULT session.temp_fn()) RETURNS TABLE (a INT)
RETURN SELECT x;
```
The same holds for `SELECT * FROM session.temp_tbl()` or `SELECT * FROM
system.session.temp_tbl()` inside a CTE definition. On the base branch such a
qualified call failed only in the cyclic check, with `SCHEMA_NOT_FOUND` or
`IDENTIFIER_TOO_MANY_NAME_PARTS`. That check never visits table-function
arguments, CTE definitions or a table function's parameter defaults, and the
base scan never looked at table-function names and treated a
`session.`-qualified scalar name as not temporary.
The affected forms are the ones in those positions, including anything
nested in them: a two-part `session.` temporary scalar or table-function call
when no persistent function of that name exists in a schema named `session`,
and a three-part `system.session.` temporary table-function call. Rejecting
them by default is correct, because such a function fails, or binds another
session's function, elsewhere. What is missing is the rollback that the PR
describes for every newly rejected form, and the migration note does not name
these forms. The legacy-mode rejection list in the tests has only top-level
calls, which the base branch also rejected.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60214#discussion_r4562533446).
See **Shared repair plan 1** in the review body.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/SQLFunctionSuite.scala:
##########
@@ -534,4 +534,469 @@ 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 name qualified with `builtin.` 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_mid" -> false, "perm_legacy_outer" -> 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))
+ }
+ sql("CREATE FUNCTION perm_mid() RETURNS INT RETURN (SELECT a FROM
temp_tbl())")
+ 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))
+ }
+ // So is a call to a function that depends on one.
+ sql("CREATE FUNCTION perm_legacy_outer() RETURNS INT RETURN
perm_legacy()")
+ checkAnswer(sql("SELECT perm_legacy_outer()"), Row(1))
+ Seq(
Review Comment:
**Nit (P3):** This is the only list of bodies the legacy flag must still
reject, and every entry is a top-level call. With the flag set,
`verifyTemporaryObjectsNotExists` drops the record of bound temporary functions
(CreateSQLFunctionCommand.scala:545), so the rewritten scan alone rejects a
temporary reference: the new `UnresolvedTableValuedFunction` case, which must
scan `functionArgs` itself, and the subquery, CTE and parameter-default
recursion. The default-mode tests of those nested forms, such as
`tbl_fn(temp_fn())` and parameter defaults, are also caught by the record.
Reading the code, if the scan stopped descending, then with the flag set
`SELECT * FROM tbl_fn(temp_fn())`, `(SELECT temp_fn())`, `(WITH c AS (SELECT
temp_fn() AS a) SELECT a FROM c)` and `x INT DEFAULT temp_fn()` would be
created, though the base branch rejects each, and no test would fail.
See **Shared repair plan 1** in the review body.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala:
##########
@@ -374,24 +376,53 @@ case class CreateSQLFunctionCommand(
}.distinct
}
- def collectTempFunctions(child: LogicalPlan): Seq[String] = {
+ // With `followPath`, an unqualified name counts only when the SQL PATH
resolves it to the temp
+ // function. Calls that an IDENTIFIER clause builds use it, as earlier
versions accepted them.
+ def isTempScalarCall(nameParts: Seq[String], followPath: Boolean): Boolean
=
+ isTemporaryScalarFunctionName(catalog, nameParts) &&
+ (!followPath || nameParts.length > 1 ||
+ analyzer.unqualifiedFunctionResolvesToTemp(nameParts.head))
+
+ def collectInExpression(expr: Expression, followPath: Boolean):
Seq[String] = expr.flatMap {
+ case e: SubqueryExpression => collectTempFunctions(e.plan, followPath)
+ case e: UnresolvedFunction if isTempScalarCall(e.nameParts, followPath)
=>
+ Seq(e.nameParts.last)
+ // An IDENTIFIER-clause call: check the call it builds from its constant
name.
+ case e: ExpressionWithUnresolvedIdentifier if !legacyTempFunctionCheck =>
Review Comment:
**Nit (P3):** Now that the record of bound temporary functions also holds
scalar functions, it already rejects what this case checks. Reading the code,
every resolution path that builds a temporary function goes through
`resolveScalarFunctionByIdentifier` or `resolveTableFunctionByIdentifier`,
which record it, including calls that an IDENTIFIER clause builds and the
arguments of a table function named through IDENTIFIER, and a called SQL
function's expansion shares the same set. So `IDENTIFIER(concat('temp',
'_fn'))()`, `IDENTIFIER('session.temp_fn')()` and `SELECT * FROM
IDENTIFIER('tbl_fn')(temp_fn())` are rejected by the record under the same
name, while a call that the SQL PATH sends to a persistent function is recorded
by neither.
This case and the `PlanWithUnresolvedIdentifier` case run only with
`spark.sql.legacy.allowTempFunctionInPersistedSQLFunction` off, when the record
is rejected too, so no outcome depends on them. They still analyze a
non-literal IDENTIFIER name a second time, after the body's analysis, and need
`identifierNameParts`, the `followPath` parameter and the `builtinMustExist`
variant of `unqualifiedFunctionResolvesToTemp`. Because the name is evaluated
again, the check can see a different call than analysis did, for example when
another thread runs `SET VAR` on the same session in between under
`spark.sql.legacy.allowSessionVariableInPersistedView`; then it can only reject
a body that does not depend on a temporary function. No test can tell whether
these cases work, because the record also catches every IDENTIFIER rejection
the tests assert.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60214#discussion_r4562533434),
[2](https://github.com/apache/spark/pull/60214#discussion_r4598115412).
**Verification:**
- **Compatibility:** By default, persistent functions that call a temporary
function through IDENTIFIER with a literal or function-built name, or pass one
to a table function named through IDENTIFIER, still fail with
INVALID_TEMP_OBJ_REFERENCE naming it; under a SQL PATH that lists a schema
holding a same-named persistent function before system.session, the same bodies
are created; IDENTIFIER('abs')(-1) with a temporary table function named abs is
created; and with the legacy flag set the IDENTIFIER forms are created.
- **Inspection:** The temporary-function scan in CREATE FUNCTION has no case
specific to IDENTIFIER clauses and runs the analyzer no second time, and
FunctionResolution.unqualifiedFunctionResolvesToTemp takes no builtinMustExist
option.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala:
##########
@@ -387,6 +390,41 @@ case class CreateSQLFunctionCommand(
(collectTempViews(child), tempFunctions)
}
+ // 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))
+ case _ => functionIdentifierForLookup(catalog, nameParts).exists {
+ case (ident, isSystem) => isSystem &&
catalog.isTemporaryFunction(ident)
+ }
+ }
+
+ // 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)
+ // Catalog names are case-insensitive regardless of
spark.sql.caseSensitive.
+ case Seq(c, db, f) if
c.equalsIgnoreCase(CatalogManager.SESSION_CATALOG_NAME) =>
+ Some(FunctionIdentifier(f, Some(db),
Some(CatalogManager.SESSION_CATALOG_NAME)))
+ case _ => None
+ }
+ def systemFunctionExists(ident: FunctionIdentifier): Boolean =
+ catalog.lookupFunctionInfoByIdentifier(ident, tableFunction =
false).isDefined ||
+ catalog.lookupFunctionInfoByIdentifier(ident, tableFunction =
true).isDefined
+ catalog.identifierFromSystemNameParts(nameParts) match {
+ case Some(ident) if nameParts.length > 2 ||
+ (conf.prioritizeSystemCatalog && systemFunctionExists(ident)) ||
+ !catalog.isPersistentFunction(persistentIdent.get) =>
Review Comment:
Thanks, the temporary-function check now looks at the in-memory registries
first, and `persistentFunctionExists` checks the function registry before the
metastore. One part is still open in the cyclic check: for a `builtin.` or
`session.` call that falls back to a persistent function not yet in the
registry, `functionIdentifierForLookup` calls `isPersistentFunction`
(`databaseExists` plus `functionExists`), and `sqlFunctionIdentifier` then
calls `lookupFunctionInfo` for the same function. That is about two extra
metastore calls for each such function, and at every call site of a persistent
function that is not a SQL function, since the cyclic check never registers
those; the base branch made only the `lookupFunctionInfo` call. Having the
cyclic check try `lookupFunctionInfo` on the persistent identifier once, and
fall back to the system namespace when it reports the schema or function
missing, would keep the same results with a single lookup.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4537918937","thread_id":"inline:4537918937","verdict_sha256":"6f530f99f70fb9878cab8bf2e062f1e4fea7dc2599b8c5dc62aae0e6d421589e"}
-->
--
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]