aokolnychyi commented on a change in pull request #33008:
URL: https://github.com/apache/spark/pull/33008#discussion_r660076623
##########
File path:
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/V2ScanRelationPushDown.scala
##########
@@ -30,6 +30,35 @@ object V2ScanRelationPushDown extends Rule[LogicalPlan] {
import DataSourceV2Implicits._
override def apply(plan: LogicalPlan): LogicalPlan = plan transformDown {
+ case RowLevelOperation(operation, cond, relation: DataSourceV2Relation,
rewritePlan) =>
+ val mergeTable = relation.table.asMergeTable
+ val scanBuilder = mergeTable.newScanBuilder(relation.options)
+
+ val normalizedFilters = DataSourceStrategy.normalizeExprs(cond :: Nil,
relation.output)
+ val (_, normalizedFiltersWithoutSubquery) =
+ normalizedFilters.partition(SubqueryExpression.hasSubquery)
+
+ val (pushedFilters, remainingFilters) = PushDownUtils.pushFilters(
Review comment:
Not really, we still want Spark to pass filters but it is up to the data
source to apply them. For example, there may be implementations that apply
filters to partitions but not files within partitions if they can atomically
replace only partitions.
To sum up, I don't anticipate any major changes to the existing pushdown
logic.
##########
File path:
sql/catalyst/src/main/java/org/apache/spark/sql/connector/write/DeltaWriter.java
##########
@@ -0,0 +1,38 @@
+/*
+ * 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.write;
+
+import org.apache.spark.annotation.Experimental;
+
+/**
+ * A data writer returned by {@link DeltaWriterFactory#createWriter(int,
long)} and is
+ * responsible for writing a delta of rows.
+ *
+ * @since 3.2.0
+ */
+@Experimental
+public interface DeltaWriter<T> extends DataWriter<T> {
+ void delete(T id);
+ void update(T id, T row);
+ void insert(T row);
Review comment:
I should have added more docs to methods. I'll fix it in the coming
days. We don't really use `write` but it is available in the parent. I guess we
either default like now or throw an unsupported exception. Maybe, an exception
will be safer.
Thoughts, @holdenk?
##########
File path:
sql/catalyst/src/main/java/org/apache/spark/sql/connector/write/DeltaWriter.java
##########
@@ -0,0 +1,38 @@
+/*
+ * 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.write;
+
+import org.apache.spark.annotation.Experimental;
+
+/**
+ * A data writer returned by {@link DeltaWriterFactory#createWriter(int,
long)} and is
+ * responsible for writing a delta of rows.
+ *
+ * @since 3.2.0
+ */
+@Experimental
+public interface DeltaWriter<T> extends DataWriter<T> {
+ void delete(T id);
+ void update(T id, T row);
Review comment:
It is currently a full row but the same API can be used for passing just
updated columns. We could expose an optional mix-in interface for
`RowLevelOperation`.
##########
File path:
sql/catalyst/src/main/java/org/apache/spark/sql/connector/write/SupportsDelta.java
##########
@@ -0,0 +1,35 @@
+/*
+ * 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.write;
+
+import org.apache.spark.annotation.Experimental;
+import org.apache.spark.sql.connector.expressions.NamedReference;
+
+/**
+ * A mix-in interface for {@link RowLevelOperation}. Data sources can
implement this interface
+ * to indicate they support handling deltas of rows.
+ *
+ * @since 3.2.0
+ */
+@Experimental
+public interface SupportsDelta extends RowLevelOperation {
Review comment:
We assume the default `RowLevelOperation` only supports replacing groups
as it is more common and requires less from data sources. For example, regular
Hive tables in Spark would be able to easily support group-based rewrites (i.e.
partition-level granularity).
##########
File path:
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteDeleteFromTable.scala
##########
@@ -0,0 +1,186 @@
+/*
+ * 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.analysis
+
+import java.util.UUID
+
+import org.apache.spark.sql.AnalysisException
+import org.apache.spark.sql.catalyst.InternalRowProjection
+import org.apache.spark.sql.catalyst.analysis.RowDeltaUtils._
+import org.apache.spark.sql.catalyst.expressions.{Alias, AttributeReference,
EqualNullSafe, Expression, Literal, Not}
+import org.apache.spark.sql.catalyst.plans.logical.{DeleteFromTable, Filter,
LogicalPlan, Project, ReplaceData, WriteDelta}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.connector.catalog.{SupportsDelete,
SupportsRowLevelOperations}
+import org.apache.spark.sql.connector.expressions.{FieldReference,
NamedReference}
+import org.apache.spark.sql.connector.write.{LogicalWriteInfo,
LogicalWriteInfoImpl, RowLevelOperation, RowLevelOperationTable, SupportsDelta}
+import org.apache.spark.sql.connector.write.RowLevelOperation.Command.DELETE
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
+import org.apache.spark.sql.types.{BooleanType, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+/**
+ * Assigns a rewrite plan for v2 tables that support rewriting data to handle
DELETE statements.
+ *
+ * If a table implements [[SupportsDelete]] and
[[SupportsRowLevelOperations]], we assign a rewrite
+ * plan but the optimizer will check whether this particular DELETE statement
can be handled
+ * by simply passing delete filters to the connector. If yes, the optimizer
will then discard
+ * the rewrite plan.
+ */
+object RewriteDeleteFromTable extends Rule[LogicalPlan] {
+
+ override def apply(plan: LogicalPlan): LogicalPlan = plan resolveOperators {
+ case delete @ DeleteFromTable(aliasedTable, cond, None) if delete.resolved
=>
+ EliminateSubqueryAliases(aliasedTable) match {
+ case relation @ DataSourceV2Relation(table:
SupportsRowLevelOperations, _, _, _, _) =>
+ val rowLevelOperation = buildRowLevelOperation(table)
+ val rowLevelOperationTable = RowLevelOperationTable(table,
rowLevelOperation)
+ val rewritePlan = rowLevelOperation match {
+ case _: SupportsDelta => buildWriteDeltaPlan(relation,
rowLevelOperationTable, cond)
+ case _ => buildReplaceDataPlan(relation, rowLevelOperationTable,
cond)
+ }
+ // keep the original relation in DELETE so that we can attempt to
delete with metadata
+ DeleteFromTable(relation, cond, Some(rewritePlan))
+
+ case DataSourceV2Relation(_: SupportsDelete, _, _, _, _) =>
+ // don't assign a rewrite plan as the table supports deletes only
with filters
+ delete
+
+ case DataSourceV2Relation(t, _, _, _, _) =>
+ throw new AnalysisException(s"Table $t does not support DELETE
statements")
+
+ case _ =>
+ delete
+ }
+ }
+
+ // build a rewrite plan for sources that support replacing groups of data
(e.g. files, partitions)
+ private def buildReplaceDataPlan(
+ relation: DataSourceV2Relation,
+ table: RowLevelOperationTable,
+ cond: Option[Expression]): LogicalPlan = {
+
+ // resolve all columns needed for DELETE including metadata columns for
grouping data on write
+ val requiredWriteAttrs = resolveRefs(relation,
table.operation.requiredWriteAttributes)
+
+ // construct a scan relation
+ val scanAttrs = toScanAttrs(relation, requiredWriteAttrs)
+ val scanRelation = relation.copy(table = table, output = scanAttrs)
+
+ // construct a plan that contains unmatched rows in matched groups that
must be carried over
+ // such rows do not match the condition but have to be copied over as the
source can replace
+ // only groups of rows
+ val deleteCond = cond.getOrElse(Literal.TrueLiteral)
+ val remainingRowsFilter = Not(EqualNullSafe(deleteCond, Literal(true,
BooleanType)))
+ val remainingRowsPlan = Filter(remainingRowsFilter, scanRelation)
+
+ // pass only required columns for unmatched rows to the writer
+ val writeRelation = relation.copy(table = table, output =
requiredWriteAttrs)
+ ReplaceData(writeRelation, remainingRowsPlan, relation)
+ }
+
+ // build a rewrite plan for sources that support row-level changes
+ private def buildWriteDeltaPlan(
+ relation: DataSourceV2Relation,
+ table: RowLevelOperationTable,
+ cond: Option[Expression]): LogicalPlan = {
+
+ val merge = table.operation.asInstanceOf[SupportsDelta]
+
+ // resolve all columns needed for merge (e.g. row ID and columns for
grouping data on write)
+ val requiredWriteAttrs = resolveRefs(relation,
table.operation.requiredWriteAttributes)
+ val rowIdAttrs = resolveRefs(relation, merge.rowId)
+
+ // construct a scan relation and include all required columns
+ val scanAttrs = toScanAttrs(relation, requiredWriteAttrs)
+ val scanRelation = relation.copy(table = table, output = scanAttrs)
+
+ // construct a plan that only contains records to delete
+ val deleteCond = cond.getOrElse(Literal.TrueLiteral)
+ val deletedRowsPlan = Filter(deleteCond, scanRelation)
+ val operation = Alias(Literal(DELETE_OPERATION), OPERATION_COLUMN)()
+ val project = Project(operation +: requiredWriteAttrs, deletedRowsPlan)
+
+ // pass operation and required columns to the writer as we are working
with deltas
+ val operationAttr = resolveRef(project, FieldReference(OPERATION_COLUMN))
+ val writeRelationAttrs = operationAttr +: requiredWriteAttrs
Review comment:
Good question. I am not sure whether we need new expr IDs. The purpose
of `requiredWriteAttrs` is to detect what columns we need to project from the
scan. Let me take a closer look.
--
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]