srielau commented on code in PR #59874:
URL: https://github.com/apache/spark/pull/59874#discussion_r4632733541


##########
sql/core/src/test/scala/org/apache/spark/sql/catalyst/expressions/ParseSqlAnalyzeSuite.scala:
##########
@@ -921,6 +1202,767 @@ class ParseSqlAnalyzeSuite extends QueryTest with 
SharedSparkSession {
     }
   }
 
+  test("ANALYZE current_schema applies to one call and leaves the session 
unchanged") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      sql("CREATE DATABASE parse_sql_per_call_a")
+      sql("CREATE DATABASE parse_sql_per_call_b")
+      try {
+        sql("CREATE TABLE parse_sql_per_call_a.t (a INT) USING parquet")
+        sql("CREATE TABLE parse_sql_per_call_b.t (a STRING) USING parquet")
+        val before = spark.catalog.currentDatabase
+        val inA = evalCall(
+          "SELECT parse_sql('SELECT a FROM t', 'ANALYZE', NULL, 
'parse_sql_per_call_a')")
+        val inB = evalCall(
+          "SELECT parse_sql('SELECT a FROM t', 'ANALYZE', NULL, 
'parse_sql_per_call_b')")
+        assert(inA.head \ "analyze_success" === JBool(true))
+        assert(inA.head \ "source_table_references" === JArray(List(
+          ref("spark_catalog", "parse_sql_per_call_a", "t"))))
+        assert(inA.head \ "select_list" === typedColumns("a" -> jsonInt))
+        assert(inB.head \ "analyze_success" === JBool(true))
+        assert(inB.head \ "source_table_references" === JArray(List(
+          ref("spark_catalog", "parse_sql_per_call_b", "t"))))
+        assert(inB.head \ "select_list" === typedColumns("a" -> jsonString))
+        assert(spark.catalog.currentDatabase === before)
+      } finally {
+        sql("DROP DATABASE IF EXISTS parse_sql_per_call_a CASCADE")
+        sql("DROP DATABASE IF EXISTS parse_sql_per_call_b CASCADE")
+      }
+    }
+  }
+
+  test("ANALYZE of a missing current_schema is an error and keeps the 
session") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      val before = spark.catalog.currentDatabase
+      intercept[NoSuchNamespaceException] {
+        spark.sql("SELECT parse_sql('SELECT a FROM t', 'ANALYZE', NULL, " +
+          "'parse_sql_per_call_missing')").collect()
+      }
+      assert(spark.catalog.currentDatabase === before)
+    }
+  }
+
+  test("ANALYZE current_schema does not change the invoker's later 
resolution") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      sql("CREATE DATABASE parse_sql_per_call_c")
+      try {
+        sql("CREATE TABLE parse_sql_per_call_c.t (a INT) USING parquet")
+        val overridden = evalCall(
+          "SELECT parse_sql('SELECT a FROM t', 'ANALYZE', NULL, 
'parse_sql_per_call_c')")
+        assert(overridden.head \ "analyze_success" === JBool(true))
+        // A later call with no context still resolves against the invoker's 
database.
+        val inherited = evalStatement("SELECT a FROM t")
+        assert(inherited \ "analyze_success" === JBool(false))
+      } finally {
+        sql("DROP DATABASE IF EXISTS parse_sql_per_call_c CASCADE")
+      }
+    }
+  }
+
+  test("ANALYZE current_catalog matches the session catalog in any case") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      sql("CREATE DATABASE parse_sql_per_call_d")
+      try {
+        sql("CREATE TABLE parse_sql_per_call_d.t (a INT) USING parquet")
+        val result = evalCall(
+          "SELECT parse_sql('SELECT a FROM t; SELECT a FROM 
parse_sql_missing_t', " +
+            "'ANALYZE', 'SPARK_CATALOG', 'parse_sql_per_call_d')")
+        assert(result.head \ "analyze_success" === JBool(true))
+        assert(result.head \ "source_table_references" === JArray(List(
+          ref("spark_catalog", "parse_sql_per_call_d", "t"))))
+        // A statement that fails analysis is still qualified with the call's 
schema.
+        assert(result(1) \ "analyze_success" === JBool(false))
+        assert(result(1) \ "source_table_references" === JArray(List(
+          ref("spark_catalog", "parse_sql_per_call_d", 
"parse_sql_missing_t"))))
+      } finally {
+        sql("DROP DATABASE IF EXISTS parse_sql_per_call_d CASCADE")
+      }
+    }
+  }
+
+  test("ANALYZE current_schema qualifies persistent function references with 
the call") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      sql("CREATE DATABASE parse_sql_per_call_e")
+      try {
+        sql("CREATE FUNCTION parse_sql_per_call_e.parse_sql_f() RETURNS INT 
RETURN 1")
+        val result = evalCall(
+          "SELECT parse_sql('SELECT parse_sql_f() AS x', 'ANALYZE', NULL, " +
+            "'parse_sql_per_call_e')")
+        assert(result.head \ "analyze_success" === JBool(true), result)
+        assert(result.head \ "function_references" === JArray(List(
+          ref("spark_catalog", "parse_sql_per_call_e", "parse_sql_f"))))
+      } finally {
+        sql("DROP DATABASE IF EXISTS parse_sql_per_call_e CASCADE")
+      }
+    }
+  }
+
+  test("ANALYZE current_path expands PATH to the invoker's path") {
+    withSQLConf(
+        SQLConf.PARSE_SQL_ENABLED.key -> "true",
+        SQLConf.PATH_ENABLED.key -> "true") {
+      sql("CREATE DATABASE parse_sql_per_call_f")
+      try {
+        sql("CREATE TABLE parse_sql_per_call_f.parse_sql_path_t (a INT) USING 
parquet")
+        sql("SET PATH = spark_catalog.parse_sql_per_call_f, system.builtin")
+        val result = evalCall(
+          "SELECT parse_sql('SELECT a FROM parse_sql_path_t', 'ANALYZE', " +
+            "current_path => 'PATH, system.session')")
+        assert(result.head \ "analyze_success" === JBool(true), result)
+        assert(result.head \ "source_table_references" === JArray(List(
+          ref("spark_catalog", "parse_sql_per_call_f", "parse_sql_path_t"))))
+      } finally {
+        sql("SET PATH = DEFAULT_PATH")
+        sql("DROP DATABASE IF EXISTS parse_sql_per_call_f CASCADE")
+      }
+    }
+  }
+
+  test("ANALYZE current_path qualifies a persistent function found on the 
path") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      sql("CREATE DATABASE parse_sql_per_call_g")
+      try {
+        sql("CREATE FUNCTION parse_sql_per_call_g.parse_sql_g() RETURNS INT 
RETURN 1")
+        val result = evalCall(
+          "SELECT parse_sql('SELECT parse_sql_g() AS x', 'ANALYZE', " +
+            "current_path => 'system.builtin, 
SPARK_CATALOG.PARSE_SQL_PER_CALL_G')")
+        assert(result.head \ "analyze_success" === JBool(true), result)
+        assert(result.head \ "function_references" === JArray(List(
+          ref("spark_catalog", "parse_sql_per_call_g", "parse_sql_g"))))
+      } finally {
+        sql("DROP DATABASE IF EXISTS parse_sql_per_call_g CASCADE")
+      }
+    }
+  }
+
+  test("ANALYZE current_path orders a temp function before a builtin of the 
same name") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      spark.udf.register("upper", (s: String) => s.length)
+      try {
+        val builtinFirst = evalCall(
+          "SELECT parse_sql('SELECT upper(''a'') AS x', 'ANALYZE', " +
+            "current_path => 'system.builtin, system.session')")
+        assert(builtinFirst.head \ "select_list" === typedColumns("x" -> 
jsonString),
+          builtinFirst)
+        assert(builtinFirst.head \ "function_references" === JArray(List(
+          ref("system", "builtin", "upper"))))
+        val sessionFirst = evalCall(
+          "SELECT parse_sql('SELECT upper(''a'') AS x', 'ANALYZE', " +
+            "current_path => 'system.session, system.builtin')")
+        assert(sessionFirst.head \ "select_list" === typedColumns("x" -> 
jsonInt),
+          sessionFirst)
+        assert(sessionFirst.head \ "function_references" === JArray(List(
+          ref("system", "session", "upper"))))
+      } finally {
+        spark.sessionState.catalog.dropTempFunction("upper", ignoreIfNotExists 
= true)
+      }
+    }
+  }
+
+  test("ANALYZE overlays do not replace a temp view read by a temp view") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      withTempView("parse_sql_tv_base", "parse_sql_tv_outer") {
+        sql("CREATE TEMPORARY VIEW parse_sql_tv_base AS SELECT 1 AS a")
+        sql("CREATE TEMPORARY VIEW parse_sql_tv_outer AS SELECT * FROM 
parse_sql_tv_base")
+        val result = evalCall(
+          "SELECT parse_sql('SELECT * FROM parse_sql_tv_outer; SELECT * FROM 
parse_sql_tv_base', " +
+            "'ANALYZE', relations => array(named_struct(" +
+            "'name', 'system.session.parse_sql_tv_base', 'schema', 'b 
STRING')))")
+        assert(result.head \ "select_list" === typedColumns("a" -> jsonInt), 
result)
+        assert(result(1) \ "select_list" === typedColumns("b" -> jsonString), 
result)
+      }
+    }
+  }
+
+  test("ANALYZE overlays do not replace a session variable read by a temp 
view") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      sql("DECLARE VARIABLE parse_sql_view_var INT DEFAULT 1")
+      try {
+        withTempView("parse_sql_var_v") {
+          sql("CREATE TEMPORARY VIEW parse_sql_var_v AS SELECT 
parse_sql_view_var AS x")
+          val result = evalCall(
+            "SELECT parse_sql('SELECT x FROM parse_sql_var_v; SELECT 
parse_sql_view_var AS y', " +
+              "'ANALYZE', variables => array(named_struct(" +
+              "'name', 'parse_sql_view_var', 'type', 'STRING')))")
+          assert(result.head \ "select_list" === typedColumns("x" -> jsonInt), 
result)
+          assert(result(1) \ "select_list" === typedColumns("y" -> 
jsonString), result)
+        }
+      } finally {
+        sql("DROP TEMPORARY VARIABLE IF EXISTS parse_sql_view_var")
+      }
+    }
+  }
+
+  test("ANALYZE overlays do not replace a table read by a SQL function body") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      withTable("parse_sql_fn_base") {
+        withUserDefinedFunction("parse_sql_fn" -> false) {
+          sql("CREATE TABLE parse_sql_fn_base (a INT) USING parquet")
+          sql("CREATE FUNCTION parse_sql_fn() RETURNS TABLE (a INT) " +
+            "RETURN SELECT a FROM parse_sql_fn_base")
+          val result = evalCall(
+            "SELECT parse_sql('SELECT a FROM parse_sql_fn()', 'ANALYZE', " +
+              "relations => array(named_struct(" +
+              "'name', 'spark_catalog.default.parse_sql_fn_base', 'schema', 'b 
STRING')))")
+          assert(result.head \ "analyze_success" === JBool(true), result)
+          assert(result.head \ "select_list" === typedColumns("a" -> jsonInt), 
result)
+        }
+      }
+    }
+  }
+
+  test("ANALYZE overlays do not replace a table read by a scalar SQL function 
body") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      withTable("parse_sql_sfn_base") {
+        withUserDefinedFunction("parse_sql_sfn" -> false) {
+          sql("CREATE TABLE parse_sql_sfn_base (a INT) USING parquet")
+          sql("CREATE FUNCTION parse_sql_sfn() RETURNS INT " +
+            "RETURN (SELECT max(a) FROM parse_sql_sfn_base)")
+          val result = evalCall(
+            "SELECT parse_sql('SELECT parse_sql_sfn() AS x', 'ANALYZE', " +
+              "relations => array(named_struct(" +
+              "'name', 'spark_catalog.default.parse_sql_sfn_base', 'schema', 
'b STRING')))")
+          assert(result.head \ "analyze_success" === JBool(true), result)
+          assert(result.head \ "select_list" === typedColumns("x" -> jsonInt), 
result)
+        }
+      }
+    }
+  }
+
+  test("ANALYZE overlays apply to the statement an EXECUTE IMMEDIATE runs") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      val result = evalCall(
+        "SELECT parse_sql('EXECUTE IMMEDIATE ''SELECT b FROM 
parse_sql_ei_t''', 'ANALYZE', " +
+          "relations => array(named_struct(" +
+          "'name', 'spark_catalog.default.parse_sql_ei_t', 'schema', 'b 
STRING')))")
+      assert(result.head \ "analyze_success" === JBool(true), result)
+    }
+  }
+
+  test("ANALYZE overlays do not replace a table read by a persistent view") {
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      withTable("parse_sql_view_base") {
+        withView("parse_sql_evolving_v") {
+          sql("CREATE TABLE parse_sql_view_base (a INT) USING parquet")
+          sql("CREATE VIEW parse_sql_evolving_v WITH SCHEMA EVOLUTION AS " +
+            "SELECT * FROM parse_sql_view_base")
+          val result = evalCall(
+            "SELECT parse_sql('SELECT * FROM parse_sql_evolving_v', 'ANALYZE', 
" +
+              "relations => array(named_struct(" +
+              "'name', 'spark_catalog.default.parse_sql_view_base', " +
+              "'schema', 'b STRING')))")
+          assert(result.head \ "analyze_success" === JBool(true), result)
+          assert(result.head \ "select_list" === typedColumns("a" -> jsonInt), 
result)
+          // A view WITH SCHEMA EVOLUTION would write an overlay's schema to 
the catalog.
+          val stored = spark.sessionState.catalog.getTableMetadata(
+            TableIdentifier("parse_sql_evolving_v"))
+          assert(stored.schema.fieldNames.toSeq === Seq("a"))
+        }
+      }
+    }
+  }
+
+  test("supplied relation identities are canonical under case-sensitive 
analysis") {
+    withSQLConf(
+        SQLConf.PARSE_SQL_ENABLED.key -> "true",
+        SQLConf.CASE_SENSITIVE.key -> "true") {
+      val mgr = spark.sessionState.catalogManager
+      val globalDb = spark.conf.get(StaticSQLConf.GLOBAL_TEMP_DATABASE)
+      assert(SuppliedRelationRegistry.canonicalize(mgr, Seq("SYSTEM", 
"SESSION", "v")) ===
+        Seq("system", "session", "v"))
+      assert(SuppliedRelationRegistry.canonicalize(mgr, Seq("System", 
"Session", "v")) ===
+        SuppliedRelationRegistry.sessionIdentity("v"))
+      assert(SuppliedRelationRegistry.canonicalize(mgr, Seq("SPARK_CATALOG", 
"default", "t")) ===
+        Seq("spark_catalog", "default", "t"))
+      assert(SuppliedRelationRegistry.canonicalize(mgr, Seq("GLOBAL_TEMP", 
"v")) ===
+        Seq(globalDb, "v"))
+      // Idempotent, so a stored identity and a looked-up identity agree.
+      val once = SuppliedRelationRegistry.canonicalize(mgr, 
Seq("SPARK_CATALOG", "default", "t"))
+      assert(SuppliedRelationRegistry.canonicalize(mgr, once) === once)
+    }
+  }
+
+  test("ANALYZE resolves injected session variables and restores the invoker") 
{
+    withSQLConf(SQLConf.PARSE_SQL_ENABLED.key -> "true") {
+      sql("DECLARE VARIABLE parse_sql_existing_v INT DEFAULT 1")
+      try {
+        val json = spark.sql(
+          """SELECT parse_sql(
+            |  'SELECT system.session.v AS x',
+            |  'ANALYZE',
+            |  variables => array(named_struct('name', 'system.session.v', 
'type', 'INT')))
+            |""".stripMargin).head().getString(0)
+        val analyzed = parse(json) match {
+          case JArray(List(value: JObject)) => value
+          case other => fail(s"expected one statement object, got: $other")
+        }
+        assert(analyzed \ "analyze_success" === JBool(true), json)
+        assert(analyzed \ "select_list" === JArray(List(
+          JObject("name" -> JArray(List(JString("x"))), "type" -> jsonInt))))
+        assert(spark.sql("SELECT parse_sql_existing_v").head().getInt(0) === 1)

Review Comment:
   Fixed in 4c69a8a9caf. The test now supplies a STRING overlay for the same 
`system.session` name that it reads, checks the call's result type is STRING, 
then checks that the declared INT variable is still typed INT after the call.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RelationResolution.scala:
##########
@@ -235,13 +246,27 @@ class RelationResolution(
     None
   }
 
+  /**
+   * Schema-only stand-in for a caller-supplied relation identity. Eclipses the
+   * real object of that identity for this analysis.
+   */
+  private def lookupSuppliedRelation(identity: Seq[String]): 
Option[LogicalPlan] = {
+    SuppliedRelationRegistry.lookup(identity, conf.resolver).map { schema =>
+      val local = LocalRelation(schema)
+      local.setTagValue(SuppliedRelationRegistry.IDENTITY_TAG, identity)
+      SubqueryAlias(identity, local)
+    }
+  }
+
   /**
    * Try to resolve the identifier as a persistent table/view (current 
catalog/namespace).
    */
   private def tryResolvePersistent(
       u: UnresolvedRelation,
       identifier: Seq[String],
       finalTimeTravelSpec: Option[TimeTravelSpec]): Option[LogicalPlan] = {
+    val supplied = lookupSuppliedPersistentRelation(identifier)

Review Comment:
   Fixed in 4c69a8a9caf. `ResolveRelations` tags the targets of ADD CONSTRAINT, 
CACHE TABLE and UNCACHE TABLE, and `resolveRelation` runs those lookups without 
the supplied overlay. An overlay with the same name no longer stands in for the 
catalog target. Covered by 'ANALYZE does not let a supplied relation stand in 
for a catalog command target'.



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