ganeshashree commented on code in PR #60214:
URL: https://github.com/apache/spark/pull/60214#discussion_r4640985715
##########
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:
Done.
##########
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:
Done, both texts now state the rule once and give examples.
##########
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:
Done. `tbl_fn(session.temp_fn())` stays rejected, though: the base branch's
cyclic check expands a SQL `tbl_fn` together with its arguments, so it failed
there too.
##########
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:
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]