Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
9a21551
Atomic CTAS
mccheah Jun 4, 2019
266784e
Wire together the rest of replace table logical plans.
mccheah Jun 4, 2019
baeabc8
Remove redundant code
mccheah Jun 4, 2019
bc8d3b5
Some unit tests
mccheah Jun 5, 2019
6c958b9
DDL parser tests for replace table
mccheah Jun 5, 2019
8c0270f
Merge remote-tracking branch 'origin/master' into spark-27724
mccheah Jun 5, 2019
95ba92d
Merge remote-tracking branch 'origin/master' into spark-27724
mccheah Jun 7, 2019
08f115e
Fix merge conflicts
mccheah Jun 7, 2019
89aea5e
Address comments
mccheah Jun 8, 2019
a9142e9
Fix javadoc
mccheah Jun 8, 2019
842886e
Address comments
mccheah Jun 15, 2019
b68df7c
Merge remote-tracking branch 'origin/master' into spark-27724
mccheah Jun 15, 2019
2bf4b5f
Fix merge conflicts
mccheah Jun 15, 2019
80dc0cc
Address comments
mccheah Jun 25, 2019
71f29ed
Merge remote-tracking branch 'origin/master' into spark-27724
mccheah Jun 25, 2019
a333df8
Merge remote-tracking branch 'origin/master' into spark-27724
mccheah Jul 3, 2019
4011a8b
Resolve conflict
mccheah Jul 3, 2019
aebf767
Newline
mccheah Jul 3, 2019
6231f6a
Add support for CREATE OR REPLACE TABLE
mccheah Jul 8, 2019
96b6db6
Name more boolean parameters
mccheah Jul 8, 2019
295ff75
Remove REPLACE...TEMPORARY
mccheah Jul 11, 2019
d7e1e67
Merge remote-tracking branch 'origin/master' into spark-27724
mccheah Jul 11, 2019
deaf255
Address comments
mccheah Jul 12, 2019
0b5c029
Merge remote-tracking branch 'origin/master' into spark-27724
mccheah Jul 16, 2019
581dba2
Address comments
mccheah Jul 16, 2019
be04476
Address comments
mccheah Jul 18, 2019
609eb9c
Add stageCreateOrReplace to indicate to the staging catalog the appro…
mccheah Jul 19, 2019
2f6e0b6
Revert droppedTables stuff
mccheah Jul 19, 2019
05a827d
Address comments
mccheah Jul 19, 2019
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 @@ -111,6 +111,14 @@ statement
(AS? query)? #createHiveTable
| CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier
LIKE source=tableIdentifier locationSpec? #createTableLike
| replaceTableHeader ('(' colTypeList ')')? tableProvider

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Are there other flavors of REPLACE TABLE that we need to support?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'm not sure that we should support all of what's already here, at least not to begin with.

I think that the main use of REPLACE TABLE as an atomic operation is REPLACE TABLE ... AS SELECT. That's because the replacement should only happen if the write succeeds and the write could easily fail for a lot of reasons. Without a write, this is just syntactic sugar for a combined drop and create.

I think the initial PR should focus on just the RTAS case. That simplifies this because it no longer needs the type list. What do you think?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think this should support the USING clause that is used to pass the provider name.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Because of the tableProvider field at the end I think USING is still supported right? As mentioned elsewhere, this is copied from CTAS.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Is there a test for it?

