flyrain commented on code in PR #247: URL: https://github.com/apache/polaris/pull/247#discussion_r1759403628
########## extension/persistence/eclipselink/src/main/java/org/apache/polaris/extension/persistence/impl/eclipselink/PolarisSequenceManager.java: ########## @@ -0,0 +1,115 @@ +/* + * 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.extension.persistence.impl.eclipselink; + +import jakarta.persistence.*; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; +import org.apache.polaris.core.persistence.models.ModelSequenceId; +import org.eclipse.persistence.internal.jpa.EntityManagerImpl; +import org.eclipse.persistence.platform.database.DatabasePlatform; +import org.eclipse.persistence.platform.database.PostgreSQLPlatform; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Used to generate sequence IDs for Polaris entities. If the legacy `POLARIS_SEQ` generator is + * available it will be used then cleaned up. In all other cases the `POLARIS_SEQUENCE` table is + * used directly. + */ +public class PolarisSequenceManager { + private static final Logger LOGGER = LoggerFactory.getLogger(PolarisSequenceManager.class); + + private static AtomicBoolean sequenceCleaned = new AtomicBoolean(false); + + /* Get the database platform associated with the `EntityManager` */ + private static DatabasePlatform getDatabasePlatform(EntityManager session) { + EntityManagerImpl entityManagerImpl = session.unwrap(EntityManagerImpl.class); + return entityManagerImpl.getDatabaseSession().getPlatform(); + } + + private static void removeSequence(EntityManager session) { + LOGGER.info("Renaming legacy sequence `POLARIS_SEQ` to `POLARIS_SEQ_UNUSED`"); + String renameSequenceQuery = "ALTER SEQUENCE POLARIS_SEQ RENAME TO POLARIS_SEQ_UNUSED"; + session.createNativeQuery(renameSequenceQuery).executeUpdate(); + } + + private static synchronized Optional<Long> getSequenceId(EntityManager session) { + DatabasePlatform databasePlatform = getDatabasePlatform(session); + if (databasePlatform instanceof PostgreSQLPlatform) { + Optional<Long> result = Optional.empty(); + if (!sequenceCleaned.get()) { + try { + LOGGER.info("Checking if the sequence POLARIS_SEQ exists"); + String checkSequenceQuery = + "SELECT COUNT(*) FROM information_schema.sequences WHERE sequence_name IN ('polaris_seq', 'POLARIS_SEQ')"; + int sequenceExists = + ((Number) session.createNativeQuery(checkSequenceQuery).getSingleResult()).intValue(); + + if (sequenceExists > 0) { + LOGGER.info("POLARIS_SEQ exists, calling NEXTVAL"); + long queryResult = + (long) session.createNativeQuery("SELECT NEXTVAL('POLARIS_SEQ')").getSingleResult(); + result = Optional.of(queryResult); + } else { + LOGGER.info("POLARIS_SEQ does not exist, skipping NEXTVAL"); + } + } catch (Exception e) { + LOGGER.info( + "Encountered an exception when checking sequence or calling `NEXTVAL('POLARIS_SEQ')`", + e); + } + if (result.isPresent()) { + removeSequence(session); + } + sequenceCleaned.set(true); + } + return result; + } else { + LOGGER.info("Skipping POLARIS_SEQ / NEXTVAL check for platform " + databasePlatform); + return Optional.empty(); + } + } Review Comment: Sorry I wasn't clear in my first comment. The code is mainly for migration in case anyone is already using Postgres in production. We have two approaches: 1. Ignore it, assuming no one is actually using it in production yet—especially since Apache Polaris hasn't had its first release. 2. Wrap the migration logic into a method so we can easily remove it in the future. I prefer the second option. With that, we could make the following changes: 1. Call the migration code only in the initialization method, instead of reusing it in `getNewId()`, since the migration happens only once. In case of migration failure, we should just throw. 2. Simplify `getNewId()`, as we don't need to distinguish if it's migrated or not. Specifically, we can remove the line `getSequenceId(session).ifPresent(modelSequenceId::setId);`. 3. Eliminate `PolarisSequenceUtil::sequenceCleaned` and `PolarisEclipseLinkStore::initialized`, as we throwed in case of migration failure, there is no need to check if migration actually happened. ########## extension/persistence/eclipselink/src/main/java/org/apache/polaris/extension/persistence/impl/eclipselink/PolarisEclipseLinkStore.java: ########## @@ -62,14 +66,22 @@ public PolarisEclipseLinkStore(@NotNull PolarisDiagnostics diagnostics) { this.diagnosticServices = diagnostics; } + /** Initialize the store. This should be called before other methods. */ + public void initialize(EntityManager session) { + PolarisSequenceManager.initialize(session); + initialized.set(true); + } Review Comment: Make sense, In that case, we should throw when initialization failed, so that we don't have to check whether it initialized. -- 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]
