bennychow commented on code in PR #9830: URL: https://github.com/apache/iceberg/pull/9830#discussion_r3471705560
########## spark/v3.5/spark-extensions/src/main/scala/org/apache/spark/sql/execution/datasources/v2/RefreshMaterializedViewExec.scala: ########## @@ -0,0 +1,148 @@ +/* + * 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.execution.datasources.v2 + +import org.apache.iceberg.catalog.Namespace +import org.apache.iceberg.catalog.TableIdentifier +import org.apache.iceberg.relocated.com.google.common.base.Preconditions +import org.apache.iceberg.spark.SparkCatalog +import org.apache.iceberg.view.RefreshState +import org.apache.iceberg.view.RefreshStateParser +import org.apache.iceberg.view.SourceTableState +import org.apache.iceberg.view.SQLViewRepresentation +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.analysis.NoSuchTableException +import org.apache.spark.sql.catalyst.expressions.Attribute +import org.apache.spark.sql.connector.catalog.Identifier +import org.apache.spark.sql.connector.catalog.ViewCatalog +import org.apache.spark.sql.functions +import scala.collection.JavaConverters._ + +case class RefreshMaterializedViewExec(catalog: ViewCatalog, ident: Identifier) + extends LeafV2CommandExec { + + override def output: Seq[Attribute] = Nil + + override protected def run(): Seq[InternalRow] = { + val sparkCatalog = catalog.asInstanceOf[SparkCatalog] + val icebergCatalog = sparkCatalog.icebergCatalog() + val icebergViewCatalog = + icebergCatalog.asInstanceOf[org.apache.iceberg.catalog.ViewCatalog] + val viewId = TableIdentifier.of(Namespace.of(ident.namespace(): _*), ident.name()) + val view = icebergViewCatalog.loadView(viewId) + + val storageTableId = view.currentVersion().storageTable() + Preconditions.checkState( + storageTableId != null, + "Cannot refresh %s: not a materialized view (no storage table)", + ident) + + // Extract the SQL query from the view's representations + val sparkSql = view + .currentVersion() + .representations() + .asScala + .collect { case sql: SQLViewRepresentation if sql.dialect() == "spark" => sql.sql() } + .headOption + .getOrElse(throw new IllegalStateException( + s"Cannot refresh $ident: no Spark SQL representation found")) + + val refreshStartTimestampMs = System.currentTimeMillis() + + // Execute the view's query to get the current result set + val queryResult = session.sql(sparkSql) + + // Discover source tables from the query's logical plan and capture their current state + val sourceStates = collectSourceTableStates(queryResult.queryExecution.analyzed) + + // Build refresh state + val refreshState = new RefreshState( + view.currentVersion().versionId(), + sourceStates.asJava, + refreshStartTimestampMs) + val refreshStateJson = RefreshStateParser.toJson(refreshState) + + // Write results to storage table, replacing existing data + val storageTableRef = String.format( + "%s.%s.%s", + sparkCatalog.name(), + storageTableId.namespace().toString, + storageTableId.name()) + try { + queryResult + .writeTo(storageTableRef) + .option("snapshot-property." + RefreshState.REFRESH_STATE_SUMMARY_KEY, refreshStateJson) + .overwrite(functions.lit(true)) + } catch { + case e: NoSuchTableException => + throw new IllegalStateException( + s"Storage table $storageTableRef not found during refresh", + e) + } + + Nil + } + + private def collectSourceTableStates( + plan: org.apache.spark.sql.catalyst.plans.logical.LogicalPlan) + : List[org.apache.iceberg.view.SourceState] = { + val sparkCatalog = catalog.asInstanceOf[SparkCatalog] + val icebergCatalog = + sparkCatalog.icebergCatalog().asInstanceOf[org.apache.iceberg.catalog.Catalog] + val tables = scala.collection.mutable.LinkedHashSet.empty[String] + val states = scala.collection.mutable.ListBuffer.empty[org.apache.iceberg.view.SourceState] + + plan.collectLeaves().foreach { + case r: org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation + if r.catalog.exists(_.name() == sparkCatalog.name()) => + val tableIdent = r.identifier.get + val key = tableIdent.toString + if (!tables.contains(key)) { + tables.add(key) + val icebergId = + TableIdentifier.of(Namespace.of(tableIdent.namespace(): _*), tableIdent.name()) + try { + val table = icebergCatalog.loadTable(icebergId) + val snapshotId = + if (table.currentSnapshot() != null) { + table.currentSnapshot().snapshotId() + } else { + -1L + } + states += new SourceTableState( Review Comment: What about the view logical nodes? ########## spark/v3.5/spark-extensions/src/main/scala/org/apache/spark/sql/execution/datasources/v2/RefreshMaterializedViewExec.scala: ########## @@ -0,0 +1,148 @@ +/* + * 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.execution.datasources.v2 + +import org.apache.iceberg.catalog.Namespace +import org.apache.iceberg.catalog.TableIdentifier +import org.apache.iceberg.relocated.com.google.common.base.Preconditions +import org.apache.iceberg.spark.SparkCatalog +import org.apache.iceberg.view.RefreshState +import org.apache.iceberg.view.RefreshStateParser +import org.apache.iceberg.view.SourceTableState +import org.apache.iceberg.view.SQLViewRepresentation +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.analysis.NoSuchTableException +import org.apache.spark.sql.catalyst.expressions.Attribute +import org.apache.spark.sql.connector.catalog.Identifier +import org.apache.spark.sql.connector.catalog.ViewCatalog +import org.apache.spark.sql.functions +import scala.collection.JavaConverters._ + +case class RefreshMaterializedViewExec(catalog: ViewCatalog, ident: Identifier) + extends LeafV2CommandExec { + + override def output: Seq[Attribute] = Nil + + override protected def run(): Seq[InternalRow] = { + val sparkCatalog = catalog.asInstanceOf[SparkCatalog] + val icebergCatalog = sparkCatalog.icebergCatalog() + val icebergViewCatalog = + icebergCatalog.asInstanceOf[org.apache.iceberg.catalog.ViewCatalog] + val viewId = TableIdentifier.of(Namespace.of(ident.namespace(): _*), ident.name()) + val view = icebergViewCatalog.loadView(viewId) + + val storageTableId = view.currentVersion().storageTable() + Preconditions.checkState( + storageTableId != null, + "Cannot refresh %s: not a materialized view (no storage table)", + ident) + + // Extract the SQL query from the view's representations + val sparkSql = view + .currentVersion() + .representations() + .asScala + .collect { case sql: SQLViewRepresentation if sql.dialect() == "spark" => sql.sql() } + .headOption + .getOrElse(throw new IllegalStateException( + s"Cannot refresh $ident: no Spark SQL representation found")) + + val refreshStartTimestampMs = System.currentTimeMillis() + + // Execute the view's query to get the current result set + val queryResult = session.sql(sparkSql) + + // Discover source tables from the query's logical plan and capture their current state + val sourceStates = collectSourceTableStates(queryResult.queryExecution.analyzed) + + // Build refresh state + val refreshState = new RefreshState( + view.currentVersion().versionId(), + sourceStates.asJava, + refreshStartTimestampMs) + val refreshStateJson = RefreshStateParser.toJson(refreshState) + + // Write results to storage table, replacing existing data + val storageTableRef = String.format( + "%s.%s.%s", + sparkCatalog.name(), + storageTableId.namespace().toString, + storageTableId.name()) + try { + queryResult + .writeTo(storageTableRef) + .option("snapshot-property." + RefreshState.REFRESH_STATE_SUMMARY_KEY, refreshStateJson) + .overwrite(functions.lit(true)) + } catch { + case e: NoSuchTableException => + throw new IllegalStateException( + s"Storage table $storageTableRef not found during refresh", + e) + } + + Nil + } + + private def collectSourceTableStates( + plan: org.apache.spark.sql.catalyst.plans.logical.LogicalPlan) + : List[org.apache.iceberg.view.SourceState] = { + val sparkCatalog = catalog.asInstanceOf[SparkCatalog] + val icebergCatalog = + sparkCatalog.icebergCatalog().asInstanceOf[org.apache.iceberg.catalog.Catalog] + val tables = scala.collection.mutable.LinkedHashSet.empty[String] + val states = scala.collection.mutable.ListBuffer.empty[org.apache.iceberg.view.SourceState] + + plan.collectLeaves().foreach { + case r: org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation + if r.catalog.exists(_.name() == sparkCatalog.name()) => + val tableIdent = r.identifier.get + val key = tableIdent.toString + if (!tables.contains(key)) { + tables.add(key) + val icebergId = + TableIdentifier.of(Namespace.of(tableIdent.namespace(): _*), tableIdent.name()) + try { + val table = icebergCatalog.loadTable(icebergId) + val snapshotId = + if (table.currentSnapshot() != null) { + table.currentSnapshot().snapshotId() Review Comment: If the source table is modified after planning, could this return the wrong snapshot id? ########## spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/SparkCatalog.java: ########## @@ -576,7 +577,14 @@ public View loadView(Identifier ident) throws NoSuchViewException { if (null != asViewCatalog) { try { org.apache.iceberg.view.View view = asViewCatalog.loadView(buildIdentifier(ident)); - return new SparkView(catalogName, view); + // Check if the view is a materialized view. If it is, and storage table is fresh, throw + // IllegalStateException + if (isMaterializedView(view) && isFresh(view)) { Review Comment: I agree with @danielcweeks too. I don't see why we need to do a freshness check here when the purpose of this method is to return the view definition if it exists. ########## spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/SparkCatalog.java: ########## @@ -585,6 +593,82 @@ public View loadView(Identifier ident) throws NoSuchViewException { throw new NoSuchViewException(ident); } + private boolean isMaterializedView(org.apache.iceberg.view.View view) { + return view.currentVersion().storageTable() != null; + } + + private org.apache.iceberg.catalog.TableIdentifier getStorageTableId( + org.apache.iceberg.view.View view) { + org.apache.iceberg.catalog.TableIdentifier storageTable = view.currentVersion().storageTable(); + Preconditions.checkState( + storageTable != null, "Storage table identifier is not set for materialized view."); + return storageTable; + } + + private Table loadStorageTable(org.apache.iceberg.view.View view) { + org.apache.iceberg.catalog.TableIdentifier storageTableId = getStorageTableId(view); + try { + Identifier sparkIdent = + Identifier.of(storageTableId.namespace().levels(), storageTableId.name()); + return loadTable(sparkIdent); + } catch (NoSuchTableException e) { + throw new IllegalStateException("Unable to load storage table for materialized view.", e); + } + } + + private boolean isFresh(org.apache.iceberg.view.View view) { + Table sparkStorageTable = loadStorageTable(view); + org.apache.iceberg.Table storageTable = ((SparkTable) sparkStorageTable).table(); + if (storageTable.currentSnapshot() == null) { + return false; + } + + String refreshStateJson = + storageTable + .currentSnapshot() + .summary() + .get(org.apache.iceberg.view.RefreshState.REFRESH_STATE_SUMMARY_KEY); + if (refreshStateJson == null) { + return false; + } + + org.apache.iceberg.view.RefreshState refreshState = + org.apache.iceberg.view.RefreshStateParser.fromJson(refreshStateJson); + + // If the refresh was performed against a different view version, the MV is not fresh + if (refreshState.viewVersionId() != view.currentVersion().versionId()) { + return false; + } + + // Check each source table state against the current state + for (org.apache.iceberg.view.SourceState sourceState : refreshState.sourceStates()) { + if (sourceState instanceof org.apache.iceberg.view.SourceTableState) { + org.apache.iceberg.view.SourceTableState tableState = + (org.apache.iceberg.view.SourceTableState) sourceState; + org.apache.iceberg.catalog.TableIdentifier sourceId = + org.apache.iceberg.catalog.TableIdentifier.of( + org.apache.iceberg.catalog.Namespace.of( + tableState.namespace().toArray(new String[0])), + tableState.name()); + try { + org.apache.iceberg.Table sourceTable = + ((org.apache.iceberg.catalog.Catalog) icebergCatalog()).loadTable(sourceId); + long currentSnapshotId = + sourceTable.currentSnapshot() == null + ? -1 + : sourceTable.currentSnapshot().snapshotId(); + if (currentSnapshotId != tableState.snapshotId()) { + return false; + } + } catch (Exception e) { + return false; Review Comment: Should this be logged with stacktrace? -- 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]