((OPTIONS options=tablePropertyList) |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Should OPTIONS be supported in v2? Right now, we copy options into table properties because v2 has no separate options. I also think it is confusing to users that there are table properties and options.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

In general I copied this entirely from the equivalent create table statement. How does the syntax for REPLACE TABLE differ from that of the existing CREATE TABLE? My understanding is REPLACE TABLE is exactly equivalent to CREATE TABLE with the exception of not having an IF NOT EXISTS option.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

True, it should be the same a CREATE TABLE. That's a good reason to carry this forward.

(PARTITIONED BY partitioning=transformList) |
bucketSpec |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Should bucketing be added using BUCKET BY? Or should we rely on bucket as a transform in the PARTITIONED BY clause?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Same as #24798 (comment) - this is copied from the create table spec.

locationSpec |
(COMMENT comment=STRING) |
(TBLPROPERTIES tableProps=tablePropertyList))*
(AS? query)? #replaceTable
| ANALYZE TABLE tableIdentifier partitionSpec? COMPUTE STATISTICS
(identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze
| ALTER TABLE tableIdentifier
Expand Down Expand Up @@ -244,6 +252,10 @@ createTableHeader
: CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier
;

replaceTableHeader

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'm worried about creating new SQL syntax in Spark. AFAIK a similar syntax is CREATE OR REPLACE TABLE, which is implemented in DB2 and google BigQuery.

This is not a standard SQL syntax, so it's not surprising to see that Oracle doesn't support it. If Spark want a API for replace table, I think it's more reasonable to follow DB2 and BigQuery here.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'm fine using [CREATE OR] REPLACE TABLE instead of REPLACE TABLE [IF NOT EXISTS]. I think that is better syntax.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

So do we remove the existing support for the IF NOT EXISTS syntax in the SQL syntax? I think we'd want to avoid breaking existing SQL queries even in the 3.0 release.

Or do we support:

CREATE (OR REPLACE)? TABLE ... (IF NOT EXISTS)?

and then throw AnalysisException if: CREATE OR REPLACE TABLE ... IF NOT EXISTS?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'm fine using [CREATE OR] REPLACE TABLE instead of REPLACE TABLE [IF NOT EXISTS]. I think that is better syntax.

We don't support REPLACE... IF NOT EXISTS in this PR. It's only either CREATE TABLE IF NOT EXISTS or REPLACE TABLE. I don't see any reason to include CREATE OR REPLACE table if we don't want to replace the IF NOT EXISTS parameter in existing spark-sql, but removing support for IF NOT EXISTS risks breaking existing SQL workflows as I've described above.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'd say let's remove IF NOT EXISTS from the parser, but just for REPLACE TABLE.

Then, we should add an option to add CREATE OR, to the start, which would set an orCreate flag to true. If that is true, and the table doesn't exist, then create the table instead of replacing it. If that is false, then throw an exception that the table doesn't exist.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think that makes sense, though the current implementation doesn't have a rule supporting REPLACE TABLE IF NOT EXISTS.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

It it isn't supported, then we can throw an exception.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Since that clause isn't supported in the SqlBase.g4 file itself, I'd expect the parser to throw an exception for us.

: REPLACE TEMPORARY? TABLE multipartIdentifier

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'd probably remove TEMPORARY to begin with. What is the behavior of a temporary table? I think it used to be a view.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actually, it looks fine since this is not allowed in the AST builder.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Let's get rid of TEMPORARY TABLE. It was a mistake and we've almost removed everything about TEMPORARY TABLE in Spark, only a few parser rules are left for backward compatibility reason.

To clarify, there is no TEMPORARY TABLE in Spark, it never had. Spark only has TABLE, VIEW and TEMP VIEW.

;

bucketSpec
: CLUSTERED BY identifierList
(SORTED BY orderedIdentifierList)?
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* 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.catalog.v2;

import java.util.Map;

import org.apache.spark.sql.catalog.v2.expressions.Transform;
import org.apache.spark.sql.sources.v2.StagedTable;
import org.apache.spark.sql.types.StructType;

public interface TransactionalTableCatalog {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

TransactionalTableCatalog is proposed in the SPIP, but we don't really encode any formal notion of transactions in these APIs. Transactionality has a particular connotation in the DBMS nomenclature, e.g. START TRANSACTION statements. Perhaps we can rename this to AtomicTableCatalog or SupportsAtomicOperations?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think renaming this is a good idea. How about StagingTableCatalog? The main capability it introduces is staging a table so that it can be used for a write, but doesn't yet exist.


StagedTable stageCreate(
Identifier ident,
StructType schema,
Transform[] partitions,
Map<String, String> properties);

StagedTable stageReplace(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

These also need Javadoc.

Identifier ident,
StructType schema,
Transform[] partitions,
Map<String, String> properties);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* 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.sources.v2;

public interface StagedTable extends Table {

void commitStagedChanges();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It's not immediately obvious if this API belongs in StagedTable, or if it should be tied to the BatchWrite's commit() operation. The idea I had with tying it to StagedTable is:

  1. Make the atomic swap part more explicit from the perspective of the physical plan execution, and
  2. Allow both StagedTable and Table to share the same WriteBuilder and BatchWrite implementations that persist the rows, and decouple the atomic swap in this module only.

If we wanted to move the swap implementation behind the BatchWrite#commit and BatchWrite#abort APIs, then it's worth asking if we need the StagedTable interface at all - so TransactionalTableCatalog would return plain Table objects.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I like this. So the write's commit stashes changes in the staged table, which can finish or roll back.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This also solves the problem of where to document how to complete the changes staged in a StagedTable. Can you add docs that describe what these methods should do, and for the StagedTable interface?


void abortStagedChanges();
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ import org.apache.spark.sql.catalyst.expressions.aggregate.{First, Last}
import org.apache.spark.sql.catalyst.parser.SqlBaseParser._
import org.apache.spark.sql.catalyst.plans._
import org.apache.spark.sql.catalyst.plans.logical._
import org.apache.spark.sql.catalyst.plans.logical.sql.{CreateTableAsSelectStatement, CreateTableStatement, DropTableStatement, DropViewStatement}
import org.apache.spark.sql.catalyst.plans.logical.sql.{CreateTableAsSelectStatement, CreateTableStatement, DropTableStatement, DropViewStatement, ReplaceTableAsSelectStatement, ReplaceTableStatement}
import org.apache.spark.sql.catalyst.util.DateTimeUtils.{getZoneId, stringToDate, stringToTimestamp}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types._
Expand Down Expand Up @@ -2035,6 +2035,16 @@ class AstBuilder(conf: SQLConf) extends SqlBaseBaseVisitor[AnyRef] with Logging
(multipartIdentifier, temporary, ifNotExists, ctx.EXTERNAL != null)
}

/**
* Validate a replace table statement and return the [[TableIdentifier]].
*/
override def visitReplaceTableHeader(
ctx: ReplaceTableHeaderContext): TableHeader = withOrigin(ctx) {
val temporary = ctx.TEMPORARY != null
val multipartIdentifier = ctx.multipartIdentifier.parts.asScala.map(_.getText)
(multipartIdentifier, temporary, false, false)
}

/**
* Parse a list of transforms.
*/
Expand Down Expand Up @@ -2195,6 +2205,76 @@ class AstBuilder(conf: SQLConf) extends SqlBaseBaseVisitor[AnyRef] with Logging
}
}

