diff --git a/core/src/main/java/org/apache/iceberg/inmemory/InMemoryCatalog.java b/core/src/main/java/org/apache/iceberg/inmemory/InMemoryCatalog.java index 566e56eec9b5..8a701fa3763c 100644 --- a/core/src/main/java/org/apache/iceberg/inmemory/InMemoryCatalog.java +++ b/core/src/main/java/org/apache/iceberg/inmemory/InMemoryCatalog.java @@ -165,6 +165,10 @@ public void renameTable(TableIdentifier from, TableIdentifier to) { throw new AlreadyExistsException("Cannot rename %s to %s. Table already exists", from, to); } + if (views.containsKey(to)) { + throw new AlreadyExistsException("Cannot rename %s to %s. View already exists", from, to); + } + tables.put(to, fromLocation); tables.remove(from); } diff --git a/core/src/test/java/org/apache/iceberg/view/ViewCatalogTests.java b/core/src/test/java/org/apache/iceberg/view/ViewCatalogTests.java index 3c88efe61b16..d5825030297b 100644 --- a/core/src/test/java/org/apache/iceberg/view/ViewCatalogTests.java +++ b/core/src/test/java/org/apache/iceberg/view/ViewCatalogTests.java @@ -669,6 +669,41 @@ public void renameViewTargetAlreadyExistsAsTable() { .hasMessageContaining("Cannot rename ns.view to ns.table. Table already exists"); } + @Test + public void renameTableTargetAlreadyExistsAsView() { + Assumptions.assumeThat(tableCatalog()) + .as("Only valid for catalogs that support tables") + .isNotNull(); + + TableIdentifier viewIdentifier = TableIdentifier.of("ns", "view"); + TableIdentifier tableIdentifier = TableIdentifier.of("ns", "table"); + + if (requiresNamespaceCreate()) { + catalog().createNamespace(tableIdentifier.namespace()); + } + + assertThat(tableCatalog().tableExists(tableIdentifier)).as("Table should not exist").isFalse(); + + tableCatalog().buildTable(tableIdentifier, SCHEMA).create(); + + assertThat(tableCatalog().tableExists(tableIdentifier)).as("Table should exist").isTrue(); + + assertThat(catalog().viewExists(viewIdentifier)).as("View should not exist").isFalse(); + + catalog() + .buildView(viewIdentifier) + .withSchema(SCHEMA) + .withDefaultNamespace(viewIdentifier.namespace()) + .withQuery("spark", "select * from ns.tbl") + .create(); + + assertThat(catalog().viewExists(viewIdentifier)).as("View should exist").isTrue(); + + assertThatThrownBy(() -> tableCatalog().renameTable(tableIdentifier, viewIdentifier)) + .isInstanceOf(AlreadyExistsException.class) + .hasMessageContaining("Cannot rename ns.table to ns.view. View already exists"); + } + @Test public void listViews() { Namespace ns1 = Namespace.of("ns1");