Remove TransactionManagerFactory.jpaTm() (#1883)

Since JPA is the only TM now, there's no point distinguishing tm() from
jpaTm().
This commit is contained in:
Lai Jiang 2022-12-13 14:37:46 -05:00 committed by GitHub
parent 1242e3d50c
commit 3848771c75
123 changed files with 806 additions and 1181 deletions

View file

@ -14,7 +14,6 @@
package google.registry.batch;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.google.common.collect.ImmutableList;
@ -71,8 +70,7 @@ public class CheckPackagesComplianceAction implements Runnable {
for (PackagePromotion packagePromo : packages) {
Long creates =
(Long)
jpaTm()
.query(
tm().query(
"SELECT COUNT(*) FROM DomainHistory WHERE current_package_token ="
+ " :token AND modificationTime >= :lastBilling AND type ="
+ " 'DOMAIN_CREATE'")

View file

@ -21,7 +21,6 @@ import static google.registry.batch.BatchModule.PARAM_DRY_RUN;
import static google.registry.config.RegistryEnvironment.PRODUCTION;
import static google.registry.model.reporting.HistoryEntry.Type.DOMAIN_DELETE;
import static google.registry.model.tld.Registries.getTldsOfType;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.request.Action.Method.POST;
import static google.registry.request.RequestParameters.PARAM_TLDS;
@ -140,7 +139,7 @@ public class DeleteProberDataAction implements Runnable {
private void runSqlJob(ImmutableSet<String> deletableTlds) {
AtomicInteger softDeletedDomains = new AtomicInteger();
AtomicInteger hardDeletedDomains = new AtomicInteger();
jpaTm().transact(() -> processDomains(deletableTlds, softDeletedDomains, hardDeletedDomains));
tm().transact(() -> processDomains(deletableTlds, softDeletedDomains, hardDeletedDomains));
logger.atInfo().log(
"%s %d domains.",
isDryRun ? "Would have soft-deleted" : "Soft-deleted", softDeletedDomains.get());
@ -157,8 +156,7 @@ public class DeleteProberDataAction implements Runnable {
// Scroll through domains, soft-deleting as necessary (very few will be soft-deleted) and
// keeping track of which domains to hard-delete (there can be many, so we batch them up)
try (ScrollableResults scrollableResult =
jpaTm()
.query(DOMAIN_QUERY_STRING, Domain.class)
tm().query(DOMAIN_QUERY_STRING, Domain.class)
.setParameter("tlds", deletableTlds)
.setParameter(
"creationTimeCutoff", CreateAutoTimestamp.create(now.minus(DOMAIN_USED_DURATION)))
@ -183,8 +181,8 @@ public class DeleteProberDataAction implements Runnable {
domainRepoIdsToHardDelete.build(), hostNamesToHardDelete.build());
domainRepoIdsToHardDelete = new ImmutableList.Builder<>();
hostNamesToHardDelete = new ImmutableList.Builder<>();
jpaTm().getEntityManager().flush();
jpaTm().getEntityManager().clear();
tm().getEntityManager().flush();
tm().getEntityManager().clear();
}
}
// process the remainder
@ -226,32 +224,25 @@ public class DeleteProberDataAction implements Runnable {
private void hardDeleteDomainsAndHosts(
ImmutableList<String> domainRepoIds, ImmutableList<String> hostNames) {
jpaTm()
.query("DELETE FROM Host WHERE hostName IN :hostNames")
tm().query("DELETE FROM Host WHERE hostName IN :hostNames")
.setParameter("hostNames", hostNames)
.executeUpdate();
jpaTm()
.query("DELETE FROM BillingEvent WHERE domainRepoId IN :repoIds")
tm().query("DELETE FROM BillingEvent WHERE domainRepoId IN :repoIds")
.setParameter("repoIds", domainRepoIds)
.executeUpdate();
jpaTm()
.query("DELETE FROM BillingRecurrence WHERE domainRepoId IN :repoIds")
tm().query("DELETE FROM BillingRecurrence WHERE domainRepoId IN :repoIds")
.setParameter("repoIds", domainRepoIds)
.executeUpdate();
jpaTm()
.query("DELETE FROM BillingCancellation WHERE domainRepoId IN :repoIds")
tm().query("DELETE FROM BillingCancellation WHERE domainRepoId IN :repoIds")
.setParameter("repoIds", domainRepoIds)
.executeUpdate();
jpaTm()
.query("DELETE FROM DomainHistory WHERE repoId IN :repoIds")
tm().query("DELETE FROM DomainHistory WHERE repoId IN :repoIds")
.setParameter("repoIds", domainRepoIds)
.executeUpdate();
jpaTm()
.query("DELETE FROM PollMessage WHERE domainRepoId IN :repoIds")
tm().query("DELETE FROM PollMessage WHERE domainRepoId IN :repoIds")
.setParameter("repoIds", domainRepoIds)
.executeUpdate();
jpaTm()
.query("DELETE FROM Domain WHERE repoId IN :repoIds")
tm().query("DELETE FROM Domain WHERE repoId IN :repoIds")
.setParameter("repoIds", domainRepoIds)
.executeUpdate();
}

View file

@ -23,7 +23,6 @@ import static google.registry.model.common.Cursor.CursorType.RECURRING_BILLING;
import static google.registry.model.domain.Period.Unit.YEARS;
import static google.registry.model.reporting.HistoryEntry.Type.DOMAIN_AUTORENEW;
import static google.registry.persistence.transaction.QueryComposer.Comparator.EQ;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.CollectionUtils.union;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
@ -118,15 +117,13 @@ public class ExpandRecurringBillingEventsAction implements Runnable {
do {
final long prevMaxProcessedRecurrenceId = maxProcessedRecurrenceId;
sqlBatchResults =
jpaTm()
.transact(
tm().transact(
() -> {
Set<String> expandedDomains = newHashSet();
int batchBillingEventsSaved = 0;
long maxRecurrenceId = prevMaxProcessedRecurrenceId;
List<Recurring> recurrings =
jpaTm()
.query(
tm().query(
"FROM BillingRecurrence "
+ "WHERE eventTime <= :executeTime "
+ "AND eventTime < recurrenceEndTime "

View file

@ -16,7 +16,6 @@ package google.registry.batch;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.request.Action.Method.POST;
import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES;
@ -189,7 +188,7 @@ public class RelockDomainAction implements Runnable {
"Domain %s has a pending delete.",
domainName);
checkArgument(
!DateTimeUtils.isAtOrAfter(jpaTm().getTransactionTime(), domain.getDeletionTime()),
!DateTimeUtils.isAtOrAfter(tm().getTransactionTime(), domain.getDeletionTime()),
"Domain %s has been deleted.",
domainName);
checkArgument(

View file

@ -14,7 +14,7 @@
package google.registry.batch;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR;
import static org.apache.http.HttpStatus.SC_OK;
@ -77,8 +77,7 @@ public class WipeOutContactHistoryPiiAction implements Runnable {
int numOfWipedEntities = 0;
do {
numOfWipedEntities =
jpaTm()
.transact(
tm().transact(
() ->
wipeOutContactHistoryData(
getNextContactHistoryEntitiesWithPiiBatch(wipeOutTime)));
@ -113,8 +112,7 @@ public class WipeOutContactHistoryPiiAction implements Runnable {
// email is one of the required fields in EPP, meaning it's initially not null.
// Therefore, checking if it's null is one way to avoid processing contact history entities
// that have been processed previously. Refer to RFC 5733 for more information.
return jpaTm()
.query(
return tm().query(
"FROM ContactHistory WHERE modificationTime < :wipeOutTime " + "AND email IS NOT NULL",
ContactHistory.class)
.setParameter("wipeOutTime", wipeOutTime)
@ -128,7 +126,7 @@ public class WipeOutContactHistoryPiiAction implements Runnable {
AtomicInteger numOfEntities = new AtomicInteger(0);
contactHistoryEntities.forEach(
contactHistoryEntity -> {
jpaTm().update(contactHistoryEntity.asBuilder().wipeOutPii().build());
tm().update(contactHistoryEntity.asBuilder().wipeOutPii().build());
numOfEntities.incrementAndGet();
});
logger.atInfo().log(

View file

@ -15,7 +15,7 @@
package google.registry.beam.common;
import static com.google.common.base.Preconditions.checkState;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.google.common.flogger.FluentLogger;
import java.util.List;
@ -52,7 +52,7 @@ public class DatabaseSnapshot implements AutoCloseable {
}
private DatabaseSnapshot open() {
entityManager = jpaTm().getStandaloneEntityManager();
entityManager = tm().getStandaloneEntityManager();
transaction = entityManager.getTransaction();
transaction.setRollbackOnly();
transaction.begin();

View file

@ -15,7 +15,7 @@
package google.registry.beam.common;
import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static org.apache.beam.sdk.values.TypeDescriptors.integers;
import com.google.auto.value.AutoValue;
@ -50,8 +50,8 @@ import org.apache.beam.sdk.values.PCollection;
*
* <p>The {@code JpaTransactionManager} is instantiated once on each pipeline worker VM (through
* {@link RegistryPipelineWorkerInitializer}), made available through the static method {@link
* TransactionManagerFactory#jpaTm()}, and is shared by all threads on the VM. Configuration is
* through {@link RegistryPipelineOptions}.
* TransactionManagerFactory#tm()}, and is shared by all threads on the VM. Configuration is through
* {@link RegistryPipelineOptions}.
*/
public final class RegistryJpaIO {
@ -231,11 +231,10 @@ public final class RegistryJpaIO {
@ProcessElement
public void processElement(OutputReceiver<T> outputReceiver) {
jpaTm()
.transactNoRetry(
tm().transactNoRetry(
() -> {
if (snapshotId != null) {
jpaTm().setDatabaseSnapshot(snapshotId);
tm().setDatabaseSnapshot(snapshotId);
}
query.stream().map(resultMapper::apply).forEach(outputReceiver::output);
});
@ -344,12 +343,11 @@ public final class RegistryJpaIO {
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList());
try {
jpaTm()
.transact(
tm().transact(
() -> {
// Don't modify existing objects as it could lead to race conditions
entities.forEach(this::verifyObjectNonexistence);
jpaTm().putAll(entities);
tm().putAll(entities);
});
counter.inc(entities.size());
} catch (RuntimeException e) {
@ -364,12 +362,11 @@ public final class RegistryJpaIO {
private void processSingly(ImmutableList<Object> entities) {
for (Object entity : entities) {
try {
jpaTm()
.transact(
tm().transact(
() -> {
// Don't modify existing objects as it could lead to race conditions
verifyObjectNonexistence(entity);
jpaTm().put(entity);
tm().put(entity);
});
counter.inc();
} catch (RuntimeException e) {
@ -381,14 +378,12 @@ public final class RegistryJpaIO {
/** Returns this entity's primary key field(s) in a string. */
private String toEntityKeyString(Object entity) {
try {
return jpaTm()
.transact(
return tm().transact(
() ->
String.format(
"%s_%s",
entity.getClass().getSimpleName(),
jpaTm()
.getEntityManager()
tm().getEntityManager()
.getEntityManagerFactory()
.getPersistenceUnitUtil()
.getIdentifier(entity)));
@ -404,8 +399,7 @@ public final class RegistryJpaIO {
// updateTimestamp) are reflected in the input object. Beam doesn't allow modification of
// input objects, so this throws an exception.
// TODO(go/non-datastore-allocateid): also check that all the objects have IDs
checkArgument(
!jpaTm().exists(obj), "Entities created in SqlBatchWriter must not already exist");
checkArgument(!tm().exists(obj), "Entities created in SqlBatchWriter must not already exist");
}
}
}

View file

@ -14,7 +14,7 @@
package google.registry.beam.common;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import google.registry.persistence.transaction.JpaTransactionManager;
import java.io.Serializable;
@ -53,7 +53,7 @@ public interface RegistryQuery<T> extends Serializable {
static <T> RegistryQuery<T> createQuery(
String sql, @Nullable Map<String, Object> parameters, boolean nativeQuery) {
return () -> {
EntityManager entityManager = jpaTm().getEntityManager();
EntityManager entityManager = tm().getEntityManager();
Query query =
nativeQuery ? entityManager.createNativeQuery(sql) : entityManager.createQuery(sql);
if (parameters != null) {
@ -76,7 +76,7 @@ public interface RegistryQuery<T> extends Serializable {
String jpql, @Nullable Map<String, Object> parameters, Class<T> clazz) {
return () -> {
// TODO(b/193662898): switch to jpaTm().query() when it can properly detach loaded entities.
EntityManager entityManager = jpaTm().getEntityManager();
EntityManager entityManager = tm().getEntityManager();
TypedQuery<T> query = entityManager.createQuery(jpql, clazz);
if (parameters != null) {
parameters.forEach(query::setParameter);
@ -98,7 +98,7 @@ public interface RegistryQuery<T> extends Serializable {
static <T> RegistryQuery<T> createQuery(CriteriaQuerySupplier<T> criteriaQuery) {
return () -> {
// TODO(b/193662898): switch to jpaTm().query() when it can properly detach loaded entities.
EntityManager entityManager = jpaTm().getEntityManager();
EntityManager entityManager = tm().getEntityManager();
TypedQuery<T> query = entityManager.createQuery(criteriaQuery.get());
JpaTransactionManager.setQueryFetchSize(query, QUERY_FETCH_SIZE);
return query.getResultStream().map(e -> detach(entityManager, e));

View file

@ -26,7 +26,7 @@ import static google.registry.beam.rde.RdePipeline.TupleTags.REFERENCED_HOSTS;
import static google.registry.beam.rde.RdePipeline.TupleTags.REVISION_ID;
import static google.registry.beam.rde.RdePipeline.TupleTags.SUPERORDINATE_DOMAINS;
import static google.registry.model.reporting.HistoryEntryDao.RESOURCE_TYPES_TO_HISTORY_TYPES;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static org.apache.beam.sdk.values.TypeDescriptors.kvs;
import com.google.common.collect.ImmutableList;
@ -305,7 +305,7 @@ public class RdePipeline implements Serializable {
(String registrarRepoId) -> {
VKey<Registrar> key = VKey.create(Registrar.class, registrarRepoId);
includedRegistrarCounter.inc();
Registrar registrar = jpaTm().transact(() -> jpaTm().loadByKey(key));
Registrar registrar = tm().transact(() -> tm().loadByKey(key));
DepositFragment fragment = marshaller.marshalRegistrar(registrar);
ImmutableSet<KV<PendingDeposit, DepositFragment>> fragments =
pendingDeposits.stream()
@ -376,11 +376,9 @@ public class RdePipeline implements Serializable {
private <T extends HistoryEntry> EppResource loadResourceByHistoryEntryId(
Class<T> historyEntryClazz, String repoId, long revisionId) {
return jpaTm()
.transact(
return tm().transact(
() ->
jpaTm()
.loadByKey(
tm().loadByKey(
VKey.create(historyEntryClazz, new HistoryEntryId(repoId, revisionId))))
.getResourceAtPointInTime()
.map(resource -> resource.cloneProjectedAtTime(watermark))

View file

@ -15,7 +15,7 @@
package google.registry.beam.resave;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static org.apache.beam.sdk.values.TypeDescriptors.integers;
import com.google.common.collect.ImmutableList;
@ -171,19 +171,18 @@ public class ResaveAllEppResourcesPipeline implements Serializable {
public void processElement(
@Element KV<ShardedKey<Integer>, Iterable<String>> element,
OutputReceiver<Void> outputReceiver) {
jpaTm()
.transact(
tm().transact(
() -> {
DateTime now = jpaTm().getTransactionTime();
DateTime now = tm().getTransactionTime();
ImmutableList<VKey<? extends EppResource>> keys =
Streams.stream(element.getValue())
.map(repoId -> VKey.create(clazz, repoId))
.collect(toImmutableList());
ImmutableList<EppResource> mappedResources =
jpaTm().loadByKeys(keys).values().stream()
tm().loadByKeys(keys).values().stream()
.map(r -> r.cloneProjectedAtTime(now))
.collect(toImmutableList());
jpaTm().putAll(mappedResources);
tm().putAll(mappedResources);
});
}
}

View file

@ -15,7 +15,7 @@
package google.registry.beam.spec11;
import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableSet;
@ -131,9 +131,8 @@ public class Spec11Pipeline implements Serializable {
public void processElement(
@Element KV<String, String> input, OutputReceiver<DomainNameInfo> output) {
Domain domain =
jpaTm()
.transact(
() -> jpaTm().loadByKey(VKey.create(Domain.class, input.getKey())));
tm().transact(
() -> tm().loadByKey(VKey.create(Domain.class, input.getKey())));
String emailAddress = input.getValue();
if (emailAddress == null) {
emailAddress = "";

View file

@ -16,7 +16,6 @@ package google.registry.export;
import static com.google.common.base.Verify.verifyNotNull;
import static google.registry.model.tld.Registries.getTldsOfType;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.request.Action.Method.POST;
import static java.nio.charset.StandardCharsets.UTF_8;
@ -89,8 +88,7 @@ public class ExportDomainListsAction implements Runnable {
// DateTime are persisted as timestamp_z in SQL. It is only the
// validation that compares the Java types, and only with the first
// field that compares with the substituted value.
jpaTm()
.query(
tm().query(
"SELECT domainName FROM Domain "
+ "WHERE tld = :tld "
+ "AND deletionTime > :now "

View file

@ -37,7 +37,6 @@ import static google.registry.model.tld.label.ReservationType.FULLY_BLOCKED;
import static google.registry.model.tld.label.ReservationType.NAME_COLLISION;
import static google.registry.model.tld.label.ReservationType.RESERVED_FOR_ANCHOR_TENANT;
import static google.registry.model.tld.label.ReservationType.RESERVED_FOR_SPECIFIC_USE;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.pricing.PricingEngineProxy.isDomainPremium;
import static google.registry.util.CollectionUtils.nullToEmpty;
@ -1179,8 +1178,7 @@ public class DomainFlowUtils {
private static List<DomainHistory> findRecentHistoryEntries(
Domain domain, DateTime now, Duration maxSearchPeriod) {
return jpaTm()
.query(
return tm().query(
"FROM DomainHistory WHERE modificationTime >= :beginning AND repoId = "
+ ":repoId ORDER BY modificationTime ASC",
DomainHistory.class)

View file

@ -15,7 +15,6 @@
package google.registry.flows.domain.token;
import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.google.common.base.Strings;
@ -229,8 +228,8 @@ public class AllocationTokenFlowUtils {
// the Recurring billing event is reloaded later in the renew flow, so we synchronize changed
// RecurringBillingEvent with storage manually
tm().put(newRecurringBillingEvent);
jpaTm().getEntityManager().flush();
jpaTm().getEntityManager().clear();
tm().getEntityManager().flush();
tm().getEntityManager().clear();
// Remove current package token
return domain

View file

@ -14,7 +14,7 @@
package google.registry.model;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import javax.annotation.Nullable;
import javax.persistence.Column;
@ -34,7 +34,7 @@ public class CreateAutoTimestamp extends ImmutableObject implements UnsafeSerial
@PreUpdate
void setTimestamp() {
if (creationTime == null) {
creationTime = jpaTm().getTransactionTime();
creationTime = tm().getTransactionTime();
}
}

View file

@ -16,7 +16,6 @@ package google.registry.model;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static google.registry.util.DateTimeUtils.isAtOrAfter;
@ -349,14 +348,12 @@ public final class EppResourceUtils {
Query query;
if (isContactKey) {
query =
jpaTm()
.query(CONTACT_LINKED_DOMAIN_QUERY, String.class)
tm().query(CONTACT_LINKED_DOMAIN_QUERY, String.class)
.setParameter("fkRepoId", key)
.setParameter("now", now);
} else {
query =
jpaTm()
.getEntityManager()
tm().getEntityManager()
.createNativeQuery(HOST_LINKED_DOMAIN_QUERY)
.setParameter("fkRepoId", key.getKey())
.setParameter("now", now.toDate());

View file

@ -18,8 +18,8 @@ import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static google.registry.config.RegistryConfig.getEppResourceCachingDuration;
import static google.registry.config.RegistryConfig.getEppResourceMaxCachedEntries;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaJpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.LoadingCache;
@ -106,12 +106,12 @@ public final class ForeignKeyUtils {
* to duplicate keys.
*/
private static <E extends EppResource> ImmutableMap<String, MostRecentResource> load(
Class<E> clazz, Collection<String> foreignKeys, boolean useReplicaJpaTm) {
Class<E> clazz, Collection<String> foreignKeys, boolean useReplicaTm) {
String fkProperty = RESOURCE_TYPE_TO_FK_PROPERTY.get(clazz);
JpaTransactionManager jpaTmToUse = useReplicaJpaTm ? replicaJpaTm() : jpaTm();
return jpaTmToUse.transact(
JpaTransactionManager tmToUse = useReplicaTm ? replicaTm() : tm();
return tmToUse.transact(
() ->
jpaTmToUse
tmToUse
.query(
("SELECT %fkProperty%, repoId, deletionTime FROM %entity% WHERE (%fkProperty%,"
+ " deletionTime) IN (SELECT %fkProperty%, MAX(deletionTime) FROM"

View file

@ -15,7 +15,7 @@
package google.registry.model;
import static com.google.common.base.Preconditions.checkState;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static org.joda.time.DateTimeZone.UTC;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
@ -70,12 +70,10 @@ public final class IdService {
* <p>The generated IDs are project-wide unique
*/
private static Long getSequenceBasedId() {
return jpaTm()
.transact(
return tm().transact(
() ->
(BigInteger)
jpaTm()
.getEntityManager()
tm().getEntityManager()
.createNativeQuery("SELECT nextval('project_wide_unique_id_seq')")
.getSingleResult())
.longValue();

View file

@ -14,7 +14,7 @@
package google.registry.model;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import java.util.Optional;
@ -38,7 +38,7 @@ public class UpdateAutoTimestamp extends ImmutableObject implements UnsafeSerial
@PrePersist
@PreUpdate
void setTimestamp() {
lastUpdateTime = jpaTm().getTransactionTime();
lastUpdateTime = tm().getTransactionTime();
}
/** Returns the timestamp, or {@code START_OF_TIME} if it's null. */

View file

@ -15,7 +15,7 @@
package google.registry.model.common;
import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import com.github.benmanes.caffeine.cache.LoadingCache;
@ -192,7 +192,7 @@ public class DatabaseMigrationStateSchedule extends CrossTldSingleton {
/** Sets and persists to SQL the provided migration transition schedule. */
public static void set(ImmutableSortedMap<DateTime, MigrationState> migrationTransitionMap) {
jpaTm().assertInTransaction();
tm().assertInTransaction();
TimedTransitionProperty<MigrationState> transitions =
TimedTransitionProperty.make(
migrationTransitionMap,
@ -201,7 +201,7 @@ public class DatabaseMigrationStateSchedule extends CrossTldSingleton {
MigrationState.DATASTORE_ONLY,
"migrationTransitionMap must start with DATASTORE_ONLY");
validateTransitionAtCurrentTime(transitions);
jpaTm().put(new DatabaseMigrationStateSchedule(transitions));
tm().put(new DatabaseMigrationStateSchedule(transitions));
CACHE.invalidateAll();
}
@ -218,12 +218,10 @@ public class DatabaseMigrationStateSchedule extends CrossTldSingleton {
/** Loads the currently-set migration schedule from SQL, or the default if none exists. */
@VisibleForTesting
static TimedTransitionProperty<MigrationState> getUncached() {
return jpaTm()
.transactWithoutBackup(
return tm().transactWithoutBackup(
() -> {
try {
return jpaTm()
.loadSingleton(DatabaseMigrationStateSchedule.class)
return tm().loadSingleton(DatabaseMigrationStateSchedule.class)
.map(s -> s.migrationTransitions)
.orElse(DEFAULT_TRANSITION_MAP);
} catch (PersistenceException e) {
@ -245,8 +243,8 @@ public class DatabaseMigrationStateSchedule extends CrossTldSingleton {
*/
private static void validateTransitionAtCurrentTime(
TimedTransitionProperty<MigrationState> newTransitions) {
MigrationState currentValue = getUncached().getValueAtTime(jpaTm().getTransactionTime());
MigrationState nextCurrentValue = newTransitions.getValueAtTime(jpaTm().getTransactionTime());
MigrationState currentValue = getUncached().getValueAtTime(tm().getTransactionTime());
MigrationState nextCurrentValue = newTransitions.getValueAtTime(tm().getTransactionTime());
checkArgument(
VALID_STATE_TRANSITIONS.get(currentValue).contains(nextCurrentValue),
"Cannot transition from current state-as-of-now %s to new state-as-of-now %s",

View file

@ -15,7 +15,7 @@
package google.registry.model.console;
import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import java.util.Optional;
@ -24,11 +24,9 @@ public class UserDao {
/** Retrieves the one user with this email address if it exists. */
public static Optional<User> loadUser(String emailAddress) {
return jpaTm()
.transact(
return tm().transact(
() ->
jpaTm()
.query("FROM User WHERE emailAddress = :emailAddress", User.class)
tm().query("FROM User WHERE emailAddress = :emailAddress", User.class)
.setParameter("emailAddress", emailAddress)
.getResultStream()
.findFirst());
@ -36,8 +34,7 @@ public class UserDao {
/** Saves the given user, checking that no existing user already exists with this email. */
public static void saveUser(User user) {
jpaTm()
.transact(
tm().transact(
() -> {
// Check for an existing user (the unique constraint protects us, but this gives a
// nicer exception)
@ -51,7 +48,7 @@ public class UserDao {
+ " email already exists with ID %s",
user.getEmailAddress(), user.getId(), savedUser.getId()));
}
jpaTm().put(user);
tm().put(user);
});
}
}

View file

@ -15,7 +15,6 @@
package google.registry.model.domain.token;
import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
@ -101,9 +100,8 @@ public class PackagePromotion extends ImmutableObject implements Buildable {
/** Loads and returns a PackagePromotion entity by its token string directly from Cloud SQL. */
public static Optional<PackagePromotion> loadByTokenString(String tokenString) {
jpaTm().assertInTransaction();
return jpaTm()
.query("FROM PackagePromotion WHERE token = :token", PackagePromotion.class)
tm().assertInTransaction();
return tm().query("FROM PackagePromotion WHERE token = :token", PackagePromotion.class)
.setParameter("token", VKey.create(AllocationToken.class, tokenString))
.getResultStream()
.findFirst();

View file

@ -27,7 +27,6 @@ import static com.google.common.io.BaseEncoding.base64;
import static google.registry.config.RegistryConfig.getDefaultRegistrarWhoisServer;
import static google.registry.model.CacheUtils.memoizeWithShortExpiration;
import static google.registry.model.tld.Registries.assertTldsExist;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.CollectionUtils.nullToEmptyImmutableCopy;
import static google.registry.util.CollectionUtils.nullToEmptyImmutableSortedCopy;
@ -580,8 +579,7 @@ public class Registrar extends UpdateAutoTimestampEntity implements Buildable, J
private Iterable<RegistrarPoc> getContactsIterable() {
return tm().transact(
() ->
jpaTm()
.query("FROM RegistrarPoc WHERE registrarId = :registrarId", RegistrarPoc.class)
tm().query("FROM RegistrarPoc WHERE registrarId = :registrarId", RegistrarPoc.class)
.setParameter("registrarId", registrarId)
.getResultStream()
.collect(toImmutableList()));

View file

@ -20,7 +20,6 @@ import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.io.BaseEncoding.base64;
import static google.registry.model.registrar.Registrar.checkValidEmail;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.CollectionUtils.nullToEmptyImmutableSortedCopy;
import static google.registry.util.PasswordUtils.SALT_SUPPLIER;
@ -185,8 +184,7 @@ public class RegistrarPoc extends ImmutableObject implements Jsonifiable, Unsafe
() -> {
ImmutableSet<String> emailAddressesToKeep =
contacts.stream().map(RegistrarPoc::getEmailAddress).collect(toImmutableSet());
jpaTm()
.query(
tm().query(
"DELETE FROM RegistrarPoc WHERE registrarId = :registrarId AND "
+ "emailAddress NOT IN :emailAddressesToKeep")
.setParameter("registrarId", registrar.getRegistrarId())

View file

@ -16,7 +16,7 @@ package google.registry.model.reporting;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
@ -56,8 +56,7 @@ public class HistoryEntryDao {
/** Loads all history objects in the times specified, including all types. */
public static ImmutableList<HistoryEntry> loadAllHistoryObjects(
DateTime afterTime, DateTime beforeTime) {
return jpaTm()
.transact(
return tm().transact(
() ->
new ImmutableList.Builder<HistoryEntry>()
.addAll(loadAllHistoryObjects(ContactHistory.class, afterTime, beforeTime))
@ -84,8 +83,8 @@ public class HistoryEntryDao {
/** Loads all history objects in the time period specified for the given {@link EppResource}. */
public static ImmutableList<HistoryEntry> loadHistoryObjectsForResource(
VKey<? extends EppResource> resourceKey, DateTime afterTime, DateTime beforeTime) {
return jpaTm()
.transact(() -> loadHistoryObjectsForResourceInternal(resourceKey, afterTime, beforeTime));
return tm().transact(
() -> loadHistoryObjectsForResourceInternal(resourceKey, afterTime, beforeTime));
}
/**
@ -119,8 +118,7 @@ public class HistoryEntryDao {
/** Loads all history objects from all time from the given registrars. */
public static Iterable<HistoryEntry> loadHistoryObjectsByRegistrars(
ImmutableCollection<String> registrarIds) {
return jpaTm()
.transact(
return tm().transact(
() ->
Streams.concat(
loadHistoryObjectByRegistrarsInternal(ContactHistory.class, registrarIds),
@ -132,8 +130,7 @@ public class HistoryEntryDao {
private static <T extends HistoryEntry> Stream<T> loadHistoryObjectByRegistrarsInternal(
Class<T> historyClass, ImmutableCollection<String> registrarIds) {
return jpaTm()
.criteriaQuery(
return tm().criteriaQuery(
CriteriaQueryBuilder.create(historyClass)
.whereFieldIsIn("clientId", registrarIds)
.build())
@ -144,7 +141,7 @@ public class HistoryEntryDao {
VKey<? extends EppResource> resourceKey, DateTime afterTime, DateTime beforeTime) {
// The class we're searching from is based on which resource type (e.g. Domain) we have
Class<? extends HistoryEntry> historyClass = getHistoryClassFromParent(resourceKey.getKind());
CriteriaBuilder criteriaBuilder = jpaTm().getEntityManager().getCriteriaBuilder();
CriteriaBuilder criteriaBuilder = tm().getEntityManager().getCriteriaBuilder();
CriteriaQuery<? extends HistoryEntry> criteriaQuery =
CriteriaQueryBuilder.create(historyClass)
.where("modificationTime", criteriaBuilder::greaterThanOrEqualTo, afterTime)
@ -154,7 +151,7 @@ public class HistoryEntryDao {
.orderByAsc("modificationTime")
.build();
return ImmutableList.copyOf(jpaTm().criteriaQuery(criteriaQuery).getResultList());
return ImmutableList.copyOf(tm().criteriaQuery(criteriaQuery).getResultList());
}
public static Class<? extends HistoryEntry> getHistoryClassFromParent(
@ -168,9 +165,8 @@ public class HistoryEntryDao {
private static <T extends HistoryEntry> List<T> loadAllHistoryObjects(
Class<T> historyClass, DateTime afterTime, DateTime beforeTime) {
CriteriaBuilder criteriaBuilder = jpaTm().getEntityManager().getCriteriaBuilder();
return jpaTm()
.criteriaQuery(
CriteriaBuilder criteriaBuilder = tm().getEntityManager().getCriteriaBuilder();
return tm().criteriaQuery(
CriteriaQueryBuilder.create(historyClass)
.where("modificationTime", criteriaBuilder::greaterThanOrEqualTo, afterTime)
.where("modificationTime", criteriaBuilder::lessThanOrEqualTo, beforeTime)

View file

@ -15,7 +15,7 @@
package google.registry.model.server;
import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DateTimeUtils.isAtOrAfter;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
@ -212,12 +212,11 @@ public class Lock extends ImmutableObject implements Serializable {
String scope = tld != null ? tld : GLOBAL;
Supplier<AcquireResult> lockAcquirer =
() -> {
DateTime now = jpaTm().getTransactionTime();
DateTime now = tm().getTransactionTime();
// Checking if an unexpired lock still exists - if so, the lock can't be acquired.
Lock lock =
jpaTm()
.loadByKeyIfPresent(VKey.create(Lock.class, new LockId(resourceName, scope)))
tm().loadByKeyIfPresent(VKey.create(Lock.class, new LockId(resourceName, scope)))
.orElse(null);
if (lock != null) {
logger.atInfo().log(
@ -237,11 +236,11 @@ public class Lock extends ImmutableObject implements Serializable {
Lock newLock =
create(resourceName, scope, requestStatusChecker.getLogId(), now, leaseLength);
jpaTm().put(newLock);
tm().put(newLock);
return AcquireResult.create(now, lock, newLock, lockState);
};
AcquireResult acquireResult = jpaTm().transactWithoutBackup(lockAcquirer);
AcquireResult acquireResult = tm().transactWithoutBackup(lockAcquirer);
logAcquireResult(acquireResult);
lockMetrics.recordAcquire(resourceName, scope, acquireResult.lockState());
@ -258,15 +257,15 @@ public class Lock extends ImmutableObject implements Serializable {
// this can happen if release() is called around the expiration time and the lock
// expires underneath us.
VKey<Lock> key = VKey.create(Lock.class, new LockId(resourceName, scope));
Lock loadedLock = jpaTm().loadByKeyIfPresent(key).orElse(null);
Lock loadedLock = tm().loadByKeyIfPresent(key).orElse(null);
if (equals(loadedLock)) {
// Use deleteIgnoringReadOnly() so that we don't create a commit log entry for deleting
// the lock.
logger.atInfo().log("Deleting lock: %s", lockId);
jpaTm().delete(key);
tm().delete(key);
lockMetrics.recordRelease(
resourceName, scope, new Duration(acquiredTime, jpaTm().getTransactionTime()));
resourceName, scope, new Duration(acquiredTime, tm().getTransactionTime()));
} else {
logger.atSevere().log(
"The lock we acquired was transferred to someone else before we"
@ -278,7 +277,7 @@ public class Lock extends ImmutableObject implements Serializable {
}
return null;
};
jpaTm().transactWithoutBackup(lockReleaser);
tm().transactWithoutBackup(lockReleaser);
}
static class LockId extends ImmutableObject implements Serializable {

View file

@ -14,7 +14,7 @@
package google.registry.model.smd;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import com.google.common.collect.ImmutableMap;
@ -28,15 +28,12 @@ public class SignedMarkRevocationListDao {
/** Loads the {@link SignedMarkRevocationList}. */
static SignedMarkRevocationList load() {
Optional<SignedMarkRevocationList> smdrl =
jpaTm()
.transact(
tm().transact(
() -> {
Long revisionId =
jpaTm()
.query("SELECT MAX(revisionId) FROM SignedMarkRevocationList", Long.class)
tm().query("SELECT MAX(revisionId) FROM SignedMarkRevocationList", Long.class)
.getSingleResult();
return jpaTm()
.query(
return tm().query(
"FROM SignedMarkRevocationList smrl LEFT JOIN FETCH smrl.revokes "
+ "WHERE smrl.revisionId = :revisionId",
SignedMarkRevocationList.class)
@ -49,7 +46,7 @@ public class SignedMarkRevocationListDao {
/** Save the given {@link SignedMarkRevocationList} */
static void save(SignedMarkRevocationList signedMarkRevocationList) {
jpaTm().transact(() -> jpaTm().insert(signedMarkRevocationList));
tm().transact(() -> tm().insert(signedMarkRevocationList));
logger.atInfo().log(
"Inserted %,d signed mark revocations into Cloud SQL.",
signedMarkRevocationList.revokes.size());

View file

@ -22,7 +22,6 @@ import static com.google.common.base.Strings.emptyToNull;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Maps.filterValues;
import static google.registry.model.CacheUtils.memoizeWithShortExpiration;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.CollectionUtils.entriesToImmutableMap;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
@ -59,7 +58,7 @@ public final class Registries {
() ->
tm().transact(
() -> {
EntityManager entityManager = jpaTm().getEntityManager();
EntityManager entityManager = tm().getEntityManager();
Stream<?> resultStream =
entityManager
.createQuery("SELECT tldStr, tldType FROM Tld")

View file

@ -15,7 +15,7 @@
package google.registry.model.tld;
import static com.google.common.base.Preconditions.checkNotNull;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.google.common.collect.ImmutableList;
import google.registry.model.domain.RegistryLock;
@ -26,31 +26,29 @@ public final class RegistryLockDao {
/** Returns the {@link RegistryLock} referred to by this revision ID, or empty if none exists. */
public static Optional<RegistryLock> getByRevisionId(long revisionId) {
jpaTm().assertInTransaction();
return Optional.ofNullable(jpaTm().getEntityManager().find(RegistryLock.class, revisionId));
tm().assertInTransaction();
return Optional.ofNullable(tm().getEntityManager().find(RegistryLock.class, revisionId));
}
/** Returns the most recent version of the {@link RegistryLock} referred to by the code. */
public static Optional<RegistryLock> getByVerificationCode(String verificationCode) {
jpaTm().assertInTransaction();
tm().assertInTransaction();
Long revisionId =
jpaTm()
.query(
tm().query(
"SELECT MAX(revisionId) FROM RegistryLock WHERE verificationCode ="
+ " :verificationCode",
Long.class)
.setParameter("verificationCode", verificationCode)
.getSingleResult();
return Optional.ofNullable(revisionId)
.map(revision -> jpaTm().getEntityManager().find(RegistryLock.class, revision));
.map(revision -> tm().getEntityManager().find(RegistryLock.class, revision));
}
/** Returns all lock objects that this registrar has created, including pending locks. */
public static ImmutableList<RegistryLock> getLocksByRegistrarId(String registrarId) {
jpaTm().assertInTransaction();
tm().assertInTransaction();
return ImmutableList.copyOf(
jpaTm()
.query(
tm().query(
"SELECT lock FROM RegistryLock lock WHERE lock.registrarId = :registrarId"
+ " AND lock.unlockCompletionTime IS NULL ORDER BY lock.domainName ASC",
RegistryLock.class)
@ -64,9 +62,8 @@ public final class RegistryLockDao {
* <p>Returns empty if this domain hasn't been locked before.
*/
public static Optional<RegistryLock> getMostRecentByRepoId(String repoId) {
jpaTm().assertInTransaction();
return jpaTm()
.query(
tm().assertInTransaction();
return tm().query(
"SELECT lock FROM RegistryLock lock WHERE lock.repoId = :repoId"
+ " ORDER BY lock.revisionId DESC",
RegistryLock.class)
@ -83,9 +80,8 @@ public final class RegistryLockDao {
* {@link #getMostRecentByRepoId(String)} in that it only returns verified locks.
*/
public static Optional<RegistryLock> getMostRecentVerifiedLockByRepoId(String repoId) {
jpaTm().assertInTransaction();
return jpaTm()
.query(
tm().assertInTransaction();
return tm().query(
"SELECT lock FROM RegistryLock lock WHERE lock.repoId = :repoId AND"
+ " lock.lockCompletionTime IS NOT NULL AND lock.unlockCompletionTime IS NULL"
+ " ORDER BY lock.revisionId DESC",
@ -103,9 +99,8 @@ public final class RegistryLockDao {
* {@link #getMostRecentByRepoId(String)} in that it only returns verified unlocks.
*/
public static Optional<RegistryLock> getMostRecentVerifiedUnlockByRepoId(String repoId) {
jpaTm().assertInTransaction();
return jpaTm()
.query(
tm().assertInTransaction();
return tm().query(
"SELECT lock FROM RegistryLock lock WHERE lock.repoId = :repoId AND"
+ " lock.unlockCompletionTime IS NOT NULL ORDER BY lock.revisionId DESC",
RegistryLock.class)
@ -116,8 +111,8 @@ public final class RegistryLockDao {
}
public static RegistryLock save(RegistryLock registryLock) {
jpaTm().assertInTransaction();
tm().assertInTransaction();
checkNotNull(registryLock, "Null registry lock cannot be saved");
return jpaTm().getEntityManager().merge(registryLock);
return tm().getEntityManager().merge(registryLock);
}
}

View file

@ -19,7 +19,7 @@ import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.config.RegistryConfig.getDomainLabelListCacheDuration;
import static google.registry.config.RegistryConfig.getSingletonCachePersistDuration;
import static google.registry.config.RegistryConfig.getStaticPremiumListMaxCachedEntries;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.CollectionUtils.isNullOrEmpty;
import com.github.benmanes.caffeine.cache.LoadingCache;
@ -135,11 +135,10 @@ public class PremiumListDao {
/** Saves the given premium list (and its premium list entries) to Cloud SQL. */
public static PremiumList save(PremiumList premiumList) {
jpaTm()
.transact(
tm().transact(
() -> {
jpaTm().insert(premiumList);
jpaTm().getEntityManager().flush(); // This populates the revisionId.
tm().insert(premiumList);
tm().getEntityManager().flush(); // This populates the revisionId.
long revisionId = premiumList.getRevisionId();
if (!isNullOrEmpty(premiumList.getLabelsToPrices())) {
@ -148,7 +147,7 @@ public class PremiumListDao {
.getLabelsToPrices()
.forEach(
(key, value) -> entries.add(PremiumEntry.create(revisionId, value, key)));
jpaTm().insertAll(entries.build());
tm().insertAll(entries.build());
}
});
premiumListCache.invalidate(premiumList.getName());
@ -156,27 +155,23 @@ public class PremiumListDao {
}
public static void delete(PremiumList premiumList) {
jpaTm()
.transact(
tm().transact(
() -> {
Optional<PremiumList> persistedList = getLatestRevision(premiumList.getName());
if (persistedList.isPresent()) {
jpaTm()
.query("DELETE FROM PremiumEntry WHERE revisionId = :revisionId")
tm().query("DELETE FROM PremiumEntry WHERE revisionId = :revisionId")
.setParameter("revisionId", persistedList.get().getRevisionId())
.executeUpdate();
jpaTm().delete(persistedList.get());
tm().delete(persistedList.get());
}
});
premiumListCache.invalidate(premiumList.getName());
}
private static Optional<PremiumList> getLatestRevisionUncached(String premiumListName) {
return jpaTm()
.transact(
return tm().transact(
() ->
jpaTm()
.query(
tm().query(
"FROM PremiumList WHERE name = :name ORDER BY revisionId DESC",
PremiumList.class)
.setParameter("name", premiumListName)
@ -191,11 +186,9 @@ public class PremiumListDao {
* <p>This is an expensive operation and should only be used when the entire list is required.
*/
public static List<PremiumEntry> loadPremiumEntries(PremiumList premiumList) {
return jpaTm()
.transact(
return tm().transact(
() ->
jpaTm()
.query(
tm().query(
"FROM PremiumEntry pe WHERE pe.revisionId = :revisionId",
PremiumEntry.class)
.setParameter("revisionId", premiumList.getRevisionId())
@ -207,11 +200,9 @@ public class PremiumListDao {
* retrieval so it should only be done in a cached context.
*/
static Optional<BigDecimal> getPriceForLabelUncached(RevisionIdAndLabel revisionIdAndLabel) {
return jpaTm()
.transact(
return tm().transact(
() ->
jpaTm()
.query(
tm().query(
"SELECT pe.price FROM PremiumEntry pe WHERE pe.revisionId = :revisionId"
+ " AND pe.domainLabel = :label",
BigDecimal.class)

View file

@ -22,7 +22,7 @@ import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static google.registry.config.RegistryConfig.getDomainLabelListCacheDuration;
import static google.registry.model.tld.label.ReservationType.FULLY_BLOCKED;
import static google.registry.persistence.transaction.QueryComposer.Comparator.EQ;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.CollectionUtils.nullToEmpty;
import static org.joda.time.DateTimeZone.UTC;
@ -78,8 +78,7 @@ public final class ReservedList
@PreRemove
void preRemove() {
jpaTm()
.query("DELETE FROM ReservedEntry WHERE revision_id = :revisionId")
tm().query("DELETE FROM ReservedEntry WHERE revision_id = :revisionId")
.setParameter("revisionId", revisionId)
.executeUpdate();
}
@ -101,7 +100,7 @@ public final class ReservedList
entry -> {
// We can safely change the revision id since it's "Insignificant".
entry.revisionId = revisionId;
jpaTm().insert(entry);
tm().insert(entry);
});
}
}
@ -200,10 +199,9 @@ public final class ReservedList
public synchronized ImmutableMap<String, ReservedListEntry> getReservedListEntries() {
if (reservedListMap == null) {
reservedListMap =
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
tm()
.createQueryComposer(ReservedListEntry.class)
.where("revisionId", EQ, revisionId)
.stream()

View file

@ -14,7 +14,7 @@
package google.registry.model.tld.label;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
import com.google.common.flogger.FluentLogger;
@ -31,7 +31,7 @@ public class ReservedListDao {
public static void save(ReservedList reservedList) {
checkArgumentNotNull(reservedList, "Must specify reservedList");
logger.atInfo().log("Saving reserved list %s to Cloud SQL.", reservedList.getName());
jpaTm().transact(() -> jpaTm().insert(reservedList));
tm().transact(() -> tm().insert(reservedList));
logger.atInfo().log(
"Saved reserved list %s with %d entries to Cloud SQL.",
reservedList.getName(), reservedList.getReservedListEntries().size());
@ -39,7 +39,7 @@ public class ReservedListDao {
/** Deletes a reserved list from Cloud SQL. */
public static void delete(ReservedList reservedList) {
jpaTm().transact(() -> jpaTm().delete(reservedList));
tm().transact(() -> tm().delete(reservedList));
}
/**
@ -47,11 +47,9 @@ public class ReservedListDao {
* exists.
*/
public static Optional<ReservedList> getLatestRevision(String reservedListName) {
return jpaTm()
.transact(
return tm().transact(
() ->
jpaTm()
.query(
tm().query(
"FROM ReservedList WHERE revisionId IN "
+ "(SELECT MAX(revisionId) FROM ReservedList WHERE name = :name)",
ReservedList.class)
@ -66,11 +64,9 @@ public class ReservedListDao {
* <p>This means that at least one reserved list revision must exist for the given name.
*/
public static boolean checkExists(String reservedListName) {
return jpaTm()
.transact(
return tm().transact(
() ->
jpaTm()
.query("SELECT 1 FROM ReservedList WHERE name = :name", Integer.class)
tm().query("SELECT 1 FROM ReservedList WHERE name = :name", Integer.class)
.setParameter("name", reservedListName)
.setMaxResults(1)
.getResultList()

View file

@ -18,7 +18,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static google.registry.persistence.transaction.QueryComposer.Comparator.EQ;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.google.common.annotations.VisibleForTesting;
@ -104,8 +104,7 @@ public class ClaimsList extends ImmutableObject {
@PreRemove
void preRemove() {
jpaTm()
.query("DELETE FROM ClaimsEntry WHERE revision_id = :revisionId")
tm().query("DELETE FROM ClaimsEntry WHERE revision_id = :revisionId")
.setParameter("revisionId", revisionId)
.executeUpdate();
}
@ -123,7 +122,7 @@ public class ClaimsList extends ImmutableObject {
if (labelsToKeys != null) {
labelsToKeys.forEach(
(domainLabel, claimKey) ->
jpaTm().insert(new ClaimsEntry(revisionId, domainLabel, claimKey)));
tm().insert(new ClaimsEntry(revisionId, domainLabel, claimKey)));
}
}
@ -169,10 +168,9 @@ public class ClaimsList extends ImmutableObject {
public ImmutableMap<String, String> getLabelsToKeys() {
if (labelsToKeys == null) {
labelsToKeys =
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
tm()
.createQueryComposer(ClaimsEntry.class)
.where("revisionId", EQ, revisionId)
.stream()
@ -191,8 +189,7 @@ public class ClaimsList extends ImmutableObject {
*/
public long size() {
if (labelsToKeys == null) {
return jpaTm()
.createQueryComposer(ClaimsEntry.class)
return tm().createQueryComposer(ClaimsEntry.class)
.where("revisionId", EQ, revisionId)
.count();
}
@ -209,11 +206,9 @@ public class ClaimsList extends ImmutableObject {
if (labelsToKeys != null) {
return Optional.ofNullable(labelsToKeys.get(label));
}
return jpaTm()
.transact(
return tm().transact(
() ->
jpaTm()
.createQueryComposer(ClaimsEntry.class)
tm().createQueryComposer(ClaimsEntry.class)
.where("revisionId", EQ, revisionId)
.where("domainLabel", EQ, label)
.first()

View file

@ -16,7 +16,7 @@ package google.registry.model.tmch;
import static google.registry.config.RegistryConfig.getClaimsListCacheDuration;
import static google.registry.persistence.transaction.QueryComposer.Comparator.EQ;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import com.github.benmanes.caffeine.cache.LoadingCache;
@ -51,7 +51,7 @@ public class ClaimsListDao {
/** Saves the given {@link ClaimsList} to Cloud SQL. */
public static void save(ClaimsList claimsList) {
jpaTm().transact(() -> jpaTm().insert(claimsList));
tm().transact(() -> tm().insert(claimsList));
CACHE.put(ClaimsListDao.class, claimsList);
}
@ -65,15 +65,12 @@ public class ClaimsListDao {
* doesn't exist.
*/
private static ClaimsList getUncached() {
return jpaTm()
.transact(
return tm().transact(
() -> {
Long revisionId =
jpaTm()
.query("SELECT MAX(revisionId) FROM ClaimsList", Long.class)
tm().query("SELECT MAX(revisionId) FROM ClaimsList", Long.class)
.getSingleResult();
return jpaTm()
.createQueryComposer(ClaimsList.class)
return tm().createQueryComposer(ClaimsList.class)
.where("revisionId", EQ, revisionId)
.first();
})

View file

@ -15,7 +15,7 @@
package google.registry.model.tmch;
import static com.google.common.base.Preconditions.checkNotNull;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import google.registry.model.common.CrossTldSingleton;
import java.util.Optional;
@ -39,7 +39,7 @@ public final class TmchCrl extends CrossTldSingleton {
/** Returns the singleton instance of this entity, without memoization. */
public static Optional<TmchCrl> get() {
return jpaTm().transact(() -> jpaTm().loadSingleton(TmchCrl.class));
return tm().transact(() -> tm().loadSingleton(TmchCrl.class));
}
/**
@ -49,14 +49,13 @@ public final class TmchCrl extends CrossTldSingleton {
* and actually newer than the one currently in the database.
*/
public static void set(final String crl, final String url) {
jpaTm()
.transact(
tm().transact(
() -> {
TmchCrl tmchCrl = new TmchCrl();
tmchCrl.updated = jpaTm().getTransactionTime();
tmchCrl.updated = tm().getTransactionTime();
tmchCrl.crl = checkNotNull(crl, "crl");
tmchCrl.url = checkNotNull(url, "url");
jpaTm().put(tmchCrl);
tm().put(tmchCrl);
});
}

View file

@ -14,7 +14,7 @@
package google.registry.persistence.transaction;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.google.common.collect.ImmutableList;
import java.util.Collection;
@ -104,7 +104,7 @@ public class CriteriaQueryBuilder<T> {
/** Creates a query builder that will SELECT from the given class. */
public static <T> CriteriaQueryBuilder<T> create(Class<T> clazz) {
return create(jpaTm(), clazz);
return create(tm(), clazz);
}
/** Creates a query builder for the given entity manager. */

View file

@ -20,8 +20,8 @@ import java.lang.reflect.Proxy;
* A dummy implementation for {@link JpaTransactionManager} which throws exception when any of its
* method is invoked.
*
* <p>This is used to initialize the {@link TransactionManagerFactory#jpaTm()} when running unit
* tests, because obviously we cannot connect to the actual Cloud SQL backend in a unit test.
* <p>This is used to initialize the {@link TransactionManagerFactory#tm()} when running unit tests,
* because obviously we cannot connect to the actual Cloud SQL backend in a unit test.
*
* <p>If a unit test needs to access the Cloud SQL database, it must add {@code
* JpaTransactionManagerExtension} as a JUnit extension in the test class.

View file

@ -14,7 +14,7 @@
package google.registry.persistence.transaction;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
@ -210,7 +210,7 @@ public abstract class QueryComposer<T> {
}
public void addToCriteriaQueryBuilder(CriteriaQueryBuilder queryBuilder) {
CriteriaBuilder criteriaBuilder = jpaTm().getEntityManager().getCriteriaBuilder();
CriteriaBuilder criteriaBuilder = tm().getEntityManager().getCriteriaBuilder();
queryBuilder.where(
fieldName, comparator.getComparisonFactory().apply(criteriaBuilder), value);
}

View file

@ -19,22 +19,16 @@ import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
import com.google.appengine.api.utils.SystemProperty;
import com.google.appengine.api.utils.SystemProperty.Environment.Value;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Suppliers;
import google.registry.config.RegistryEnvironment;
import google.registry.persistence.DaggerPersistenceComponent;
import google.registry.tools.RegistryToolEnvironment;
import google.registry.util.NonFinalForTesting;
import java.util.Optional;
import java.util.function.Supplier;
/** Factory class to create {@link TransactionManager} instance. */
// TODO: Rename this to PersistenceFactory and move to persistence package.
public final class TransactionManagerFactory {
/** Optional override to manually set the transaction manager per-test. */
private static Optional<TransactionManager> tmForTest = Optional.empty();
/** Supplier for jpaTm so that it is initialized only once, upon first usage. */
@NonFinalForTesting
private static Supplier<JpaTransactionManager> jpaTm =
@ -77,42 +71,22 @@ public final class TransactionManagerFactory {
return SystemProperty.environment.value() == Value.Production;
}
/**
* Returns the {@link TransactionManager} instance.
*
* <p>Returns the {@link JpaTransactionManager} or replica based on the possible manually
* specified per-test transaction manager.
*/
public static TransactionManager tm() {
return tmForTest.orElseGet(TransactionManagerFactory::jpaTm);
}
/**
* Returns {@link JpaTransactionManager} instance.
*
* <p>Between invocations of {@link TransactionManagerFactory#setJpaTm} every call to this method
* returns the same instance.
*/
public static JpaTransactionManager jpaTm() {
public static JpaTransactionManager tm() {
return jpaTm.get();
}
/** Returns a read-only {@link JpaTransactionManager} instance if configured. */
public static JpaTransactionManager replicaJpaTm() {
public static JpaTransactionManager replicaTm() {
return replicaJpaTm.get();
}
/**
* Returns a {@link TransactionManager} that uses a replica database if one exists.
*
* <p>In Datastore mode, this is unchanged from the regular transaction manager. In SQL mode,
* however, this will be a reference to the read-only replica database if one is configured.
*/
public static TransactionManager replicaTm() {
return replicaJpaTm();
}
/** Sets the return of {@link #jpaTm()} to the given instance of {@link JpaTransactionManager}. */
/** Sets the return of {@link #tm()} to the given instance of {@link JpaTransactionManager}. */
public static void setJpaTm(Supplier<JpaTransactionManager> jpaTmSupplier) {
checkArgumentNotNull(jpaTmSupplier, "jpaTmSupplier");
checkState(
@ -122,7 +96,7 @@ public final class TransactionManagerFactory {
jpaTm = Suppliers.memoize(jpaTmSupplier::get);
}
/** Sets the value of {@link #replicaJpaTm()} to the given {@link JpaTransactionManager}. */
/** Sets the value of {@link #replicaTm()} to the given {@link JpaTransactionManager}. */
public static void setReplicaJpaTm(Supplier<JpaTransactionManager> replicaJpaTmSupplier) {
checkArgumentNotNull(replicaJpaTmSupplier, "replicaJpaTmSupplier");
checkState(
@ -133,7 +107,7 @@ public final class TransactionManagerFactory {
}
/**
* Makes {@link #jpaTm()} return the {@link JpaTransactionManager} instance provided by {@code
* Makes {@link #tm()} return the {@link JpaTransactionManager} instance provided by {@code
* jpaTmSupplier} from now on. This method should only be called by an implementor of {@link
* org.apache.beam.sdk.harness.JvmInitializer}.
*/
@ -141,24 +115,4 @@ public final class TransactionManagerFactory {
checkArgumentNotNull(jpaTmSupplier, "jpaTmSupplier");
jpaTm = Suppliers.memoize(jpaTmSupplier::get);
}
/**
* Sets the return of {@link #tm()} to the given instance of {@link TransactionManager}.
*
* <p>DO NOT CALL THIS DIRECTLY IF POSSIBLE. Strongly prefer the use of <code>TmOverrideExtension
* </code> in test code instead.
*
* <p>Used when overriding the per-test transaction manager for dual-database tests. Should be
* matched with a corresponding invocation of {@link #removeTmOverrideForTest()} either at the end
* of the test or in an <code>@AfterEach</code> handler.
*/
@VisibleForTesting
public static void setTmOverrideForTest(TransactionManager newTmOverride) {
tmForTest = Optional.of(newTmOverride);
}
/** Resets the overridden transaction manager post-test. */
public static void removeTmOverrideForTest() {
tmForTest = Optional.empty();
}
}

View file

@ -16,7 +16,7 @@ package google.registry.rdap;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static google.registry.model.EppResourceUtils.loadByForeignKeyCached;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaJpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaTm;
import static google.registry.request.Action.Method.GET;
import static google.registry.request.Action.Method.HEAD;
import static google.registry.util.DateTimeUtils.END_OF_TIME;
@ -203,13 +203,13 @@ public class RdapDomainSearchAction extends RdapSearchActionBase {
int querySizeLimit = RESULT_SET_SIZE_SCALING_FACTOR * rdapResultSetMaxSize;
RdapResultSet<Domain> resultSet;
resultSet =
replicaJpaTm()
replicaTm()
.transact(
() -> {
CriteriaBuilder criteriaBuilder =
replicaJpaTm().getEntityManager().getCriteriaBuilder();
replicaTm().getEntityManager().getCriteriaBuilder();
CriteriaQueryBuilder<Domain> queryBuilder =
CriteriaQueryBuilder.create(replicaJpaTm(), Domain.class)
CriteriaQueryBuilder.create(replicaTm(), Domain.class)
.where(
"domainName",
criteriaBuilder::like,
@ -239,7 +239,7 @@ public class RdapDomainSearchAction extends RdapSearchActionBase {
int querySizeLimit = RESULT_SET_SIZE_SCALING_FACTOR * rdapResultSetMaxSize;
RdapResultSet<Domain> resultSet;
resultSet =
replicaJpaTm()
replicaTm()
.transact(
() -> {
CriteriaQueryBuilder<Domain> builder =
@ -305,7 +305,7 @@ public class RdapDomainSearchAction extends RdapSearchActionBase {
// incomplete result set if a search asks for something like "ns*", but we need to enforce a
// limit in order to avoid arbitrarily long-running queries.
Optional<String> desiredRegistrar = getDesiredRegistrar();
return replicaJpaTm()
return replicaTm()
.transact(
() -> {
CriteriaQueryBuilder<Host> builder =
@ -319,7 +319,7 @@ public class RdapDomainSearchAction extends RdapSearchActionBase {
builder =
builder.where(
"currentSponsorRegistrarId",
replicaJpaTm().getEntityManager().getCriteriaBuilder()::equal,
replicaTm().getEntityManager().getCriteriaBuilder()::equal,
desiredRegistrar.get());
}
return getMatchingResources(builder, true, maxNameserversInFirstStage)
@ -438,11 +438,11 @@ public class RdapDomainSearchAction extends RdapSearchActionBase {
parameters.put("desiredRegistrar", desiredRegistrar.get());
}
hostKeys =
replicaJpaTm()
replicaTm()
.transact(
() -> {
javax.persistence.Query query =
replicaJpaTm()
replicaTm()
.getEntityManager()
.createNativeQuery(queryBuilder.toString())
.setMaxResults(maxNameserversInFirstStage);
@ -475,37 +475,37 @@ public class RdapDomainSearchAction extends RdapSearchActionBase {
int numHostKeysSearched = 0;
for (List<VKey<Host>> chunk : Iterables.partition(hostKeys, 30)) {
numHostKeysSearched += chunk.size();
replicaJpaTm()
.transact(
() -> {
for (VKey<Host> hostKey : hostKeys) {
CriteriaQueryBuilder<Domain> queryBuilder =
CriteriaQueryBuilder.create(replicaJpaTm(), Domain.class)
.whereFieldContains("nsHosts", hostKey)
.orderByAsc("domainName");
CriteriaBuilder criteriaBuilder =
replicaJpaTm().getEntityManager().getCriteriaBuilder();
if (!shouldIncludeDeleted()) {
queryBuilder =
queryBuilder.where(
"deletionTime", criteriaBuilder::greaterThan, getRequestTime());
}
if (cursorString.isPresent()) {
queryBuilder =
queryBuilder.where(
"domainName", criteriaBuilder::greaterThan, cursorString.get());
}
replicaJpaTm()
.criteriaQuery(queryBuilder.build())
.getResultStream()
.filter(this::isAuthorized)
.forEach(
(domain) -> {
Hibernate.initialize(domain.getDsData());
domainSetBuilder.add(domain);
});
replicaTm()
.transact(
() -> {
for (VKey<Host> hostKey : hostKeys) {
CriteriaQueryBuilder<Domain> queryBuilder =
CriteriaQueryBuilder.create(replicaTm(), Domain.class)
.whereFieldContains("nsHosts", hostKey)
.orderByAsc("domainName");
CriteriaBuilder criteriaBuilder =
replicaTm().getEntityManager().getCriteriaBuilder();
if (!shouldIncludeDeleted()) {
queryBuilder =
queryBuilder.where(
"deletionTime", criteriaBuilder::greaterThan, getRequestTime());
}
});
if (cursorString.isPresent()) {
queryBuilder =
queryBuilder.where(
"domainName", criteriaBuilder::greaterThan, cursorString.get());
}
replicaTm()
.criteriaQuery(queryBuilder.build())
.getResultStream()
.filter(this::isAuthorized)
.forEach(
(domain) -> {
Hibernate.initialize(domain.getDsData());
domainSetBuilder.add(domain);
});
}
});
}
List<Domain> domains = domainSetBuilder.build().asList();
metricInformationBuilder.setNumHostsRetrieved(numHostKeysSearched);

View file

@ -14,7 +14,7 @@
package google.registry.rdap;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaJpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaTm;
import static google.registry.rdap.RdapUtils.getRegistrarByIanaIdentifier;
import static google.registry.rdap.RdapUtils.getRegistrarByName;
import static google.registry.request.Action.Method.GET;
@ -71,7 +71,7 @@ public class RdapEntityAction extends RdapActionBase {
if (ROID_PATTERN.matcher(pathSearchString).matches()) {
VKey<Contact> contactVKey = VKey.create(Contact.class, pathSearchString);
Optional<Contact> contact =
replicaJpaTm().transact(() -> replicaJpaTm().loadByKeyIfPresent(contactVKey));
replicaTm().transact(() -> replicaTm().loadByKeyIfPresent(contactVKey));
// As per Andy Newton on the regext mailing list, contacts by themselves have no role, since
// they are global, and might have different roles for different domains.
if (contact.isPresent() && isAuthorized(contact.get())) {

View file

@ -15,7 +15,7 @@
package google.registry.rdap;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaJpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaTm;
import static google.registry.rdap.RdapUtils.getRegistrarByIanaIdentifier;
import static google.registry.request.Action.Method.GET;
import static google.registry.request.Action.Method.HEAD;
@ -260,7 +260,7 @@ public class RdapEntitySearchAction extends RdapSearchActionBase {
resultSet = RdapResultSet.create(ImmutableList.of());
} else {
resultSet =
replicaJpaTm()
replicaTm()
.transact(
() -> {
CriteriaQueryBuilder<Contact> builder =
@ -307,10 +307,10 @@ public class RdapEntitySearchAction extends RdapSearchActionBase {
contactList = ImmutableList.of();
} else {
Optional<Contact> contact =
replicaJpaTm()
replicaTm()
.transact(
() ->
replicaJpaTm()
replicaTm()
.loadByKeyIfPresent(
VKey.create(Contact.class, partialStringQuery.getInitialString())));
contactList =
@ -370,7 +370,7 @@ public class RdapEntitySearchAction extends RdapSearchActionBase {
contactResultSet = RdapResultSet.create(ImmutableList.of());
} else {
contactResultSet =
replicaJpaTm()
replicaTm()
.transact(
() ->
getMatchingResources(

View file

@ -20,7 +20,7 @@ import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.ImmutableSetMultimap.toImmutableSetMultimap;
import static google.registry.model.EppResourceUtils.isLinked;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaJpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaTm;
import static google.registry.rdap.RdapIcannStandardInformation.CONTACT_REDACTED_VALUE;
import static google.registry.util.CollectionUtils.union;
@ -366,15 +366,13 @@ public class RdapJsonFormatter {
// Kick off the database loads of the nameservers that we will need, so it can load
// asynchronously while we load and process the contacts.
ImmutableSet<Host> loadedHosts =
replicaJpaTm()
replicaTm()
.transact(
() ->
ImmutableSet.copyOf(
replicaJpaTm().loadByKeys(domain.getNameservers()).values()));
ImmutableSet.copyOf(replicaTm().loadByKeys(domain.getNameservers()).values()));
// Load the registrant and other contacts and add them to the data.
ImmutableMap<VKey<? extends Contact>, Contact> loadedContacts =
replicaJpaTm()
.transact(() -> replicaJpaTm().loadByKeysIfPresent(domain.getReferencedContacts()));
replicaTm().transact(() -> replicaTm().loadByKeysIfPresent(domain.getReferencedContacts()));
// RDAP Response Profile 2.7.3, A domain MUST have the REGISTRANT, ADMIN, TECH roles and MAY
// have others. We also add the BILLING.
//
@ -453,10 +451,10 @@ public class RdapJsonFormatter {
statuses.add(StatusValue.LINKED);
}
if (host.isSubordinate()
&& replicaJpaTm()
&& replicaTm()
.transact(
() ->
replicaJpaTm()
replicaTm()
.loadByKey(host.getSuperordinateDomain())
.cloneProjectedAtTime(getRequestTime())
.getStatusValues()
@ -907,10 +905,10 @@ public class RdapJsonFormatter {
.replace("%entityName%", entityName)
.replace("%repoIdValue%", resourceVkey.getKey().toString());
Iterable<HistoryEntry> historyEntries =
replicaJpaTm()
replicaTm()
.transact(
() ->
replicaJpaTm()
replicaTm()
.getEntityManager()
.createQuery(jpql, HistoryEntry.class)
.getResultList());

View file

@ -15,7 +15,7 @@
package google.registry.rdap;
import static google.registry.model.EppResourceUtils.loadByForeignKeyCached;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaJpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaTm;
import static google.registry.request.Action.Method.GET;
import static google.registry.request.Action.Method.HEAD;
import static google.registry.util.DateTimeUtils.END_OF_TIME;
@ -217,7 +217,7 @@ public class RdapNameserverSearchAction extends RdapSearchActionBase {
private NameserverSearchResponse searchByNameUsingPrefix(RdapSearchPattern partialStringQuery) {
// Add 1 so we can detect truncation.
int querySizeLimit = getStandardQuerySizeLimit();
return replicaJpaTm()
return replicaTm()
.transact(
() -> {
CriteriaQueryBuilder<Host> queryBuilder =
@ -260,20 +260,20 @@ public class RdapNameserverSearchAction extends RdapSearchActionBase {
parameters.put("desiredRegistrar", getDesiredRegistrar().get());
}
queryBuilder.append(" ORDER BY repo_id ASC");
rdapResultSet =
replicaJpaTm()
.transact(
() -> {
javax.persistence.Query query =
replicaJpaTm()
.getEntityManager()
.createNativeQuery(queryBuilder.toString(), Host.class)
.setMaxResults(querySizeLimit);
parameters.build().forEach(query::setParameter);
@SuppressWarnings("unchecked")
List<Host> resultList = query.getResultList();
return filterResourcesByVisibility(resultList, querySizeLimit);
});
rdapResultSet =
replicaTm()
.transact(
() -> {
javax.persistence.Query query =
replicaTm()
.getEntityManager()
.createNativeQuery(queryBuilder.toString(), Host.class)
.setMaxResults(querySizeLimit);
parameters.build().forEach(query::setParameter);
@SuppressWarnings("unchecked")
List<Host> resultList = query.getResultList();
return filterResourcesByVisibility(resultList, querySizeLimit);
});
return makeSearchResults(rdapResultSet, CursorType.ADDRESS);
}

View file

@ -15,7 +15,7 @@
package google.registry.rdap;
import static com.google.common.base.Charsets.UTF_8;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaJpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaTm;
import static google.registry.util.DateTimeUtils.END_OF_TIME;
import com.google.common.collect.ImmutableList;
@ -158,17 +158,17 @@ public abstract class RdapSearchActionBase extends RdapActionBase {
*/
<T extends EppResource> RdapResultSet<T> getMatchingResources(
CriteriaQueryBuilder<T> builder, boolean checkForVisibility, int querySizeLimit) {
replicaJpaTm().assertInTransaction();
replicaTm().assertInTransaction();
Optional<String> desiredRegistrar = getDesiredRegistrar();
if (desiredRegistrar.isPresent()) {
builder =
builder.where(
"currentSponsorRegistrarId",
replicaJpaTm().getEntityManager().getCriteriaBuilder()::equal,
replicaTm().getEntityManager().getCriteriaBuilder()::equal,
desiredRegistrar.get());
}
List<T> queryResult =
replicaJpaTm().criteriaQuery(builder.build()).setMaxResults(querySizeLimit).getResultList();
replicaTm().criteriaQuery(builder.build()).setMaxResults(querySizeLimit).getResultList();
if (checkForVisibility) {
return filterResourcesByVisibility(queryResult, querySizeLimit);
} else {
@ -311,7 +311,7 @@ public abstract class RdapSearchActionBase extends RdapActionBase {
RdapSearchPattern partialStringQuery,
Optional<String> cursorString,
DeletedItemHandling deletedItemHandling) {
replicaJpaTm().assertInTransaction();
replicaTm().assertInTransaction();
if (partialStringQuery.getInitialString().length()
< RdapSearchPattern.MIN_INITIAL_STRING_LENGTH) {
throw new UnprocessableEntityException(
@ -319,8 +319,8 @@ public abstract class RdapSearchActionBase extends RdapActionBase {
"Initial search string must be at least %d characters",
RdapSearchPattern.MIN_INITIAL_STRING_LENGTH));
}
CriteriaBuilder criteriaBuilder = replicaJpaTm().getEntityManager().getCriteriaBuilder();
CriteriaQueryBuilder<T> builder = CriteriaQueryBuilder.create(replicaJpaTm(), clazz);
CriteriaBuilder criteriaBuilder = replicaTm().getEntityManager().getCriteriaBuilder();
CriteriaQueryBuilder<T> builder = CriteriaQueryBuilder.create(replicaTm(), clazz);
if (partialStringQuery.getHasWildcard()) {
builder =
builder.where(
@ -367,9 +367,9 @@ public abstract class RdapSearchActionBase extends RdapActionBase {
"Initial search string must be at least %d characters",
RdapSearchPattern.MIN_INITIAL_STRING_LENGTH));
}
replicaJpaTm().assertInTransaction();
CriteriaQueryBuilder<T> builder = CriteriaQueryBuilder.create(replicaJpaTm(), clazz);
CriteriaBuilder criteriaBuilder = replicaJpaTm().getEntityManager().getCriteriaBuilder();
replicaTm().assertInTransaction();
CriteriaQueryBuilder<T> builder = CriteriaQueryBuilder.create(replicaTm(), clazz);
CriteriaBuilder criteriaBuilder = replicaTm().getEntityManager().getCriteriaBuilder();
builder = builder.where(filterField, criteriaBuilder::equal, queryString);
if (cursorString.isPresent()) {
if (cursorField.isPresent()) {
@ -388,7 +388,7 @@ public abstract class RdapSearchActionBase extends RdapActionBase {
RdapSearchPattern partialStringQuery,
Optional<String> cursorString,
DeletedItemHandling deletedItemHandling) {
replicaJpaTm().assertInTransaction();
replicaTm().assertInTransaction();
return queryItems(clazz, "repoId", partialStringQuery, cursorString, deletedItemHandling);
}
@ -398,7 +398,7 @@ public abstract class RdapSearchActionBase extends RdapActionBase {
builder =
builder.where(
"deletionTime",
replicaJpaTm().getEntityManager().getCriteriaBuilder()::equal,
replicaTm().getEntityManager().getCriteriaBuilder()::equal,
END_OF_TIME);
}
return builder;

View file

@ -16,7 +16,6 @@ package google.registry.request.auth;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkNotNull;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.google.appengine.api.users.User;
@ -311,11 +310,9 @@ public class AuthenticatedRegistrarAccessor {
logger.atInfo().log("Checking registrar contacts for user ID %s.", user.getEmail());
// Find all registrars that have a registrar contact with this user's ID.
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
.query(
tm().query(
"SELECT r FROM Registrar r INNER JOIN RegistrarPoc rp ON r.registrarId ="
+ " rp.registrarId WHERE lower(rp.loginEmailAddress) = :email AND"
+ " r.state != :state",

View file

@ -18,7 +18,7 @@ import static com.google.common.base.Strings.isNullOrEmpty;
import static google.registry.flows.poll.PollFlowUtils.createPollMessageQuery;
import static google.registry.model.poll.PollMessageExternalKeyConverter.makePollMessageExternalId;
import static google.registry.persistence.transaction.QueryComposer.Comparator.LIKE;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
@ -81,8 +81,7 @@ final class AckPollMessagesCommand implements Command {
/** Loads and acks all matching poll messages from SQL in one transaction. */
private void ackPollMessagesSql() {
jpaTm()
.transact(
tm().transact(
() -> {
QueryComposer<PollMessage> query = createPollMessageQuery(clientId, clock.nowUtc());
if (!isNullOrEmpty(message)) {

View file

@ -15,7 +15,6 @@
package google.registry.tools;
import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.beust.jcommander.Parameter;
@ -87,8 +86,7 @@ abstract class CreateOrUpdatePackagePromotionCommand extends MutatingCommand {
@Override
protected final void init() throws Exception {
for (String token : mainParameters) {
jpaTm()
.transact(
tm().transact(
() -> {
PackagePromotion oldPackage = getOldPackagePromotion(token);
checkArgument(

View file

@ -17,7 +17,6 @@ package google.registry.tools;
import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.batch.AsyncTaskEnqueuer.QUEUE_ASYNC_ACTIONS;
import static google.registry.model.EppResourceUtils.loadByForeignKeyCached;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES;
@ -76,8 +75,7 @@ public final class DomainLockUtils {
*/
public RegistryLock saveNewRegistryLockRequest(
String domainName, String registrarId, @Nullable String registrarPocId, boolean isAdmin) {
return jpaTm()
.transact(
return tm().transact(
() ->
RegistryLockDao.save(
createLockBuilder(domainName, registrarId, registrarPocId, isAdmin).build()));
@ -90,8 +88,7 @@ public final class DomainLockUtils {
*/
public RegistryLock saveNewRegistryUnlockRequest(
String domainName, String registrarId, boolean isAdmin, Optional<Duration> relockDuration) {
return jpaTm()
.transact(
return tm().transact(
() ->
RegistryLockDao.save(
createUnlockBuilder(domainName, registrarId, isAdmin, relockDuration).build()));
@ -99,10 +96,9 @@ public final class DomainLockUtils {
/** Verifies and applies the lock request previously requested by a user. */
public RegistryLock verifyAndApplyLock(String verificationCode, boolean isAdmin) {
return jpaTm()
.transact(
return tm().transact(
() -> {
DateTime now = jpaTm().getTransactionTime();
DateTime now = tm().getTransactionTime();
RegistryLock lock = getByVerificationCode(verificationCode);
checkArgument(
@ -128,10 +124,9 @@ public final class DomainLockUtils {
/** Verifies and applies the unlock request previously requested by a user. */
public RegistryLock verifyAndApplyUnlock(String verificationCode, boolean isAdmin) {
RegistryLock lock =
jpaTm()
.transact(
tm().transact(
() -> {
DateTime now = jpaTm().getTransactionTime();
DateTime now = tm().getTransactionTime();
RegistryLock previousLock = getByVerificationCode(verificationCode);
checkArgument(
!previousLock.getUnlockCompletionTime().isPresent(),
@ -165,10 +160,9 @@ public final class DomainLockUtils {
*/
public RegistryLock administrativelyApplyLock(
String domainName, String registrarId, @Nullable String registrarPocId, boolean isAdmin) {
return jpaTm()
.transact(
return tm().transact(
() -> {
DateTime now = jpaTm().getTransactionTime();
DateTime now = tm().getTransactionTime();
RegistryLock newLock =
RegistryLockDao.save(
createLockBuilder(domainName, registrarId, registrarPocId, isAdmin)
@ -188,10 +182,9 @@ public final class DomainLockUtils {
public RegistryLock administrativelyApplyUnlock(
String domainName, String registrarId, boolean isAdmin, Optional<Duration> relockDuration) {
RegistryLock lock =
jpaTm()
.transact(
tm().transact(
() -> {
DateTime now = jpaTm().getTransactionTime();
DateTime now = tm().getTransactionTime();
RegistryLock result =
RegistryLockDao.save(
createUnlockBuilder(domainName, registrarId, isAdmin, relockDuration)
@ -240,8 +233,7 @@ public final class DomainLockUtils {
}
private void setAsRelock(RegistryLock newLock) {
jpaTm()
.transact(
tm().transact(
() ->
RegistryLockDao.getMostRecentVerifiedUnlockByRepoId(newLock.getRepoId())
.ifPresent(
@ -251,7 +243,7 @@ public final class DomainLockUtils {
private RegistryLock.Builder createLockBuilder(
String domainName, String registrarId, @Nullable String registrarPocId, boolean isAdmin) {
DateTime now = jpaTm().getTransactionTime();
DateTime now = tm().getTransactionTime();
Domain domain = getDomain(domainName, registrarId, now);
verifyDomainNotLocked(domain, isAdmin);
@ -276,7 +268,7 @@ public final class DomainLockUtils {
private RegistryLock.Builder createUnlockBuilder(
String domainName, String registrarId, boolean isAdmin, Optional<Duration> relockDuration) {
DateTime now = jpaTm().getTransactionTime();
DateTime now = tm().getTransactionTime();
Domain domain = getDomain(domainName, registrarId, now);
Optional<RegistryLock> lockOptional =
RegistryLockDao.getMostRecentVerifiedLockByRepoId(domain.getRepoId());

View file

@ -14,7 +14,7 @@
package google.registry.tools;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
import com.beust.jcommander.Parameter;
@ -32,8 +32,7 @@ public class GetPackagePromotionCommand extends GetEppResourceCommand {
@Override
void runAndPrint() {
for (String token : mainParameters) {
jpaTm()
.transact(
tm().transact(
() -> {
PackagePromotion packagePromotion =
checkArgumentPresent(

View file

@ -20,7 +20,6 @@ import static com.google.common.collect.Iterables.partition;
import static google.registry.model.eppcommon.StatusValue.SERVER_DELETE_PROHIBITED;
import static google.registry.model.eppcommon.StatusValue.SERVER_TRANSFER_PROHIBITED;
import static google.registry.model.eppcommon.StatusValue.SERVER_UPDATE_PROHIBITED;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.CollectionUtils.findDuplicates;
@ -84,8 +83,7 @@ public abstract class LockOrUnlockDomainCommand extends ConfirmingCommand {
.forEach(
batch ->
// we require that the jpaTm is the outer transaction in DomainLockUtils
jpaTm()
.transact(
tm().transact(
() ->
tm().transact(
() -> {

View file

@ -15,7 +15,7 @@
package google.registry.tools;
import static com.google.common.base.Preconditions.checkState;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.tools.Injector.injectReflectively;
import com.beust.jcommander.JCommander;
@ -218,7 +218,7 @@ final class RegistryCli implements CommandRunner {
// Reset the JPA transaction manager after every command to avoid a situation where a test can
// interfere with other tests
JpaTransactionManager cachedJpaTm = jpaTm();
JpaTransactionManager cachedJpaTm = tm();
TransactionManagerFactory.setJpaTm(() -> component.nomulusToolJpaTransactionManager().get());
TransactionManagerFactory.setReplicaJpaTm(
() -> component.nomulusToolReplicaJpaTransactionManager().get());

View file

@ -14,7 +14,7 @@
package google.registry.tools;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
@ -48,11 +48,10 @@ public class SetDatabaseMigrationStateCommand extends ConfirmingCommand {
@Override
protected String prompt() {
return jpaTm()
.transact(
return tm().transact(
() -> {
StringBuilder result = new StringBuilder();
DateTime now = jpaTm().getTransactionTime();
DateTime now = tm().getTransactionTime();
DateTime nextTransition = transitionSchedule.ceilingKey(now);
if (nextTransition != null && nextTransition.isBefore(now.plusMinutes(10))) {
result.append(WARNING_MESSAGE);
@ -65,7 +64,7 @@ public class SetDatabaseMigrationStateCommand extends ConfirmingCommand {
@Override
protected String execute() {
jpaTm().transact(() -> DatabaseMigrationStateSchedule.set(transitionSchedule));
tm().transact(() -> DatabaseMigrationStateSchedule.set(transitionSchedule));
return String.format("Successfully set new migration state schedule %s", transitionSchedule);
}
}

View file

@ -17,7 +17,6 @@ package google.registry.tools.server;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.io.BaseEncoding.base16;
import static google.registry.model.EppResourceUtils.loadAtPointInTime;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.request.Action.Method.POST;
import static java.nio.charset.StandardCharsets.UTF_8;
@ -144,7 +143,7 @@ public class GenerateZoneFilesAction implements Runnable, JsonActionRunner.JsonA
}
private void generateForTld(String tld, DateTime exportTime) {
ImmutableList<String> stanzas = jpaTm().transact(() -> getStanzasForTld(tld, exportTime));
ImmutableList<String> stanzas = tm().transact(() -> getStanzasForTld(tld, exportTime));
BlobId outputBlobId = BlobId.of(bucket, String.format(FILENAME_FORMAT, tld, exportTime));
try (OutputStream gcsOutput = gcsUtils.openOutputStream(outputBlobId);
Writer osWriter = new OutputStreamWriter(gcsOutput, UTF_8);
@ -160,8 +159,7 @@ public class GenerateZoneFilesAction implements Runnable, JsonActionRunner.JsonA
private ImmutableList<String> getStanzasForTld(String tld, DateTime exportTime) {
ImmutableList.Builder<String> result = new ImmutableList.Builder<>();
ScrollableResults scrollableResults =
jpaTm()
.query("FROM Domain WHERE tld = :tld AND deletionTime > :exportTime")
tm().query("FROM Domain WHERE tld = :tld AND deletionTime > :exportTime")
.setParameter("tld", tld)
.setParameter("exportTime", exportTime)
.unwrap(Query.class)
@ -171,8 +169,8 @@ public class GenerateZoneFilesAction implements Runnable, JsonActionRunner.JsonA
Domain domain = (Domain) scrollableResults.get(0);
populateStanzasForDomain(domain, exportTime, result);
if (i == 0) {
jpaTm().getEntityManager().flush();
jpaTm().getEntityManager().clear();
tm().getEntityManager().flush();
tm().getEntityManager().clear();
}
}
return result.build();

View file

@ -17,7 +17,7 @@ package google.registry.tools.server;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.model.tld.Registries.assertTldsExist;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.request.Action.Method.GET;
import static google.registry.request.Action.Method.POST;
import static google.registry.request.RequestParameters.PARAM_TLDS;
@ -74,18 +74,16 @@ public final class ListDomainsAction extends ListObjectsAction<Domain> {
}
private ImmutableList<Domain> loadDomains() {
return jpaTm()
.transact(
return tm().transact(
() ->
jpaTm()
.query(
tm().query(
"FROM Domain WHERE tld IN (:tlds) AND deletionTime > "
+ "current_timestamp() ORDER BY creationTime DESC",
Domain.class)
.setParameter("tlds", tlds)
.setMaxResults(limit)
.getResultStream()
.map(EppResourceUtils.transformAtTime(jpaTm().getTransactionTime()))
.map(EppResourceUtils.transformAtTime(tm().getTransactionTime()))
.collect(toImmutableList()));
}
}

View file

@ -15,7 +15,7 @@
package google.registry.tools.server;
import static com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.request.Action.Method.GET;
import static google.registry.request.Action.Method.POST;
@ -49,10 +49,9 @@ public final class ListPremiumListsAction extends ListObjectsAction<PremiumList>
@Override
public ImmutableSet<PremiumList> loadObjects() {
return jpaTm()
.transact(
return tm().transact(
() ->
jpaTm().loadAllOf(PremiumList.class).stream()
tm().loadAllOf(PremiumList.class).stream()
.map(PremiumList::getName)
.map(PremiumListDao::getLatestRevision)
.filter(Optional::isPresent)

View file

@ -15,7 +15,7 @@
package google.registry.tools.server;
import static com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.request.Action.Method.GET;
import static google.registry.request.Action.Method.POST;
@ -47,10 +47,9 @@ public final class ListReservedListsAction extends ListObjectsAction<ReservedLis
@Override
public ImmutableSet<ReservedList> loadObjects() {
return jpaTm()
.transact(
return tm().transact(
() ->
jpaTm().loadAllOf(ReservedList.class).stream()
tm().loadAllOf(ReservedList.class).stream()
.map(ReservedList::getName)
.map(ReservedListDao::getLatestRevision)
.filter(Optional::isPresent)

View file

@ -16,7 +16,6 @@ package google.registry.tools.server;
import static com.google.common.base.Preconditions.checkArgument;
import static google.registry.model.tld.Registries.assertTldsExist;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.request.RequestParameters.PARAM_TLDS;
@ -80,8 +79,7 @@ public class RefreshDnsForAllDomainsAction implements Runnable {
checkArgument(smearMinutes > 0, "Must specify a positive number of smear minutes");
tm().transact(
() ->
jpaTm()
.query(
tm().query(
"SELECT domainName FROM Domain "
+ "WHERE tld IN (:tlds) "
+ "AND deletionTime > :now",

View file

@ -19,7 +19,6 @@ import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Sets.difference;
import static google.registry.config.RegistryEnvironment.PRODUCTION;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.security.JsonResponseHelper.Status.ERROR;
import static google.registry.security.JsonResponseHelper.Status.SUCCESS;
@ -243,7 +242,7 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA
Registrar registrar = loadRegistrarUnchecked(registrarId);
// Detach the registrar to avoid Hibernate object-updates, since we wish to email
// out the diffs between the existing and updated registrar objects
jpaTm().getEntityManager().detach(registrar);
tm().getEntityManager().detach(registrar);
// Verify that the registrar hasn't been changed.
// To do that - we find the latest update time (or null if the registrar has been
// deleted) and compare to the update time from the args. The update time in the args

View file

@ -16,7 +16,7 @@ package google.registry.ui.server.registrar;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.security.JsonResponseHelper.Status.SUCCESS;
import static google.registry.ui.server.registrar.RegistrarConsoleModule.PARAM_CLIENT_ID;
import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
@ -196,17 +196,16 @@ public final class RegistryLockGetAction implements JsonGetAction {
private static ImmutableList<ImmutableMap<String, ?>> getLockedDomains(
String registrarId, boolean isAdmin) {
return jpaTm()
.transact(
return tm().transact(
() ->
RegistryLockDao.getLocksByRegistrarId(registrarId).stream()
.filter(lock -> !lock.isLockRequestExpired(jpaTm().getTransactionTime()))
.filter(lock -> !lock.isLockRequestExpired(tm().getTransactionTime()))
.map(lock -> lockToMap(lock, isAdmin))
.collect(toImmutableList()));
}
private static ImmutableMap<String, ?> lockToMap(RegistryLock lock, boolean isAdmin) {
DateTime now = jpaTm().getTransactionTime();
DateTime now = tm().getTransactionTime();
return new ImmutableMap.Builder<String, Object>()
.put(DOMAIN_NAME_PARAM, lock.getDomainName())
.put(LOCKED_TIME_PARAM, lock.getLockCompletionTime().map(DateTime::toString).orElse(""))

View file

@ -16,7 +16,7 @@ package google.registry.ui.server.registrar;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.security.JsonResponseHelper.Status.ERROR;
import static google.registry.security.JsonResponseHelper.Status.SUCCESS;
import static google.registry.ui.server.registrar.RegistryLockGetAction.getContactMatchingLogin;
@ -127,8 +127,7 @@ public class RegistryLockPostAction implements Runnable, JsonActionRunner.JsonAc
.orElseThrow(() -> new ForbiddenException("User is not logged in"));
String userEmail = verifyPasswordAndGetEmail(userAuthInfo, postInput);
jpaTm()
.transact(
tm().transact(
() -> {
RegistryLock registryLock =
postInput.isLock

View file

@ -16,7 +16,7 @@ package google.registry.whois;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import com.google.common.annotations.VisibleForTesting;
@ -51,12 +51,10 @@ final class NameserverLookupByIpCommand implements WhoisCommand {
public WhoisResponse executeQuery(DateTime now) throws WhoisException {
Iterable<Host> hostsFromDb;
hostsFromDb =
jpaTm()
.transact(
tm().transact(
() ->
// We cannot query @Convert-ed fields in HQL, so we must use native Postgres.
jpaTm()
.getEntityManager()
tm().getEntityManager()
/*
* Using array_operator <@ (contained-by) with gin index on inet_address.
* Without gin index, this is slightly slower than the alternative form of

View file

@ -17,7 +17,7 @@ package google.registry.whois;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaJpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.replicaTm;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
@ -53,13 +53,13 @@ final class NameserverWhoisResponse extends WhoisResponseImpl {
ImmutableMap<Host, String> hostRegistrars =
subordinateHosts.isEmpty()
? ImmutableMap.of()
: replicaJpaTm()
: replicaTm()
.transact(
() ->
Maps.toMap(
subordinateHosts.iterator(),
host ->
replicaJpaTm()
replicaTm()
.loadByKey(host.getSuperordinateDomain())
.cloneProjectedAtTime(getTimestamp())
.getCurrentSponsorRegistrarId()));

View file

@ -14,7 +14,7 @@
package google.registry.batch;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.createTld;
import static google.registry.testing.DatabaseHelper.persistActiveContact;
import static google.registry.testing.DatabaseHelper.persistEppResource;
@ -110,7 +110,7 @@ public class CheckPackagesComplianceActionTest {
.setLastNotificationSent(DateTime.parse("2010-11-12T05:00:00Z"))
.build();
jpaTm().transact(() -> jpaTm().put(packagePromotion));
tm().transact(() -> tm().put(packagePromotion));
contact = persistActiveContact("contact1234");
}
@ -199,7 +199,7 @@ public class CheckPackagesComplianceActionTest {
.setPackagePrice(Money.of(CurrencyUnit.USD, 1000))
.setNextBillingDate(DateTime.parse("2012-11-12T05:00:00Z"))
.build();
jpaTm().transact(() -> jpaTm().put(packagePromotion2));
tm().transact(() -> tm().put(packagePromotion2));
persistEppResource(
DatabaseHelper.newDomain("foo2.tld", contact)
@ -253,7 +253,7 @@ public class CheckPackagesComplianceActionTest {
.setPackagePrice(Money.of(CurrencyUnit.USD, 1000))
.setNextBillingDate(DateTime.parse("2015-11-12T05:00:00Z"))
.build();
jpaTm().transact(() -> jpaTm().put(packagePromotion2));
tm().transact(() -> tm().put(packagePromotion2));
// Create limit is 1, creating 2 domains to go over the limit
persistEppResource(

View file

@ -17,7 +17,7 @@ package google.registry.batch;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.common.truth.Truth8.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.persistResource;
import static org.apache.http.HttpStatus.SC_OK;
@ -118,8 +118,7 @@ class WipeOutContactHistoryPiiActionTest {
void getAllHistoryEntitiesOlderThan_returnsAllPersistedEntities() {
ImmutableList<ContactHistory> expectedToBeWipedOut =
persistLotsOfContactHistoryEntities(20, MIN_MONTHS_BEFORE_WIPE_OUT + 1, 0, DEFAULT_CONTACT);
jpaTm()
.transact(
tm().transact(
() ->
assertThat(
action.getNextContactHistoryEntitiesWithPiiBatch(
@ -135,8 +134,7 @@ class WipeOutContactHistoryPiiActionTest {
// persisted entities that should not be part of the actual result
persistLotsOfContactHistoryEntities(15, 17, MIN_MONTHS_BEFORE_WIPE_OUT - 1, DEFAULT_CONTACT);
jpaTm()
.transact(
tm().transact(
() ->
assertThat(
action.getNextContactHistoryEntitiesWithPiiBatch(
@ -147,8 +145,7 @@ class WipeOutContactHistoryPiiActionTest {
@Test
void run_withNoEntitiesToWipeOut_success() {
assertThat(
jpaTm()
.transact(
tm().transact(
() ->
action
.getNextContactHistoryEntitiesWithPiiBatch(
@ -158,8 +155,7 @@ class WipeOutContactHistoryPiiActionTest {
action.run();
assertThat(
jpaTm()
.transact(
tm().transact(
() ->
action
.getNextContactHistoryEntitiesWithPiiBatch(
@ -180,8 +176,7 @@ class WipeOutContactHistoryPiiActionTest {
// The query should return a stream of all persisted entities.
assertThat(
jpaTm()
.transact(
tm().transact(
() ->
action
.getNextContactHistoryEntitiesWithPiiBatch(
@ -197,8 +192,7 @@ class WipeOutContactHistoryPiiActionTest {
// The query should return an empty stream after the wipe out action.
assertThat(
jpaTm()
.transact(
tm().transact(
() ->
action
.getNextContactHistoryEntitiesWithPiiBatch(
@ -217,8 +211,7 @@ class WipeOutContactHistoryPiiActionTest {
// The query should return a subset of all persisted data.
assertThat(
jpaTm()
.transact(
tm().transact(
() ->
action
.getNextContactHistoryEntitiesWithPiiBatch(
@ -233,8 +226,7 @@ class WipeOutContactHistoryPiiActionTest {
// The query should return an empty stream after the wipe out action.
assertThat(
jpaTm()
.transact(
tm().transact(
() ->
action
.getNextContactHistoryEntitiesWithPiiBatch(
@ -254,8 +246,7 @@ class WipeOutContactHistoryPiiActionTest {
// The query should return a subset of all persisted data.
assertThat(
jpaTm()
.transact(
tm().transact(
() ->
action
.getNextContactHistoryEntitiesWithPiiBatch(
@ -270,8 +261,7 @@ class WipeOutContactHistoryPiiActionTest {
// The query should return an empty stream after the wipe out action.
assertThat(
jpaTm()
.transact(
tm().transact(
() ->
action
.getNextContactHistoryEntitiesWithPiiBatch(
@ -284,8 +274,7 @@ class WipeOutContactHistoryPiiActionTest {
@Test
void wipeOutContactHistoryData_wipesOutNoEntity() {
jpaTm()
.transact(
tm().transact(
() ->
assertThat(
action.wipeOutContactHistoryData(
@ -302,8 +291,7 @@ class WipeOutContactHistoryPiiActionTest {
assertAllEntitiesContainPii(DatabaseHelper.loadByEntitiesIfPresent(expectedToBeWipedOut));
jpaTm()
.transact(
tm().transact(
() -> {
action.wipeOutContactHistoryData(
action.getNextContactHistoryEntitiesWithPiiBatch(

View file

@ -14,7 +14,7 @@
package google.registry.beam.common;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.google.common.collect.ImmutableMap;
import com.google.common.truth.Truth;
@ -81,12 +81,12 @@ public class DatabaseSnapshotTest {
jpa =
new JpaTransactionManagerImpl(
Persistence.createEntityManagerFactory("nomulus", jpaProperties), new FakeClock());
origJpa = jpaTm();
origJpa = tm();
TransactionManagerFactory.setJpaTm(() -> jpa);
Registry tld = DatabaseHelper.newRegistry("tld", "TLD");
jpaTm().transact(() -> jpaTm().put(tld));
registry = jpaTm().transact(() -> jpaTm().loadByEntity(tld));
tm().transact(() -> tm().put(tld));
registry = tm().transact(() -> tm().loadByEntity(tld));
}
@AfterAll
@ -113,11 +113,9 @@ public class DatabaseSnapshotTest {
void readSnapshot() {
try (DatabaseSnapshot databaseSnapshot = DatabaseSnapshot.createSnapshot()) {
Registry snapshotRegistry =
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
.setDatabaseSnapshot(databaseSnapshot.getSnapshotId())
tm().setDatabaseSnapshot(databaseSnapshot.getSnapshotId())
.loadByEntity(registry));
Truth.assertThat(snapshotRegistry).isEqualTo(registry);
}
@ -131,22 +129,20 @@ public class DatabaseSnapshotTest {
.asBuilder()
.setCreateBillingCost(registry.getStandardCreateCost().plus(1))
.build();
jpaTm().transact(() -> jpaTm().put(updated));
tm().transact(() -> tm().put(updated));
Registry persistedUpdate = jpaTm().transact(() -> jpaTm().loadByEntity(registry));
Registry persistedUpdate = tm().transact(() -> tm().loadByEntity(registry));
Truth.assertThat(persistedUpdate).isNotEqualTo(registry);
Registry snapshotRegistry =
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
.setDatabaseSnapshot(databaseSnapshot.getSnapshotId())
tm().setDatabaseSnapshot(databaseSnapshot.getSnapshotId())
.loadByEntity(registry));
Truth.assertThat(snapshotRegistry).isEqualTo(registry);
} finally {
// Revert change to registry in DB, which is shared by all test methods.
jpaTm().transact(() -> jpaTm().put(registry));
tm().transact(() -> tm().put(registry));
}
}
@ -158,7 +154,7 @@ public class DatabaseSnapshotTest {
.asBuilder()
.setCreateBillingCost(registry.getStandardCreateCost().plus(1))
.build();
jpaTm().transact(() -> jpaTm().put(updated));
tm().transact(() -> tm().put(updated));
Read<Registry, Registry> read =
RegistryJpaIO.read(() -> CriteriaQueryBuilder.create(Registry.class).build(), x -> x)
@ -172,7 +168,7 @@ public class DatabaseSnapshotTest {
testPipeline.run();
} finally {
// Revert change to registry in DB, which is shared by all test methods.
jpaTm().transact(() -> jpaTm().put(registry));
tm().transact(() -> tm().put(registry));
}
}
}

View file

@ -16,7 +16,7 @@ package google.registry.beam.common;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.immutableObjectCorrespondence;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.loadAllOf;
import static google.registry.testing.DatabaseHelper.newContact;
import static org.junit.jupiter.api.Assertions.assertThrows;
@ -51,7 +51,7 @@ class RegistryJpaWriteTest implements Serializable {
@Test
void writeToSql_twoWriters() {
jpaTm().transact(() -> jpaTm().put(AppEngineExtension.makeRegistrar2()));
tm().transact(() -> tm().put(AppEngineExtension.makeRegistrar2()));
ImmutableList.Builder<Contact> contactsBuilder = new ImmutableList.Builder<>();
for (int i = 0; i < 3; i++) {
contactsBuilder.add(newContact("contact_" + i));
@ -72,11 +72,10 @@ class RegistryJpaWriteTest implements Serializable {
// RegistryJpaIO.Write actions should not write existing objects to the database because the
// object could have been mutated in between creation and when the Write actually occurs,
// causing a race condition
jpaTm()
.transact(
tm().transact(
() -> {
jpaTm().put(AppEngineExtension.makeRegistrar2());
jpaTm().put(newContact("contact"));
tm().put(AppEngineExtension.makeRegistrar2());
tm().put(newContact("contact"));
});
Contact contact = Iterables.getOnlyElement(loadAllOf(Contact.class));
testPipeline

View file

@ -16,7 +16,7 @@ package google.registry.beam.resave;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.createTld;
import static google.registry.testing.DatabaseHelper.loadAllOf;
import static google.registry.testing.DatabaseHelper.loadByEntity;
@ -151,7 +151,7 @@ public class ResaveAllEppResourcesPipelineTest {
persistDomainWithDependentResources("renewed", "tld", contact, now, now, now.plusYears(1));
persistActiveDomain("nonrenewed.tld", now, now.plusYears(20));
// Spy the transaction manager so we can be sure we're only saving the renewed domain
JpaTransactionManager spy = spy(jpaTm());
JpaTransactionManager spy = spy(tm());
TransactionManagerFactory.setJpaTm(() -> spy);
ArgumentCaptor<Domain> domainPutCaptor = ArgumentCaptor.forClass(Domain.class);
runPipeline();
@ -171,7 +171,7 @@ public class ResaveAllEppResourcesPipelineTest {
persistDomainWithDependentResources(
"nonrenewed", "tld", contact, now, now, now.plusYears(20));
// Spy the transaction manager so we can be sure we're attempting to save everything
JpaTransactionManager spy = spy(jpaTm());
JpaTransactionManager spy = spy(tm());
TransactionManagerFactory.setJpaTm(() -> spy);
ArgumentCaptor<EppResource> eppResourcePutCaptor = ArgumentCaptor.forClass(EppResource.class);
runPipeline();

View file

@ -17,7 +17,7 @@ package google.registry.beam.spec11;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.immutableObjectCorrespondence;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.AppEngineExtension.makeRegistrar1;
import static google.registry.testing.DatabaseHelper.createTld;
import static google.registry.testing.DatabaseHelper.persistActiveContact;
@ -278,11 +278,10 @@ class Spec11PipelineTest {
}
private void verifySaveToCloudSql() {
jpaTm()
.transact(
tm().transact(
() -> {
ImmutableList<Spec11ThreatMatch> sqlThreatMatches =
Spec11ThreatMatchDao.loadEntriesByDate(jpaTm(), new LocalDate(2020, 1, 27));
Spec11ThreatMatchDao.loadEntriesByDate(tm(), new LocalDate(2020, 1, 27));
assertThat(sqlThreatMatches)
.comparingElementsUsing(immutableObjectCorrespondence("id"))
.containsExactlyElementsIn(sqlThreatMatches);

View file

@ -22,7 +22,7 @@ import static google.registry.model.common.DatabaseMigrationStateSchedule.Migrat
import static google.registry.model.common.DatabaseMigrationStateSchedule.MigrationState.SQL_ONLY;
import static google.registry.model.common.DatabaseMigrationStateSchedule.MigrationState.SQL_PRIMARY;
import static google.registry.model.common.DatabaseMigrationStateSchedule.MigrationState.SQL_PRIMARY_READ_ONLY;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static org.junit.Assert.assertThrows;
@ -128,7 +128,7 @@ public class DatabaseMigrationStateScheduleTest extends EntityTestCase {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
() -> jpaTm().transact(() -> DatabaseMigrationStateSchedule.set(nowInvalidMap)));
() -> tm().transact(() -> DatabaseMigrationStateSchedule.set(nowInvalidMap)));
assertThat(thrown)
.hasMessageThat()
.isEqualTo(
@ -150,7 +150,7 @@ public class DatabaseMigrationStateScheduleTest extends EntityTestCase {
private void runValidTransition(MigrationState from, MigrationState to) {
ImmutableSortedMap<DateTime, MigrationState> transitions =
createMapEndingWithTransition(from, to);
jpaTm().transact(() -> DatabaseMigrationStateSchedule.set(transitions));
tm().transact(() -> DatabaseMigrationStateSchedule.set(transitions));
assertThat(DatabaseMigrationStateSchedule.getUncached().toValueMap())
.containsExactlyEntriesIn(transitions);
}
@ -161,7 +161,7 @@ public class DatabaseMigrationStateScheduleTest extends EntityTestCase {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
() -> jpaTm().transact(() -> DatabaseMigrationStateSchedule.set(transitions)));
() -> tm().transact(() -> DatabaseMigrationStateSchedule.set(transitions)));
assertThat(thrown)
.hasMessageThat()
.isEqualTo(

View file

@ -15,7 +15,7 @@
package google.registry.model.console;
import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.google.common.truth.Truth8;
@ -62,7 +62,7 @@ public class UserDaoTest extends EntityTestCase {
// nonexistent one should never exist
Truth8.assertThat(UserDao.loadUser("nonexistent@email.com")).isEmpty();
// now try deleting the one that does exist
jpaTm().transact(() -> jpaTm().delete(fromDb));
tm().transact(() -> tm().delete(fromDb));
Truth8.assertThat(UserDao.loadUser("email@email.com")).isEmpty();
}

View file

@ -16,7 +16,7 @@ package google.registry.model.console;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static org.junit.jupiter.api.Assertions.assertThrows;
import google.registry.model.EntityTestCase;
@ -38,19 +38,15 @@ public class UserTest extends EntityTestCase {
.setUserRoles(
new UserRoles.Builder().setGlobalRole(GlobalRole.FTE).setIsAdmin(true).build())
.build();
jpaTm().transact(() -> jpaTm().put(user));
jpaTm()
.transact(
tm().transact(() -> tm().put(user));
tm().transact(
() -> {
assertAboutImmutableObjects()
.that(
jpaTm()
.query("FROM User WHERE gaiaId = 'gaiaId'", User.class)
.getSingleResult())
tm().query("FROM User WHERE gaiaId = 'gaiaId'", User.class).getSingleResult())
.isEqualExceptFields(user, "id", "updateTimestamp");
assertThat(
jpaTm()
.query("FROM User WHERE gaiaId = 'badGaiaId'", User.class)
tm().query("FROM User WHERE gaiaId = 'badGaiaId'", User.class)
.getResultList())
.isEmpty();
});

View file

@ -18,7 +18,7 @@ import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects;
import static google.registry.model.domain.token.AllocationToken.TokenStatus.NOT_STARTED;
import static google.registry.model.domain.token.AllocationToken.TokenType.PACKAGE;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.createTld;
import static google.registry.testing.DatabaseHelper.insertInDb;
import static google.registry.testing.DatabaseHelper.loadByEntity;
@ -177,11 +177,10 @@ public class DomainSqlTest {
@Test
void testResaveDomain_succeeds() {
persistDomain();
jpaTm()
.transact(
tm().transact(
() -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey());
jpaTm().put(persisted.asBuilder().build());
Domain persisted = tm().loadByKey(domain.createVKey());
tm().put(persisted.asBuilder().build());
});
// Load the domain in its entirety.
assertEqualDomainExcept(loadByKey(domain.createVKey()));
@ -190,18 +189,16 @@ public class DomainSqlTest {
@Test
void testModifyGracePeriod_setEmptyCollectionSuccessfully() {
persistDomain();
jpaTm()
.transact(
tm().transact(
() -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey());
Domain persisted = tm().loadByKey(domain.createVKey());
Domain modified = persisted.asBuilder().setGracePeriods(ImmutableSet.of()).build();
jpaTm().put(modified);
tm().put(modified);
});
jpaTm()
.transact(
tm().transact(
() -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey());
Domain persisted = tm().loadByKey(domain.createVKey());
assertThat(persisted.getGracePeriods()).isEmpty();
});
}
@ -209,18 +206,16 @@ public class DomainSqlTest {
@Test
void testModifyGracePeriod_setNullCollectionSuccessfully() {
persistDomain();
jpaTm()
.transact(
tm().transact(
() -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey());
Domain persisted = tm().loadByKey(domain.createVKey());
Domain modified = persisted.asBuilder().setGracePeriods(null).build();
jpaTm().put(modified);
tm().put(modified);
});
jpaTm()
.transact(
tm().transact(
() -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey());
Domain persisted = tm().loadByKey(domain.createVKey());
assertThat(persisted.getGracePeriods()).isEmpty();
});
}
@ -228,10 +223,9 @@ public class DomainSqlTest {
@Test
void testModifyGracePeriod_addThenRemoveSuccessfully() {
persistDomain();
jpaTm()
.transact(
tm().transact(
() -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey());
Domain persisted = tm().loadByKey(domain.createVKey());
Domain modified =
persisted
.asBuilder()
@ -244,13 +238,12 @@ public class DomainSqlTest {
null,
200L))
.build();
jpaTm().put(modified);
tm().put(modified);
});
jpaTm()
.transact(
tm().transact(
() -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey());
Domain persisted = tm().loadByKey(domain.createVKey());
assertThat(persisted.getGracePeriods())
.containsExactly(
GracePeriod.create(
@ -260,23 +253,21 @@ public class DomainSqlTest {
assertEqualDomainExcept(persisted, "gracePeriods");
});
jpaTm()
.transact(
tm().transact(
() -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey());
Domain persisted = tm().loadByKey(domain.createVKey());
Domain.Builder builder = persisted.asBuilder();
for (GracePeriod gracePeriod : persisted.getGracePeriods()) {
if (gracePeriod.getType() == GracePeriodStatus.RENEW) {
builder.removeGracePeriod(gracePeriod);
}
}
jpaTm().put(builder.build());
tm().put(builder.build());
});
jpaTm()
.transact(
tm().transact(
() -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey());
Domain persisted = tm().loadByKey(domain.createVKey());
assertEqualDomainExcept(persisted);
});
}
@ -284,18 +275,16 @@ public class DomainSqlTest {
@Test
void testModifyGracePeriod_removeThenAddSuccessfully() {
persistDomain();
jpaTm()
.transact(
tm().transact(
() -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey());
Domain persisted = tm().loadByKey(domain.createVKey());
Domain modified = persisted.asBuilder().setGracePeriods(ImmutableSet.of()).build();
jpaTm().put(modified);
tm().put(modified);
});
jpaTm()
.transact(
tm().transact(
() -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey());
Domain persisted = tm().loadByKey(domain.createVKey());
assertThat(persisted.getGracePeriods()).isEmpty();
Domain modified =
persisted
@ -309,13 +298,12 @@ public class DomainSqlTest {
null,
100L))
.build();
jpaTm().put(modified);
tm().put(modified);
});
jpaTm()
.transact(
tm().transact(
() -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey());
Domain persisted = tm().loadByKey(domain.createVKey());
assertThat(persisted.getGracePeriods())
.containsExactly(
GracePeriod.create(
@ -332,37 +320,33 @@ public class DomainSqlTest {
Sets.union(domain.getDsData(), ImmutableSet.of(extraDsData)).immutableCopy();
// Add an extra DomainDsData to dsData set.
jpaTm()
.transact(
tm().transact(
() -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey());
Domain persisted = tm().loadByKey(domain.createVKey());
assertThat(persisted.getDsData()).containsExactlyElementsIn(domain.getDsData());
Domain modified = persisted.asBuilder().setDsData(unionDsData).build();
jpaTm().put(modified);
tm().put(modified);
});
// Verify that the persisted domain entity contains both DomainDsData records.
jpaTm()
.transact(
tm().transact(
() -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey());
Domain persisted = tm().loadByKey(domain.createVKey());
assertThat(persisted.getDsData()).containsExactlyElementsIn(unionDsData);
assertEqualDomainExcept(persisted, "dsData");
});
// Remove the extra DomainDsData record from dsData set.
jpaTm()
.transact(
tm().transact(
() -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey());
jpaTm().put(persisted.asBuilder().setDsData(domain.getDsData()).build());
Domain persisted = tm().loadByKey(domain.createVKey());
tm().put(persisted.asBuilder().setDsData(domain.getDsData()).build());
});
// Verify that the persisted domain is equal to the original domain.
jpaTm()
.transact(
tm().transact(
() -> {
Domain persisted = jpaTm().loadByKey(domain.createVKey());
Domain persisted = tm().loadByKey(domain.createVKey());
assertEqualDomainExcept(persisted);
});
}
@ -371,7 +355,7 @@ public class DomainSqlTest {
void testSerializable() {
createTld("com");
insertInDb(contact, contact2, domain, host);
Domain persisted = jpaTm().transact(() -> jpaTm().loadByEntity(domain));
Domain persisted = tm().transact(() -> tm().loadByEntity(domain));
assertThat(SerializeUtils.serializeDeserialize(persisted)).isEqualTo(persisted);
}
@ -427,8 +411,7 @@ public class DomainSqlTest {
DateTime originalUpdateTime = persisted.getUpdateTimestamp().getTimestamp();
fakeClock.advanceOneMilli();
DateTime transactionTime =
jpaTm()
.transact(
tm().transact(
() -> {
Host host2 =
new Host.Builder()
@ -440,7 +423,7 @@ public class DomainSqlTest {
insertInDb(host2);
domain = persisted.asBuilder().addNameserver(host2.createVKey()).build();
updateInDb(domain);
return jpaTm().getTransactionTime();
return tm().getTransactionTime();
});
domain = loadByKey(domain.createVKey());
assertThat(domain.getUpdateTimestamp().getTimestamp()).isEqualTo(transactionTime);
@ -454,8 +437,7 @@ public class DomainSqlTest {
DateTime originalUpdateTime = persisted.getUpdateTimestamp().getTimestamp();
fakeClock.advanceOneMilli();
DateTime transactionTime =
jpaTm()
.transact(
tm().transact(
() -> {
domain =
persisted
@ -464,7 +446,7 @@ public class DomainSqlTest {
ImmutableSet.of(DomainDsData.create(1, 2, 3, new byte[] {0, 1, 2})))
.build();
updateInDb(domain);
return jpaTm().getTransactionTime();
return tm().getTransactionTime();
});
domain = loadByKey(domain.createVKey());
assertThat(domain.getUpdateTimestamp().getTimestamp()).isEqualTo(transactionTime);

View file

@ -16,7 +16,7 @@ package google.registry.model.domain.token;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.createTld;
import static google.registry.testing.DatabaseHelper.persistResource;
import static org.junit.jupiter.api.Assertions.assertThrows;
@ -66,9 +66,9 @@ public class PackagePromotionTest extends EntityTestCase {
.setNextBillingDate(DateTime.parse("2011-11-12T05:00:00Z"))
.build();
jpaTm().transact(() -> jpaTm().put(packagePromotion));
tm().transact(() -> tm().put(packagePromotion));
assertAboutImmutableObjects()
.that(jpaTm().transact(() -> PackagePromotion.loadByTokenString("abc123")).get())
.that(tm().transact(() -> PackagePromotion.loadByTokenString("abc123")).get())
.isEqualExceptFields(packagePromotion, "packagePromotionId");
}

View file

@ -15,7 +15,7 @@
package google.registry.model.eppcommon;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb;
import static google.registry.testing.DatabaseHelper.loadByEntity;
import static org.junit.jupiter.api.Assertions.assertThrows;
@ -83,7 +83,7 @@ class AddressTest {
/** Test the merge behavior. */
@Test
void testSuccess_putAndLoadStreetLines() {
jpaTm().transact(() -> jpaTm().put(entity));
tm().transact(() -> tm().put(entity));
assertAddress(loadByEntity(entity).address, "123 W 14th St", "8th Fl", "Rm 8");
}

View file

@ -16,7 +16,7 @@ package google.registry.model.history;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb;
import static google.registry.testing.DatabaseHelper.loadByEntity;
import static google.registry.testing.DatabaseHelper.newContactWithRoid;
@ -49,10 +49,9 @@ public class ContactHistoryTest extends EntityTestCase {
Contact contactFromDb = loadByEntity(contact);
ContactHistory contactHistory = createContactHistory(contactFromDb);
insertInDb(contactHistory);
jpaTm()
.transact(
tm().transact(
() -> {
ContactHistory fromDatabase = jpaTm().loadByKey(contactHistory.createVKey());
ContactHistory fromDatabase = tm().loadByKey(contactHistory.createVKey());
assertContactHistoriesEqual(fromDatabase, contactHistory);
assertThat(fromDatabase.getRepoId()).isEqualTo(contactHistory.getRepoId());
});
@ -65,8 +64,7 @@ public class ContactHistoryTest extends EntityTestCase {
Contact contactFromDb = loadByEntity(contact);
ContactHistory contactHistory = createContactHistory(contactFromDb);
insertInDb(contactHistory);
ContactHistory fromDatabase =
jpaTm().transact(() -> jpaTm().loadByKey(contactHistory.createVKey()));
ContactHistory fromDatabase = tm().transact(() -> tm().loadByKey(contactHistory.createVKey()));
assertThat(SerializeUtils.serializeDeserialize(fromDatabase)).isEqualTo(fromDatabase);
}

View file

@ -16,7 +16,7 @@ package google.registry.model.history;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.createTld;
import static google.registry.testing.DatabaseHelper.insertInDb;
import static google.registry.testing.DatabaseHelper.newContactWithRoid;
@ -64,10 +64,9 @@ public class DomainHistoryTest extends EntityTestCase {
DomainHistory domainHistory = createDomainHistory(domain);
insertInDb(domainHistory);
jpaTm()
.transact(
tm().transact(
() -> {
DomainHistory fromDatabase = jpaTm().loadByKey(domainHistory.createVKey());
DomainHistory fromDatabase = tm().loadByKey(domainHistory.createVKey());
assertDomainHistoriesEqual(fromDatabase, domainHistory);
assertThat(fromDatabase.getRepoId()).isEqualTo(domainHistory.getRepoId());
});
@ -78,8 +77,7 @@ public class DomainHistoryTest extends EntityTestCase {
Domain domain = addGracePeriodForSql(createDomainWithContactsAndHosts());
DomainHistory domainHistory = createDomainHistory(domain);
insertInDb(domainHistory);
DomainHistory fromDatabase =
jpaTm().transact(() -> jpaTm().loadByKey(domainHistory.createVKey()));
DomainHistory fromDatabase = tm().transact(() -> tm().loadByKey(domainHistory.createVKey()));
assertThat(SerializeUtils.serializeDeserialize(fromDatabase)).isEqualTo(fromDatabase);
}
@ -88,11 +86,10 @@ public class DomainHistoryTest extends EntityTestCase {
Host host = newHostWithRoid("ns1.example.com", "host1");
Contact contact = newContactWithRoid("contactId", "contact1");
jpaTm()
.transact(
tm().transact(
() -> {
jpaTm().insert(host);
jpaTm().insert(contact);
tm().insert(host);
tm().insert(contact);
});
Domain domain =

View file

@ -16,7 +16,7 @@ package google.registry.model.history;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb;
import static google.registry.testing.DatabaseHelper.loadByEntity;
import static google.registry.testing.DatabaseHelper.newHostWithRoid;
@ -45,10 +45,9 @@ public class HostHistoryTest extends EntityTestCase {
Host hostFromDb = loadByEntity(host);
HostHistory hostHistory = createHostHistory(hostFromDb);
insertInDb(hostHistory);
jpaTm()
.transact(
tm().transact(
() -> {
HostHistory fromDatabase = jpaTm().loadByKey(hostHistory.createVKey());
HostHistory fromDatabase = tm().loadByKey(hostHistory.createVKey());
assertHostHistoriesEqual(fromDatabase, hostHistory);
assertThat(fromDatabase.getRepoId()).isEqualTo(hostHistory.getRepoId());
});
@ -61,7 +60,7 @@ public class HostHistoryTest extends EntityTestCase {
Host hostFromDb = loadByEntity(host);
HostHistory hostHistory = createHostHistory(hostFromDb);
insertInDb(hostHistory);
HostHistory fromDatabase = jpaTm().transact(() -> jpaTm().loadByKey(hostHistory.createVKey()));
HostHistory fromDatabase = tm().transact(() -> tm().loadByKey(hostHistory.createVKey()));
assertThat(SerializeUtils.serializeDeserialize(fromDatabase)).isEqualTo(fromDatabase);
}

View file

@ -16,7 +16,7 @@ package google.registry.model.reporting;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.immutableObjectCorrespondence;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.createTlds;
import static google.registry.testing.DatabaseHelper.persistActiveContact;
import static google.registry.testing.DatabaseHelper.persistResource;
@ -51,32 +51,29 @@ class Spec11ThreatMatchDaoTest extends EntityTestCase {
todayOrgDomain = persistResource(DatabaseHelper.newDomain("today.org", contact));
yesterdayComDomain = persistResource(DatabaseHelper.newDomain("yesterday.com", contact));
yesterdayOrgDomain = persistResource(DatabaseHelper.newDomain("yesterday.org", contact));
jpaTm()
.transact(
tm().transact(
() -> {
jpaTm().insertAll(getThreatMatchesToday());
jpaTm().insertAll(getThreatMatchesYesterday());
tm().insertAll(getThreatMatchesToday());
tm().insertAll(getThreatMatchesYesterday());
});
}
@Test
void testDeleteEntriesByDate() {
// Verify that all entries with the date TODAY were removed
jpaTm()
.transact(
tm().transact(
() -> {
Spec11ThreatMatchDao.deleteEntriesByDate(jpaTm(), TODAY);
Spec11ThreatMatchDao.deleteEntriesByDate(tm(), TODAY);
ImmutableList<Spec11ThreatMatch> persistedToday =
Spec11ThreatMatchDao.loadEntriesByDate(jpaTm(), TODAY);
Spec11ThreatMatchDao.loadEntriesByDate(tm(), TODAY);
assertThat(persistedToday).isEmpty();
});
// Verify that all other entries were not removed
jpaTm()
.transact(
tm().transact(
() -> {
ImmutableList<Spec11ThreatMatch> persistedYesterday =
Spec11ThreatMatchDao.loadEntriesByDate(jpaTm(), YESTERDAY);
Spec11ThreatMatchDao.loadEntriesByDate(tm(), YESTERDAY);
assertThat(persistedYesterday)
.comparingElementsUsing(immutableObjectCorrespondence("id"))
.containsExactlyElementsIn(getThreatMatchesYesterday());
@ -85,11 +82,10 @@ class Spec11ThreatMatchDaoTest extends EntityTestCase {
@Test
void testLoadEntriesByDate() {
jpaTm()
.transact(
tm().transact(
() -> {
ImmutableList<Spec11ThreatMatch> persisted =
Spec11ThreatMatchDao.loadEntriesByDate(jpaTm(), TODAY);
Spec11ThreatMatchDao.loadEntriesByDate(tm(), TODAY);
assertThat(persisted)
.comparingElementsUsing(immutableObjectCorrespondence("id"))

View file

@ -17,7 +17,7 @@ package google.registry.model.tld;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.SqlHelper.getMostRecentRegistryLockByRepoId;
import static google.registry.testing.SqlHelper.getMostRecentUnlockedRegistryLockByRepoId;
import static google.registry.testing.SqlHelper.getMostRecentVerifiedRegistryLockByRepoId;
@ -55,16 +55,14 @@ public final class RegistryLockDaoTest extends EntityTestCase {
RegistryLock lock = createLock();
saveRegistryLock(lock);
fakeClock.advanceOneMilli();
jpaTm()
.transact(
tm().transact(
() -> {
RegistryLock updatedLock =
RegistryLockDao.getByVerificationCode(lock.getVerificationCode()).get();
RegistryLockDao.save(
updatedLock.asBuilder().setLockCompletionTime(fakeClock.nowUtc()).build());
});
jpaTm()
.transact(
tm().transact(
() -> {
RegistryLock fromDatabase =
RegistryLockDao.getByVerificationCode(lock.getVerificationCode()).get();
@ -97,8 +95,7 @@ public final class RegistryLockDaoTest extends EntityTestCase {
fakeClock.advanceOneMilli();
RegistryLock updatedLock = lock.asBuilder().setLockCompletionTime(fakeClock.nowUtc()).build();
saveRegistryLock(updatedLock);
jpaTm()
.transact(
tm().transact(
() -> {
RegistryLock fromDatabase =
RegistryLockDao.getByVerificationCode(lock.getVerificationCode()).get();

View file

@ -17,7 +17,7 @@ package google.registry.model.tld.label;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.newRegistry;
import static google.registry.testing.DatabaseHelper.persistResource;
import static org.joda.money.CurrencyUnit.JPY;
@ -28,7 +28,6 @@ import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.flogger.FluentLogger;
import google.registry.persistence.transaction.TransactionManagerFactory;
import google.registry.testing.AppEngineExtension;
import google.registry.testing.FakeClock;
import google.registry.testing.TestCacheExtension;
@ -88,8 +87,7 @@ public class PremiumListDaoTest {
@Test
void saveNew_worksSuccessfully() {
PremiumListDao.save(testList);
jpaTm()
.transact(
tm().transact(
() -> {
Optional<PremiumList> persistedListOpt = PremiumListDao.getLatestRevision("testname");
assertThat(persistedListOpt).isPresent();
@ -119,8 +117,7 @@ public class PremiumListDaoTest {
BigDecimal.valueOf(30.03)))
.setCreationTimestamp(fakeClock.nowUtc())
.build());
jpaTm()
.transact(
tm().transact(
() -> {
Optional<PremiumList> savedListOpt = PremiumListDao.getLatestRevision("testname");
assertThat(savedListOpt).isPresent();
@ -167,8 +164,7 @@ public class PremiumListDaoTest {
.setLabelsToPrices(TEST_PRICES)
.setCreationTimestamp(fakeClock.nowUtc())
.build());
jpaTm()
.transact(
tm().transact(
() -> {
Optional<PremiumList> persistedList = PremiumListDao.getLatestRevision("list1");
assertThat(persistedList).isPresent();
@ -188,8 +184,7 @@ public class PremiumListDaoTest {
.setLabelsToPrices(TEST_PRICES)
.setCreationTimestamp(fakeClock.nowUtc())
.build());
jpaTm()
.transact(
tm().transact(
() -> {
PremiumList premiumList = PremiumListDao.getLatestRevision("list1").get();
assertThat(premiumList.getLabelsToPrices())
@ -260,8 +255,7 @@ public class PremiumListDaoTest {
PremiumListDao.save(testList);
PremiumList pl = PremiumListDao.getLatestRevision("testname").get();
assertThat(PremiumListDao.premiumListCache.getIfPresent("testname")).hasValue(pl);
TransactionManagerFactory.tm()
.transact(() -> PremiumListDao.save("testname", USD, ImmutableList.of("test,USD 1")));
tm().transact(() -> PremiumListDao.save("testname", USD, ImmutableList.of("test,USD 1")));
assertThat(PremiumListDao.premiumListCache.getIfPresent("testname")).isNull();
}

View file

@ -15,7 +15,7 @@
package google.registry.model.tld.label;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import com.google.common.collect.ImmutableMap;
import google.registry.model.tld.label.ReservedList.ReservedListEntry;
@ -60,12 +60,10 @@ public class ReservedListDaoTest {
@Test
void save_worksSuccessfully() {
ReservedListDao.save(testReservedList);
jpaTm()
.transact(
tm().transact(
() -> {
ReservedList persistedList =
jpaTm()
.query("FROM ReservedList WHERE name = :name", ReservedList.class)
tm().query("FROM ReservedList WHERE name = :name", ReservedList.class)
.setParameter("name", "testlist")
.getSingleResult();
assertThat(persistedList.getReservedListEntries())

View file

@ -15,7 +15,7 @@
package google.registry.model.tmch;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.google.common.collect.ImmutableMap;
@ -110,7 +110,7 @@ public class ClaimsListDaoTest {
ClaimsList claimsList =
ClaimsList.create(fakeClock.nowUtc(), ImmutableMap.of("label1", "key1", "label2", "key2"));
// Bypass the DAO to avoid the cache
jpaTm().transact(() -> jpaTm().insert(claimsList));
tm().transact(() -> tm().insert(claimsList));
ClaimsList fromDatabase = ClaimsListDao.get();
// At first, we haven't loaded any entries
assertThat(fromDatabase.claimKeyCache.getIfPresent("label1")).isNull();

View file

@ -17,7 +17,7 @@ package google.registry.persistence;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb;
import com.google.common.collect.ImmutableSet;
@ -56,27 +56,24 @@ class EntityCallbacksListenerTest {
TestEntity testUpdate = new TestEntity();
TestEntity updated =
jpaTm()
.transact(
tm().transact(
() -> {
TestEntity merged = jpaTm().getEntityManager().merge(testUpdate);
TestEntity merged = tm().getEntityManager().merge(testUpdate);
merged.nonTransientField++;
jpaTm().getEntityManager().flush();
tm().getEntityManager().flush();
return merged;
});
// Note that when we get the merged entity, its @PostLoad callbacks are also invoked
checkAll(updated, 0, 1, 0, 1);
TestEntity testLoad =
jpaTm().transact(() -> jpaTm().loadByKey(VKey.create(TestEntity.class, "id")));
TestEntity testLoad = tm().transact(() -> tm().loadByKey(VKey.create(TestEntity.class, "id")));
checkAll(testLoad, 0, 0, 0, 1);
TestEntity testRemove =
jpaTm()
.transact(
tm().transact(
() -> {
TestEntity removed = jpaTm().loadByKey(VKey.create(TestEntity.class, "id"));
return jpaTm().delete(removed);
TestEntity removed = tm().loadByKey(VKey.create(TestEntity.class, "id"));
return tm().delete(removed);
});
checkAll(testRemove, 0, 0, 1, 1);
}
@ -104,11 +101,10 @@ class EntityCallbacksListenerTest {
void verifyCallbacksNotCalledOnCommit() {
insertInDb(new TestEntity());
TestEntity testLoad =
jpaTm().transact(() -> jpaTm().loadByKey(VKey.create(TestEntity.class, "id")));
TestEntity testLoad = tm().transact(() -> tm().loadByKey(VKey.create(TestEntity.class, "id")));
assertThat(testLoad.entityPreUpdate).isEqualTo(0);
testLoad = jpaTm().transact(() -> jpaTm().loadByKey(VKey.create(TestEntity.class, "id")));
testLoad = tm().transact(() -> tm().loadByKey(VKey.create(TestEntity.class, "id")));
// Verify that post-load happened but pre-update didn't.
assertThat(testLoad.entityPostLoad).isEqualTo(1);

View file

@ -17,7 +17,7 @@ package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.domain.token.AllocationToken.TokenType.SINGLE_USE;
import static google.registry.model.domain.token.AllocationToken.TokenType.UNLIMITED_USE;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb;
import com.google.common.collect.ImmutableList;
@ -52,9 +52,7 @@ public class AllocationTokenListConverterTest {
new TestAllocationTokenVKeyList(tokens);
insertInDb(testAllocationTokenVKeyList);
TestAllocationTokenVKeyList persisted =
jpaTm()
.transact(
() -> jpaTm().getEntityManager().find(TestAllocationTokenVKeyList.class, "id"));
tm().transact(() -> tm().getEntityManager().find(TestAllocationTokenVKeyList.class, "id"));
assertThat(persisted.tokenList).isEqualTo(tokens);
}

View file

@ -18,7 +18,7 @@ import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.domain.token.AllocationToken.TokenStatus.ENDED;
import static google.registry.model.domain.token.AllocationToken.TokenStatus.NOT_STARTED;
import static google.registry.model.domain.token.AllocationToken.TokenStatus.VALID;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
@ -60,11 +60,9 @@ public class AllocationTokenStatusTransitionConverterTest {
new AllocationTokenStatusTransitionConverterTestEntity(timedTransitionProperty);
insertInDb(testEntity);
AllocationTokenStatusTransitionConverterTestEntity persisted =
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
.getEntityManager()
tm().getEntityManager()
.find(AllocationTokenStatusTransitionConverterTestEntity.class, "id"));
assertThat(persisted.timedTransitionProperty).containsExactlyEntriesIn(timedTransitionProperty);
}

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static org.joda.money.CurrencyUnit.USD;
@ -53,7 +53,7 @@ public class BillingCostTransitionConverterTest {
TestEntity testEntity = new TestEntity(timedTransitionProperty);
insertInDb(testEntity);
TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id"));
tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.timedTransitionProperty).containsExactlyEntriesIn(timedTransitionProperty);
}

View file

@ -16,7 +16,7 @@ package google.registry.persistence.converter;
import static com.google.common.base.Charsets.US_ASCII;
import static com.google.common.hash.Funnels.stringFunnel;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb;
import com.google.common.collect.ImmutableSet;
@ -43,7 +43,7 @@ class BloomFilterConverterTest {
TestEntity entity = new TestEntity(bloomFilter);
insertInDb(entity);
TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id"));
tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.bloomFilter).isEqualTo(bloomFilter);
}

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb;
import com.google.common.collect.ImmutableList;
@ -48,7 +48,7 @@ public class CidrAddressBlockListConverterTest {
TestEntity testEntity = new TestEntity(addresses);
insertInDb(testEntity);
TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id"));
tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.addresses).isEqualTo(addresses);
}

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb;
import com.google.common.collect.ImmutableMap;
@ -45,7 +45,7 @@ public class CurrencyToBillingConverterTest {
TestEntity testEntity = new TestEntity(currencyToBilling);
insertInDb(testEntity);
TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id"));
tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.currencyToBilling).containsExactlyEntriesIn(currencyToBilling);
}

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb;
import static org.junit.jupiter.api.Assertions.assertThrows;
@ -41,27 +41,23 @@ public class CurrencyUnitConverterTest {
TestEntity entity = new TestEntity(CurrencyUnit.EUR);
insertInDb(entity);
assertThat(
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
.getEntityManager()
tm().getEntityManager()
.createNativeQuery(
"SELECT currency FROM \"TestEntity\" WHERE name = 'id'")
.getResultList()))
.containsExactly("EUR");
TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id"));
tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.currency).isEqualTo(CurrencyUnit.EUR);
}
@Test
void invalidCurrency() {
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
.getEntityManager()
tm().getEntityManager()
.createNativeQuery(
"INSERT INTO \"TestEntity\" (name, currency) VALUES('id', 'XXXX')")
.executeUpdate());
@ -69,9 +65,7 @@ public class CurrencyUnitConverterTest {
assertThrows(
PersistenceException.class,
() ->
jpaTm()
.transact(
() -> jpaTm().getEntityManager().find(TestEntity.class, "id").currency));
tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id").currency));
assertThat(thrown).hasCauseThat().hasMessageThat().isEqualTo("Unknown currency 'XXXX'");
}

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
@ -63,11 +63,9 @@ public class DatabaseMigrationScheduleTransitionConverterTest {
new DatabaseMigrationScheduleTransitionConverterTestEntity(timedTransitionProperty);
insertInDb(testEntity);
DatabaseMigrationScheduleTransitionConverterTestEntity persisted =
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
.getEntityManager()
tm().getEntityManager()
.find(DatabaseMigrationScheduleTransitionConverterTestEntity.class, "id"));
assertThat(persisted.timedTransitionProperty).containsExactlyEntriesIn(timedTransitionProperty);
}

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb;
import google.registry.model.ImmutableObject;
@ -72,9 +72,7 @@ public class DateTimeConverterTest {
TestEntity entity = new TestEntity("normalized_utc_time", dt);
insertInDb(entity);
TestEntity retrievedEntity =
jpaTm()
.transact(
() -> jpaTm().getEntityManager().find(TestEntity.class, "normalized_utc_time"));
tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "normalized_utc_time"));
assertThat(retrievedEntity.dt.toString()).isEqualTo("2019-09-01T01:01:01.000Z");
}
@ -85,7 +83,7 @@ public class DateTimeConverterTest {
insertInDb(entity);
TestEntity retrievedEntity =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "new_york_time"));
tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "new_york_time"));
assertThat(retrievedEntity.dt.toString()).isEqualTo("2019-09-01T06:01:01.000Z");
}

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb;
import google.registry.model.ImmutableObject;
@ -82,7 +82,7 @@ public class DurationConverterTest {
DurationTestEntity entity = new DurationTestEntity(duration);
insertInDb(entity);
DurationTestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(DurationTestEntity.class, "id"));
tm().transact(() -> tm().getEntityManager().find(DurationTestEntity.class, "id"));
assertThat(persisted.duration.getMillis()).isEqualTo(duration.getMillis());
}

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb;
import com.google.common.collect.ImmutableSet;
@ -65,8 +65,7 @@ public class InetAddressSetConverterTest {
InetAddressSetTestEntity testEntity = new InetAddressSetTestEntity(inetAddresses);
insertInDb(testEntity);
InetAddressSetTestEntity persisted =
jpaTm()
.transact(() -> jpaTm().loadByKey(VKey.create(InetAddressSetTestEntity.class, "id")));
tm().transact(() -> tm().loadByKey(VKey.create(InetAddressSetTestEntity.class, "id")));
assertThat(persisted.addresses).isEqualTo(inetAddresses);
}

View file

@ -14,7 +14,7 @@
package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb;
import static org.junit.jupiter.api.Assertions.assertThrows;
@ -60,11 +60,9 @@ public class JodaMoneyConverterTest {
TestEntity entity = new TestEntity(money);
insertInDb(entity);
List<?> result =
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
.getEntityManager()
tm().getEntityManager()
.createNativeQuery(
"SELECT amount, currency FROM \"TestEntity\" WHERE name = 'id'")
.getResultList());
@ -75,7 +73,7 @@ public class JodaMoneyConverterTest {
.containsExactly(BigDecimal.valueOf(100.12).setScale(2), "USD")
.inOrder();
TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id"));
tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.money).isEqualTo(money);
}
@ -86,11 +84,9 @@ public class JodaMoneyConverterTest {
TestEntity entity = new TestEntity(money);
insertInDb(entity);
List<?> result =
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
.getEntityManager()
tm().getEntityManager()
.createNativeQuery(
"SELECT amount, currency FROM \"TestEntity\" WHERE name = 'id'")
.getResultList());
@ -102,11 +98,9 @@ public class JodaMoneyConverterTest {
.inOrder();
result =
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
.getEntityManager()
tm().getEntityManager()
.createQuery("SELECT money FROM TestEntity WHERE name" + " = 'id'")
.getResultList());
@ -114,7 +108,7 @@ public class JodaMoneyConverterTest {
assertThat(result.get(0)).isEqualTo(money);
TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id"));
tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.money).isEqualTo(money);
}
@ -130,11 +124,9 @@ public class JodaMoneyConverterTest {
ComplexTestEntity entity = new ComplexTestEntity(moneyMap, myMoney, yourMoney);
insertInDb(entity);
List<?> result =
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
.getEntityManager()
tm().getEntityManager()
.createNativeQuery(
"SELECT my_amount, my_currency, your_amount, your_currency FROM"
+ " \"ComplexTestEntity\" WHERE name = 'id'")
@ -145,17 +137,15 @@ public class JodaMoneyConverterTest {
BigDecimal.valueOf(100).setScale(2), "USD", BigDecimal.valueOf(80).setScale(2), "GBP")
.inOrder();
result =
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
.getEntityManager()
tm().getEntityManager()
.createNativeQuery(
"SELECT map_amount, map_currency FROM \"MoneyMap\""
+ " WHERE entity_name = 'id' AND map_key = 'dos'")
.getResultList());
ComplexTestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(ComplexTestEntity.class, "id"));
tm().transact(() -> tm().getEntityManager().find(ComplexTestEntity.class, "id"));
assertThat(result).hasSize(1);
assertThat(Arrays.asList((Object[]) result.get(0)))
@ -173,32 +163,26 @@ public class JodaMoneyConverterTest {
*/
@Test
void testNullSafeGet_nullAmountNullCurrency_returnsNull() throws SQLException {
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
.getEntityManager()
tm().getEntityManager()
.createNativeQuery(
"INSERT INTO \"TestEntity\" (name, amount, currency) VALUES('id', null,"
+ " null)")
.executeUpdate());
List<?> result =
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
.getEntityManager()
tm().getEntityManager()
.createNativeQuery(
"SELECT amount, currency FROM \"TestEntity\" WHERE name = 'id'")
.getResultList());
assertThat(result).hasSize(1);
assertThat(Arrays.asList((Object[]) result.get(0))).containsExactly(null, null).inOrder();
assertThat(
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
.getEntityManager()
tm().getEntityManager()
.createQuery("SELECT money FROM TestEntity WHERE name = 'id'")
.getResultList())
.get(0))
@ -207,21 +191,17 @@ public class JodaMoneyConverterTest {
@Test
void testNullSafeGet_nullAMountValidCurrency_throwsHibernateException() throws SQLException {
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
.getEntityManager()
tm().getEntityManager()
.createNativeQuery(
"INSERT INTO \"TestEntity\" (name, amount, currency) VALUES('id', null,"
+ " 'USD')")
.executeUpdate());
List<?> result =
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
.getEntityManager()
tm().getEntityManager()
.createNativeQuery(
"SELECT amount, currency FROM \"TestEntity\" WHERE name = 'id'")
.getResultList());
@ -232,11 +212,9 @@ public class JodaMoneyConverterTest {
assertThrows(
PersistenceException.class,
() ->
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
.getEntityManager()
tm().getEntityManager()
.createQuery("SELECT money FROM TestEntity WHERE name = 'id'")
.getResultList()));
assertThat(thrown)
@ -249,21 +227,17 @@ public class JodaMoneyConverterTest {
@Test
void testNullSafeGet_nullAMountInValidCurrency_throwsIllegalCurrencyException()
throws SQLException {
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
.getEntityManager()
tm().getEntityManager()
.createNativeQuery(
"INSERT INTO \"TestEntity\" (name, amount, currency) VALUES('id', 100,"
+ " 'INVALIDCURRENCY')")
.executeUpdate());
List<?> result =
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
.getEntityManager()
tm().getEntityManager()
.createNativeQuery(
"SELECT amount, currency FROM \"TestEntity\" WHERE name = 'id'")
.getResultList());
@ -275,11 +249,9 @@ public class JodaMoneyConverterTest {
assertThrows(
IllegalCurrencyException.class,
() ->
jpaTm()
.transact(
tm().transact(
() ->
jpaTm()
.getEntityManager()
tm().getEntityManager()
.createQuery("SELECT money FROM TestEntity WHERE name = 'id'")
.getResultList()));
assertThat(thrown).hasMessageThat().isEqualTo("Unknown currency 'INVALIDCURRENCY'");

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb;
import google.registry.model.ImmutableObject;
@ -55,8 +55,8 @@ public class LocalDateConverterTest {
private LocalDateConverterTestEntity persistAndLoadTestEntity(LocalDate date) {
LocalDateConverterTestEntity entity = new LocalDateConverterTestEntity(date);
insertInDb(entity);
return jpaTm()
.transact(() -> jpaTm().loadByKey(VKey.create(LocalDateConverterTestEntity.class, "id")));
return tm().transact(
() -> tm().loadByKey(VKey.create(LocalDateConverterTestEntity.class, "id")));
}
/** Override entity name to avoid the nested class reference. */

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb;
import com.google.common.collect.ImmutableSet;
@ -43,7 +43,7 @@ public class StatusValueSetConverterTest {
insertInDb(obj);
TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "foo"));
tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "foo"));
assertThat(persisted.data).isEqualTo(enums);
}

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb;
import static org.junit.jupiter.api.Assertions.assertThrows;
@ -43,7 +43,7 @@ public class StringListConverterTest {
TestEntity testEntity = new TestEntity(tlds);
insertInDb(testEntity);
TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id"));
tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.tlds).containsExactly("app", "dev", "how");
}
@ -53,11 +53,10 @@ public class StringListConverterTest {
TestEntity testEntity = new TestEntity(tlds);
insertInDb(testEntity);
TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id"));
tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
persisted.tlds = ImmutableList.of("com", "gov");
jpaTm().transact(() -> jpaTm().getEntityManager().merge(persisted));
TestEntity updated =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id"));
tm().transact(() -> tm().getEntityManager().merge(persisted));
TestEntity updated = tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(updated.tlds).containsExactly("com", "gov");
}
@ -66,7 +65,7 @@ public class StringListConverterTest {
TestEntity testEntity = new TestEntity(null);
insertInDb(testEntity);
TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id"));
tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.tlds).isNull();
}
@ -75,7 +74,7 @@ public class StringListConverterTest {
TestEntity testEntity = new TestEntity(ImmutableList.of());
insertInDb(testEntity);
TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id"));
tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.tlds).isEmpty();
}
@ -107,13 +106,11 @@ public class StringListConverterTest {
}
private static Object getSingleResultFromNativeQuery(String sql) {
return jpaTm()
.transact(() -> jpaTm().getEntityManager().createNativeQuery(sql).getSingleResult());
return tm().transact(() -> tm().getEntityManager().createNativeQuery(sql).getSingleResult());
}
private static Object executeNativeQuery(String sql) {
return jpaTm()
.transact(() -> jpaTm().getEntityManager().createNativeQuery(sql).executeUpdate());
return tm().transact(() -> tm().getEntityManager().createNativeQuery(sql).executeUpdate());
}
@Entity(name = "TestEntity") // Override entity name to avoid the nested class reference.

View file

@ -15,7 +15,7 @@
package google.registry.persistence.converter;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.testing.DatabaseHelper.insertInDb;
import static org.junit.jupiter.api.Assertions.assertThrows;
@ -51,7 +51,7 @@ public class StringMapConverterBaseTest {
TestEntity testEntity = new TestEntity(MAP);
insertInDb(testEntity);
TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id"));
tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.map).containsExactlyEntriesIn(MAP);
}
@ -60,12 +60,11 @@ public class StringMapConverterBaseTest {
TestEntity testEntity = new TestEntity(MAP);
insertInDb(testEntity);
TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id"));
tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.map).containsExactlyEntriesIn(MAP);
persisted.map = ImmutableMap.of(new Key("key4"), new Value("value4"));
jpaTm().transact(() -> jpaTm().getEntityManager().merge(persisted));
TestEntity updated =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id"));
tm().transact(() -> tm().getEntityManager().merge(persisted));
TestEntity updated = tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(updated.map).containsExactly(new Key("key4"), new Value("value4"));
}
@ -74,7 +73,7 @@ public class StringMapConverterBaseTest {
TestEntity testEntity = new TestEntity(null);
insertInDb(testEntity);
TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id"));
tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.map).isNull();
}
@ -83,7 +82,7 @@ public class StringMapConverterBaseTest {
TestEntity testEntity = new TestEntity(ImmutableMap.of());
insertInDb(testEntity);
TestEntity persisted =
jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id"));
tm().transact(() -> tm().getEntityManager().find(TestEntity.class, "id"));
assertThat(persisted.map).isEmpty();
}
@ -117,13 +116,11 @@ public class StringMapConverterBaseTest {
}
private static Object getSingleResultFromNativeQuery(String sql) {
return jpaTm()
.transact(() -> jpaTm().getEntityManager().createNativeQuery(sql).getSingleResult());
return tm().transact(() -> tm().getEntityManager().createNativeQuery(sql).getSingleResult());
}
private static Object executeNativeQuery(String sql) {
return jpaTm()
.transact(() -> jpaTm().getEntityManager().createNativeQuery(sql).executeUpdate());
return tm().transact(() -> tm().getEntityManager().createNativeQuery(sql).executeUpdate());
}
private static class Key extends ImmutableObject {

Some files were not shown because too many files have changed in this diff Show more