/**
* Replace a table, returning a [[ReplaceTableStatement]] logical plan.
*
* Expected format:
* {{{
* REPLACE TABLE [IF NOT EXISTS] [db_name.]table_name

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

this doesn't match the actual syntax now.

* USING table_provider
* replace_table_clauses
* [[AS] select_statement];
*
* replace_table_clauses (order insensitive):
* [OPTIONS table_property_list]
* [PARTITIONED BY (col_name, transform(col_name), transform(constant, col_name), ...)]
* [CLUSTERED BY (col_name, col_name, ...)
* [SORTED BY (col_name [ASC|DESC], ...)]
* INTO num_buckets BUCKETS
* ]
* [LOCATION path]
* [COMMENT table_comment]
* [TBLPROPERTIES (property_name=property_value, ...)]
* }}}
*/
override def visitReplaceTable(ctx: ReplaceTableContext): LogicalPlan = withOrigin(ctx) {
val (table, temp, ifNotExists, external) = visitReplaceTableHeader(ctx.replaceTableHeader)
if (external) {
operationNotAllowed("REPLACE EXTERNAL TABLE ... USING", ctx)
}

checkDuplicateClauses(ctx.TBLPROPERTIES, "TBLPROPERTIES", ctx)
checkDuplicateClauses(ctx.OPTIONS, "OPTIONS", ctx)
checkDuplicateClauses(ctx.PARTITIONED, "PARTITIONED BY", ctx)
checkDuplicateClauses(ctx.COMMENT, "COMMENT", ctx)
checkDuplicateClauses(ctx.bucketSpec(), "CLUSTERED BY", ctx)
checkDuplicateClauses(ctx.locationSpec, "LOCATION", ctx)

val schema = Option(ctx.colTypeList()).map(createSchema)
val partitioning: Seq[Transform] =
Option(ctx.partitioning).map(visitTransformList).getOrElse(Nil)
val bucketSpec = ctx.bucketSpec().asScala.headOption.map(visitBucketSpec)
val properties = Option(ctx.tableProps).map(visitPropertyKeyValues).getOrElse(Map.empty)
val options = Option(ctx.options).map(visitPropertyKeyValues).getOrElse(Map.empty)

val provider = ctx.tableProvider.qualifiedName.getText
val location = ctx.locationSpec.asScala.headOption.map(visitLocationSpec)
val comment = Option(ctx.comment).map(string)

Option(ctx.query).map(plan) match {
case Some(_) if temp =>
operationNotAllowed("REPLACE TEMPORARY TABLE ... USING ... AS query", ctx)

case Some(_) if schema.isDefined =>
operationNotAllowed(
"Schema may not be specified in a Replace Table As Select (RTAS) statement",
ctx)

case Some(query) =>
ReplaceTableAsSelectStatement(
table, query, partitioning, bucketSpec, properties, provider, options, location, comment)

case None if temp =>
// REPLACE TEMPORARY TABLE ... USING ... is not supported by the catalyst parser.
// Use REPLACE TEMPORARY VIEW ... USING ... instead.
operationNotAllowed("REPLACE TEMPORARY TABLE IF NOT EXISTS", ctx)

case _ =>
ReplaceTableStatement(table, schema.getOrElse(new StructType), partitioning, bucketSpec,
properties, provider, options, location, comment)
}
}

