Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SPARK-30314] Add identifier and catalog information to DataSourceV2Relation #26957

Closed
wants to merge 26 commits into from
Closed
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -624,7 +624,7 @@ class KafkaRelationSuiteV2 extends KafkaRelationSuiteBase {
val topic = newTopic()
val df = createDF(topic)
assert(df.logicalPlan.collect {
case DataSourceV2Relation(_, _, _) => true
case _: DataSourceV2Relation => true
}.nonEmpty)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -809,22 +809,27 @@ class Analyzer(
.getOrElse(i)

case desc @ DescribeTable(u: UnresolvedV2Relation, _) =>
CatalogV2Util.loadRelation(u.catalog, u.tableName)
.map(rel => desc.copy(table = rel))
.getOrElse(desc)
CatalogV2Util
.loadRelation(u.catalog, catalogManager.catalogIdentifier(u.catalog), u.tableName)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be easier to have a separate util method for UnresolvedV2Relation? The interesting thing about UnresolvedV2Relation is that you have access to the originalNameParts. If that doesn't contain the catalog identifier, then we shouldn't need to add it to the DataSourceV2Relation

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, I will do the refactoring.

However in terms of using originalNameParts, I think the major reason why we are adding the two additional fields to DSV2 relation is that both CatalogPlugin and Table implementation doesn't include the resolved unique identifier for the table. Even though the originalNameParts don't have a catalog name in it, it might point to some default catalog in which case we would still want it to be in the resolved unique identifier. Otherwise, we might have two V2Relations pointing to the same table but has different identifiers which would be inconsistent and pretty confusing.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's fine to reproduce the full identifier that was actually loaded by adding in catalog and namespace if they are missing. But I'm not sure it is a good idea to rely on this behavior since there is no guarantee.

.map(rel => desc.copy(table = rel))
.getOrElse(desc)

case alter @ AlterTable(_, _, u: UnresolvedV2Relation, _) =>
CatalogV2Util.loadRelation(u.catalog, u.tableName)
.map(rel => alter.copy(table = rel))
.getOrElse(alter)
CatalogV2Util
.loadRelation(u.catalog, catalogManager.catalogIdentifier(u.catalog), u.tableName)
.map(rel => alter.copy(table = rel))
.getOrElse(alter)

case show @ ShowTableProperties(u: UnresolvedV2Relation, _) =>
CatalogV2Util.loadRelation(u.catalog, u.tableName)
CatalogV2Util
.loadRelation(u.catalog, catalogManager.catalogIdentifier(u.catalog), u.tableName)
.map(rel => show.copy(table = rel))
.getOrElse(show)

case u: UnresolvedV2Relation =>
CatalogV2Util.loadRelation(u.catalog, u.tableName).getOrElse(u)
CatalogV2Util
.loadRelation(u.catalog, catalogManager.catalogIdentifier(u.catalog), u.tableName)
.getOrElse(u)
}

/**
Expand All @@ -834,7 +839,11 @@ class Analyzer(
expandRelationName(identifier) match {
case NonSessionCatalogAndIdentifier(catalog, ident) =>
CatalogV2Util.loadTable(catalog, ident) match {
case Some(table) => Some(DataSourceV2Relation.create(table))
case Some(table) =>
Some(DataSourceV2Relation.create(
table,
catalogManager.catalogIdentifier(catalog),
Seq(ident)))
case None => None
}
case _ => None
Expand Down Expand Up @@ -915,7 +924,11 @@ class Analyzer(
AnalysisContext.get.relationCache.getOrElseUpdate(
key, v1SessionCatalog.getRelation(v1Table.v1Table))
case table =>
DataSourceV2Relation.create(table)
DataSourceV2Relation.create(
table,
catalogManager.catalogIdentifier(catalog),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are we using "identifier" for the catalog name? Everywhere else we call it the catalog name, so I don't see a reason to make this more complicated.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure. I was thinking about making the naming convention consistent since it's called identifier for tables. I'm totally okay with CatalogName.

Seq(ident)
)
}
case _ => None
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,35 @@ class CatalogManager(
import CatalogManager.SESSION_CATALOG_NAME

private val catalogs = mutable.HashMap.empty[String, CatalogPlugin]
// Map from catalog back to it's original name for easy name look up, we don't use the
// CatalogPlugin's name as it might be different from the catalog name depending on
// implementation.
private val catalogIdentifiers = mutable.HashMap.empty[CatalogPlugin, String]
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to handle v1SessionCatalog passed by the constructor here too?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no, that catalog doesn't have a name

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd add a comment here stating that we will have a new instance of a catalog for each catalog name, therefore this reverse map works as intended. We should also add a test for it

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is the reverse map needed? Can't we just call CatalogPlugin.name?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to my understand CatalogPlugin.name depends on the underlying implementation which might not be the actual identifier name for the catalog.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The plugin name is intended to prevent needing to do this. While we do rely on the catalog not to report the wrong name, I think it is reasonable to use it. I'm not strongly against this, though. If you think this is cleaner we can do that.

catalogIdentifiers(defaultSessionCatalog) = SESSION_CATALOG_NAME
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe you should do this as part of loadV2SessionCatalog?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, the concern here is that if a user set a custom session catalog implementation and spark fail to load it, it would fall back to use defaultSessionCatalog. https://github.com/apache/spark/blob/master/sql/catalyst/src/main/scala/org/apache/spark/sql/connector/catalog/CatalogManager.scala#L88. So we need to set the defaultSessionCatalog in the reverse map here


def catalog(name: String): CatalogPlugin = synchronized {
if (name.equalsIgnoreCase(SESSION_CATALOG_NAME)) {
v2SessionCatalog
} else {
catalogs.getOrElseUpdate(name, Catalogs.load(name, conf))
catalogs.getOrElseUpdate(name, {
val catalog = Catalogs.load(name, conf)
catalogIdentifiers(catalog) = name
catalog
})
}
}

/**
* Returns the identifier string for the given catalog
*
* @param catalog catalog to look up
* @return string identifier for the given catalog. If the catalog hasn't be registered return
* None
*/
def catalogIdentifier(catalog: CatalogPlugin): Option[String] = synchronized {
catalogIdentifiers.get(catalog)
}

def isCatalogRegistered(name: String): Boolean = {
try {
catalog(name)
Expand Down Expand Up @@ -83,7 +103,11 @@ class CatalogManager(
private[sql] def v2SessionCatalog: CatalogPlugin = {
conf.getConf(SQLConf.V2_SESSION_CATALOG_IMPLEMENTATION).map { customV2SessionCatalog =>
try {
catalogs.getOrElseUpdate(SESSION_CATALOG_NAME, loadV2SessionCatalog())
catalogs.getOrElseUpdate(SESSION_CATALOG_NAME, {
val catalog = loadV2SessionCatalog()
catalogIdentifiers(catalog) = SESSION_CATALOG_NAME
catalog
})
} catch {
case NonFatal(_) =>
logError(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -256,8 +256,11 @@ private[sql] object CatalogV2Util {
case _: NoSuchNamespaceException => None
}

def loadRelation(catalog: CatalogPlugin, ident: Identifier): Option[NamedRelation] = {
loadTable(catalog, ident).map(DataSourceV2Relation.create)
def loadRelation(
catalog: CatalogPlugin,
catalogIdentifier: Option[String],
ident: Identifier): Option[NamedRelation] = {
loadTable(catalog, ident).map(DataSourceV2Relation.create(_, catalogIdentifier, Seq(ident)))
}

def isSessionCatalog(catalog: CatalogPlugin): Boolean = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import org.apache.spark.sql.catalyst.analysis.{MultiInstanceRelation, NamedRelat
import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeReference}
import org.apache.spark.sql.catalyst.plans.logical.{LeafNode, LogicalPlan, Statistics}
import org.apache.spark.sql.catalyst.util.truncatedString
import org.apache.spark.sql.connector.catalog.{Table, TableCapability}
import org.apache.spark.sql.connector.catalog.{CatalogPlugin, Identifier, Table, TableCapability}
import org.apache.spark.sql.connector.read.{Scan, ScanBuilder, Statistics => V2Statistics, SupportsReportStatistics}
import org.apache.spark.sql.connector.read.streaming.{Offset, SparkDataStream}
import org.apache.spark.sql.connector.write.WriteBuilder
Expand All @@ -32,12 +32,18 @@ import org.apache.spark.util.Utils
* A logical plan representing a data source v2 table.
*
* @param table The table that this relation represents.
* @param output the output attributes of this relation
* @param catalogIdentifier the string identifier for the catalog
* @param identifiers the identifiers for the v2 relation. For multipath dataframe, there could be
* more than one identifier
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

or none if a V2 relation is instantiated using options

* @param options The options for this table operation. It's used to create fresh [[ScanBuilder]]
* and [[WriteBuilder]].
*/
case class DataSourceV2Relation(
table: Table,
output: Seq[AttributeReference],
catalogIdentifier: Option[String],
identifiers: Seq[Identifier],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it is a good idea to have multiple identifiers here. DSv2 doesn't yet cover how file-based tables should work and I think we need a design document for them. Adding multiple identifiers here in support of something that has undefined behavior seems premature.

Design and behavior of path-based identifiers aside, a table should use one and only one identifier. When path-based tables are supported, I expect them to use a single Identifier with possibly more than one path embedded in it, like we do with the paths key.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see. If the specification is that there should be one and only one identifier, shall I just define it as identifier: Identifier instead of identifier: Option[Identifier]? The tricky part is still in load(paths: String*), I might need to use some placeholder or null if we choose to not use Option. What do you guys think? cc @brkyvz

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two things:

  1. There should be only one identifier for a table because it is what identified the table
  2. Let's use null for load(paths: String*) because path-based tables are not designed or supported in v2

options: CaseInsensitiveStringMap)
extends LeafNode with MultiInstanceRelation with NamedRelation {

Expand Down Expand Up @@ -137,12 +143,20 @@ case class StreamingDataSourceV2Relation(
}

object DataSourceV2Relation {
def create(table: Table, options: CaseInsensitiveStringMap): DataSourceV2Relation = {
def create(
table: Table,
catalogIdentifier: Option[String],
identifiers: Seq[Identifier],
options: CaseInsensitiveStringMap): DataSourceV2Relation = {
val output = table.schema().toAttributes
DataSourceV2Relation(table, output, options)
DataSourceV2Relation(table, output, catalogIdentifier, identifiers, options)
}

def create(table: Table): DataSourceV2Relation = create(table, CaseInsensitiveStringMap.empty)
def create(
table: Table,
catalogIdentifier: Option[String],
identifiers: Seq[Identifier]): DataSourceV2Relation =
create(table, catalogIdentifier, identifiers, CaseInsensitiveStringMap.empty)

/**
* This is used to transform data source v2 statistics to logical.Statistics.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,26 @@ class CatalogManagerSuite extends SparkFunSuite {
catalogManager.setCurrentNamespace(Array("test2"))
assert(v1SessionCatalog.getCurrentDatabase == "default")
}

test("Catalog manager should be able to return the string identifier for registered catalog") {
val conf = new SQLConf
conf.setConfString("spark.sql.catalog.dummy", classOf[DummyCatalog].getName)
conf.setConfString(s"spark.sql.catalog.${CatalogManager.SESSION_CATALOG_NAME}",
classOf[DummyCatalog].getName)
val catalogManager = new CatalogManager(conf, FakeV2SessionCatalog, createSessionCatalog(conf))

assert(catalogManager.catalogIdentifier(catalogManager.catalog("dummy")) == Some("dummy"))
assert(catalogManager.catalogIdentifier(catalogManager.v2SessionCatalog) ==
Some(CatalogManager.SESSION_CATALOG_NAME))
}

test("Catalog manager should be able to return the string identifier for default catalog " +
"if no custom session catalog is provided") {
val conf = new SQLConf
val catalogManager = new CatalogManager(conf, FakeV2SessionCatalog, createSessionCatalog(conf))
assert(catalogManager.catalogIdentifier(catalogManager.v2SessionCatalog) ==
Some(CatalogManager.SESSION_CATALOG_NAME))
}
}

class DummyCatalog extends SupportsNamespaces {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.spark.sql.connector.catalog

import org.mockito.Mockito.{mock, when}

import org.apache.spark.SparkFunSuite
import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
import org.apache.spark.sql.types.StructType

class CatalogV2UtilSuite extends SparkFunSuite {
test("Load relation should encode the identifiers for V2Relations") {
val testCatalog = mock(classOf[TableCatalog])
val ident = mock(classOf[Identifier])
val table = mock(classOf[Table])
when(table.schema()).thenReturn(mock(classOf[StructType]))
when(testCatalog.loadTable(ident)).thenReturn(table)
val r = CatalogV2Util.loadRelation(testCatalog, Some("dummy"), ident)
assert(r.isDefined)
assert(r.get.isInstanceOf[DataSourceV2Relation])
val v2Relation = r.get.asInstanceOf[DataSourceV2Relation]
assert(v2Relation.catalogIdentifier == Some("dummy"))
assert(v2Relation.identifiers == Seq(ident))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ class DataFrameReader private[sql](sparkSession: SparkSession) extends Logging {
}

DataSource.lookupDataSourceV2(source, sparkSession.sessionState.conf).map { provider =>
val catalogManager = sparkSession.sessionState.catalogManager
val sessionOptions = DataSourceV2Utils.extractSessionConfigs(
source = provider, conf = sparkSession.sessionState.conf)
val pathsOption = if (paths.isEmpty) {
Expand All @@ -206,27 +207,29 @@ class DataFrameReader private[sql](sparkSession: SparkSession) extends Logging {

val finalOptions = sessionOptions ++ extraOptions.toMap ++ pathsOption
val dsOptions = new CaseInsensitiveStringMap(finalOptions.asJava)
val table = provider match {
val (table, catalogOpt, ident) = provider match {
case _: SupportsCatalogOptions if userSpecifiedSchema.nonEmpty =>
throw new IllegalArgumentException(
s"$source does not support user specified schema. Please don't specify the schema.")
case hasCatalog: SupportsCatalogOptions =>
val ident = hasCatalog.extractIdentifier(dsOptions)
val catalog = CatalogV2Util.getTableProviderCatalog(
hasCatalog,
sparkSession.sessionState.catalogManager,
catalogManager,
dsOptions)
catalog.loadTable(ident)
(catalog.loadTable(ident), catalogManager.catalogIdentifier(catalog), Seq(ident))
case _ =>
userSpecifiedSchema match {
case Some(schema) => provider.getTable(dsOptions, schema)
case _ => provider.getTable(dsOptions)
case Some(schema) => (provider.getTable(dsOptions, schema), None, Nil)
case _ => (provider.getTable(dsOptions), None, Nil)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no catalog in this case, do we need to care what's the table identifier? I.e. for here, looks like the paths are the identifiers? @brkyvz

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They will be in the future, not yet though. This is fine for now

}
}
import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Implicits._
table match {
case _: SupportsRead if table.supports(BATCH_READ) =>
Dataset.ofRows(sparkSession, DataSourceV2Relation.create(table, dsOptions))
Dataset.ofRows(
sparkSession,
DataSourceV2Relation.create(table, catalogOpt, ident, dsOptions))

case _ => loadV1Source(paths: _*)
}
Expand Down
29 changes: 18 additions & 11 deletions sql/core/src/main/scala/org/apache/spark/sql/DataFrameWriter.scala
Original file line number Diff line number Diff line change
Expand Up @@ -258,20 +258,20 @@ final class DataFrameWriter[T] private[sql](ds: Dataset[T]) {
val dsOptions = new CaseInsensitiveStringMap(options.asJava)

import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Implicits._
val catalogManager = df.sparkSession.sessionState.catalogManager
mode match {
case SaveMode.Append | SaveMode.Overwrite =>
val table = provider match {
val (table, catalogOpt, ident) = provider match {
case supportsExtract: SupportsCatalogOptions =>
val ident = supportsExtract.extractIdentifier(dsOptions)
val sessionState = df.sparkSession.sessionState
val catalog = CatalogV2Util.getTableProviderCatalog(
supportsExtract, sessionState.catalogManager, dsOptions)
supportsExtract, catalogManager, dsOptions)

catalog.loadTable(ident)
(catalog.loadTable(ident), catalogManager.catalogIdentifier(catalog), Seq(ident))
case tableProvider: TableProvider =>
val t = tableProvider.getTable(dsOptions)
if (t.supports(BATCH_WRITE)) {
t
(t, None, Nil)
} else {
// Streaming also uses the data source V2 API. So it may be that the data source
// implements v2, but has no v2 implementation for batch writes. In that case, we
Expand All @@ -280,7 +280,7 @@ final class DataFrameWriter[T] private[sql](ds: Dataset[T]) {
}
}

val relation = DataSourceV2Relation.create(table, dsOptions)
val relation = DataSourceV2Relation.create(table, catalogOpt, ident, dsOptions)
checkPartitioningMatchesV2Table(table)
if (mode == SaveMode.Append) {
runCommand(df.sparkSession, "save") {
Expand All @@ -299,9 +299,8 @@ final class DataFrameWriter[T] private[sql](ds: Dataset[T]) {
provider match {
case supportsExtract: SupportsCatalogOptions =>
val ident = supportsExtract.extractIdentifier(dsOptions)
val sessionState = df.sparkSession.sessionState
val catalog = CatalogV2Util.getTableProviderCatalog(
supportsExtract, sessionState.catalogManager, dsOptions)
supportsExtract, catalogManager, dsOptions)

val location = Option(dsOptions.get("path")).map(TableCatalog.PROP_LOCATION -> _)

Expand Down Expand Up @@ -413,13 +412,14 @@ final class DataFrameWriter[T] private[sql](ds: Dataset[T]) {
}

private def insertInto(catalog: CatalogPlugin, ident: Identifier): Unit = {
import df.sparkSession.sessionState.analyzer.catalogManager
import org.apache.spark.sql.connector.catalog.CatalogV2Implicits._

val table = catalog.asTableCatalog.loadTable(ident) match {
case _: V1Table =>
return insertInto(TableIdentifier(ident.name(), ident.namespace().headOption))
case t =>
DataSourceV2Relation.create(t)
DataSourceV2Relation.create(t, catalogManager.catalogIdentifier(catalog), Seq(ident))
}

val command = mode match {
Expand Down Expand Up @@ -544,6 +544,8 @@ final class DataFrameWriter[T] private[sql](ds: Dataset[T]) {


private def saveAsTable(catalog: TableCatalog, ident: Identifier): Unit = {
import df.sparkSession.sessionState.analyzer.catalogManager

val tableOpt = try Option(catalog.loadTable(ident)) catch {
case _: NoSuchTableException => None
}
Expand All @@ -554,12 +556,17 @@ final class DataFrameWriter[T] private[sql](ds: Dataset[T]) {
}

val command = (mode, tableOpt) match {
case (_, Some(table: V1Table)) =>
case (_, Some(_: V1Table)) =>
return saveAsTable(TableIdentifier(ident.name(), ident.namespace().headOption))

case (SaveMode.Append, Some(table)) =>
checkPartitioningMatchesV2Table(table)
AppendData.byName(DataSourceV2Relation.create(table), df.logicalPlan, extraOptions.toMap)
AppendData.byName(
DataSourceV2Relation.create(
table,
catalogManager.catalogIdentifier(catalog),
Seq(ident)),
df.logicalPlan, extraOptions.toMap)

case (SaveMode.Overwrite, _) =>
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A little curious why Overwrite doesn't need to create a DataSourceV2Relation?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It drops and recreates a table. It's a DDL operation instead of DML

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still probably a dumb question. Why does DDL/DML affects how we generate the query plan? I'm asking this because in the save() function for the DataFrameWriter, we do generate a DataSourceV2Relation for Overwrite mode. I'm curious about why there is such a difference here.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in save, we don't update table information in a catalog. saveAsTable updates the catalog, therefore is doing different work. So we need to do a separate operation

ReplaceTableAsSelect(
Expand Down
Loading