Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve batch insertion for entities with auto-increment primary keys. #1191

Merged
merged 3 commits into from
Sep 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,9 @@ protected int executeUpdate(PreparedStatement preparedStatement, PreparedSql sql
throw e;
}
}

@Override
protected void postExecuteBatch(PreparedStatement preparedStatement, int position, int size) {
query.generateIds(preparedStatement, position, size);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ protected int[] executeBatch(PreparedStatement preparedStatement, List<PreparedS
if (i == sqlSize - 1 || (batchSize > 0 && (i + 1) % batchSize == 0)) {
int[] rows = executeBatch(preparedStatement, sql);
validateRows(preparedStatement, sql, rows);
postExecuteBatch(preparedStatement, pos, rows.length);
System.arraycopy(rows, 0, updatedRows, pos, rows.length);
pos = i + 1;
}
Expand All @@ -118,6 +119,15 @@ protected int[] executeBatch(PreparedStatement preparedStatement, PreparedSql sq
}
}

/**
* Invoked after the batch execution.
*
* @param preparedStatement the prepared statement
* @param position the position of the first element in the batch
* @param size the size of the executed batch
*/
protected void postExecuteBatch(PreparedStatement preparedStatement, int position, int size) {}

protected void log(PreparedSql sql) {
JdbcLogger logger = query.getConfig().getJdbcLogger();
logger.logSql(query.getClassName(), query.getMethodName(), sql);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ default boolean supportsBatchExecutionReturningGeneratedValues() {
*
* @return {@code true}, if this object supports it
*/
@Deprecated
boolean supportsIdentityReservation();

/**
Expand Down Expand Up @@ -218,6 +219,7 @@ Sql<?> getIdentitySelectSql(
* @throws DomaNullPointerException if either the {@code tableName} or the {@code columnName} is
* {@code null}
*/
@Deprecated
Sql<?> getIdentityReservationSql(
String catalogName,
String schemaName,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ public boolean supportsUpsertEmulationWithMergeStatement() {
return true;
}

@Override
public boolean supportsBatchExecutionReturningGeneratedValues() {
return true;
}

public static class H2JdbcMappingVisitor extends H214199JdbcMappingVisitor {}

public static class H2SqlLogFormattingVisitor extends H214199SqlLogFormattingVisitor {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,11 @@ public boolean supportsAliasInDeleteClause() {
return true;
}

@Override
public boolean supportsBatchExecutionReturningGeneratedValues() {
return true;
}

@Override
protected SqlNode toCountCalculatingSqlNode(SqlNode sqlNode) {
switch (version) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,11 @@ public boolean supportsAutoGeneratedKeys() {
return true;
}

@Override
public boolean supportsBatchExecutionReturningGeneratedValues() {
return true;
}

@Override
public JdbcType<ResultSet> getResultSetType() {
return RESULT_SET;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,7 @@ public boolean supportsSequence() {
return false;
}

@SuppressWarnings("deprecation")
@Override
public boolean supportsIdentityReservation() {
return false;
Expand Down Expand Up @@ -342,6 +343,7 @@ public Sql<?> getIdentitySelectSql(
throw new JdbcUnsupportedOperationException(getClass().getName(), "getIdentitySelectSql");
}

@SuppressWarnings("deprecation")
@Override
public Sql<?> getIdentityReservationSql(
String catalogName,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,39 +19,26 @@ public class BuiltinIdentityIdGenerator extends AbstractIdGenerator implements I

@Override
public boolean supportsBatch(IdGenerationConfig config) {
return config.getIdProvider().isAvailable();
return config.getDialect().supportsBatchExecutionReturningGeneratedValues();
}

@Override
public boolean includesIdentityColumn(IdGenerationConfig config) {
if (config.getIdProvider().isAvailable()) {
return true;
}
return config.getDialect().includesIdentityColumn();
}

@Override
public boolean supportsAutoGeneratedKeys(IdGenerationConfig config) {
if (config.getIdProvider().isAvailable()) {
return false;
}
return config.getDialect().supportsAutoGeneratedKeys();
}

@Override
public Long generatePreInsert(IdGenerationConfig config) {
IdProvider idProvider = config.getIdProvider();
if (idProvider.isAvailable()) {
return idProvider.get();
}
return null;
}

@Override
public Long generatePostInsert(IdGenerationConfig config, Statement statement) {
if (config.getIdProvider().isAvailable()) {
return null;
}
if (config.getDialect().supportsAutoGeneratedKeys()) {
return getGeneratedValue(config, statement);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public class IdGenerationConfig {

protected final EntityType<?> entityType;

@SuppressWarnings("deprecation")
protected final IdProvider idProvider;

public IdGenerationConfig(Config config, EntityType<?> entityType) {
Expand Down Expand Up @@ -70,10 +71,13 @@ public EntityType<?> getEntityType() {
return entityType;
}

@SuppressWarnings("deprecation")
public IdProvider getIdProvider() {
return idProvider;
}

@SuppressWarnings("DeprecatedIsStillUsed")
@Deprecated
protected static class UnavailableIdProvider implements IdProvider {
@Override
public boolean isAvailable() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.seasar.doma.jdbc.id;

/** An identity provider. */
@Deprecated
public interface IdProvider {

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import org.seasar.doma.message.Message;

/** An identity provider that reserves identity values in advance. */
@Deprecated
public class ReservedIdProvider implements IdProvider {

protected final Config config;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import java.util.ListIterator;
import java.util.Objects;
import java.util.stream.Collectors;
import org.seasar.doma.DomaIllegalArgumentException;
import org.seasar.doma.internal.jdbc.entity.AbstractPostInsertContext;
import org.seasar.doma.internal.jdbc.entity.AbstractPreInsertContext;
import org.seasar.doma.internal.jdbc.sql.PreparedSqlBuilder;
Expand All @@ -26,7 +27,6 @@
import org.seasar.doma.jdbc.entity.GeneratedIdPropertyType;
import org.seasar.doma.jdbc.entity.Property;
import org.seasar.doma.jdbc.id.IdGenerationConfig;
import org.seasar.doma.jdbc.id.ReservedIdProvider;
import org.seasar.doma.message.Message;

public class AutoBatchInsertQuery<ENTITY> extends AutoBatchModifyQuery<ENTITY>
Expand Down Expand Up @@ -106,14 +106,7 @@ protected void prepareIdAndVersionPropertyTypes() {
generatedIdPropertyType = entityType.getGeneratedIdPropertyType();
if (generatedIdPropertyType != null) {
if (idGenerationConfig == null) {
// TODO should we stop supporting ReservedIdProvider?
if (generatedKeysIgnored || duplicateKeyType != DuplicateKeyType.EXCEPTION) {
idGenerationConfig = new IdGenerationConfig(config, entityType);
} else {
idGenerationConfig =
new IdGenerationConfig(
config, entityType, new ReservedIdProvider(config, entityType, entities.size()));
}
idGenerationConfig = new IdGenerationConfig(config, entityType);
generatedIdPropertyType.validateGenerationStrategy(idGenerationConfig);
autoGeneratedKeysSupported =
!generatedKeysIgnored
Expand Down Expand Up @@ -233,7 +226,7 @@ public boolean isBatchSupported() {

@Override
public void generateId(Statement statement, int index) {
if (generatedIdPropertyType != null && idGenerationConfig != null) {
if (isAutoGeneratedKeysSupported()) {
ENTITY entity = entities.get(index);
ENTITY newEntity =
generatedIdPropertyType
Expand All @@ -246,6 +239,32 @@ public void generateId(Statement statement, int index) {
}
}

@Override
public void generateIds(Statement statement, int position, int size) {
if (isAutoGeneratedKeysSupported() && isBatchSupported()) {
if ((position + size) > entities.size()) {
throw new DomaIllegalArgumentException(
"position or length",
"position = "
+ position
+ ", size = "
+ size
+ ", entities.size() = "
+ entities.size());
}
List<ENTITY> subEntities = entities.subList(position, position + size);
List<ENTITY> newEntities =
generatedIdPropertyType
.postInsert(entityType, subEntities, idGenerationConfig, statement)
.stream()
.toList();
if (subEntities.size() == newEntities.size()) {
subEntities.clear();
subEntities.addAll(newEntities);
}
}
}

@Override
public void complete() {
for (ListIterator<ENTITY> it = entities.listIterator(); it.hasNext(); ) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,13 @@ public interface BatchInsertQuery extends BatchModifyQuery {
boolean isBatchSupported();

void generateId(Statement statement, int index);

/**
* Generates IDs for the batch.
*
* @param statement the statement
* @param position the position of the first element in the batch
* @param size the size of the executed batch
*/
default void generateIds(Statement statement, int position, int size) {}
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
package org.seasar.doma.jdbc.id;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;

import example.entity.IdGeneratedEmp;
import example.entity._IdGeneratedEmp;
import org.junit.jupiter.api.Test;
import org.seasar.doma.internal.jdbc.mock.MockConfig;
import org.seasar.doma.internal.jdbc.mock.MockResultSet;
import org.seasar.doma.internal.jdbc.mock.RowData;
import org.seasar.doma.jdbc.dialect.PostgresDialect;
import org.seasar.doma.jdbc.entity.EntityType;

public class BuiltinIdentityIdGeneratorTest {

Expand Down Expand Up @@ -38,35 +35,4 @@ public boolean supportsAutoGeneratedKeys() {
"select currval(pg_catalog.pg_get_serial_sequence('\"CATA\".\"EMP\"', 'id'))",
config.dataSource.connection.preparedStatement.sql);
}

@Test
public void test_identityReservationSql() {
MockConfig config = new MockConfig();
config.setDialect(new PostgresDialect());
MockResultSet resultSet = config.dataSource.connection.preparedStatement.resultSet;
resultSet.rows.add(new RowData(11L));
resultSet.rows.add(new RowData(12L));
resultSet.rows.add(new RowData(13L));

EntityType<IdGeneratedEmp> entityType = _IdGeneratedEmp.getSingletonInternal();
BuiltinIdentityIdGenerator identityIdGenerator = new BuiltinIdentityIdGenerator();
IdGenerationConfig idGenerationConfig =
new IdGenerationConfig(config, entityType, new ReservedIdProvider(config, entityType, 3));
Long value = identityIdGenerator.generatePreInsert(idGenerationConfig);
assertEquals(11L, value);
assertEquals(
"select nextval(pg_catalog.pg_get_serial_sequence('\"CATA\".\"EMP\"', 'id')) from generate_series(1, 3)",
config.dataSource.connection.preparedStatement.sql);
value = identityIdGenerator.generatePreInsert(idGenerationConfig);
assertEquals(12L, value);
value = identityIdGenerator.generatePreInsert(idGenerationConfig);
assertEquals(13L, value);

try {
identityIdGenerator.generatePreInsert(idGenerationConfig);
fail();
} catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
}
}