/**
* Create a [[DropTableStatement]] command.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,42 @@ case class CreateTableAsSelect(
}
}

/**
* Replace a table with a v2 catalog.
*
* If the table does not exist, it will be created. The persisted table will have no contents
* as a result of this operation.
*/
case class ReplaceTable(
catalog: TableCatalog,
tableName: Identifier,
tableSchema: StructType,
partitioning: Seq[Transform],
properties: Map[String, String]) extends Command

/**
* Replaces a table from a select query with a v2 catalog.
*
* If the table does not already exist, it will be created.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

it will be created if orCreate = true?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Yeah, looks like this doc is out of date.

*/
case class ReplaceTableAsSelect(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What is the behavior if query depends on the table being replaced?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Great question. I'm fairly certain that:

  • If non-atomic catalog is being used, the table will have been dropped, so loading the table for the query will result in an error
  • If the atomic catalog is being used, the drop part of the replace isn't committed yet, so the catalog should be able to load the table's contents before the write is committed.

@rdblue - curious to hear your thoughts on the first situation. It makes a stronger case for trying to ban replacing tables without an atomic catalog.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I agree. If the drop happens first and is not atomic, then the create will fail.

We should be able to add a rule to check for this and fail the query in analysis if the table doesn't support atomic updates. @mccheah, can you open an issue for adding a rule like that?

@cloud-fan cloud-fan Jul 17, 2019

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

+1, I think we should fail the query if atomic RTAS is not supported. It's a valid use case to access the table being replaced in RTAS, Spark shouldn't throw table not found exception in this case, which is quite confusing.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@cloud-fan, we discussed this in the DSv2 sync and decided that, in general, RTAS should be supported even if the source is not atomic. Just to clarify, this would be a rule to fail RTAS if it is not atomic when the query depends on the table being replaced. We don't want to drop a table and then find that we can't replace it because it was dropped.

catalog: TableCatalog,
tableName: Identifier,
partitioning: Seq[Transform],
query: LogicalPlan,
properties: Map[String, String],
writeOptions: Map[String, String]) extends Command {

override def children: Seq[LogicalPlan] = Seq(query)

override lazy val resolved: Boolean = {
// the table schema is created from the query schema, so the only resolution needed is to check
// that the columns referenced by the table's partitioning exist in the query schema
val references = partitioning.flatMap(_.references).toSet
references.map(_.fieldNames).forall(query.schema.findNestedField(_).isDefined)
}
}

/**
* Append data to an existing table.
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* 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.catalyst.plans.logical.sql

import org.apache.spark.sql.catalog.v2.expressions.Transform
import org.apache.spark.sql.catalyst.catalog.BucketSpec
import org.apache.spark.sql.catalyst.expressions.Attribute
import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
import org.apache.spark.sql.types.StructType

/**
* A REPLACE TABLE command, as parsed from SQL.
*
* If the table exists prior to running this command, executing this statement
* will replace the table's metadata and clear the underlying rows from the table.
*/
case class ReplaceTableStatement(
tableName: Seq[String],
tableSchema: StructType,
partitioning: Seq[Transform],
bucketSpec: Option[BucketSpec],
properties: Map[String, String],
provider: String,
options: Map[String, String],
location: Option[String],
comment: Option[String]) extends ParsedStatement {

override def output: Seq[Attribute] = Seq.empty

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ParsedStatement now defaults these methods, so you can remove them.


override def children: Seq[LogicalPlan] = Seq.empty
}

