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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckAnalysis.scala:
##########
@@ -78,13 +78,17 @@ trait CheckAnalysis extends LookupCatalog with 
QueryErrorsBase with PlanToString
   }
 
   /**
-   * Formats [[CatalogManager.sqlResolutionPathEntries]] with [[toSQLId]]
-   * for TABLE_OR_VIEW_NOT_FOUND error messages.
+   * Formats the analysis-time path entries that participate in resolving 
`multipartIdentifier`
+   * with [[toSQLId]] for TABLE_OR_VIEW_NOT_FOUND messages.
    */
-  private def fullSearchPathForError(catalogPath: Seq[String]): Seq[String] = {
-    val catalog = catalogPath.head
-    val ns = catalogPath.tail.toSeq
-    catalogManager.sqlResolutionPathEntries(catalog, ns).map(toSQLId)
+  private def fullSearchPathForError(
+      catalogPath: Seq[String],
+      multipartIdentifier: Seq[String]): Seq[String] = {
+    CatalogManager.identifierPathEntries(
+      catalogManager.resolutionPathEntriesForAnalysis(
+        AnalysisContext.get.resolutionPathEntries, catalogPath),

Review Comment:
   Addressed in 70b72ead07e.
   
   With PATH enabled, a top-level not-found error reports the session path (SET 
PATH or DEFAULT_PATH). Inside a view or SQL function body it reports the body's 
path, matching the fixed-point analyzer.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/Resolver.scala:
##########
@@ -593,8 +592,10 @@ class Resolver(
           }
           val searchPath = catalogManager
             .sqlResolutionPathEntries(catalogPath.head, catalogPath.tail.toSeq)
-            .map(toSQLId)
-          unresolvedRelation.tableNotFound(multipartId, searchPath)
+          val relevantSearchPath =
+            CatalogManager.identifierPathEntries(

Review Comment:
   Addressed in 67b5064d204.
   
   The single-pass not-found error now uses 
relationResolution.resolutionSearchPathForError(multipartId), so it reports the 
path the analysis resolved against.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/RelationMetadataProvider.scala:
##########
@@ -76,17 +76,24 @@ trait RelationMetadataProvider extends LookupCatalog {
    * This method is public, because it's used in [[MetadataResolverSuite]].
    */
   def relationIdFromUnresolvedRelation(unresolvedRelation: 
UnresolvedRelation): RelationId = {
-    
relationResolution.expandIdentifier(unresolvedRelation.multipartIdentifier) 
match {
+    val nameParts = unresolvedRelation.multipartIdentifier
+    val usesPath = CatalogManager.identifierUsesPath(
+      nameParts, catalogManager.isCatalogRegistered)
+    relationResolution.expandIdentifier(nameParts) match {
       case CatalogAndIdentifier(catalog, ident) =>
         RelationId(
           multipartIdentifier =
             Seq(catalog.name()) ++ ident.namespace().toImmutableArraySeq ++ 
Seq(ident.name()),
+          pathIdentifier = Option.when(usesPath)(nameParts),
+          resolutionPathEntries = 
Option.when(usesPath)(AnalysisContext.get.resolutionPathEntries)

Review Comment:
   Addressed in 67b5064d204.
   
   PATH-resolved relation keys now include the analysis home 
catalogAndNamespace when it is non-empty. A top-level t and a t inside a 
pathless view therefore get different RelationIds. No regression test yet for 
this (see the PR-level comment).



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FunctionResolution.scala:
##########
@@ -871,31 +894,33 @@ class FunctionResolution(
         CatalogAndIdentifier.unapply(expanded).foreach { case (catalog, ident) 
=>
           catalog match {
             case pc: ProcedureCatalog =>
-              try {
-                val procedure = pc.loadProcedure(ident)
-                // A null means the catalog has no such procedure. Treat it as 
a miss, so an
-                // unqualified name keeps searching PATH and a qualified one 
fails as unresolved.
-                if (procedure != null) {
-                  return ResolvedProcedure(pc, ident, procedure)
-                }
-              } catch {
-                // ProcedureCatalog has no standard "not found" exception type 
today. For
-                // unqualified names searched through PATH, treat candidate 
failures as misses and
-                // continue to the next entry (matching table/function PATH 
iteration semantics).
-                // Explicitly catalog-qualified names still preserve existing 
error behavior.
-                case _: AnalysisException if skipCandidateFailures =>
-                case _: SparkThrowable if skipCandidateFailures =>
-                case NonFatal(_) if skipCandidateFailures =>
-                case e: AnalysisException => throw e
-                case e: SparkThrowable => throw e
-                case NonFatal(e) =>
-                  val cause = e match {
-                    case ex: Exception => ex
-                    case th => new RuntimeException(th)
+              if (!safelyProbeCandidateExistence || procedureExists(pc, 
ident)) {

Review Comment:
   Addressed in 67b5064d204.
   
   A PROCEDURE candidate is probed with listProcedures only when a later 
candidate remains, and names are compared with conf.resolver. A miss falls 
through to the next candidate. Non-miss failures still propagate. No test 
asserts that listProcedures is not called for a single candidate yet.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FunctionResolution.scala:
##########
@@ -645,15 +661,7 @@ class FunctionResolution(
           case e: AnalysisException if e.getCondition == "FORBIDDEN_OPERATION" 
=>
         }
       }
-      return FunctionType.NotFound
     }
-
-    val CatalogAndIdentifier(catalog, ident) = 
relationResolution.expandIdentifier(nameParts)

Review Comment:
   Addressed in 67b5064d204.
   
   lookupFunctionType now expands each candidate with 
relationResolution.expandIdentifier, as resolveFunctionCandidate does. 
Multi-part names no longer skip view-context qualification.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FunctionResolution.scala:
##########
@@ -181,6 +208,12 @@ class FunctionResolution(
           None
         case e: AnalysisException if e.getCondition == "FORBIDDEN_OPERATION" =>
           None
+        case e: AnalysisException

Review Comment:
   Addressed in 67b5064d204.
   
   The REQUIRES_SINGLE_PART_NAMESPACE miss rule now applies in 
persistentFunctionExists, lookupFunctionType and the table-function candidate 
path whenever the name uses PATH. An explicit spark_catalog.<name> still fails 
as before. No test covers the new misses yet.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/connector/catalog/CatalogManager.scala:
##########
@@ -588,13 +584,81 @@ private[sql] object CatalogManager extends Logging {
       parts(1).equalsIgnoreCase(BUILTIN_NAMESPACE)
 
   /**
-   * True when `system.builtin` is the first entry of `pathEntries`. This is 
the path-shape
-   * condition under which a built-in function found by an unqualified 
single-part name cannot be
-   * shadowed by any earlier path entry -- the precise property the 
function-resolution built-in
-   * fast-path relies on. Pure predicate over the path shape; callers decide 
how to use it.
+   * True when `system.builtin` is the first schema entry of `pathEntries`. 
Catalog-only entries do
+   * not participate in one-part resolution. This is the path-shape condition 
under which a
+   * built-in function found by an unqualified single-part name cannot be 
shadowed by any earlier
+   * relevant entry -- the precise property the function-resolution built-in 
fast-path relies on.
+   * Pure predicate over the path shape; callers decide how to use it.
    */
   def isBuiltinFirstOnPath(pathEntries: Seq[Seq[String]]): Boolean =
-    pathEntries.headOption.exists(isSystemBuiltinPathEntry)
+    pathEntries.find(_.length > 1).exists(isSystemBuiltinPathEntry)
+
+  /**
+   * True if an identifier is resolved through SQL PATH. A two-part name whose 
first part is a
+   * registered catalog is already fully catalog-qualified and bypasses PATH.
+   */
+  def identifierUsesPath(
+      nameParts: Seq[String],
+      isCatalogRegistered: String => Boolean): Boolean = {
+    nameParts.length == 1 ||
+      (nameParts.length == 2 && !isCatalogRegistered(nameParts.head))
+  }
+
+  /**
+   * Select the SQL path entries that participate in resolving an identifier.
+   *
+   * - One-part names use schema entries (catalog + namespace). Catalog-only 
entries are included
+   *   only when that catalog is not already present as the prefix of a schema 
entry -- the case
+   *   where CURRENT_SCHEMA collapses to the catalog name because the default 
namespace is empty
+   *   (common for V2 catalogs). Catalog-only entries that duplicate a schema 
prefix are omitted
+   *   so session-catalog probes like `spark_catalog.<name>` (invalid empty 
namespace) are not
+   *   introduced when `spark_catalog.<schema>` is already on the path.
+   * - Two-part partially qualified names use the distinct catalog prefixes of 
the path. Explicit
+   *   catalog-only entries and catalogs implied by schema entries both 
participate, so a PATH that
+   *   lists only schemas (e.g. `spark_catalog.db_a, system.builtin`) still 
resolves `db.table`.
+   * - Fully catalog-qualified names do not use the path for resolution, but 
retain the historical
+   *   schema-shaped path for diagnostics.
+   */
+  def identifierPathEntries(
+      pathEntries: Seq[Seq[String]],
+      nameParts: Seq[String],
+      isCatalogRegistered: String => Boolean): Seq[Seq[String]] = 
nameParts.length match {
+    case 1 =>
+      val schemaEntries = pathEntries.filter(_.length > 1)
+      val catalogsWithSchema = 
schemaEntries.map(_.head.toLowerCase(java.util.Locale.ROOT)).toSet
+      val uncoveredCatalogEntries = pathEntries.filter { e =>
+        e.length == 1 && 
!catalogsWithSchema.contains(e.head.toLowerCase(java.util.Locale.ROOT))
+      }
+      schemaEntries ++ uncoveredCatalogEntries
+    case 2 if identifierUsesPath(nameParts, isCatalogRegistered) =>
+      // Catalog-only entries keep their configured order (e.g. 
persistentCatalogFirst). Catalogs
+      // that appear only as the prefix of a schema entry are appended after 
them.
+      val catalogOnly = pathEntries.filter(_.length == 1)
+      val schemaCatalogs = pathEntries.filter(_.length > 1).map(_.take(1))
+      (catalogOnly ++ schemaCatalogs).distinct
+    case _ => pathEntries.filter(_.length > 1)
+  }
+
+  /**
+   * Build resolution candidates for an identifier from the SQL path. Schema 
path entries
+   * (catalog + namespace) qualify one-part names, while catalog path entries 
qualify two-part
+   * names. Names with three or more parts are already fully qualified.
+   */
+  def identifierPathCandidates(
+      pathEntries: Seq[Seq[String]],
+      nameParts: Seq[String],
+      isCatalogRegistered: String => Boolean): Seq[Seq[String]] = {
+    if (identifierUsesPath(nameParts, isCatalogRegistered)) {
+      val entries = identifierPathEntries(pathEntries, nameParts, 
isCatalogRegistered).to(LazyList)
+      val applicableEntries = entries.filter { entry =>
+        entry.head.equalsIgnoreCase(SYSTEM_CATALOG_NAME) ||

Review Comment:
   Addressed in 67b5064d204.
   
   onePartPathEntries no longer includes a bare system catalog entry, so 
one-part names never probe a schema named system.



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