You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@polaris.apache.org by yu...@apache.org on 2026/07/25 06:00:40 UTC

(polaris) branch main updated: Fix JDBC writeEntities issuing a wasteful full-row lookup per entity (#5134)

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

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


The following commit(s) were added to refs/heads/main by this push:
     new 7fc70181bc Fix JDBC writeEntities issuing a wasteful full-row lookup per entity (#5134)
7fc70181bc is described below

commit 7fc70181bc530e2eb6c1f60fefce582024d8336b
Author: Ayush Saxena <ay...@apache.org>
AuthorDate: Sat Jul 25 11:30:35 2026 +0530

    Fix JDBC writeEntities issuing a wasteful full-row lookup per entity (#5134)
---
 .../relational/jdbc/JdbcBasePersistenceImpl.java   |  61 +++++++----
 .../jdbc/JdbcBasePersistenceImplTest.java          | 121 +++++++++++++++++++++
 2 files changed, 162 insertions(+), 20 deletions(-)

diff --git a/persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/JdbcBasePersistenceImpl.java b/persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/JdbcBasePersistenceImpl.java
index 393fa12623..59cad1598a 100644
--- a/persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/JdbcBasePersistenceImpl.java
+++ b/persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/JdbcBasePersistenceImpl.java
@@ -31,6 +31,7 @@ import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Optional;
+import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicReference;
 import java.util.function.Function;
 import java.util.function.Predicate;
@@ -93,6 +94,21 @@ public class JdbcBasePersistenceImpl implements BasePersistence, IntegrationPers
   // The max number of components a location can have before the optimized sibling check is not used
   private static final int MAX_LOCATION_COMPONENTS = 40;
 
+  // Converter for SELECT 1 existence probes: only the presence of a row matters, so every row maps
+  // to 1 and toMap is never used (existence queries are read-only).
+  private static final Converter<Integer> ROW_EXISTS_CONVERTER =
+      new Converter<>() {
+        @Override
+        public Integer fromResultSet(ResultSet rs) {
+          return 1;
+        }
+
+        @Override
+        public Map<String, Object> toMap(DatabaseType databaseType) {
+          throw new UnsupportedOperationException();
+        }
+      };
+
   public JdbcBasePersistenceImpl(
       PolarisDiagnostics diagnostics,
       DatasourceOperations databaseOperations,
@@ -143,15 +159,7 @@ public class JdbcBasePersistenceImpl implements BasePersistence, IntegrationPers
               PolarisBaseEntity entity = entities.get(i);
               PolarisBaseEntity originalEntity =
                   originalEntities != null ? originalEntities.get(i) : null;
-              // first, check if the entity has already been created, in which case we will simply
-              // return it.
-              PolarisBaseEntity entityFound =
-                  lookupEntity(
-                      callCtx, entity.getCatalogId(), entity.getId(), entity.getTypeCode());
-              if (entityFound != null && originalEntity == null) {
-                // probably the client retried, simply return it
-                // TODO: Check correctness of returning entityFound vs entity here. It may have
-                // already been updated after the creation.
+              if (originalEntity == null && entityExists(connection, entity.getId())) {
                 continue;
               }
               persistEntity(
@@ -167,6 +175,25 @@ public class JdbcBasePersistenceImpl implements BasePersistence, IntegrationPers
     }
   }
 
+  /**
+   * Returns whether an entity row already exists, using a {@code SELECT 1 ... LIMIT 1} on the
+   * supplied transaction connection. Only existence is needed by {@link #writeEntities} on the
+   * create path, so this avoids fetching the full entity row (including the large JSON property
+   * blobs).
+   */
+  private boolean entityExists(@NonNull Connection connection, long entityId) throws SQLException {
+    AtomicBoolean exists = new AtomicBoolean(false);
+    datasourceOperations.executeSelectOverStream(
+        connection,
+        QueryGenerator.generateExistsQuery(
+            ModelEntity.getAllColumnNames(schemaVersion),
+            ModelEntity.TABLE_NAME,
+            entityKeyParams(entityId)),
+        ROW_EXISTS_CONVERTER,
+        stream -> exists.set(stream.findAny().isPresent()));
+    return exists.get();
+  }
+
   private void persistEntity(
       @NonNull PolarisCallContext callCtx,
       @NonNull PolarisBaseEntity entity,
@@ -422,6 +449,10 @@ public class JdbcBasePersistenceImpl implements BasePersistence, IntegrationPers
             ModelEntity.getAllColumnNames(schemaVersion), ModelEntity.TABLE_NAME, params));
   }
 
+  private Map<String, Object> entityKeyParams(long entityId) {
+    return Map.of("id", entityId, "realm_id", realmId);
+  }
+
   @Override
   public PolarisBaseEntity lookupEntityByName(
       @NonNull PolarisCallContext callCtx,
@@ -740,17 +771,7 @@ public class JdbcBasePersistenceImpl implements BasePersistence, IntegrationPers
           datasourceOperations.executeSelect(
               QueryGenerator.generateExistsQuery(
                   ModelEntity.getAllColumnNames(schemaVersion), ModelEntity.TABLE_NAME, params),
-              new Converter<Integer>() {
-                @Override
-                public Integer fromResultSet(ResultSet rs) {
-                  return 1;
-                }
-
-                @Override
-                public Map<String, Object> toMap(DatabaseType databaseType) {
-                  throw new UnsupportedOperationException();
-                }
-              });
+              ROW_EXISTS_CONVERTER);
       return results != null && !results.isEmpty();
     } catch (SQLException e) {
       throw new RuntimeException(
diff --git a/persistence/relational-jdbc/src/test/java/org/apache/polaris/persistence/relational/jdbc/JdbcBasePersistenceImplTest.java b/persistence/relational-jdbc/src/test/java/org/apache/polaris/persistence/relational/jdbc/JdbcBasePersistenceImplTest.java
index 2a7cb38041..9ece4880b7 100644
--- a/persistence/relational-jdbc/src/test/java/org/apache/polaris/persistence/relational/jdbc/JdbcBasePersistenceImplTest.java
+++ b/persistence/relational-jdbc/src/test/java/org/apache/polaris/persistence/relational/jdbc/JdbcBasePersistenceImplTest.java
@@ -25,11 +25,13 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.doCallRealMethod;
 import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 import java.io.IOException;
 import java.io.InputStream;
+import java.sql.Connection;
 import java.sql.SQLException;
 import java.util.List;
 import java.util.Optional;
@@ -43,6 +45,7 @@ import org.apache.polaris.core.entity.PolarisEntitySubType;
 import org.apache.polaris.core.entity.PolarisEntityType;
 import org.apache.polaris.core.entity.PolarisGrantRecord;
 import org.h2.jdbcx.JdbcConnectionPool;
+import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.ValueSource;
 import org.mockito.ArgumentCaptor;
@@ -289,6 +292,124 @@ class JdbcBasePersistenceImplTest {
         .build();
   }
 
+  /**
+   * On the create path (no original entity) {@code writeEntities} must detect an already-created
+   * entity with a cheap {@code SELECT 1 ... LIMIT 1} existence check that does not fetch the large
+   * JSON property blobs, and a retried create must stay idempotent.
+   */
+  @Test
+  void writeEntitiesCreatePathUsesExistsCheckNotFullRowFetch() throws SQLException, IOException {
+    int schemaVersion = 5;
+    JdbcConnectionPool dataSource =
+        JdbcConnectionPool.create(
+            "jdbc:h2:mem:write_entities_create_v"
+                + schemaVersion
+                + "_"
+                + System.nanoTime()
+                + ";DB_CLOSE_DELAY=-1",
+            "sa",
+            "");
+    DatasourceOperations real = new DatasourceOperations(dataSource, new TestJdbcConfiguration());
+    try (InputStream script = DatabaseType.H2.openInitScriptResource(schemaVersion)) {
+      real.executeScript(script);
+    }
+    DatasourceOperations spy = Mockito.spy(real);
+
+    JdbcBasePersistenceImpl impl =
+        new JdbcBasePersistenceImpl(
+            new PolarisDefaultDiagServiceImpl(),
+            spy,
+            RANDOM_SECRETS,
+            REALM_CONTEXT.getRealmIdentifier(),
+            schemaVersion);
+    PolarisCallContext callCtx = new PolarisCallContext(REALM_CONTEXT, impl);
+
+    PolarisBaseEntity entity = principalEntity(1L, "create-me", 1);
+    impl.writeEntities(callCtx, List.of(entity), null);
+
+    // The create-path existence check must run as SELECT 1 ... LIMIT 1 (no JSON property columns),
+    // on the transaction connection.
+    ArgumentCaptor<QueryGenerator.PreparedQuery> captor =
+        ArgumentCaptor.forClass(QueryGenerator.PreparedQuery.class);
+    verify(spy).executeSelectOverStream(any(Connection.class), captor.capture(), any(), any());
+    String sql = captor.getValue().sql();
+    assertThat(sql).contains("SELECT 1").contains("LIMIT 1");
+    assertThat(sql).doesNotContain("properties");
+
+    // The entity was actually inserted.
+    assertThat(
+            impl.lookupEntity(callCtx, entity.getCatalogId(), entity.getId(), entity.getTypeCode()))
+        .isNotNull();
+
+    // A retried create is idempotent (the existence check short-circuits the insert).
+    assertThatCode(() -> impl.writeEntities(callCtx, List.of(entity), null))
+        .doesNotThrowAnyException();
+  }
+
+  /**
+   * On the update path (original entity supplied) {@code writeEntities} already knows the entity
+   * exists, so it must not issue any pre-write existence/lookup SELECT before the CAS update.
+   */
+  @Test
+  void writeEntitiesUpdatePathSkipsExistenceLookup() throws SQLException, IOException {
+    int schemaVersion = 5;
+    JdbcConnectionPool dataSource =
+        JdbcConnectionPool.create(
+            "jdbc:h2:mem:write_entities_update_v"
+                + schemaVersion
+                + "_"
+                + System.nanoTime()
+                + ";DB_CLOSE_DELAY=-1",
+            "sa",
+            "");
+    DatasourceOperations real = new DatasourceOperations(dataSource, new TestJdbcConfiguration());
+    try (InputStream script = DatabaseType.H2.openInitScriptResource(schemaVersion)) {
+      real.executeScript(script);
+    }
+    DatasourceOperations spy = Mockito.spy(real);
+
+    JdbcBasePersistenceImpl impl =
+        new JdbcBasePersistenceImpl(
+            new PolarisDefaultDiagServiceImpl(),
+            spy,
+            RANDOM_SECRETS,
+            REALM_CONTEXT.getRealmIdentifier(),
+            schemaVersion);
+    PolarisCallContext callCtx = new PolarisCallContext(REALM_CONTEXT, impl);
+
+    PolarisBaseEntity original = principalEntity(1L, "update-me", 1);
+    impl.writeEntities(callCtx, List.of(original), null);
+
+    // Only observe the update below.
+    Mockito.clearInvocations(spy);
+
+    PolarisBaseEntity updated = principalEntity(1L, "update-me", 2);
+    impl.writeEntities(callCtx, List.of(updated), List.of(original));
+
+    // No existence/lookup SELECT is issued before the CAS update.
+    verify(spy, never()).executeSelectOverStream(any(Connection.class), any(), any(), any());
+
+    // The CAS update was applied (original v1 -> v2).
+    PolarisBaseEntity reloaded =
+        impl.lookupEntity(callCtx, updated.getCatalogId(), updated.getId(), updated.getTypeCode());
+    assertThat(reloaded).isNotNull();
+    assertThat(reloaded.getEntityVersion()).isEqualTo(2);
+  }
+
+  private static PolarisBaseEntity principalEntity(long id, String name, int entityVersion) {
+    return new PolarisBaseEntity.Builder()
+        .id(id)
+        .catalogId(0L)
+        .parentId(0L)
+        .typeCode(PolarisEntityType.PRINCIPAL.getCode())
+        .subTypeCode(PolarisEntitySubType.NULL_SUBTYPE.getCode())
+        .name(name)
+        .entityVersion(entityVersion)
+        .grantRecordsVersion(1)
+        .createTimestamp(System.currentTimeMillis())
+        .build();
+  }
+
   private static final class TestJdbcConfiguration implements RelationalJdbcConfiguration {
     @Override
     public Optional<Integer> maxRetries() {