/**
* A REPLACE TABLE AS SELECT command, as parsed from SQL.
*/
case class ReplaceTableAsSelectStatement(
tableName: Seq[String],
asSelect: LogicalPlan,
partitioning: Seq[Transform],
bucketSpec: Option[BucketSpec],
properties: Map[String, String],
provider: String,
options: Map[String, String],
location: Option[String],
comment: Option[String]) extends ParsedStatement {

override def output: Seq[Attribute] = Seq.empty

override def children: Seq[LogicalPlan] = Seq(asSelect)
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ import org.apache.spark.sql.catalog.v2.expressions.Transform
import org.apache.spark.sql.catalyst.TableIdentifier
import org.apache.spark.sql.catalyst.analysis.CastSupport
import org.apache.spark.sql.catalyst.catalog.{BucketSpec, CatalogTable, CatalogTableType, CatalogUtils}
import org.apache.spark.sql.catalyst.plans.logical.{CreateTableAsSelect, CreateV2Table, DropTable, LogicalPlan}
import org.apache.spark.sql.catalyst.plans.logical.sql.{CreateTableAsSelectStatement, CreateTableStatement, DropTableStatement, DropViewStatement}
import org.apache.spark.sql.catalyst.plans.logical.{CreateTableAsSelect, CreateV2Table, DropTable, LogicalPlan, ReplaceTable, ReplaceTableAsSelect}
import org.apache.spark.sql.catalyst.plans.logical.sql.{CreateTableAsSelectStatement, CreateTableStatement, DropTableStatement, DropViewStatement, ReplaceTableAsSelectStatement, ReplaceTableStatement}
import org.apache.spark.sql.catalyst.rules.Rule
import org.apache.spark.sql.execution.command.DropTableCommand
import org.apache.spark.sql.internal.SQLConf
Expand Down Expand Up @@ -85,6 +85,38 @@ case class DataSourceResolution(
.asTableCatalog
convertCTAS(catalog, identifier, create)

case ReplaceTableStatement(
AsTableIdentifier(table), schema, partitionCols, bucketSpec, properties,
V1WriteProvider(provider), options, location, comment) =>
throw new AnalysisException(
s"Replacing tables is not supported using the legacy / v1 Spark external catalog" +
s" API. Write provider name: $provider, identifier: $table.")

case ReplaceTableAsSelectStatement(
AsTableIdentifier(table), query, partitionCols, bucketSpec, properties,
V1WriteProvider(provider), options, location, comment) =>
throw new AnalysisException(
s"Replacing tables is not supported using the legacy / v1 Spark external catalog" +
s" API. Write provider name: $provider, identifier: $table.")

case replace: ReplaceTableStatement =>
// the provider was not a v1 source, convert to a v2 plan
val CatalogObjectIdentifier(maybeCatalog, identifier) = replace.tableName
val catalog = maybeCatalog.orElse(defaultCatalog)
.getOrElse(throw new AnalysisException(
s"No catalog specified for table ${identifier.quoted} and no default catalog is set"))
.asTableCatalog
convertReplaceTable(catalog, identifier, replace)

case rtas: ReplaceTableAsSelectStatement =>
// the provider was not a v1 source, convert to a v2 plan
val CatalogObjectIdentifier(maybeCatalog, identifier) = rtas.tableName
val catalog = maybeCatalog.orElse(defaultCatalog)
.getOrElse(throw new AnalysisException(
s"No catalog specified for table ${identifier.quoted} and no default catalog is set"))
.asTableCatalog
convertRTAS(catalog, identifier, rtas)

case DropTableStatement(CatalogObjectIdentifier(Some(catalog), ident), ifExists, _) =>
DropTable(catalog.asTableCatalog, ident, ifExists)

Expand Down Expand Up @@ -194,6 +226,41 @@ case class DataSourceResolution(
ignoreIfExists = create.ifNotExists)
}

private def convertRTAS(
catalog: TableCatalog,
identifier: Identifier,
rtas: ReplaceTableAsSelectStatement): ReplaceTableAsSelect = {
// convert the bucket spec and add it as a transform
val partitioning = rtas.partitioning ++ rtas.bucketSpec.map(_.asTransform)
val properties = convertTableProperties(
rtas.properties, rtas.options, rtas.location, rtas.comment, rtas.provider)

ReplaceTableAsSelect(
catalog,
identifier,
partitioning,
rtas.asSelect,
properties,
writeOptions = rtas.options.filterKeys(_ != "path"))
}

private def convertReplaceTable(
catalog: TableCatalog,
identifier: Identifier,
replace: ReplaceTableStatement): ReplaceTable = {
// convert the bucket spec and add it as a transform
val partitioning = replace.partitioning ++ replace.bucketSpec.map(_.asTransform)
val properties = convertTableProperties(
replace.properties, replace.options, replace.location, replace.comment, replace.provider)

ReplaceTable(
catalog,
identifier,
replace.tableSchema,
partitioning,
properties)
}

private def convertTableProperties(
properties: Map[String, String],
options: Map[String, String],
Expand Down
Loading