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

Use lambdas for transaction scoping; Don't reload objects after commit #552

Merged
merged 2 commits into from
May 5, 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
10 changes: 10 additions & 0 deletions alpine-infra/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -77,11 +77,21 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down

Large diffs are not rendered by default.

638 changes: 310 additions & 328 deletions alpine-infra/src/main/java/alpine/persistence/AlpineQueryManager.java

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ public static Properties unit() {
properties.put(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_CONSTRAINTS, "true");
properties.put(PropertyNames.PROPERTY_SCHEMA_GENERATE_DATABASE_MODE, "create");
properties.put(PropertyNames.PROPERTY_QUERY_JDOQL_ALLOWALL, "true");
properties.put(PropertyNames.PROPERTY_RETAIN_VALUES, "true");
return properties;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* This file is part of Alpine.
*
* Licensed 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.
*
* SPDX-License-Identifier: Apache-2.0
* Copyright (c) Steve Springett. All Rights Reserved.
*/
package alpine.persistence;

import org.datanucleus.api.jdo.JDOPersistenceManager;

import javax.jdo.PersistenceManager;
import java.util.ArrayDeque;
import java.util.Deque;

public class ScopedCustomization implements AutoCloseable {

private final JDOPersistenceManager pm;
private final Deque<Runnable> cleanUpItems = new ArrayDeque<>();

public ScopedCustomization(final PersistenceManager pm) {
if (pm instanceof final JDOPersistenceManager jdoPm) {
this.pm = jdoPm;
} else {
throw new IllegalArgumentException("Unsupported PersistenceManager type: %s"
.formatted(pm.getClass().getName()));
}
}

public ScopedCustomization withDetachmentOptions(final int detachmentOptions) {
final var originalOptions = pm.getFetchPlan().getDetachmentOptions();
cleanUpItems.add(() -> pm.getFetchPlan().setDetachmentOptions(originalOptions));
pm.getFetchPlan().setDetachmentOptions(detachmentOptions);
return this;
}

public ScopedCustomization withFetchGroup(final String fetchGroup) {
final var originalFetchGroups = pm.getFetchPlan().getGroups();
cleanUpItems.add(() -> pm.getFetchPlan().setGroups(originalFetchGroups));
pm.getFetchPlan().setGroups(fetchGroup);
return this;
}

public ScopedCustomization withProperty(final String name, final String value) {
final Object originalValue = pm.getExecutionContext().getProperty(name);
cleanUpItems.add(() -> pm.setProperty(name, originalValue));
pm.setProperty(name, value);
return this;
}

@Override
public void close() {
cleanUpItems.forEach(Runnable::run);
}

}
157 changes: 157 additions & 0 deletions alpine-infra/src/main/java/alpine/persistence/Transaction.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
/*
* This file is part of Alpine.
*
* Licensed 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.
*
* SPDX-License-Identifier: Apache-2.0
* Copyright (c) Steve Springett. All Rights Reserved.
*/
package alpine.persistence;

import javax.jdo.Constants;
import javax.jdo.PersistenceManager;
import java.util.ArrayList;
import java.util.concurrent.Callable;

public final class Transaction {

public enum Isolation {

READ_UNCOMMITTED,
READ_COMMITTED,
REPEATABLE_READ,
SNAPSHOT,
SERIALIZABLE;

private String jdoName() {
return switch (this) {
case READ_UNCOMMITTED -> Constants.TX_READ_UNCOMMITTED;
case READ_COMMITTED -> Constants.TX_READ_COMMITTED;
case REPEATABLE_READ -> Constants.TX_REPEATABLE_READ;
case SNAPSHOT -> Constants.TX_SNAPSHOT;
case SERIALIZABLE -> Constants.TX_SERIALIZABLE;
};
}

private static Isolation fromJdoName(final String jdoName) {
return switch (jdoName) {
case Constants.TX_READ_UNCOMMITTED -> READ_UNCOMMITTED;
case Constants.TX_READ_COMMITTED -> READ_COMMITTED;
case Constants.TX_REPEATABLE_READ -> REPEATABLE_READ;
case Constants.TX_SNAPSHOT -> SNAPSHOT;
case Constants.TX_SERIALIZABLE -> SERIALIZABLE;
default -> throw new IllegalArgumentException("Unknown isolation: %s".formatted(jdoName));
};
}

}

public enum Propagation {
REQUIRED,
REQUIRES_NEW
}

public static class Options {

private Isolation isolation;
private Propagation propagation;
private Boolean serializeRead;

public Options withIsolation(final Isolation isolation) {
this.isolation = isolation;
return this;
}

public Options withPropagation(final Propagation propagation) {
this.propagation = propagation;
return this;
}

public Options withSerializeRead(final boolean serializeRead) {
this.serializeRead = serializeRead;
return this;
}

}

private Transaction() {
}

public static Options defaultOptions() {
return new Options();
}

public static <T> T call(final PersistenceManager pm, final Options options, final Callable<T> callable) {
final javax.jdo.Transaction jdoTransaction = pm.currentTransaction();

// A PersistenceManager's currentTransaction is not reset upon commit or rollback.
// Changes made to a transaction object will persist until the owning PM is closed.
// Ensure we're doing our best to leave the transaction as we found it.
final var cleanups = new ArrayList<Runnable>();

final boolean isJoiningExisting = jdoTransaction.isActive();
if (isJoiningExisting && options.propagation == Propagation.REQUIRES_NEW) {
throw new IllegalStateException("Propagation is set to %s, but a transaction is already active"
.formatted(Propagation.REQUIRES_NEW));
}

final Isolation currentIsolation = Isolation.fromJdoName(jdoTransaction.getIsolationLevel());
final Isolation requestedIsolation = options.isolation;
if (requestedIsolation != null && currentIsolation != requestedIsolation) {
if (isJoiningExisting) {
throw new IllegalStateException("""
Requested isolation is %s, but transaction is already \
active with isolation %s""".formatted(requestedIsolation, currentIsolation));
}

cleanups.add(() -> jdoTransaction.setIsolationLevel(currentIsolation.jdoName()));
jdoTransaction.setIsolationLevel(requestedIsolation.jdoName());
}

final Boolean currentSerializeRead = jdoTransaction.getSerializeRead();
final Boolean requestedSerializeRead = options.serializeRead;
if (requestedSerializeRead != null && currentSerializeRead != requestedSerializeRead) {
if (isJoiningExisting) {
throw new IllegalStateException("""
Requested serializeRead=%s, but transaction is already \
active with serializeRead=%s""".formatted(requestedSerializeRead, currentSerializeRead));
}

cleanups.add(() -> jdoTransaction.setSerializeRead(currentSerializeRead));
jdoTransaction.setSerializeRead(requestedSerializeRead);
}

try {
if (!isJoiningExisting) {
jdoTransaction.begin();
}

final T result = callable.call();

if (!isJoiningExisting) {
jdoTransaction.commit();
}

return result;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (jdoTransaction.isActive() && !isJoiningExisting) {
jdoTransaction.rollback();
}

cleanups.forEach(Runnable::run);
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* This file is part of Alpine.
*
* Licensed 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.
*
* SPDX-License-Identifier: Apache-2.0
* Copyright (c) Steve Springett. All Rights Reserved.
*/
package alpine.persistence;

import org.datanucleus.api.jdo.JDOPersistenceManager;
import org.datanucleus.api.jdo.JDOPersistenceManagerFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import javax.jdo.JDOHelper;

import static javax.jdo.FetchPlan.DETACH_LOAD_FIELDS;
import static javax.jdo.FetchPlan.DETACH_UNLOAD_FIELDS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.datanucleus.PropertyNames.PROPERTY_DETACH_ALL_ON_COMMIT;

public class ScopedCustomizationTest {

private JDOPersistenceManagerFactory pmf;
private JDOPersistenceManager pm;

@Before
public void setUp() {
pmf = (JDOPersistenceManagerFactory) JDOHelper.getPersistenceManagerFactory(JdoProperties.unit(), "Alpine");
pm = (JDOPersistenceManager) pmf.getPersistenceManager();
}

@After
public void tearDown() {
if (pm != null) {
pm.close();
}

if (pmf != null) {
pmf.close();
}
}

@Test
public void testRestoreDetachmentOptions() {
pm.getFetchPlan().setDetachmentOptions(DETACH_LOAD_FIELDS);
assertThat(pm.getFetchPlan().getDetachmentOptions()).isEqualTo(DETACH_LOAD_FIELDS);

try (var ignored = new ScopedCustomization(pm).withDetachmentOptions(DETACH_UNLOAD_FIELDS)) {
assertThat(pm.getFetchPlan().getDetachmentOptions()).isEqualTo(DETACH_UNLOAD_FIELDS);
}

assertThat(pm.getFetchPlan().getDetachmentOptions()).isEqualTo(DETACH_LOAD_FIELDS);
}

@Test
@SuppressWarnings("unchecked")
public void testRestoreFetchGroups() {
pm.getFetchPlan().setGroups("foo");
assertThat(pm.getFetchPlan().getGroups()).containsOnly("foo");

try (var ignored = new ScopedCustomization(pm).withFetchGroup("bar")) {
assertThat(pm.getFetchPlan().getGroups()).containsOnly("bar");
}

assertThat(pm.getFetchPlan().getGroups()).containsOnly("foo");
}

@Test
public void testRestoreProperties() {
pm.setProperty(PROPERTY_DETACH_ALL_ON_COMMIT, "true");
assertThat(pm.getExecutionContext().getProperty(PROPERTY_DETACH_ALL_ON_COMMIT)).isEqualTo("true");

try (var ignored = new ScopedCustomization(pm).withProperty(PROPERTY_DETACH_ALL_ON_COMMIT, "false")) {
assertThat(pm.getExecutionContext().getProperty(PROPERTY_DETACH_ALL_ON_COMMIT)).isEqualTo("false");
}

assertThat(pm.getExecutionContext().getProperty(PROPERTY_DETACH_ALL_ON_COMMIT)).isEqualTo("true");
}

}
Loading