This is an automated email from the ASF dual-hosted git repository.

etudenhoefner pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/iceberg.git


The following commit(s) were added to refs/heads/main by this push:
     new e1f50fd350 Core: Use V0 SQL schema as default /  rename 
jdbc.add-view-support to jdbc.schema-version (#9765)
e1f50fd350 is described below

commit e1f50fd3505b48e37f98049f8ea243aa9f1e08dd
Author: JB Onofré <[email protected]>
AuthorDate: Wed Feb 21 12:15:55 2024 +0100

    Core: Use V0 SQL schema as default /  rename jdbc.add-view-support to 
jdbc.schema-version (#9765)
---
 .../java/org/apache/iceberg/jdbc/JdbcCatalog.java  | 158 ++++++++++++---------
 .../java/org/apache/iceberg/jdbc/JdbcUtil.java     |   8 +-
 .../org/apache/iceberg/jdbc/TestJdbcCatalog.java   |  70 +++++----
 .../apache/iceberg/jdbc/TestJdbcViewCatalog.java   |   1 +
 4 files changed, 138 insertions(+), 99 deletions(-)

diff --git a/core/src/main/java/org/apache/iceberg/jdbc/JdbcCatalog.java 
b/core/src/main/java/org/apache/iceberg/jdbc/JdbcCatalog.java
index 8d0a93b727..73c7e05865 100644
--- a/core/src/main/java/org/apache/iceberg/jdbc/JdbcCatalog.java
+++ b/core/src/main/java/org/apache/iceberg/jdbc/JdbcCatalog.java
@@ -20,7 +20,6 @@ package org.apache.iceberg.jdbc;
 
 import java.io.IOException;
 import java.io.UncheckedIOException;
-import java.sql.Connection;
 import java.sql.DatabaseMetaData;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
@@ -75,7 +74,7 @@ public class JdbcCatalog extends BaseMetastoreViewCatalog
   private static final Logger LOG = LoggerFactory.getLogger(JdbcCatalog.class);
   private static final Joiner SLASH = Joiner.on("/");
   static final String VIEW_WARNING_LOG_MESSAGE =
-      "JDBC catalog is initialized without view support. To auto-migrate the 
database's schema and enable view support, set jdbc.add-view-support=true";
+      "JDBC catalog is initialized without view support. To auto-migrate the 
database's schema and enable view support, set jdbc.schema-version=V1";
 
   private FileIO io;
   private String catalogName = "jdbc";
@@ -87,7 +86,7 @@ public class JdbcCatalog extends BaseMetastoreViewCatalog
   private final Function<Map<String, String>, JdbcClientPool> 
clientPoolBuilder;
   private final boolean initializeCatalogTables;
   private CloseableGroup closeableGroup;
-  private JdbcUtil.SchemaVersion schemaVersion = JdbcUtil.SchemaVersion.V1;
+  private JdbcUtil.SchemaVersion schemaVersion = JdbcUtil.SchemaVersion.V0;
 
   public JdbcCatalog() {
     this(null, null, true);
@@ -136,10 +135,60 @@ public class JdbcCatalog extends BaseMetastoreViewCatalog
       this.connections = new JdbcClientPool(uri, properties);
     }
 
+    if (initializeCatalogTables) {
+      initializeCatalogTables();
+    }
+
+    updateSchemaIfRequired();
+
+    this.closeableGroup = new CloseableGroup();
+    closeableGroup.addCloseable(metricsReporter());
+    closeableGroup.addCloseable(connections);
+    closeableGroup.setSuppressCloseFailure(true);
+  }
+
+  private void initializeCatalogTables() {
+    LOG.trace("Creating database tables (if missing) to store iceberg 
catalog");
     try {
-      if (initializeCatalogTables) {
-        initializeCatalogTables();
-      }
+      connections.run(
+          conn -> {
+            DatabaseMetaData dbMeta = conn.getMetaData();
+            ResultSet tableExists =
+                dbMeta.getTables(
+                    null /* catalog name */,
+                    null /* schemaPattern */,
+                    JdbcUtil.CATALOG_TABLE_VIEW_NAME /* tableNamePattern */,
+                    null /* types */);
+            if (tableExists.next()) {
+              return true;
+            }
+
+            LOG.debug(
+                "Creating table {} to store iceberg catalog tables",
+                JdbcUtil.CATALOG_TABLE_VIEW_NAME);
+            return 
conn.prepareStatement(JdbcUtil.V0_CREATE_CATALOG_SQL).execute();
+          });
+
+      connections.run(
+          conn -> {
+            DatabaseMetaData dbMeta = conn.getMetaData();
+            ResultSet tableExists =
+                dbMeta.getTables(
+                    null /* catalog name */,
+                    null /* schemaPattern */,
+                    JdbcUtil.NAMESPACE_PROPERTIES_TABLE_NAME /* 
tableNamePattern */,
+                    null /* types */);
+
+            if (tableExists.next()) {
+              return true;
+            }
+
+            LOG.debug(
+                "Creating table {} to store iceberg catalog namespace 
properties",
+                JdbcUtil.NAMESPACE_PROPERTIES_TABLE_NAME);
+            return 
conn.prepareStatement(JdbcUtil.CREATE_NAMESPACE_PROPERTIES_TABLE_SQL).execute();
+          });
+
     } catch (SQLTimeoutException e) {
       throw new UncheckedSQLException(e, "Cannot initialize JDBC catalog: 
Query timed out");
     } catch (SQLTransientConnectionException | 
SQLNonTransientConnectionException e) {
@@ -150,69 +199,44 @@ public class JdbcCatalog extends BaseMetastoreViewCatalog
       Thread.currentThread().interrupt();
       throw new UncheckedInterruptedException(e, "Interrupted in call to 
initialize");
     }
-    this.closeableGroup = new CloseableGroup();
-    closeableGroup.addCloseable(metricsReporter());
-    closeableGroup.addCloseable(connections);
-    closeableGroup.setSuppressCloseFailure(true);
   }
 
-  private void initializeCatalogTables() throws InterruptedException, 
SQLException {
-    LOG.trace("Creating database tables (if missing) to store iceberg 
catalog");
-    connections.run(
-        conn -> {
-          DatabaseMetaData dbMeta = conn.getMetaData();
-          ResultSet tableExists =
-              dbMeta.getTables(
-                  null /* catalog name */,
-                  null /* schemaPattern */,
-                  JdbcUtil.CATALOG_TABLE_VIEW_NAME /* tableNamePattern */,
-                  null /* types */);
-          if (tableExists.next()) {
-            updateCatalogTables(conn);
-            return true;
-          }
-
-          LOG.debug(
-              "Creating table {} to store iceberg catalog tables",
-              JdbcUtil.CATALOG_TABLE_VIEW_NAME);
-          return conn.prepareStatement(JdbcUtil.CREATE_CATALOG_SQL).execute();
-        });
-
-    connections.run(
-        conn -> {
-          DatabaseMetaData dbMeta = conn.getMetaData();
-          ResultSet tableExists =
-              dbMeta.getTables(
-                  null /* catalog name */,
-                  null /* schemaPattern */,
-                  JdbcUtil.NAMESPACE_PROPERTIES_TABLE_NAME /* tableNamePattern 
*/,
-                  null /* types */);
-
-          if (tableExists.next()) {
-            return true;
-          }
-
-          LOG.debug(
-              "Creating table {} to store iceberg catalog namespace 
properties",
-              JdbcUtil.NAMESPACE_PROPERTIES_TABLE_NAME);
-          return 
conn.prepareStatement(JdbcUtil.CREATE_NAMESPACE_PROPERTIES_TABLE_SQL).execute();
-        });
-  }
-
-  private void updateCatalogTables(Connection connection) throws SQLException {
-    DatabaseMetaData dbMeta = connection.getMetaData();
-    ResultSet typeColumn =
-        dbMeta.getColumns(null, null, JdbcUtil.CATALOG_TABLE_VIEW_NAME, 
JdbcUtil.RECORD_TYPE);
-    if (typeColumn.next()) {
-      LOG.debug("{} already supports views", JdbcUtil.CATALOG_TABLE_VIEW_NAME);
-    } else {
-      if (PropertyUtil.propertyAsBoolean(
-          catalogProperties, JdbcUtil.ADD_VIEW_SUPPORT_PROPERTY, false)) {
-        connection.prepareStatement(JdbcUtil.UPDATE_CATALOG_SQL).execute();
-      } else {
-        LOG.warn(VIEW_WARNING_LOG_MESSAGE);
-        schemaVersion = JdbcUtil.SchemaVersion.V0;
-      }
+  private void updateSchemaIfRequired() {
+    try {
+      connections.run(
+          conn -> {
+            DatabaseMetaData dbMeta = conn.getMetaData();
+            ResultSet typeColumn =
+                dbMeta.getColumns(
+                    null, null, JdbcUtil.CATALOG_TABLE_VIEW_NAME, 
JdbcUtil.RECORD_TYPE);
+            if (typeColumn.next()) {
+              LOG.debug("{} already supports views", 
JdbcUtil.CATALOG_TABLE_VIEW_NAME);
+              schemaVersion = JdbcUtil.SchemaVersion.V1;
+              return true;
+            } else {
+              if (PropertyUtil.propertyAsString(
+                      catalogProperties,
+                      JdbcUtil.SCHEMA_VERSION_PROPERTY,
+                      JdbcUtil.SchemaVersion.V0.name())
+                  .equalsIgnoreCase(JdbcUtil.SchemaVersion.V1.name())) {
+                LOG.debug("{} is being updated to support views", 
JdbcUtil.CATALOG_TABLE_VIEW_NAME);
+                schemaVersion = JdbcUtil.SchemaVersion.V1;
+                return 
conn.prepareStatement(JdbcUtil.V1_UPDATE_CATALOG_SQL).execute();
+              } else {
+                LOG.warn(VIEW_WARNING_LOG_MESSAGE);
+                return true;
+              }
+            }
+          });
+    } catch (SQLTimeoutException e) {
+      throw new UncheckedSQLException(e, "Cannot update JDBC catalog: Query 
timed out");
+    } catch (SQLTransientConnectionException | 
SQLNonTransientConnectionException e) {
+      throw new UncheckedSQLException(e, "Cannot update JDBC catalog: 
Connection failed");
+    } catch (SQLException e) {
+      throw new UncheckedSQLException(e, "Cannot check and eventually update 
SQL schema");
+    } catch (InterruptedException e) {
+      Thread.currentThread().interrupt();
+      throw new UncheckedInterruptedException(e, "Interrupted in call to 
initialize");
     }
   }
 
diff --git a/core/src/main/java/org/apache/iceberg/jdbc/JdbcUtil.java 
b/core/src/main/java/org/apache/iceberg/jdbc/JdbcUtil.java
index 20a2f7ea62..077c33321b 100644
--- a/core/src/main/java/org/apache/iceberg/jdbc/JdbcUtil.java
+++ b/core/src/main/java/org/apache/iceberg/jdbc/JdbcUtil.java
@@ -38,7 +38,7 @@ final class JdbcUtil {
   // property to control strict-mode (aka check if namespace exists when 
creating a table)
   static final String STRICT_MODE_PROPERTY = JdbcCatalog.PROPERTY_PREFIX + 
"strict-mode";
   // property to control if view support is added to the existing database
-  static final String ADD_VIEW_SUPPORT_PROPERTY = JdbcCatalog.PROPERTY_PREFIX 
+ "add-view-support";
+  static final String SCHEMA_VERSION_PROPERTY = JdbcCatalog.PROPERTY_PREFIX + 
"schema-version";
 
   enum SchemaVersion {
     V0,
@@ -90,7 +90,7 @@ final class JdbcUtil {
           + " = ? AND "
           + JdbcTableOperations.METADATA_LOCATION_PROP
           + " = ?";
-  static final String CREATE_CATALOG_SQL =
+  static final String V0_CREATE_CATALOG_SQL =
       "CREATE TABLE "
           + CATALOG_TABLE_VIEW_NAME
           + "("
@@ -104,8 +104,6 @@ final class JdbcUtil {
           + " VARCHAR(1000),"
           + JdbcTableOperations.PREVIOUS_METADATA_LOCATION_PROP
           + " VARCHAR(1000),"
-          + RECORD_TYPE
-          + " VARCHAR(100),"
           + "PRIMARY KEY ("
           + CATALOG_NAME
           + ", "
@@ -114,7 +112,7 @@ final class JdbcUtil {
           + TABLE_NAME
           + ")"
           + ")";
-  static final String UPDATE_CATALOG_SQL =
+  static final String V1_UPDATE_CATALOG_SQL =
       "ALTER TABLE " + CATALOG_TABLE_VIEW_NAME + " ADD COLUMN " + RECORD_TYPE 
+ " VARCHAR(5)";
 
   private static final String GET_VIEW_SQL =
diff --git a/core/src/test/java/org/apache/iceberg/jdbc/TestJdbcCatalog.java 
b/core/src/test/java/org/apache/iceberg/jdbc/TestJdbcCatalog.java
index 3c39ed3c13..f9bbb527be 100644
--- a/core/src/test/java/org/apache/iceberg/jdbc/TestJdbcCatalog.java
+++ b/core/src/test/java/org/apache/iceberg/jdbc/TestJdbcCatalog.java
@@ -140,6 +140,7 @@ public class TestJdbcCatalog extends 
CatalogTests<JdbcCatalog> {
 
     properties.put(JdbcCatalog.PROPERTY_PREFIX + "username", "user");
     properties.put(JdbcCatalog.PROPERTY_PREFIX + "password", "password");
+    properties.put(JdbcUtil.SCHEMA_VERSION_PROPERTY, 
JdbcUtil.SchemaVersion.V1.name());
     warehouseLocation = this.tableDir.toAbsolutePath().toString();
     properties.put(CatalogProperties.WAREHOUSE_LOCATION, warehouseLocation);
     properties.put("type", "jdbc");
@@ -153,6 +154,7 @@ public class TestJdbcCatalog extends 
CatalogTests<JdbcCatalog> {
     Map<String, String> properties = Maps.newHashMap();
     properties.put(CatalogProperties.WAREHOUSE_LOCATION, 
this.tableDir.toAbsolutePath().toString());
     properties.put(CatalogProperties.URI, 
"jdbc:sqlite:file::memory:?icebergDB");
+    properties.put(JdbcUtil.SCHEMA_VERSION_PROPERTY, 
JdbcUtil.SchemaVersion.V1.name());
     JdbcCatalog jdbcCatalog = new JdbcCatalog();
     jdbcCatalog.setConf(conf);
     jdbcCatalog.initialize("test_jdbc_catalog", properties);
@@ -161,6 +163,41 @@ public class TestJdbcCatalog extends 
CatalogTests<JdbcCatalog> {
     jdbcCatalog.initialize("test_jdbc_catalog", properties);
   }
 
+  @Test
+  public void testInitSchemaV0() {
+    Map<String, String> properties = Maps.newHashMap();
+    properties.put(CatalogProperties.WAREHOUSE_LOCATION, 
this.tableDir.toAbsolutePath().toString());
+    properties.put(CatalogProperties.URI, 
"jdbc:sqlite:file::memory:?icebergDBV0");
+    properties.put(JdbcUtil.SCHEMA_VERSION_PROPERTY, 
JdbcUtil.SchemaVersion.V0.name());
+    JdbcCatalog jdbcCatalog = new JdbcCatalog();
+    jdbcCatalog.setConf(conf);
+    jdbcCatalog.initialize("v0catalog", properties);
+
+    TableIdentifier tableIdent = TableIdentifier.of(Namespace.of("ns1"), 
"tbl");
+    Table table =
+        jdbcCatalog
+            .buildTable(tableIdent, SCHEMA)
+            .withPartitionSpec(PARTITION_SPEC)
+            .withProperty("key1", "value1")
+            .withProperty("key2", "value2")
+            .create();
+
+    assertThat(table.schema().asStruct()).isEqualTo(SCHEMA.asStruct());
+    assertThat(table.spec().fields()).hasSize(1);
+    assertThat(table.properties()).containsEntry("key1", 
"value1").containsEntry("key2", "value2");
+
+    
assertThat(jdbcCatalog.listTables(Namespace.of("ns1"))).hasSize(1).contains(tableIdent);
+
+    assertThatThrownBy(() -> jdbcCatalog.listViews(Namespace.of("namespace1")))
+        .isInstanceOf(UnsupportedOperationException.class)
+        .hasMessage(JdbcCatalog.VIEW_WARNING_LOG_MESSAGE);
+
+    assertThatThrownBy(
+            () -> jdbcCatalog.buildView(TableIdentifier.of("namespace1", 
"view")).create())
+        .isInstanceOf(UnsupportedOperationException.class)
+        .hasMessage(JdbcCatalog.VIEW_WARNING_LOG_MESSAGE);
+  }
+
   @Test
   public void testSchemaIsMigratedToAddViewSupport() throws Exception {
     // as this test uses different connections, we can't use memory database 
(as it's per
@@ -173,7 +210,7 @@ public class TestJdbcCatalog extends 
CatalogTests<JdbcCatalog> {
     Map<String, String> properties = Maps.newHashMap();
     properties.put(CatalogProperties.WAREHOUSE_LOCATION, 
this.tableDir.toAbsolutePath().toString());
     properties.put(CatalogProperties.URI, jdbcUrl);
-    properties.put(JdbcUtil.ADD_VIEW_SUPPORT_PROPERTY, "true");
+    properties.put(JdbcUtil.SCHEMA_VERSION_PROPERTY, 
JdbcUtil.SchemaVersion.V1.name());
     JdbcCatalog jdbcCatalog = new JdbcCatalog();
     jdbcCatalog.setConf(conf);
     jdbcCatalog.initialize("TEST", properties);
@@ -201,8 +238,9 @@ public class TestJdbcCatalog extends 
CatalogTests<JdbcCatalog> {
     
assertThat(jdbcCatalog.listViews(Namespace.of("namespace1"))).hasSize(1).containsExactly(view);
   }
 
-  @Test
-  public void testLegacySchemaSupport() throws Exception {
+  @ParameterizedTest
+  @ValueSource(booleans = {true, false})
+  public void testExistingV0SchemaSupport(boolean initializeCatalogTables) 
throws Exception {
     // as this test uses different connection, we can't use memory database 
(as it's per
     // connection), but a
     // file database instead
@@ -214,7 +252,7 @@ public class TestJdbcCatalog extends 
CatalogTests<JdbcCatalog> {
     Map<String, String> properties = Maps.newHashMap();
     properties.put(CatalogProperties.WAREHOUSE_LOCATION, 
this.tableDir.toAbsolutePath().toString());
     properties.put(CatalogProperties.URI, jdbcUrl);
-    JdbcCatalog jdbcCatalog = new JdbcCatalog();
+    JdbcCatalog jdbcCatalog = new JdbcCatalog(null, null, 
initializeCatalogTables);
     jdbcCatalog.setConf(conf);
     jdbcCatalog.initialize("TEST", properties);
 
@@ -949,29 +987,7 @@ public class TestJdbcCatalog extends 
CatalogTests<JdbcCatalog> {
 
     try (Connection connection = dataSource.getConnection()) {
       // create "old style" SQL schema
-      connection
-          .prepareStatement(
-              "CREATE TABLE "
-                  + JdbcUtil.CATALOG_TABLE_VIEW_NAME
-                  + "("
-                  + JdbcUtil.CATALOG_NAME
-                  + " VARCHAR(255) NOT NULL,"
-                  + JdbcUtil.TABLE_NAMESPACE
-                  + " VARCHAR(255) NOT NULL,"
-                  + JdbcUtil.TABLE_NAME
-                  + " VARCHAR(255) NOT NULL,"
-                  + JdbcTableOperations.METADATA_LOCATION_PROP
-                  + " VARCHAR(1000),"
-                  + JdbcTableOperations.PREVIOUS_METADATA_LOCATION_PROP
-                  + " VARCHAR(1000),"
-                  + "PRIMARY KEY("
-                  + JdbcUtil.CATALOG_NAME
-                  + ","
-                  + JdbcUtil.TABLE_NAMESPACE
-                  + ","
-                  + JdbcUtil.TABLE_NAME
-                  + "))")
-          .executeUpdate();
+      
connection.prepareStatement(JdbcUtil.V0_CREATE_CATALOG_SQL).executeUpdate();
       connection
           .prepareStatement(
               "INSERT INTO "
diff --git 
a/core/src/test/java/org/apache/iceberg/jdbc/TestJdbcViewCatalog.java 
b/core/src/test/java/org/apache/iceberg/jdbc/TestJdbcViewCatalog.java
index c7bdb158cd..8c02557642 100644
--- a/core/src/test/java/org/apache/iceberg/jdbc/TestJdbcViewCatalog.java
+++ b/core/src/test/java/org/apache/iceberg/jdbc/TestJdbcViewCatalog.java
@@ -43,6 +43,7 @@ public class TestJdbcViewCatalog extends 
ViewCatalogTests<JdbcCatalog> {
     properties.put(JdbcCatalog.PROPERTY_PREFIX + "username", "user");
     properties.put(JdbcCatalog.PROPERTY_PREFIX + "password", "password");
     properties.put(CatalogProperties.WAREHOUSE_LOCATION, 
tableDir.toAbsolutePath().toString());
+    properties.put(JdbcUtil.SCHEMA_VERSION_PROPERTY, 
JdbcUtil.SchemaVersion.V1.name());
 
     catalog = new JdbcCatalog();
     catalog.setConf(new Configuration());

Reply via email to