flyrain commented on code in PR #2328:
URL: https://github.com/apache/polaris/pull/2328#discussion_r2271522016


##########
persistence/google-cloud-spanner/src/main/java/org/apache/polaris/persistence/relational/spanner/GoogleCloudSpannerDatabaseClientLifecycleManager.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.polaris.persistence.relational.spanner;
+
+import com.google.cloud.spanner.Database;
+import com.google.cloud.spanner.DatabaseAdminClient;
+import com.google.cloud.spanner.DatabaseId;
+import com.google.cloud.spanner.Dialect;
+import com.google.cloud.spanner.Spanner;
+import com.google.cloud.spanner.SpannerException;
+import com.google.common.collect.ImmutableList;
+import jakarta.annotation.PostConstruct;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.inject.Produces;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.function.Consumer;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.persistence.bootstrap.SchemaOptions;
+import org.apache.polaris.persistence.relational.spanner.model.Realm;
+import org.apache.polaris.persistence.relational.spanner.util.SpannerUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@ApplicationScoped
+public class GoogleCloudSpannerDatabaseClientLifecycleManager {
+
+  private static Logger LOGGER =
+      
LoggerFactory.getLogger(GoogleCloudSpannerDatabaseClientLifecycleManager.class);
+
+  protected final GoogleCloudSpannerConfiguration spannerConfiguration;
+
+  public GoogleCloudSpannerDatabaseClientLifecycleManager(
+      GoogleCloudSpannerConfiguration spannerConfiguration) {
+    this.spannerConfiguration = spannerConfiguration;
+  }
+
+  protected Spanner spanner;
+  protected DatabaseId databaseId;
+
+  @PostConstruct
+  protected void init() {
+    spanner = SpannerUtil.spannerFromConfiguration(spannerConfiguration);
+    databaseId = SpannerUtil.databaseFromConfiguration(spannerConfiguration);
+  }
+
+  protected List<String> getSpannerDatabaseDdl(SchemaOptions options) {
+    final InputStream schemaStream;
+    if (options.schemaFile() != null) {
+      try {
+        schemaStream = new FileInputStream(options.schemaFile());
+      } catch (IOException e) {
+        throw new IllegalArgumentException("Unable to load file " + 
options.schemaFile(), e);
+      }
+    } else {
+      if (options.schemaVersion() == null || options.schemaVersion() == 1) {
+        schemaStream =
+            
getClass().getResourceAsStream("/org/apache/polaris/persistence/spanner/schema-v1.sql");
+      } else {
+        throw new IllegalArgumentException("Unknown schema version " + 
options.schemaVersion());
+      }
+    }
+    try (schemaStream) {
+      String schema = new String(schemaStream.readAllBytes(), 
Charset.forName("UTF-8"));
+      List<String> lines = new ArrayList<>();
+      for (String s : schema.split("\n")) {
+        s = s.trim();
+        if (s.startsWith("--") || s.length() == 0) {
+          continue;
+        }
+        lines.add(s);
+      }
+      return List.of(String.join(" ", lines).split(";"));
+    } catch (IOException e) {
+      throw new RuntimeException("Unable to retrieve DDL statements", e);
+    }
+  }
+
+  @Produces
+  public SchemaInitializer getSchemaInitializer() {
+    return (options) -> {
+      List<String> ddlStatements = getSpannerDatabaseDdl(options);
+      LOGGER.info(
+          "Attempting to initialize Spanner database DDL with {} statements,",
+          ddlStatements.size());
+      DatabaseAdminClient client = spanner.getDatabaseAdminClient();
+      Database dbInfo =
+          
client.newDatabaseBuilder(databaseId).setDialect(Dialect.GOOGLE_STANDARD_SQL).build();
+      try {
+        spanner.getDatabaseAdminClient().updateDatabaseDdl(dbInfo, 
ddlStatements, null).get();
+        LOGGER.info("Successfully applied DDL update.");
+      } catch (InterruptedException | ExecutionException e) {
+        LOGGER.error("Unable to update Spanner DDL.", e);

Review Comment:
   I think the error message isn't necessary as we throw the runtime exception 
next line.



##########
persistence/google-cloud-spanner/src/main/java/org/apache/polaris/persistence/relational/spanner/GoogleCloudSpannerDatabaseClientLifecycleManager.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.polaris.persistence.relational.spanner;
+
+import com.google.cloud.spanner.Database;
+import com.google.cloud.spanner.DatabaseAdminClient;
+import com.google.cloud.spanner.DatabaseId;
+import com.google.cloud.spanner.Dialect;
+import com.google.cloud.spanner.Spanner;
+import com.google.cloud.spanner.SpannerException;
+import com.google.common.collect.ImmutableList;
+import jakarta.annotation.PostConstruct;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.inject.Produces;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.function.Consumer;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.persistence.bootstrap.SchemaOptions;
+import org.apache.polaris.persistence.relational.spanner.model.Realm;
+import org.apache.polaris.persistence.relational.spanner.util.SpannerUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@ApplicationScoped
+public class GoogleCloudSpannerDatabaseClientLifecycleManager {
+
+  private static Logger LOGGER =
+      
LoggerFactory.getLogger(GoogleCloudSpannerDatabaseClientLifecycleManager.class);
+
+  protected final GoogleCloudSpannerConfiguration spannerConfiguration;
+
+  public GoogleCloudSpannerDatabaseClientLifecycleManager(
+      GoogleCloudSpannerConfiguration spannerConfiguration) {
+    this.spannerConfiguration = spannerConfiguration;
+  }
+
+  protected Spanner spanner;
+  protected DatabaseId databaseId;
+
+  @PostConstruct
+  protected void init() {
+    spanner = SpannerUtil.spannerFromConfiguration(spannerConfiguration);
+    databaseId = SpannerUtil.databaseFromConfiguration(spannerConfiguration);
+  }
+
+  protected List<String> getSpannerDatabaseDdl(SchemaOptions options) {
+    final InputStream schemaStream;
+    if (options.schemaFile() != null) {
+      try {
+        schemaStream = new FileInputStream(options.schemaFile());
+      } catch (IOException e) {
+        throw new IllegalArgumentException("Unable to load file " + 
options.schemaFile(), e);
+      }
+    } else {
+      if (options.schemaVersion() == null || options.schemaVersion() == 1) {
+        schemaStream =
+            
getClass().getResourceAsStream("/org/apache/polaris/persistence/spanner/schema-v1.sql");
+      } else {
+        throw new IllegalArgumentException("Unknown schema version " + 
options.schemaVersion());
+      }
+    }
+    try (schemaStream) {
+      String schema = new String(schemaStream.readAllBytes(), 
Charset.forName("UTF-8"));
+      List<String> lines = new ArrayList<>();
+      for (String s : schema.split("\n")) {
+        s = s.trim();
+        if (s.startsWith("--") || s.length() == 0) {
+          continue;
+        }
+        lines.add(s);
+      }
+      return List.of(String.join(" ", lines).split(";"));
+    } catch (IOException e) {
+      throw new RuntimeException("Unable to retrieve DDL statements", e);
+    }
+  }
+
+  @Produces
+  public SchemaInitializer getSchemaInitializer() {
+    return (options) -> {
+      List<String> ddlStatements = getSpannerDatabaseDdl(options);
+      LOGGER.info(
+          "Attempting to initialize Spanner database DDL with {} statements,",
+          ddlStatements.size());
+      DatabaseAdminClient client = spanner.getDatabaseAdminClient();
+      Database dbInfo =
+          
client.newDatabaseBuilder(databaseId).setDialect(Dialect.GOOGLE_STANDARD_SQL).build();
+      try {
+        spanner.getDatabaseAdminClient().updateDatabaseDdl(dbInfo, 
ddlStatements, null).get();

Review Comment:
   Minor: reuse the client?
   ```suggestion
           client.updateDatabaseDdl(dbInfo, ddlStatements, null).get();
   ```



##########
persistence/google-cloud-spanner/src/main/java/org/apache/polaris/persistence/relational/spanner/GoogleCloudSpannerDatabaseClientLifecycleManager.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.polaris.persistence.relational.spanner;
+
+import com.google.cloud.spanner.Database;
+import com.google.cloud.spanner.DatabaseAdminClient;
+import com.google.cloud.spanner.DatabaseId;
+import com.google.cloud.spanner.Dialect;
+import com.google.cloud.spanner.Spanner;
+import com.google.cloud.spanner.SpannerException;
+import com.google.common.collect.ImmutableList;
+import jakarta.annotation.PostConstruct;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.inject.Produces;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.function.Consumer;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.persistence.bootstrap.SchemaOptions;
+import org.apache.polaris.persistence.relational.spanner.model.Realm;
+import org.apache.polaris.persistence.relational.spanner.util.SpannerUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@ApplicationScoped
+public class GoogleCloudSpannerDatabaseClientLifecycleManager {
+
+  private static Logger LOGGER =
+      
LoggerFactory.getLogger(GoogleCloudSpannerDatabaseClientLifecycleManager.class);
+
+  protected final GoogleCloudSpannerConfiguration spannerConfiguration;
+
+  public GoogleCloudSpannerDatabaseClientLifecycleManager(
+      GoogleCloudSpannerConfiguration spannerConfiguration) {
+    this.spannerConfiguration = spannerConfiguration;
+  }
+
+  protected Spanner spanner;
+  protected DatabaseId databaseId;
+
+  @PostConstruct
+  protected void init() {
+    spanner = SpannerUtil.spannerFromConfiguration(spannerConfiguration);
+    databaseId = SpannerUtil.databaseFromConfiguration(spannerConfiguration);
+  }
+
+  protected List<String> getSpannerDatabaseDdl(SchemaOptions options) {
+    final InputStream schemaStream;
+    if (options.schemaFile() != null) {
+      try {
+        schemaStream = new FileInputStream(options.schemaFile());
+      } catch (IOException e) {
+        throw new IllegalArgumentException("Unable to load file " + 
options.schemaFile(), e);
+      }
+    } else {
+      if (options.schemaVersion() == null || options.schemaVersion() == 1) {
+        schemaStream =
+            
getClass().getResourceAsStream("/org/apache/polaris/persistence/spanner/schema-v1.sql");
+      } else {
+        throw new IllegalArgumentException("Unknown schema version " + 
options.schemaVersion());
+      }
+    }
+    try (schemaStream) {
+      String schema = new String(schemaStream.readAllBytes(), 
Charset.forName("UTF-8"));
+      List<String> lines = new ArrayList<>();
+      for (String s : schema.split("\n")) {
+        s = s.trim();
+        if (s.startsWith("--") || s.length() == 0) {
+          continue;
+        }
+        lines.add(s);
+      }
+      return List.of(String.join(" ", lines).split(";"));
+    } catch (IOException e) {
+      throw new RuntimeException("Unable to retrieve DDL statements", e);
+    }
+  }
+
+  @Produces
+  public SchemaInitializer getSchemaInitializer() {
+    return (options) -> {
+      List<String> ddlStatements = getSpannerDatabaseDdl(options);
+      LOGGER.info(
+          "Attempting to initialize Spanner database DDL with {} statements,",
+          ddlStatements.size());
+      DatabaseAdminClient client = spanner.getDatabaseAdminClient();
+      Database dbInfo =
+          
client.newDatabaseBuilder(databaseId).setDialect(Dialect.GOOGLE_STANDARD_SQL).build();
+      try {
+        spanner.getDatabaseAdminClient().updateDatabaseDdl(dbInfo, 
ddlStatements, null).get();
+        LOGGER.info("Successfully applied DDL update.");
+      } catch (InterruptedException | ExecutionException e) {
+        LOGGER.error("Unable to update Spanner DDL.", e);
+        throw new RuntimeException(
+            "Unable to update Spanner DDL. Please disable this option for this 
database configuration.",
+            e);
+      }
+    };
+  }
+
+  @Produces
+  public Consumer<RealmContext> getRealmInitializer() {
+    return (realmContext) -> {
+      try {
+        spanner
+            .getDatabaseClient(databaseId)
+            
.write(ImmutableList.of(Realm.upsert(realmContext.getRealmIdentifier())));

Review Comment:
   Agreed with @dimas-b. The realm initialization doesn't happen very often. It 
only happens when we bootstrap a new realm, 
https://polaris.apache.org/in-dev/unreleased/admin-tool/#bootstrapping-realms-and-principal-credentials.
 Producing a bean here isn't necessary to me, as Polaris server will never use 
it for realm initialization. Here is the reference code path in JDBC impl.: 
https://github.com/polaris-catalog/polaris/blob/main/persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/JdbcMetaStoreManagerFactory.java#L142-L142



##########
persistence/google-cloud-spanner/src/main/java/org/apache/polaris/persistence/relational/spanner/GoogleCloudSpannerDatabaseClientLifecycleManager.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.polaris.persistence.relational.spanner;
+
+import com.google.cloud.spanner.Database;
+import com.google.cloud.spanner.DatabaseAdminClient;
+import com.google.cloud.spanner.DatabaseId;
+import com.google.cloud.spanner.Dialect;
+import com.google.cloud.spanner.Spanner;
+import com.google.cloud.spanner.SpannerException;
+import com.google.common.collect.ImmutableList;
+import jakarta.annotation.PostConstruct;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.inject.Produces;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.function.Consumer;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.persistence.bootstrap.SchemaOptions;
+import org.apache.polaris.persistence.relational.spanner.model.Realm;
+import org.apache.polaris.persistence.relational.spanner.util.SpannerUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@ApplicationScoped
+public class GoogleCloudSpannerDatabaseClientLifecycleManager {
+
+  private static Logger LOGGER =
+      
LoggerFactory.getLogger(GoogleCloudSpannerDatabaseClientLifecycleManager.class);
+
+  protected final GoogleCloudSpannerConfiguration spannerConfiguration;
+
+  public GoogleCloudSpannerDatabaseClientLifecycleManager(
+      GoogleCloudSpannerConfiguration spannerConfiguration) {
+    this.spannerConfiguration = spannerConfiguration;
+  }
+
+  protected Spanner spanner;
+  protected DatabaseId databaseId;
+
+  @PostConstruct
+  protected void init() {
+    spanner = SpannerUtil.spannerFromConfiguration(spannerConfiguration);
+    databaseId = SpannerUtil.databaseFromConfiguration(spannerConfiguration);
+  }
+
+  protected List<String> getSpannerDatabaseDdl(SchemaOptions options) {

Review Comment:
   I think we could make this method static.



##########
persistence/google-cloud-spanner/src/main/java/org/apache/polaris/persistence/relational/spanner/GoogleCloudSpannerDatabaseClientLifecycleManager.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.polaris.persistence.relational.spanner;
+
+import com.google.cloud.spanner.Database;
+import com.google.cloud.spanner.DatabaseAdminClient;
+import com.google.cloud.spanner.DatabaseId;
+import com.google.cloud.spanner.Dialect;
+import com.google.cloud.spanner.Spanner;
+import com.google.cloud.spanner.SpannerException;
+import com.google.common.collect.ImmutableList;
+import jakarta.annotation.PostConstruct;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.inject.Produces;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.function.Consumer;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.persistence.bootstrap.SchemaOptions;
+import org.apache.polaris.persistence.relational.spanner.model.Realm;
+import org.apache.polaris.persistence.relational.spanner.util.SpannerUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@ApplicationScoped
+public class GoogleCloudSpannerDatabaseClientLifecycleManager {
+
+  private static Logger LOGGER =
+      
LoggerFactory.getLogger(GoogleCloudSpannerDatabaseClientLifecycleManager.class);
+
+  protected final GoogleCloudSpannerConfiguration spannerConfiguration;
+
+  public GoogleCloudSpannerDatabaseClientLifecycleManager(
+      GoogleCloudSpannerConfiguration spannerConfiguration) {
+    this.spannerConfiguration = spannerConfiguration;
+  }
+
+  protected Spanner spanner;
+  protected DatabaseId databaseId;
+
+  @PostConstruct
+  protected void init() {
+    spanner = SpannerUtil.spannerFromConfiguration(spannerConfiguration);
+    databaseId = SpannerUtil.databaseFromConfiguration(spannerConfiguration);
+  }
+
+  protected List<String> getSpannerDatabaseDdl(SchemaOptions options) {
+    final InputStream schemaStream;
+    if (options.schemaFile() != null) {
+      try {
+        schemaStream = new FileInputStream(options.schemaFile());
+      } catch (IOException e) {
+        throw new IllegalArgumentException("Unable to load file " + 
options.schemaFile(), e);
+      }
+    } else {
+      if (options.schemaVersion() == null || options.schemaVersion() == 1) {
+        schemaStream =
+            
getClass().getResourceAsStream("/org/apache/polaris/persistence/spanner/schema-v1.sql");
+      } else {
+        throw new IllegalArgumentException("Unknown schema version " + 
options.schemaVersion());
+      }
+    }
+    try (schemaStream) {
+      String schema = new String(schemaStream.readAllBytes(), 
Charset.forName("UTF-8"));
+      List<String> lines = new ArrayList<>();
+      for (String s : schema.split("\n")) {
+        s = s.trim();
+        if (s.startsWith("--") || s.length() == 0) {
+          continue;
+        }
+        lines.add(s);
+      }
+      return List.of(String.join(" ", lines).split(";"));
+    } catch (IOException e) {
+      throw new RuntimeException("Unable to retrieve DDL statements", e);
+    }
+  }
+
+  @Produces
+  public SchemaInitializer getSchemaInitializer() {

Review Comment:
   Same here. The scheme options are only used while bootstrapping. 
Bootstrappping was done by the Admin tool. It doesn't seem necessary to me that 
we need a SchemaInitializer bean for any dynamic options inside Polaris server. 
A normal function with schema options should be good enough.



##########
persistence/google-cloud-spanner/src/main/java/org/apache/polaris/persistence/relational/spanner/GoogleCloudSpannerDatabaseClientLifecycleManager.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.polaris.persistence.relational.spanner;
+
+import com.google.cloud.spanner.Database;
+import com.google.cloud.spanner.DatabaseAdminClient;
+import com.google.cloud.spanner.DatabaseId;
+import com.google.cloud.spanner.Dialect;
+import com.google.cloud.spanner.Spanner;
+import com.google.cloud.spanner.SpannerException;
+import com.google.common.collect.ImmutableList;
+import jakarta.annotation.PostConstruct;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.inject.Produces;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.function.Consumer;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.persistence.bootstrap.SchemaOptions;
+import org.apache.polaris.persistence.relational.spanner.model.Realm;
+import org.apache.polaris.persistence.relational.spanner.util.SpannerUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@ApplicationScoped
+public class GoogleCloudSpannerDatabaseClientLifecycleManager {
+
+  private static Logger LOGGER =
+      
LoggerFactory.getLogger(GoogleCloudSpannerDatabaseClientLifecycleManager.class);
+
+  protected final GoogleCloudSpannerConfiguration spannerConfiguration;
+
+  public GoogleCloudSpannerDatabaseClientLifecycleManager(
+      GoogleCloudSpannerConfiguration spannerConfiguration) {
+    this.spannerConfiguration = spannerConfiguration;
+  }
+
+  protected Spanner spanner;
+  protected DatabaseId databaseId;
+
+  @PostConstruct
+  protected void init() {
+    spanner = SpannerUtil.spannerFromConfiguration(spannerConfiguration);
+    databaseId = SpannerUtil.databaseFromConfiguration(spannerConfiguration);
+  }
+
+  protected List<String> getSpannerDatabaseDdl(SchemaOptions options) {
+    final InputStream schemaStream;
+    if (options.schemaFile() != null) {
+      try {
+        schemaStream = new FileInputStream(options.schemaFile());
+      } catch (IOException e) {
+        throw new IllegalArgumentException("Unable to load file " + 
options.schemaFile(), e);
+      }
+    } else {
+      if (options.schemaVersion() == null || options.schemaVersion() == 1) {
+        schemaStream =
+            
getClass().getResourceAsStream("/org/apache/polaris/persistence/spanner/schema-v1.sql");
+      } else {
+        throw new IllegalArgumentException("Unknown schema version " + 
options.schemaVersion());
+      }
+    }
+    try (schemaStream) {
+      String schema = new String(schemaStream.readAllBytes(), 
Charset.forName("UTF-8"));
+      List<String> lines = new ArrayList<>();
+      for (String s : schema.split("\n")) {
+        s = s.trim();
+        if (s.startsWith("--") || s.length() == 0) {
+          continue;
+        }
+        lines.add(s);
+      }
+      return List.of(String.join(" ", lines).split(";"));
+    } catch (IOException e) {
+      throw new RuntimeException("Unable to retrieve DDL statements", e);
+    }
+  }
+
+  @Produces
+  public SchemaInitializer getSchemaInitializer() {
+    return (options) -> {
+      List<String> ddlStatements = getSpannerDatabaseDdl(options);
+      LOGGER.info(
+          "Attempting to initialize Spanner database DDL with {} statements,",
+          ddlStatements.size());
+      DatabaseAdminClient client = spanner.getDatabaseAdminClient();
+      Database dbInfo =
+          
client.newDatabaseBuilder(databaseId).setDialect(Dialect.GOOGLE_STANDARD_SQL).build();
+      try {
+        spanner.getDatabaseAdminClient().updateDatabaseDdl(dbInfo, 
ddlStatements, null).get();
+        LOGGER.info("Successfully applied DDL update.");
+      } catch (InterruptedException | ExecutionException e) {
+        LOGGER.error("Unable to update Spanner DDL.", e);
+        throw new RuntimeException(
+            "Unable to update Spanner DDL. Please disable this option for this 
database configuration.",
+            e);
+      }
+    };
+  }
+
+  @Produces
+  public Consumer<RealmContext> getRealmInitializer() {
+    return (realmContext) -> {
+      try {
+        spanner
+            .getDatabaseClient(databaseId)
+            
.write(ImmutableList.of(Realm.upsert(realmContext.getRealmIdentifier())));
+      } catch (SpannerException e) {
+        LOGGER.error("Unable to initialize realm " + 
realmContext.getRealmIdentifier(), e);

Review Comment:
   Throw a runtime exception instead of logging an error? So that the stack 
trace will show the complete call chain.



-- 
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: issues-unsubscr...@polaris.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to