xanderbailey commented on code in PR #3778: URL: https://github.com/apache/iceberg-rust/pull/3778#discussion_r4712727797
########## crates/iceberg/src/transaction/replace_table.rs: ########## @@ -0,0 +1,564 @@ +// 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. + +use std::collections::HashMap; +use std::sync::Arc; + +use async_trait::async_trait; + +use crate::error::{Error, ErrorKind, Result}; +use crate::spec::{ + FormatVersion, MAIN_BRANCH, PartitionSpecRef, Schema, SortOrder, SortOrderRef, StructType, + TableMetadata, TableMetadataBuildResult, UnboundPartitionSpec, +}; +use crate::table::Table; +use crate::transaction::action::{ActionCommit, StatelessAction}; +use crate::{TableRequirement, TableUpdate}; + +/// Replaces a table's schema, partition spec and sort order, leaving it with no current +/// snapshot. Backs `REPLACE TABLE`. +/// +/// Must be the first action in its transaction. Write the new contents against +/// [`ReplaceTableAction::staged_table`] and add them with a later action, such as +/// [`FastAppendAction`](crate::transaction::FastAppendAction). +/// +/// Committing fails with [`ErrorKind::CatalogCommitConflicts`], without retrying, if since the +/// transaction started the table was dropped and recreated, a concurrent change assigned new +/// column or partition field ids, or a concurrent change would give the replacement's partition +/// spec or sort order a different id than its staged table. +#[derive(Clone)] +pub struct ReplaceTableAction { + table: Table, + schema: Schema, + partition_spec: UnboundPartitionSpec, + sort_order: SortOrder, + location: Option<String>, + format_version: Option<FormatVersion>, + properties: HashMap<String, String>, +} + +impl ReplaceTableAction { + pub(crate) fn new(table: Table, schema: Schema) -> Self { + Self { + table, + schema, + partition_spec: UnboundPartitionSpec::builder().build(), + sort_order: SortOrder::unsorted_order(), + location: None, + format_version: None, + properties: HashMap::new(), + } + } + + /// Sets the partition spec. Defaults to unpartitioned. + pub fn set_partition_spec(mut self, partition_spec: impl Into<UnboundPartitionSpec>) -> Self { + self.partition_spec = partition_spec.into(); + self + } + + /// Sets the sort order. Defaults to unsorted. + pub fn set_sort_order(mut self, sort_order: SortOrder) -> Self { + self.sort_order = sort_order; + self + } + + /// Moves the table to `location`. + pub fn set_location(mut self, location: String) -> Self { + self.location = Some(location); + self + } + + /// Upgrades the table to `format_version`. + pub fn set_format_version(mut self, format_version: FormatVersion) -> Self { + self.format_version = Some(format_version); + self + } + + /// Sets `properties` on top of the table's existing ones. + pub fn set_properties(mut self, properties: HashMap<String, String>) -> Self { + self.properties = properties; + self + } + + /// Returns the table as it will be after the replacement, to write its new contents against. + /// + /// # Errors + /// - The table is format version 1, which is not supported. + /// - The format version would downgrade the table. + /// - The partition spec or sort order names a column missing from the schema. + /// - The schema takes the name of a partition field in one of the table's specs without + /// being that field's source column. + /// - The properties contain a reserved property. + pub fn staged_table(&self) -> Result<Table> { + let metadata = self.replace(self.table.metadata())?.metadata; + Ok(self.table.clone().with_metadata(Arc::new(metadata))) + } + + fn replace(&self, metadata: &TableMetadata) -> Result<TableMetadataBuildResult> { + metadata + .clone() + .into_builder(None) + .build_replacement( + self.schema.clone(), + self.partition_spec.clone(), + self.sort_order.clone(), + self.location.clone(), + self.format_version, + self.properties.clone(), + )? + .build() + } +} + +#[async_trait] +impl StatelessAction for ReplaceTableAction { + async fn commit(&self, table: &Table) -> Result<ActionCommit> { + let original = self.table.metadata(); + let base = table.metadata(); + // Catches the table being dropped and recreated under the same name. + if base.uuid() != original.uuid() { + return Err(Error::new( + ErrorKind::CatalogCommitConflicts, + "Cannot replace table: it was recreated since the transaction started", + ) + .with_context("expected", original.uuid()) + .with_context("found", base.uuid())); + } + // Catches a concurrent change assigning ids the staged replacement may also have used. + if (base.last_column_id(), base.last_partition_id()) + != (original.last_column_id(), original.last_partition_id()) + { + return Err(Error::new( + ErrorKind::CatalogCommitConflicts, + "Cannot replace table: a concurrent change assigned new column or partition field ids", + )); + } + + let staged = self.replace(original)?; + let sets = |matches: fn(&TableUpdate) -> bool| staged.changes.iter().any(matches); + let mut updates = Vec::new(); + // main didn't exist when staged, but a concurrent commit such as a first append created it. Review Comment: I'm normally anti-comment but i've added comments for each of these cases to make it clear what case we're covering -- 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]
