cloud-fan commented on code in PR #60515:
URL: https://github.com/apache/spark/pull/60515#discussion_r4577690546
##########
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)
Review Comment:
**Blocking (P1):** Every one-part entry counts as a catalog here, including
the collapsed current schema. With `spark.sql.defaultCatalog` set to a V2
catalog that keeps `CatalogPlugin`'s empty default namespace, the built-in
default path is `[system.builtin, system.session, othercat, system, othercat]`,
so two-part names get `[othercat, system]` even though `persistentCatalogFirst`
is false. LookupFunctions now skips the registry quick check for two-part
names, and `lookupFunctionType` calls `asFunctionCatalog` on
`othercat.builtin.abs` first; MISSING_CATALOG_ABILITY is not in its miss list.
Reading the code, with PATH off and `othercat` an `InMemoryTableCatalog`,
`SELECT builtin.abs(-5)` returns 5 on the base branch and would fail analysis
here; `session.my_temp_fn()` and the `builtin.count(*)` rewrite gate would fail
the same way. When the catalog does implement FunctionCatalog, a persistent
`builtin.abs`, or a table `session.v` next to a temp view `v`, would now win
over the system object. `current_path()` also prints the catalog twice, and SET
PATH rejects that string with DUPLICATE_SQL_PATH_ENTRY.
FunctionQualificationSuite SECTION 16j, the only test of this case, was
rewritten to an explicit `SET PATH = system, current_catalog`.
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -292,13 +307,46 @@ object AnalysisContext {
try f finally { set(originContext) }
}
- def withAnalysisContext[A](function: SQLFunction)(f: => A): A = {
+ /** Test helper: analyze a SQL function body with an empty invoker
catalog/namespace. */
+ def withAnalysisContext[A](function: SQLFunction)(f: => A): A =
+ withAnalysisContext(function, Nil)(f)
+
+ /**
+ * Analyze a SQL function body.
+ *
+ * @param invokerCatalogAndNamespace the caller's current catalog and
namespace. Version-0
+ * frozen PATH reconstruction appends this
catalog (not the
+ * creation catalog) for two-part names,
matching the base
+ * branch. Pathless bodies also use it as
their home so they
+ * never inherit the caller's SET PATH.
+ */
+ def withAnalysisContext[A](
+ function: SQLFunction,
+ invokerCatalogAndNamespace: Seq[String])(f: => A): A = {
val originContext = value.get()
- // Function body analysis should not inherit any caller-pinned path; use
only function metadata.
+ // Validate even when PATH is absent so future metadata versions still
fail closed.
+ CatalogTable.requireSupportedMetadataVersion(
+ function.functionMetadataVersion,
+ SQLFunction.CURRENT_FUNCTION_METADATA_VERSION,
+ "SQL function",
+ function.name.unquotedString)
+ val hasFrozenPath = function.functionStoredResolutionPath.isDefined
+ // Function body analysis should not inherit any caller-pinned path. A
frozen PATH is used
+ // as stored (with version-0 enrichment against the invoker catalog). A
pathless body pins
+ // the invoker's home catalog/namespace so DEFAULT_PATH / the built-in
default apply, and
+ // the invoker's SET PATH does not.
val context = originContext.copy(
+ catalogAndNamespace =
+ if (hasFrozenPath) Nil else invokerCatalogAndNamespace,
Review Comment:
**Blocking (P1):** This puts the session's current catalog and namespace
into `catalogAndNamespace` for every SQL function that stores no frozen path,
which includes every function created with `spark.sql.path.enabled=false`, the
default. That field is also the analyzer's signal that it is resolving a stored
view: `RelationResolution.lookupTempView`, `SessionCatalog`'s temp-function
check, and `ColumnResolutionHelper.resolveVariables` hide temp objects missing
from the `referredTemp*Names` lists whenever it is non-empty, and at the top
level of a query those lists are empty.
Reading the code, `CREATE TEMPORARY VIEW t AS VALUES (0) t(a); CREATE
TEMPORARY FUNCTION f() RETURNS INT RETURN (SELECT SUM(a) FROM t); SELECT f()`
returns 0 on the base branch but would fail here with TABLE_OR_VIEW_NOT_FOUND,
or read a same-named persistent table, and the sql-udf golden query
`foo3_5e(0)` would lose its session variable the same way. In addition, a
pathless function called inside a view now resolves unqualified names against
the invoker's current schema instead of the view's home, and a frozen-path
function called inside a view clears the view's temp-object filter for its
body. The base branch, and commit b8e0889, kept the caller's context here.
**Recommended change:** Restore the base behavior of keeping the caller's
catalogAndNamespace for every SQL function body, with or without a frozen path,
as commit b8e0889 still did; commit 06246b6 replaced it with the invoker pin,
giving as its reason that pathless objects must not inherit the invoker's SET
PATH and that version-0 functions should append the invoker catalog. Keep that
isolation by pinning the path instead of the home: when PATH is enabled and the
function stores no frozen path, set the body's resolutionPathEntries to
spark.sql.defaultPath expanded against the function's home, or to the built-in
default ordering around that home, where the home is the inherited
catalogAndNamespace when it is non-empty and the session's current catalog and
namespace otherwise. Version-0 reconstruction appends that same home catalog.
Update the withAnalysisContext scaladoc and comments, and add SQL function
tests for temp-object reads and view-nested calls.
**Why this works:** Temp-object gates again see the caller's context, so a
top-level call keeps an empty catalogAndNamespace and a call inside a view
keeps the view's filter, while path selection reads the pinned entries through
resolutionPathEntriesForAnalysis's frozen-path branch, which ignores the
session's SET PATH.
**Compatibility:** PATH-off SQL function body resolution, including
temp-object visibility and view-relative qualification, stays exactly as on the
base branch.
**Risks:** Pinned entries make Analyzer++ relation and bridge keys treat
pathless function bodies like frozen-path bodies; that separates their metadata
from the caller's, which is the intended isolation and costs one extra metadata
entry per such scope.
**Constraints:** With spark.sql.path.enabled=false, SQL function body
resolution must be identical to the base branch. A pathless body must still
ignore the invoker's SET PATH when PATH is enabled.
**Verification:**
- **Regression:** On the default configuration, a temporary SQL function
reading a temporary view, one calling another temporary function, and one
reading a session variable through IDENTIFIER each return their base-branch
results.
- **Regression:** A pathless persistent SQL function whose body reads an
unqualified table, called from a view in one schema while the session uses
another schema, reads the view's schema.
- **Behavior:** With PATH enabled, a pathless SQL function body ignores an
explicit SET PATH that prefers another catalog, and follows
spark.sql.defaultPath when it is set.
- **Compatibility:** A version-0 SQL function with a frozen path, called
inside a view and at top level, qualifies two-part names with the view's
catalog and the session catalog respectively.
##########
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:
**Non-blocking (P2):** For PATH-resolved names the key is the expanded
identifier, the original spelling, and `AnalysisContext.resolutionPathEntries`,
which is only the frozen path. Since pathless view bodies stopped following the
invoker's SET PATH (CatalogManager.scala:428-442), a top-level `t` and a `t`
inside a pathless view whose home equals the current schema resolve differently
but build identical RelationIds, and `MetadataResolver.tryResolveRelation`
skips an id it already holds.
Reading the code, under the single-pass resolver with `SET PATH =
spark_catalog.other, system.builtin`, `SELECT * FROM t, default.v`, where `v`
is the pathless view `SELECT * FROM t`, would give the view body `other.t`
instead of `default.t`. Adding the analysis context's `catalogAndNamespace` to
the key for PATH-resolved names separates the two; the RelationId scaladoc also
overstates which scopes the new fields isolate. Only the single-pass resolver,
which is internal and off by default, is affected.
**Verification:**
- **Regression:** With the single-pass resolver and SET PATH preferring
another schema, a query that reads `t` at top level and through a pathless view
returns the SET PATH table for the first and the view-home table for the second.
##########
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:
**Non-blocking (P2):** This catch makes a PATH-derived
`spark_catalog.<name>` candidate a miss, but the sibling probes over the same
candidates lack it: `lookupFunctionType`, which LookupFunctions runs before
ResolveFunctions, catches only NoSuch*/CatalogNotFound/FORBIDDEN_OPERATION;
`persistentFunctionExists`, used by the built-in ownership probes, has no
catch; and `resolveTableFunctionCandidate` rethrows every AnalysisException.
Reading the code, under `SET PATH = spark_catalog, testcat` with `f` only in
`testcat`, LookupFunctions would probe `spark_catalog.f` first,
`V2SessionCatalog.functionExists` would throw REQUIRES_SINGLE_PART_NAMESPACE,
and the query would fail although this method skips that candidate. Applying
the same `usesPath && REQUIRES_SINGLE_PART_NAMESPACE` rule in those three
probes keeps an explicitly written `spark_catalog.f` failing as before. None of
the new catches has a test.
**Verification:**
- **Regression:** Under a path with an uncovered spark_catalog entry, scalar
and table functions found in a later catalog resolve through LookupFunctions,
built-in ownership probes, and table-function resolution.
- **Behavior:** An explicitly written empty-namespace session-catalog
function name still fails with REQUIRES_SINGLE_PART_NAMESPACE.
##########
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:
**Non-blocking (P2):** This keeps any `system`-headed entry, and the
one-part branch keeps a bare `system` entry when no `system.*` schema entry
covers it, giving the candidate `[system, t]`. Relation resolution skips only
three-part `system.*` candidates and `isSystemCatalogQualified` requires three
parts, so `CatalogAndIdentifier` maps `[system, t]` onto `<current
catalog>.system.t`; the procedure path filters out this remap, but relations
and functions do not.
Reading the code, under `SET PATH = spark_catalog.default, system`, with a
database named `system` in `spark_catalog`, `SELECT * FROM t` with no
`default.t` would read `spark_catalog.system.t` instead of failing, and a
version-0 view frozen with `[spark_catalog.db]` gets the same candidate from
reconstruction. The SET PATH page says catalog entries are ignored for one-part
names. Never selecting a `system` catalog entry for one-part names closes this.
**Verification:**
- **Regression:** With a database named `system` holding table t and
function f, one-part t and f under SET PATH = spark_catalog.default, system,
and in a version-0 view whose path has no system.* entry, fail as not found
instead of resolving there.
##########
docs/sql-migration-guide.md:
##########
@@ -24,6 +24,8 @@ license: |
## Upgrading from Spark SQL 4.4 to 5.0
+- Since Spark 5.0, two-part object names use catalog entries in the SQL Path.
By default, the built-in default path tries the virtual `system` catalog before
the current catalog, so `builtin.func()` and `session.func()` prefer
`system.builtin` and `system.session`. Setting
`spark.sql.legacy.persistentCatalogFirst` to `true` reverses those two catalog
entries in the built-in default path. An explicit `SET PATH` or
`spark.sql.defaultPath` value controls the order directly: each catalog-only
entry and each catalog implied by a schema entry (for example `spark_catalog`
from `spark_catalog.default`) participates, in first-seen order. Schema-only
paths that worked in Spark 4.2 and 4.3 therefore keep resolving two-part names
through those implied catalogs. Views and SQL functions without a frozen PATH
(created with PATH off, and V2 views) do not inherit the invoker's `SET PATH`;
they use `spark.sql.defaultPath` when it is set, otherwise the object's home
catalog and namespace with the buil
t-in ordering. Legacy SQL functions that store a version-0 frozen PATH
continue to qualify two-part names with the invoker's current catalog, as
before. See [Reserved system
names](sql-ref-identifier.html#reserved-system-names) and [SET
PATH](sql-ref-syntax-aux-conf-mgmt-set-path.html).
Review Comment:
**Non-blocking (P2):** Several claims here do not match the code. 'In
first-seen order': `identifierPathEntries` builds `(catalogOnly ++
schemaCatalogs).distinct`, so `SET PATH = spark_catalog.default, testcat,
system.builtin` tries `testcat`, then `spark_catalog`, then `system`.
'Otherwise the object's home catalog and namespace': for SQL functions the code
uses the invoker's current catalog and namespace (Analyzer.scala:2903-2906), so
`USE db1; CREATE FUNCTION f() RETURNS INT RETURN (SELECT max(a) FROM t); USE
db2; SELECT db1.f()` reads `db2.t`, and `spark.sql.defaultPath` applies only
when `spark.sql.path.enabled` is true at query time.
'As before' for version-0 SQL functions holds only at top level, since
inside a view earlier releases qualified two-part names with the view's
catalog. The `spark.sql.defaultPath` conf description still says it applies
when no SET PATH has been issued, although it now also governs pathless view
and function bodies under SET PATH.
See **Shared repair plan 3** in the review body.
##########
sql/core/src/test/scala/org/apache/spark/sql/connector/ProcedureSuite.scala:
##########
@@ -266,6 +266,69 @@ class ProcedureSuite extends SharedSparkSession with
BeforeAndAfter {
}
}
+ test("PATH enabled: partially qualified CALL follows catalog entries") {
+ withSQLConf(SQLConf.PATH_ENABLED.key -> "true") {
+ try {
+ catalog.createProcedure(Identifier.of(Array("ns"), "sum"), UnboundSum)
+ catalog("cat2").createProcedure(Identifier.of(Array("ns"), "sum"),
UnboundLongSum)
+
+ sql("SET PATH = cat2, cat")
+ checkAnswer(sql("CALL ns.sum(1, 2)"), Row(3L) :: Nil)
Review Comment:
**Non-blocking (P2):** `Row(3L)` and `Row(3)` are interchangeable under
`checkAnswer`: `RowComparisonUtils.compare` falls back to `a == b`, and Scala's
numeric equality makes `3L == 3` true; the existing type-coercion test already
relies on `Row(3)` matching a LongSum result. Both assertions therefore pass
whichever catalog resolves `CALL ns.sum(1, 2)`, so this test, the only one for
the new two-part CALL ordering, cannot catch a wrong order. Registering
procedures in `cat` and `cat2` that return distinguishable values, or asserting
the output schema type, makes it fail when the order is wrong.
**Verification:**
- **Regression:** With SET PATH = cat2, cat and SET PATH = cat, cat2, CALL
ns.sum returns each catalog's distinguishable result.
##########
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)) {
Review Comment:
**Non-blocking (P2):** `identifierUsesPath` runs here and again in the
two-part guard of `identifierPathEntries` (line 633) with the same inputs, and
`RelationResolution.resolveRelation`, `relationIdFromUnresolvedRelation`,
`resolveProcedure`, and `resolveFunctionName` each evaluate it once more. For
the common `db.table` form every evaluation calls `catalog(db)` under the
CatalogManager lock, and `Catalogs.load` builds SQL_CONF_NOT_FOUND and
CATALOG_NOT_FOUND exceptions before `isCatalogRegistered` catches them; misses
are not cached.
Reading the code, a fixed-point two-part relation reference goes from one
failed probe to three, a two-part function from three to five, and `builtin.f`
or `session.f` from none to about five, with the same resolved objects.
Deciding `identifierUsesPath` once per name and passing it to these helpers and
their callers removes the repeats. How much time this costs per query has not
been measured.
**Verification:**
- **Inspection:** Each resolution of one identifier evaluates
isCatalogRegistered for its first part at most once across the candidate helper
and its caller.
- **Behavior:** Candidate order and results for one-, two-, and three-part
names are unchanged.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/catalog/SQLFunction.scala:
##########
@@ -201,6 +215,20 @@ object SQLFunction {
*/
val FUNCTION_RESOLUTION_PATH: String = "function.resolutionPath"
+ /**
+ * Sequence counter for incompatible changes to persisted SQL function
property interpretation.
+ * Absent = 0. Version history matches
[[CatalogTable.VIEW_METADATA_VERSION]].
+ */
+ val FUNCTION_METADATA_VERSION: String = "function.metadataVersion"
+
+ /**
+ * Current [[FUNCTION_METADATA_VERSION]] written by this Spark build. Bump
when a change cannot
+ * read older function property payloads without a version branch. This may
diverge from
+ * [[CatalogTable.CURRENT_VIEW_METADATA_VERSION]]; callers must pass the
matching ceiling to
+ * `CatalogManager.deserializePathEntriesForAnalysisOrFail`.
+ */
+ val CURRENT_FUNCTION_METADATA_VERSION: Int =
CatalogTable.CURRENT_VIEW_METADATA_VERSION
Review Comment:
**Nit (P3):** Defining this as `CatalogTable.CURRENT_VIEW_METADATA_VERSION`
couples the two ceilings that the scaladoc above says may diverge. Bumping the
view version for a view-only format change would also raise the version every
new SQL function writes, and a reader that supports only the old function
ceiling would then reject those functions. Defining it as its own literal `1`
keeps the two independent.
**Verification:**
- **Inspection:** CURRENT_FUNCTION_METADATA_VERSION does not reference the
view constant.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/connector/catalog/PathElement.scala:
##########
@@ -73,14 +76,17 @@ private[sql] object PathElement {
catalogManager: CatalogManager,
isConfDefaultExpansion: Boolean = false): Seq[SessionPathEntry] = {
val currentSchemaSentinel = Seq("__current_schema__")
+ val currentCatalogSentinel = Seq("__current_catalog__")
def toEntries(parts: Seq[Seq[String]]): Seq[SessionPathEntry] = parts.map {
case p if p == currentSchemaSentinel => CurrentSchemaEntry
+ case p if p == currentCatalogSentinel => CurrentCatalogEntry
case p => LiteralPathEntry(p)
}
def builtinDefaultWithCurrentSchema: Seq[SessionPathEntry] =
- toEntries(conf.defaultPathOrder(Seq(currentSchemaSentinel)))
+ toEntries(conf.defaultPathOrder(
Review Comment:
**Nit (P3):** DEFAULT_PATH expansion now stores a `CurrentCatalogEntry`
marker, but the tests list DEFAULT_PATH only while `spark_catalog` is current,
so expanding `CURRENT_CATALOG` at SET time would still pass. Two related
behaviors are also untested. `spark.sql.defaultPath` markers inside a pathless
view expand against the view's home (CatalogManager.scala:436-437), but the new
SetPathSuite test sets only literal entries. An unregistered one-part entry,
such as the old `SET PATH = myschema` case, is skipped only by the
`isCatalogRegistered` filter in `identifierPathCandidates`
(CatalogManager.scala:655); without that filter it would remap to `<current
catalog>.myschema.t`. One SET PATH test per behavior gives each a failure
signal.
**Verification:**
- **Regression:** After SET PATH = DEFAULT_PATH and USE CATALOG of another
catalog, current_path() and two-part lookups use the new catalog; a pathless
view under a CURRENT_SCHEMA default path resolves in its home; SET PATH =
myschema leaves one-part names unresolved through current_catalog.myschema.
##########
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
Review Comment:
**Blocking (P1):** `schemaEntries ++ uncoveredCatalogEntries` moves every
one-part entry behind every schema entry, wherever it was declared. That
includes the collapsed current schema: `CurrentSchemaEntry` resolves to
`Seq(catalog)` when the current namespace is empty, exactly as in Spark 4.2.0,
which used it in its declared position.
Reading the code, after `USE CATALOG testcat` (empty namespace) and `SET
PATH = current_schema, system.session, system.builtin`, `SELECT * FROM t` reads
`testcat.t` on the base branch but would read a temp view `t` here. With `SET
PATH = current_schema, system.builtin`, `abs(...)` calls `testcat.abs` on the
base branch but would call the built-in here, because `isBuiltinFirstOnPath`
now skips one-part entries (CatalogManager.scala:594). Under
`sessionOrder=last` the default path would search `system.session` before
`testcat`. The `isBuiltinFirstOnPath` scaladoc and its CatalogManagerSuite
assertion say catalog-only entries take no part in one-part resolution, which
this branch contradicts.
See **Shared repair plan 1** in the review body.
##########
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
Review Comment:
**Blocking (P1):** When the path has no catalog-only entry, the two-part
catalogs here come only from schema-entry prefixes, so the current catalog is
never tried. In Spark 4.2.0, `session.x` and `builtin.x` always tried `system`
and the current catalog, and every other two-part name was qualified with the
current catalog, whatever SET PATH held.
Reading the code: after `SET PATH = spark_catalog.default`, `SELECT * FROM
session.tv` probes only `spark_catalog.session.tv` and would fail with
TABLE_OR_VIEW_NOT_FOUND, as would `builtin.abs(-1)`, `session.my_var`, and `SET
VAR session.my_var = 1`. With `USE CATALOG dev` and `spark.sql.defaultPath =
main.default, system.builtin`, `SELECT * FROM sales.orders` would read
`main.sales.orders` instead of `dev.sales.orders`, while `CREATE TABLE
sales.orders` still targets `dev`. A cluster-wide `spark.sql.defaultPath`
applies this to every session after upgrade, and a restarted streaming query
can bind a different table. The migration note says schema-only paths keep
resolving two-part names, and the rewritten tests (sql-path.sql cases 7.1, 8.1,
and 8.2, and the AlwaysPersistedConfigsSuite view read, now three-part names)
no longer exercise this case.
**Recommended change:** When the effective path contains no explicit catalog
entry (a one-part literal or CURRENT_CATALOG), give two-part names the
base-branch pair: `system` and the home catalog in
spark.sql.legacy.persistentCatalogFirst order, the same pair the PR rebuilds
for version-0 objects. Keep the catalog-entry rule for paths that list
catalogs. Commit 06246b6 added the schema-implied catalogs so that schema-only
paths would keep resolving; this replaces that with the base pair. Restore the
two-part cases the PR rewrote: the AlwaysPersistedConfigsSuite view read under
SET PATH = system.session, sql-path.sql cases 7.1, 8.1, and 8.2, and
FunctionQualificationSuite SECTION 17f without the added current_catalog entry.
**Why this works:** A path that names no catalog cannot express a two-part
catalog order, so the helper falls back to the order two-part names had before
PATH governed them; paths that do name catalogs keep the new behavior.
**Risks:** Paths that list only schemas in other catalogs stop resolving
two-part names in those catalogs, which no release supported.
**Constraints:** Paths that list catalog entries keep resolving two-part
names through those entries in order. The built-in default path keeps its
current two-part order.
**Verification:**
- **Regression:** Under a schema-only SET PATH without a system entry,
two-part session temp views, built-in functions, session variables, and SET VAR
resolve as on the base branch.
- **Regression:** Under a schema-only spark.sql.defaultPath whose schemas
live in another catalog, a two-part table name reads and writes the current
catalog's table.
- **Behavior:** Under a path that lists catalog entries, two-part relations,
functions, and procedures still follow those entries in order.
- **Compatibility:** persistentCatalogFirst orders system and the current
catalog for two-part names under a schema-only path, matching the 4.2 migration
note.
##########
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:
**Non-blocking (P2):** `catalogPathForError` falls back to the current
catalog and namespace, so `resolutionPathEntriesForAnalysis` always gets a
non-empty view argument here and takes the new pathless-view branch
(CatalogManager.scala:428-442), which deliberately ignores SET PATH. Reading
the code, after `SET PATH = spark_catalog.default, system.builtin`, `SELECT id
FROM tbl` would report `[system.builtin, system.session,
spark_catalog.default]`, a path resolution never walked, while sql-path.sql.out
(regenerated before that branch was added) still expects
`[spark_catalog.default, system.builtin]`.
Passing `AnalysisContext.get.catalogAndNamespace`, which is empty at top
level, matches what `RelationResolution.resolutionSearchPathForError` and
`FunctionResolution.resolutionSearchPathForError` do. The scaladocs of
`fullSearchPathForError`, which also builds UNRESOLVED_ROUTINE's path, and
`searchPathForUnresolvedRelation`, which no longer reads
`sqlResolutionPathEntries`, need the same correction.
See **Shared repair plan 2** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/connector/catalog/CatalogManager.scala:
##########
@@ -735,4 +803,43 @@ private[sql] object CatalogManager extends Logging {
context = Array.empty)
}
}
+
+ /**
+ * Parse a frozen path for analysis, using the object's metadata version to
decide whether the
+ * stored PATH already encodes catalog entries for two-part names. Version 0
(absent) payloads
+ * could contain catalog-only entries that did not participate in
resolution; two-part names used
+ * a separate mini-path containing `system` and the creation-time current
catalog. Preserve the
+ * schema entries and append those catalog entries in the historical order
so old views and SQL
+ * functions keep their behavior. Version
`METADATA_VERSION_PATH_WITH_CATALOG_ENTRIES` and above
+ * trusts the stored PATH as-is.
+ */
+ def deserializePathEntriesForAnalysisOrFail(
+ storedPathStr: String,
+ metadataVersion: Int,
+ creationCatalog: Option[String],
+ persistentCatalogFirst: Boolean,
+ objectType: String,
+ objectName: String,
+ currentMetadataVersion: Int): Seq[Seq[String]] = {
+ import org.apache.spark.sql.catalyst.catalog.CatalogTable.{
+ METADATA_VERSION_PATH_WITH_CATALOG_ENTRIES,
+ requireSupportedMetadataVersion
+ }
+ // Check the version before parsing PATH so a future-format payload
reports an
+ // unsupported-version error instead of a misleading invalid-path error.
+ requireSupportedMetadataVersion(
+ metadataVersion, currentMetadataVersion, objectType, objectName)
+ val entries = deserializePathEntriesOrFail(storedPathStr, objectType,
objectName)
+ if (metadataVersion >= METADATA_VERSION_PATH_WITH_CATALOG_ENTRIES) {
+ entries
+ } else {
+ val persistentCatalog = creationCatalog.map(Seq(_)).toSeq
+ val catalogEntries = if (persistentCatalogFirst) {
+ persistentCatalog :+ Seq(SYSTEM_CATALOG_NAME)
+ } else {
+ Seq(Seq(SYSTEM_CATALOG_NAME)) ++ persistentCatalog
+ }
+ entries.filter(_.length > 1) ++ catalogEntries
Review Comment:
**Blocking (P1):** `entries.filter(_.length > 1)` assumes version-0 one-part
entries never took part in resolution, but they did. A collapsed
`CURRENT_SCHEMA`, stored as `Seq(catalog)` for an empty namespace, is what
Spark 4.2.0 and the base branch write whenever a PATH-enabled view or SQL
function is created under such a catalog, even with no SET PATH, and one-part
names resolved through it in place.
Reading the code, `CREATE FUNCTION spark_catalog.default.f() RETURNS INT
RETURN (SELECT max(a) FROM t)` run with PATH enabled under `USE CATALOG
testcat` stores `[system.builtin, testcat]`. Called later with `spark_catalog`
current, this rebuilds it as `[system.builtin, system, spark_catalog]`, so `t`
would no longer resolve to `testcat.t` and analysis would fail. A view created
with `SET PATH = current_schema, system.builtin` stores `[testcat,
system.builtin]`; its body's `abs` resolved `testcat.abs` on the base branch
and would resolve to the built-in here. CatalogManagerSuite's 'legacy persisted
path is enriched' test asserts the drop.
See **Shared repair plan 1** in the review body.
##########
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:
**Non-blocking (P2):** This still starts from
`catalogManager.sqlResolutionPathEntries(...)`, the session's live SET PATH,
while the fixed-point side now reports the analysis-time path. Reading the
code, a missing `t` inside a view frozen with `SET PATH = spark_catalog.db_a,
system.builtin`, queried after `SET PATH = spark_catalog.db_b, system.builtin`,
would be reported against `[spark_catalog.db_a, system.builtin]` by the
fixed-point analyzer and against `[spark_catalog.db_b, system.builtin]` here.
On the base branch both analyzers reported the session path and agreed. Using
`relationResolution.resolutionSearchPathForError(multipartId)` keeps them in
agreement. Only the single-pass resolver, which is internal and off by default,
and dual-run comparisons are affected.
See **Shared repair plan 2** in the review body.
##########
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:
**Non-blocking (P2):** Removing `relationResolution.expandIdentifier` here
means names that bypass PATH (three or more parts) reach `CatalogAndIdentifier`
as written. Inside a view body, `expandIdentifier` prepends the view's catalog
when the first part is not a registered catalog, and
`resolveFunctionCandidate`, `persistentFunctionExists`, and LookupFunctions'
own cache key still do that.
Reading the code, a view stored in a V2 catalog `cat` with multi-level
namespaces whose body calls `ns1.ns2.f()`, queried after `USE CATALOG
spark_catalog`, was checked as `cat.ns1.ns2.f` on the base branch; here it
would be checked in `spark_catalog` with namespace `[ns1, ns2]`, failing with
REQUIRES_SINGLE_PART_NAMESPACE or UNRESOLVED_ROUTINE although ResolveFunctions
would resolve the call. Applying `expandIdentifier` to each non-system
candidate in `lookupFunctionType`, as `resolveFunctionCandidate` does, keeps
the two checks in agreement.
**Verification:**
- **Regression:** A view hosted in a V2 catalog with multi-level namespaces
whose body calls ns1.ns2.f() analyzes and returns the function's result when
queried from another current catalog.
##########
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:
**Non-blocking (P2):** With PATH off or the built-in default, the `system`
candidates are filtered out, so `CALL ns.p(...)`, including the connector form
`CALL system.<proc>(...)`, has exactly one candidate and this probe cannot
change which one wins. The base branch called `loadProcedure` directly. Now
every such call also lists the namespace, compares names exactly with `_.name()
== ident.name()`, and treats only `NoSuchNamespaceException` as a miss.
Reading the code, a catalog whose `loadProcedure` accepts `Expire_Snapshots`
case-insensitively would now raise UNRESOLVED_ROUTINE for `CALL
system.Expire_Snapshots(...)`, and a catalog whose `listProcedures` is
incomplete or throws would break a CALL that `loadProcedure` alone served;
`ProcedureCatalog` does not tie `listProcedures` to `loadProcedure`'s name
semantics. Probing only when a later candidate remains, and comparing names
with `conf.resolver`, keeps the fall-through without these failures.
**Verification:**
- **Regression:** A two-part CALL against a single candidate never calls
listProcedures, and a mixed-case CALL against a case-insensitive procedure
catalog resolves.
- **Behavior:** With two catalog entries, a missing procedure in the first
still falls through to the second, and a non-miss failure in the first still
propagates.
##########
docs/sql-ref-syntax-aux-conf-mgmt-set-path.md:
##########
@@ -132,6 +150,8 @@ path_element
* Setting the path takes effect immediately.
* Identifier case is preserved in storage and in `current_path()` output.
+* Catalog entries are ignored for one-part names, and schema entries are
ignored for two-part
Review Comment:
**Non-blocking (P2):** This sentence, together with 'Schema entries qualify
one-part names, and catalog entries qualify two-part names' (lines 28-29) and
the `catalog_name` description (lines 133-137), does not match
`CatalogManager.identifierPathEntries`. One-part names also use catalog-only
entries that no schema entry covers: `SET PATH = pathcat, system.builtin`
resolves `path_empty_ns_t` from `pathcat`, which SqlPathV2CatalogSuite relies
on. Two-part names also use the catalogs implied by schema entries: `SET PATH =
spark_catalog.db_a, system.builtin` resolves `db_b.tbl` through `spark_catalog`.
sql-ref-name-resolution.md (lines 275-285) has the same simplification and
no note that DDL still qualifies two-part names with the current catalog, and
sql-ref-syntax-aux-describe-function.md (lines 48-49) repeats it, as do the
`resolutionCandidates` scaladoc and the RelationResolution and
VariableResolution comments. These pages need to describe the rules the code
applies once the resolution fixes in this review land.
See **Shared repair plan 3** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/VariableResolution.scala:
##########
@@ -187,17 +177,15 @@ class VariableResolution(
}
}
- // The temp variables live in `SYSTEM.SESSION`, and the name can be
qualified or not.
- private def maybeTempVariableName(nameParts: Seq[String]): Boolean = {
- nameParts.length == 1 || {
- if (nameParts.length == 2) {
- nameParts.head.equalsIgnoreCase(CatalogManager.SESSION_NAMESPACE)
- } else if (nameParts.length == 3) {
- nameParts(0).equalsIgnoreCase(CatalogManager.SYSTEM_CATALOG_NAME) &&
- nameParts(1).equalsIgnoreCase(CatalogManager.SESSION_NAMESPACE)
- } else {
- false
- }
+ // The temp variables live in `SYSTEM.SESSION`. One- and two-part references
use schema and
+ // catalog entries from the SQL path; the three-part form is fully qualified.
+ private def resolvesToTempVariable(nameParts: Seq[String]): Boolean = {
+ val candidates = CatalogManager.identifierPathCandidates(
Review Comment:
**Nit (P3):** `searchPathEntriesForError` recomputes
`resolutionPathEntriesForAnalysis` on every call, and
`identifierPathCandidates` adds `isCatalogRegistered` probes, for each
last-resort variable attempt, including every prefix `resolveMultipartName`
tries. A two-part candidate is `catalogEntry ++ nameParts`, so it can match
`system.session.*` only when the first part is `session`, and for names with
three or more parts the path is built and then discarded. Returning early for
those shapes (names that bypass PATH get the fixed `system.session` check, and
two-part names without a `session` head get false) and reading the path through
`AnalysisContext.memoizedResolutionPath`, as FunctionResolution does, gives the
same answer without the extra work.
**Verification:**
- **Inspection:** Variable fallback for names with three or more parts, and
for two-part names whose first part is not session, performs no path
computation or catalog probe.
- **Behavior:** One-part and session-qualified session variables resolve
exactly as before under default and custom paths.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/catalog/SQLFunction.scala:
##########
@@ -187,6 +187,20 @@ case class SQLFunction(
/** Frozen PATH string persisted when the function was created with SQL PATH
enabled. */
def functionStoredResolutionPath: Option[String] =
properties.get(SQLFunction.FUNCTION_RESOLUTION_PATH)
+
+ /**
+ * Persisted SQL function metadata format version. Absent means version 0.
See
+ * [[SQLFunction.CURRENT_FUNCTION_METADATA_VERSION]].
+ */
+ def functionMetadataVersion: Int =
+ CatalogTable.parseMetadataVersion(
+ properties.get(SQLFunction.FUNCTION_METADATA_VERSION),
+ objectType = "SQL function",
+ objectName = name.unquotedString)
+
+ /** Catalog that was current when the function was created. */
+ def functionCreationCatalog: Option[String] =
Review Comment:
**Nit (P3):** Nothing calls this accessor: commit b8e0889 used it for
version-0 reconstruction and 06246b6 switched to the invoker's catalog, leaving
it behind with a doc that points the next reader back to the creation catalog.
`CatalogManager.deserializePathEntriesForAnalysisOrFail` still names its
parameter `creationCatalog` and documents it as the creation-time current
catalog for both callers (CatalogManager.scala:807-819), and the
`FUNCTION_METADATA_VERSION` scaladoc says its history matches the view's.
Removing the accessor and documenting the parameter as the catalog each caller
appends, the view's creation catalog or the SQL function's home catalog, keeps
the code and its docs in agreement.
**Verification:**
- **Inspection:** No reference to functionCreationCatalog remains, and the
reconstruction parameter is documented as the catalog each caller appends.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -10945,34 +10944,52 @@ class SQLConf extends Serializable with Logging with
SqlApiConf {
* Returns the resolution search path for error messages and resolution
order.
* This is the single source of truth for the search path used for
functions, tables, and views.
* Uses [[sessionFunctionResolutionOrder]]: "first" (session first),
"second" (session second),
- * "last" (session last). When catalogPath is empty, returns only system
namespaces.
+ * "last" (session last). When catalogPath is empty, current schema and
catalog entries are
+ * omitted.
*/
- def resolutionSearchPath(catalogPath: Seq[String]): Seq[Seq[String]] =
- defaultPathOrder(if (catalogPath.isEmpty) Seq.empty else Seq(catalogPath))
+ def resolutionSearchPath(catalogPath: Seq[String]): Seq[Seq[String]] = {
+ val schemaEntries = if (catalogPath.isEmpty) Seq.empty else
Seq(catalogPath)
+ val catalogEntries = catalogPath.headOption.toSeq.map(Seq(_))
+ defaultPathOrder(schemaEntries, catalogEntries)
+ }
/**
- * Orders the given catalog path entries by
[[sessionFunctionResolutionOrder]], inserting
- * system.session and system.builtin. Used by the legacy single-schema
resolution and by
- * SET PATH's DEFAULT_PATH expansion (when `spark.sql.defaultPath` is empty)
to keep
- * ordering in sync. SYSTEM_PATH no longer flows through here -- see
[[systemPathOrder]].
+ * Orders schema entries by [[sessionFunctionResolutionOrder]] with
system.session and
+ * system.builtin, then orders the system and persistent catalog entries
using
+ * [[persistentCatalogFirst]]. Used by the legacy single-schema resolution
and by SET PATH's
+ * DEFAULT_PATH expansion (when `spark.sql.defaultPath` is empty) to keep
ordering in sync.
+ * SYSTEM_PATH no longer flows through here -- see [[systemPathOrder]].
*
+ * @param schemaEntries persistent schema path entries (may be empty).
* @param catalogEntries persistent catalog path entries (may be empty).
*/
- def defaultPathOrder(catalogEntries: Seq[Seq[String]]): Seq[Seq[String]] = {
+ def defaultPathOrder(schemaEntries: Seq[Seq[String]]): Seq[Seq[String]] = {
Review Comment:
**Nit (P3):** The scaladoc above documents `@param catalogEntries` and
describes the system/current-catalog ordering, but this overload takes only
`schemaEntries`; the two-argument overload at line 10970, which does the
ordering, is undocumented. Moving the scaladoc to that overload and giving this
one a one-line doc fixes the generated docs.
**Verification:**
- **Inspection:** The two-argument defaultPathOrder carries the
schemaEntries and catalogEntries docs and the one-argument overload documents
only schemaEntries.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/command/v1/AlterViewSchemaBindingSuite.scala:
##########
@@ -52,18 +54,66 @@ class AlterViewSchemaBindingSuite
sql(s"SET PATH = $catalog.default, system.builtin")
sql(s"ALTER VIEW $view WITH SCHEMA EVOLUTION")
- val pathAfterAlter = spark.sessionState.catalog
+ val metaAfterAlter = spark.sessionState.catalog
.getTableMetadata(TableIdentifier(viewName, Some(namespace)))
- .viewStoredResolutionPath
+ val pathAfterAlter = metaAfterAlter.viewStoredResolutionPath
.getOrElse(fail("Frozen SQL path was dropped by ALTER VIEW WITH
SCHEMA"))
assert(pathAfterAlter == pathAfterCreate,
s"ALTER VIEW WITH SCHEMA must preserve the frozen path. " +
s"Before: $pathAfterCreate; after: $pathAfterAlter")
+ assert(metaAfterAlter.viewMetadataVersion == versionAfterCreate,
Review Comment:
**Nit (P3):** This view was created at the current version, so the assertion
also holds if ALTER VIEW WITH SCHEMA always stamped the current version; no
test ALTERs a version-0 view and checks that it stays version 0. Likewise,
'legacy persisted view path resolves two-part relations through creation
catalog' in AlwaysPersistedConfigsSuite creates and queries its view with
`spark_catalog` current both times, so reconstructing version-0 views with the
invoker's catalog would keep it green. ALTERing a version-0 view, and querying
a legacy view after switching to another registered catalog, give both
guarantees a failure signal.
**Verification:**
- **Regression:** A version-0 view keeps no metadata version after ALTER
VIEW WITH SCHEMA and resolves two-part names through its creation catalog when
queried under a different current catalog.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/catalog/interface.scala:
##########
@@ -815,8 +826,74 @@ object CatalogTable {
/** Frozen expanded PATH at view creation (PATH feature); not a SQL config
property. */
val VIEW_RESOLUTION_PATH = VIEW_PREFIX + "resolutionPath"
+ /**
+ * Sequence counter for incompatible changes to persisted view property
interpretation.
+ * Absent = 0. Version history:
+ * 0 - Pre-metadataVersion payloads. Frozen PATH schema entries only;
two-part names used a
+ * separate mini-path of `system` and the creation catalog.
+ * 1 - Frozen PATH may include catalog-only entries that participate in
two-part resolution.
+ */
+ val VIEW_METADATA_VERSION = VIEW_PREFIX + "metadataVersion"
+
+ /**
+ * Current [[VIEW_METADATA_VERSION]] written by this Spark build. Bump when
a change cannot
+ * read older view property payloads without a version branch.
+ */
+ val CURRENT_VIEW_METADATA_VERSION: Int = 1
+
+ /**
+ * First [[VIEW_METADATA_VERSION]] / function metadata version where frozen
PATH catalog
+ * entries are authoritative for two-part name resolution.
+ */
+ val METADATA_VERSION_PATH_WITH_CATALOG_ENTRIES: Int = 1
+
val VIEW_STORING_ANALYZED_PLAN = VIEW_PREFIX + "storingAnalyzedPlan"
+ /** Parse a persisted metadata-version property; absent means 0. */
+ def parseMetadataVersion(
+ raw: Option[String],
+ objectType: String,
+ objectName: String): Int = {
+ raw.map { value =>
+ try {
+ value.toInt
+ } catch {
+ case _: NumberFormatException =>
+ throw new AnalysisException(
Review Comment:
**Nit (P3):** This fail-closed branch runs on every view and SQL function
analysis, but CatalogManagerSuite and AlwaysPersistedConfigsSuite use only
absent, current, current+1, and negative integer versions. Defaulting a
malformed value to 0, which would silently apply version-0 reconstruction, or
letting the NumberFormatException escape would keep every test green. A view
case and a SQL function case with a non-numeric `metadataVersion` that expect
this message close the gap.
**Verification:**
- **Behavior:** A view and a SQL function with a non-numeric metadataVersion
fail analysis with 'Invalid stored metadata version' naming the object.
##########
sql/core/src/test/resources/sql-tests/inputs/sql-path.sql:
##########
@@ -179,9 +179,11 @@ SET PATH = SYSTEM_PATH, SYSTEM_PATH;
SET PATH = current_database, current_schema;
--- 4.5 Single-part schema reference rejected
-----------------------------------
+-- 4.5 Single-part catalog reference accepted
----------------------------------
Review Comment:
**Nit (P3):** Case 4.5 now succeeds, but it is still listed under section 4,
'Static error conditions at SET PATH' (lines 24 and 154), next to cases that
are all rejected statements. Renaming the section to cover accepted forms, or
moving the case to its own section, keeps the outline accurate; the golden
files need regenerating only if the query order changes.
**Verification:**
- **Inspection:** The sql-path.sql section containing the single-part
catalog case does not describe it as an error condition.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -2422,18 +2465,8 @@ class Analyzer(
UNRESOLVED_TABLE_VALUED_FUNCTION, UNRESOLVED_TVF_ALIASES,
UNRESOLVED_JSON_CONSTRUCTOR),
ruleId) {
// Resolve scalar/table functions and get the function metadata for
DESCRIBE FUNCTION.
- case u @ UnresolvedFunctionName(nameParts, _, _) =>
- functionResolution.lookupBuiltinOrTempFunction(nameParts, None)
-
.orElse(functionResolution.lookupBuiltinOrTempTableFunction(nameParts)).map {
info =>
- ResolvedNonPersistentFunc(nameParts.head,
V1Function.metadataOnly(info))
- }.getOrElse {
- val CatalogAndIdentifier(catalog, ident) =
- relationResolution.expandIdentifier(nameParts)
- val fullName = catalog.name +: ident.namespace :+ ident.name
- CatalogV2Util.loadFunction(catalog, ident).map { func =>
- ResolvedPersistentFunc(catalog.asFunctionCatalog, ident, func)
- }.getOrElse(u.copy(possibleQualifiedName =
Some(fullName.toImmutableArraySeq)))
- }
+ case u: UnresolvedFunctionName =>
+ functionResolution.resolveFunctionName(u)
Review Comment:
**Nit (P3):** `resolveFunctionName` now walks the PATH candidates for
one-part names (FunctionResolution.scala:139-169) instead of checking built-in
and temp functions and then the current namespace, but the only changed
DESCRIBE FUNCTION test, FunctionQualificationSuite SECTION 16k, covers two-part
`builtin.abs`. Cases such as `SET PATH = spark_catalog.db, system.builtin` with
`db.abs` defined, and a path without `system.builtin`, would show that
`DESCRIBE FUNCTION abs` follows the same order as a call.
**Verification:**
- **Behavior:** Under SET PATH = spark_catalog.db, system.builtin with
db.abs defined, DESCRIBE FUNCTION abs describes db.abs, and under a path
without system.builtin a built-in name is reported as not found.
##########
sql/core/src/test/scala/org/apache/spark/sql/SetPathSuite.scala:
##########
@@ -1050,7 +1228,8 @@ class SetPathSuite extends SharedSparkSession {
s"Expected BIGINT (builtin count rewrite); got: $tpe")
}
- sql("SET PATH = system.session, system.builtin")
+ // The catalog-only system entry resolves the two-part builtin.count
reference below.
Review Comment:
**Nit (P3):** The two-part catalogs for this path are `[system]` with or
without the trailing entry, because `identifierPathEntries` already takes
`system` from the `system.session` and `system.builtin` schema entries
(CatalogManager.scala:637-638). Rewording the comment to say so, or dropping
the redundant entry here and in the matching JsonArraySuite paths, keeps the
test from implying the entry is needed.
**Verification:**
- **Inspection:** The comment describes why builtin.count resolves under
that path in a way the test can observe.
--
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]