World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#9208] feat(iceberg-rest): Supply init script to create metadata tables for JDBC catalog backend (#14904)
PiotrAndrzejewskya98604bec325
diff --git a/build.gradle.kts b/build.gradle.ktsindex 6546c150d3..1e007bd7db 100644--- a/build.gradle.kts+++ b/build.gradle.kts@@ -1513,6 +1513,14 @@ tasks {fileMode = 0b111101101}+ copy {+ from(projectDir.dir("scripts")) {+ include("**/iceberg-*.sql")+ into("${rootProject.name}-iceberg-rest-server/scripts")+ }+ into(outputDir)+ }+copy {from(projectDir.dir("licenses")) { into("${rootProject.name}-iceberg-rest-server/licenses") }from(projectDir.file("LICENSE.iceberg")) { into("${rootProject.name}-iceberg-rest-server") }diff --git a/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java b/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.javaindex 01c6a4e719..d46c8d9544 100644--- a/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java+++ b/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java@@ -193,12 +193,16 @@ public class TestSQLScripts extends TestJDBCBackend {"(?:iceberg|optimizer)-metrics-schema-([\\d.]+)-"+ backendType.toLowerCase()+ "\\.sql");+ Pattern icebergJdbcPattern =+ Pattern.compile("iceberg-jdbc-schema-" + backendType.toLowerCase() + "\\.sql");Map<String, List<File>> versionScrips = new HashMap<>();+ List<File> icebergJdbcScripts = new ArrayList<>();for (File scriptFile : scriptFiles) {Matcher schemaMatcher = schemaPattern.matcher(scriptFile.getName());Matcher upgradeMatcher = upgradePattern.matcher(scriptFile.getName());Matcher metricsMatcher = metricsPattern.matcher(scriptFile.getName());+ Matcher icebergJdbcMatcher = icebergJdbcPattern.matcher(scriptFile.getName());if (schemaMatcher.matches()) {String version = schemaMatcher.group(1);@@ -213,6 +217,9 @@ public class TestSQLScripts extends TestJDBCBackend {String version = metricsMatcher.group(1);versionScrips.computeIfAbsent(version, k -> new ArrayList<>()).add(scriptFile);+ } else if (icebergJdbcMatcher.matches()) {+ icebergJdbcScripts.add(scriptFile);+} else {Assertions.fail("Unrecognized script file name: " + scriptFile.getName());}@@ -228,6 +235,14 @@ public class TestSQLScripts extends TestJDBCBackend {assertNameColumnWidths("schema " + versionScripts.getKey());}}++ Assertions.assertFalse(+ icebergJdbcScripts.isEmpty(),+ "No standalone Iceberg JDBC schema script found for " + backendType);+ for (File scriptFile : icebergJdbcScripts) {+ dropAllTables();+ executeScript(scriptFile);+ }}@TestTemplatediff --git a/docs/iceberg-rest-service.md b/docs/iceberg-rest-service.mdindex a2b28e63ae..d3f5e17b38 100644--- a/docs/iceberg-rest-service.md+++ b/docs/iceberg-rest-service.md@@ -87,6 +87,7 @@ The standalone Iceberg REST server package has the following layout:| └── hdfs-site.xml & core-site.xml # HDFS configuration files.|── libs/ # Gravitino Iceberg REST server dependencies libraries.|── logs/ # Gravitino Iceberg REST server logs. Automatically created after the server starts.+ |── scripts/ # SQL scripts for database initialization.```## Configuration@@ -248,6 +249,23 @@ Use `gravitino.iceberg-rest.jdbc-user` and `gravitino.iceberg-rest.jdbc-password:::cautionDownload the corresponding JDBC driver to the `iceberg-rest-server/libs` directory.If you are using multiple JDBC catalog backends, setting `jdbc-initialize` to true may not take effect for RDBMS like `Mysql`, you should create Iceberg meta tables explicitly.+You can initialize the metadata tables using the scripts provided in the `${GRAVITINO_HOME}/scripts/` directory:++- MySQL: `${GRAVITINO_HOME}/scripts/mysql/iceberg-jdbc-schema-mysql.sql`+- PostgreSQL: `${GRAVITINO_HOME}/scripts/postgresql/iceberg-jdbc-schema-postgresql.sql`+- H2: `${GRAVITINO_HOME}/scripts/h2/iceberg-jdbc-schema-h2.sql`++For example:++```bash+# MySQL+mysql -h <host> -u <username> -p <database> < ${GRAVITINO_HOME}/scripts/mysql/iceberg-jdbc-schema-mysql.sql++# PostgreSQL+psql -h <host> -U <username> -d <database> -f ${GRAVITINO_HOME}/scripts/postgresql/iceberg-jdbc-schema-postgresql.sql+```++When using H2, the JDBC connection URL must include `;DATABASE_TO_LOWER=TRUE` (e.g., `jdbc:h2:<path>;DATABASE_TO_LOWER=TRUE`). By default, H2 converts unquoted identifiers to uppercase, whereas Iceberg looks up metadata in lowercase. Without `DATABASE_TO_LOWER=TRUE`, Iceberg fails to detect existing columns such as `iceberg_type` and attempts an `ALTER TABLE`, which fails if the database user only has DML permissions.:::#### REST Backend Configurationdiff --git a/docs/lakehouse-iceberg-catalog.md b/docs/lakehouse-iceberg-catalog.mdindex 973cb7b6b4..394758e050 100644--- a/docs/lakehouse-iceberg-catalog.md+++ b/docs/lakehouse-iceberg-catalog.md@@ -95,6 +95,23 @@ If you have a JDBC Iceberg catalog prior, you must set `catalog-backend-name` to:::cautionDownload the corresponding JDBC driver and place it to the `catalogs/lakehouse-iceberg/libs` directory If you are using JDBC backend.If you are using multiple JDBC catalog backends, setting `jdbc-initialize` to true may not take effect for RDMS like `Mysql`, you should create Iceberg meta tables explicitly.+You can initialize the metadata tables using the scripts provided in the `${GRAVITINO_HOME}/scripts/` directory:++- MySQL: `${GRAVITINO_HOME}/scripts/mysql/iceberg-jdbc-schema-mysql.sql`+- PostgreSQL: `${GRAVITINO_HOME}/scripts/postgresql/iceberg-jdbc-schema-postgresql.sql`+- H2: `${GRAVITINO_HOME}/scripts/h2/iceberg-jdbc-schema-h2.sql`++For example:++```bash+# MySQL+mysql -h <host> -u <username> -p <database> < ${GRAVITINO_HOME}/scripts/mysql/iceberg-jdbc-schema-mysql.sql++# PostgreSQL+psql -h <host> -U <username> -d <database> -f ${GRAVITINO_HOME}/scripts/postgresql/iceberg-jdbc-schema-postgresql.sql+```++When using H2, the JDBC connection URL must include `;DATABASE_TO_LOWER=TRUE` (e.g., `jdbc:h2:<path>;DATABASE_TO_LOWER=TRUE`). By default, H2 converts unquoted identifiers to uppercase, whereas Iceberg looks up metadata in lowercase. Without `DATABASE_TO_LOWER=TRUE`, Iceberg fails to detect existing columns such as `iceberg_type` and attempts an `ALTER TABLE`, which fails if the database user only has DML permissions.:::#### REST Catalog Backenddiff --git a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/utils/TestIcebergCatalogUtil.java b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/utils/TestIcebergCatalogUtil.javaindex a7f562de46..424c75add9 100644--- a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/utils/TestIcebergCatalogUtil.java+++ b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/utils/TestIcebergCatalogUtil.java@@ -20,11 +20,16 @@package org.apache.gravitino.iceberg.common.utils;import java.io.UncheckedIOException;+import java.nio.file.Files;import java.nio.file.Path;+import java.sql.Connection;+import java.sql.DriverManager;import java.sql.SQLException;import java.sql.SQLSyntaxErrorException;+import java.sql.Statement;import java.util.HashMap;import java.util.Map;+import java.util.UUID;import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergCatalogBackend;import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;import org.apache.gravitino.iceberg.common.ClosableJdbcCatalog;@@ -32,10 +37,12 @@ import org.apache.gravitino.iceberg.common.IcebergConfig;import org.apache.gravitino.iceberg.common.authentication.AuthenticationConfig;import org.apache.gravitino.iceberg.common.rest.auth.UserPrincipalForwardingAuthManager;import org.apache.gravitino.storage.GCSProperties;+import org.apache.gravitino.utils.jdbc.JdbcSqlScriptUtils;import org.apache.iceberg.CatalogProperties;import org.apache.iceberg.Schema;import org.apache.iceberg.catalog.Catalog;import org.apache.iceberg.catalog.Namespace;+import org.apache.iceberg.catalog.SupportsNamespaces;import org.apache.iceberg.catalog.TableIdentifier;import org.apache.iceberg.exceptions.NoSuchNamespaceException;import org.apache.iceberg.hive.HiveCatalog;@@ -602,4 +609,130 @@ public class TestIcebergCatalogUtil {IcebergConstants.REST_BACKEND_AUTH_TYPE_SERVICE_ACCOUNT);return config;}++ @Test+ void testH2ManualInitWithDmlOnlyUser() throws Exception {+ Path dbPath = warehouse.resolve("iceberg_dml_test_" + UUID.randomUUID());+ String jdbcUrl = "jdbc:h2:" + dbPath.toAbsolutePath() + ";DATABASE_TO_LOWER=TRUE";+ String dmlUser = "dml_user";+ String dmlPassword = "dml_password";++ initH2WithDmlUser(jdbcUrl, dmlUser, dmlPassword);++ Map<String, String> properties = new HashMap<>();+ properties.put(CatalogProperties.URI, jdbcUrl);+ properties.put(CatalogProperties.WAREHOUSE_LOCATION, warehouse.toString());+ properties.put(IcebergConstants.GRAVITINO_JDBC_DRIVER, "org.h2.Driver");+ properties.put(IcebergConstants.ICEBERG_JDBC_USER, dmlUser);+ properties.put(IcebergConstants.ICEBERG_JDBC_PASSWORD, dmlPassword);+ properties.put(IcebergConstants.ICEBERG_JDBC_INITIALIZE, "false");++ Catalog catalog =+ IcebergCatalogUtil.loadCatalogBackend(+ IcebergCatalogBackend.JDBC, new IcebergConfig(properties));+ try {+ Assertions.assertInstanceOf(SupportsNamespaces.class, catalog);+ Namespace ns = Namespace.of("test_ns");+ Assertions.assertDoesNotThrow(() -> ((SupportsNamespaces) catalog).createNamespace(ns));+ Assertions.assertTrue(((SupportsNamespaces) catalog).namespaceExists(ns));++ // Verify DML operations on iceberg_tables+ Schema schema = new Schema(Types.NestedField.required(1, "id", Types.IntegerType.get()));+ TableIdentifier identifier = TableIdentifier.of(ns, "test_table");+ Assertions.assertNotNull(catalog.createTable(identifier, schema));+ Assertions.assertTrue(catalog.tableExists(identifier));+ Assertions.assertEquals(1, catalog.listTables(ns).size());+ } finally {+ if (catalog instanceof AutoCloseable) {+ ((AutoCloseable) catalog).close();+ }+ }+ }++ @Test+ void testH2ManualInitFailsWithoutDatabaseToLower() throws Exception {+ // Iceberg's JdbcCatalog (as of 1.11.0) looks up existing columns like 'iceberg_type' using+ // lowercase metadata names. With H2's default upper-case identifier settings, the column+ // is stored as uppercase ICEBERG_TYPE and the lookup misses. As a result, Iceberg assumes+ // view support is missing and attempts an ALTER TABLE ... ADD COLUMN migration, which fails+ // for a DML-only account with H2 error 90096 (Not enough rights).+ Path defaultDbPath = warehouse.resolve("iceberg_upper_test_" + UUID.randomUUID());+ String defaultJdbcUrl = "jdbc:h2:" + defaultDbPath.toAbsolutePath();+ String dmlUser = "dml_user";+ String dmlPassword = "dml_password";++ initH2WithDmlUser(defaultJdbcUrl, dmlUser, dmlPassword);++ Map<String, String> properties = new HashMap<>();+ properties.put(CatalogProperties.URI, defaultJdbcUrl);+ properties.put(CatalogProperties.WAREHOUSE_LOCATION, warehouse.toString());+ properties.put(IcebergConstants.GRAVITINO_JDBC_DRIVER, "org.h2.Driver");+ properties.put(IcebergConstants.ICEBERG_JDBC_USER, dmlUser);+ properties.put(IcebergConstants.ICEBERG_JDBC_PASSWORD, dmlPassword);+ properties.put(IcebergConstants.ICEBERG_JDBC_INITIALIZE, "false");++ UncheckedSQLException ex =+ Assertions.assertThrows(+ UncheckedSQLException.class,+ () ->+ IcebergCatalogUtil.loadCatalogBackend(+ IcebergCatalogBackend.JDBC, new IcebergConfig(properties)));+ Assertions.assertTrue(+ hasSqlErrorCode(ex, 90096),+ () -> "Expected H2 error 90096 (not enough rights), but got: " + ex);+ }++ private static void initH2WithDmlUser(String jdbcUrl, String dmlUser, String dmlPassword)+ throws Exception {+ Path scriptPath = findH2ScriptPath();+ String sqlContent = Files.readString(scriptPath);+ try (Connection conn = DriverManager.getConnection(jdbcUrl, "sa", "")) {+ JdbcSqlScriptUtils.executeSqlScript(conn, sqlContent);+ try (Statement stmt = conn.createStatement()) {+ stmt.execute(String.format("CREATE USER %s PASSWORD '%s'", dmlUser, dmlPassword));+ stmt.execute(+ String.format("GRANT SELECT, INSERT, UPDATE, DELETE ON iceberg_tables TO %s", dmlUser));+ stmt.execute(+ String.format(+ "GRANT SELECT, INSERT, UPDATE, DELETE ON iceberg_namespace_properties TO %s",+ dmlUser));+ }+ }+ }++ private static boolean hasSqlErrorCode(Throwable t, int expectedCode) {+ for (Throwable current = t; current != null; current = current.getCause()) {+ if (current instanceof SQLException+ && ((SQLException) current).getErrorCode() == expectedCode) {+ return true;+ }+ }+ return false;+ }++ private static Path findH2ScriptPath() {+ String gravitinoHome = System.getenv("GRAVITINO_HOME");+ if (gravitinoHome != null) {+ Path p = Path.of(gravitinoHome, "scripts", "h2", "iceberg-jdbc-schema-h2.sql");+ if (Files.exists(p)) {+ return p;+ }+ }+ String repoRoot = System.getProperty("gravitino.repositoryRoot");+ if (repoRoot != null) {+ Path p = Path.of(repoRoot, "scripts", "h2", "iceberg-jdbc-schema-h2.sql");+ if (Files.exists(p)) {+ return p;+ }+ }+ Path current = Path.of("").toAbsolutePath();+ while (current != null) {+ Path p = current.resolve("scripts/h2/iceberg-jdbc-schema-h2.sql");+ if (Files.exists(p)) {+ return p;+ }+ current = current.getParent();+ }+ throw new IllegalStateException("Cannot find scripts/h2/iceberg-jdbc-schema-h2.sql");+ }}diff --git a/scripts/h2/iceberg-jdbc-schema-h2.sql b/scripts/h2/iceberg-jdbc-schema-h2.sqlnew file mode 100644index 0000000000..570bd1b56e--- /dev/null+++ b/scripts/h2/iceberg-jdbc-schema-h2.sql@@ -0,0 +1,36 @@+--+-- 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.+--++CREATE TABLE IF NOT EXISTS iceberg_tables (+ catalog_name VARCHAR(255) NOT NULL,+ table_namespace VARCHAR(255) NOT NULL,+ table_name VARCHAR(255) NOT NULL,+ metadata_location VARCHAR(1000),+ previous_metadata_location VARCHAR(1000),+ iceberg_type VARCHAR(5),+ PRIMARY KEY (catalog_name, table_namespace, table_name)+);++CREATE TABLE IF NOT EXISTS iceberg_namespace_properties (+ catalog_name VARCHAR(255) NOT NULL,+ namespace VARCHAR(255) NOT NULL,+ property_key VARCHAR(255) NOT NULL,+ property_value VARCHAR(1000),+ PRIMARY KEY (catalog_name, namespace, property_key)+);diff --git a/scripts/mysql/iceberg-jdbc-schema-mysql.sql b/scripts/mysql/iceberg-jdbc-schema-mysql.sqlnew file mode 100644index 0000000000..2035f2aee2--- /dev/null+++ b/scripts/mysql/iceberg-jdbc-schema-mysql.sql@@ -0,0 +1,36 @@+--+-- 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.+--++CREATE TABLE IF NOT EXISTS `iceberg_tables` (+ `catalog_name` VARCHAR(255) NOT NULL,+ `table_namespace` VARCHAR(255) NOT NULL,+ `table_name` VARCHAR(255) NOT NULL,+ `metadata_location` VARCHAR(1000),+ `previous_metadata_location` VARCHAR(1000),+ `iceberg_type` VARCHAR(5),+ PRIMARY KEY (`catalog_name`, `table_namespace`, `table_name`)+);++CREATE TABLE IF NOT EXISTS `iceberg_namespace_properties` (+ `catalog_name` VARCHAR(255) NOT NULL,+ `namespace` VARCHAR(255) NOT NULL,+ `property_key` VARCHAR(255) NOT NULL,+ `property_value` VARCHAR(1000),+ PRIMARY KEY (`catalog_name`, `namespace`, `property_key`)+);diff --git a/scripts/postgresql/iceberg-jdbc-schema-postgresql.sql b/scripts/postgresql/iceberg-jdbc-schema-postgresql.sqlnew file mode 100644index 0000000000..9f7ea8f32d--- /dev/null+++ b/scripts/postgresql/iceberg-jdbc-schema-postgresql.sql@@ -0,0 +1,43 @@+--+-- 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.+--++-- Note: Database and schema creation is not included in this script. Please create the database and+-- schema before running this script. For example in psql:+-- CREATE DATABASE example_db;+-- \c example_db+-- CREATE SCHEMA example_schema;+-- SET search_path TO example_schema;++CREATE TABLE IF NOT EXISTS iceberg_tables (+ catalog_name VARCHAR(255) NOT NULL,+ table_namespace VARCHAR(255) NOT NULL,+ table_name VARCHAR(255) NOT NULL,+ metadata_location VARCHAR(1000),+ previous_metadata_location VARCHAR(1000),+ iceberg_type VARCHAR(5),+ PRIMARY KEY (catalog_name, table_namespace, table_name)+);++CREATE TABLE IF NOT EXISTS iceberg_namespace_properties (+ catalog_name VARCHAR(255) NOT NULL,+ namespace VARCHAR(255) NOT NULL,+ property_key VARCHAR(255) NOT NULL,+ property_value VARCHAR(1000),+ PRIMARY KEY (catalog_name, namespace, property_key)+);