Merge branch 'master' into wip/EntityBeanIntercept-interface

This commit is contained in:
Rob Bygrave committed 2022-05-03 10:45:45 +12:00
commit d1b5400f2c
138 files changed
+1249 -2851

No files matched your search

@@ -23,7 +23,7 @@ import java.util.stream.Stream;
/**
* Service Provider extension to EbeanServer.
*/
public interface SpiEbeanServer extends SpiServer, ExtendedServer, EbeanServer, BeanCollectionLoader {
public interface SpiEbeanServer extends SpiServer, ExtendedServer, BeanCollectionLoader {
/**
* Return true if the L2 cache has been disabled.
@@ -55,7 +55,6 @@ public interface SpiEbeanServer extends SpiServer, ExtendedServer, EbeanServer,
* <p>
* Typically used to identify the origin of queries for AutoTune and object
* graph costing.
* </p>
*/
CallOrigin createCallOrigin();
@@ -391,6 +391,11 @@ public interface SpiQuery<T> extends Query<T>, SpiQueryFetch, TxnProfileEventCod
*/
void incrementAsOfTableCount();
/**
* Increment the counter of tables used in 'As Of' query.
*/
void incrementAsOfTableCount(int asOfTableCount);
/**
* Return the table alias used for the base table.
*/
@@ -312,11 +312,6 @@ public abstract class SpiTransactionProxy implements SpiTransaction {
transaction.flush();
}
@Override
public void flushBatch() throws PersistenceException {
flush();
}
@Override
public Connection connection() {
return transaction.connection();
@@ -13,6 +13,8 @@ import java.io.Serializable;
import java.lang.ref.SoftReference;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
/**
* The default cache implementation.
@@ -43,10 +45,13 @@ public class DefaultServerCache implements ServerCache {
protected final String name;
protected final String shortName;
private final int maxSize;
private final int trimFrequency;
private final int maxIdleSecs;
private final int maxSecsToLive;
protected final int maxSize;
protected final int trimFrequency;
protected final int maxIdleSecs;
protected final int maxSecsToLive;
protected final long trimOnPut;
protected final ReentrantLock lock = new ReentrantLock();
protected final AtomicLong mutationCounter = new AtomicLong();
public DefaultServerCache(DefaultServerCacheConfig config) {
this.name = config.getName();
@@ -56,6 +61,7 @@ public class DefaultServerCache implements ServerCache {
this.maxIdleSecs = config.getMaxIdleSecs();
this.maxSecsToLive = config.getMaxSecsToLive();
this.trimFrequency = config.determineTrimFrequency();
this.trimOnPut = config.determineTrimOnPut();
MetricFactory factory = MetricFactory.get();
String prefix = "l2n.";
@@ -187,6 +193,9 @@ public class DefaultServerCache implements ServerCache {
public void put(Object key, Object value) {
map.put(key, new SoftReference<>(new CacheEntry(key, value)));
putCount.increment();
if (mutationCounter.incrementAndGet() > trimOnPut) {
runEviction();
}
}
/**
@@ -222,62 +231,72 @@ public class DefaultServerCache implements ServerCache {
* Run the eviction based on Idle time, Time to live and LRU last access.
*/
public void runEviction() {
long trimForMaxSize;
if (maxSize == 0) {
trimForMaxSize = 0;
} else {
trimForMaxSize = size() - maxSize;
}
if (maxIdleSecs == 0 && maxSecsToLive == 0 && trimForMaxSize < 0) {
// nothing to trim on this cache
return;
}
long startNanos = System.nanoTime();
long trimmedByIdle = 0;
long trimmedByGC = 0;
long trimmedByTTL = 0;
long trimmedByLRU = 0;
List<CacheEntry> activeList = new ArrayList<>(map.size());
long idleExpireNano = startNanos - TimeUnit.SECONDS.toNanos(maxIdleSecs);
long ttlExpireNano = startNanos - TimeUnit.SECONDS.toNanos(maxSecsToLive);
Iterator<SoftReference<CacheEntry>> it = map.values().iterator();
while (it.hasNext()) {
SoftReference<CacheEntry> ref = it.next();
final CacheEntry cacheEntry = ref.get();
if (cacheEntry == null) {
it.remove();
trimmedByGC++;
} else if (maxIdleSecs > 0 && idleExpireNano > cacheEntry.getLastAccessTime()) {
it.remove();
trimmedByIdle++;
} else if (maxSecsToLive > 0 && ttlExpireNano > cacheEntry.getCreateTime()) {
it.remove();
trimmedByTTL++;
} else if (trimForMaxSize > 0) {
activeList.add(cacheEntry);
lock.lock();
try {
long trimForMaxSize;
if (maxSize == 0) {
trimForMaxSize = 0;
} else {
trimForMaxSize = size() - maxSize;
}
}
if (trimForMaxSize > 0 && activeList.size() > maxSize) {
// sort into last access time ascending
activeList.sort(BY_LAST_ACCESS);
int trimSize = getTrimSize();
for (int i = trimSize; i < activeList.size(); i++) {
// remove if still in the cache
if (map.remove(activeList.get(i).getKey()) != null) {
trimmedByLRU++;
if (maxIdleSecs == 0 && maxSecsToLive == 0 && trimForMaxSize < 0) {
// nothing to trim on this cache
mutationCounter.set(0);
return;
}
long startNanos = System.nanoTime();
long trimmedByIdle = 0;
long trimmedByGC = 0;
long trimmedByTTL = 0;
long trimmedByLRU = 0;
try {
List<CacheEntry> activeList = new ArrayList<>(map.size());
long idleExpireNano = startNanos - TimeUnit.SECONDS.toNanos(maxIdleSecs);
long ttlExpireNano = startNanos - TimeUnit.SECONDS.toNanos(maxSecsToLive);
Iterator<SoftReference<CacheEntry>> it = map.values().iterator();
while (it.hasNext()) {
SoftReference<CacheEntry> ref = it.next();
final CacheEntry cacheEntry = ref.get();
if (cacheEntry == null) {
it.remove();
trimmedByGC++;
} else if (maxIdleSecs > 0 && idleExpireNano > cacheEntry.getLastAccessTime()) {
it.remove();
trimmedByIdle++;
} else if (maxSecsToLive > 0 && ttlExpireNano > cacheEntry.getCreateTime()) {
it.remove();
trimmedByTTL++;
} else if (trimForMaxSize > 0) {
activeList.add(cacheEntry.forSort());
}
}
if (trimForMaxSize > 0 && activeList.size() > maxSize) {
// sort into last access time ascending
activeList.sort(BY_LAST_ACCESS);
int trimSize = getTrimSize();
for (int i = trimSize; i < activeList.size(); i++) {
// remove if still in the cache
if (map.remove(activeList.get(i).getKey()) != null) {
trimmedByLRU++;
}
}
}
mutationCounter.set(0);
evictCount.add(trimmedByIdle);
evictCount.add(trimmedByGC);
evictCount.add(trimmedByTTL);
evictCount.add(trimmedByLRU);
if (logger.isTraceEnabled()) {
long exeMicros = TimeUnit.MICROSECONDS.convert(System.nanoTime() - startNanos, TimeUnit.NANOSECONDS);
logger.trace("Executed trim of cache {} in [{}]millis idle[{}] timeToLive[{}] accessTime[{}] gc[{}]",
name, exeMicros, trimmedByIdle, trimmedByTTL, trimmedByLRU, trimmedByGC);
}
} catch (Throwable e) {
logger.warn("Error during trim of DefaultServerCache [" + name + "]. Cache might be bigger than desired.", e);
}
}
evictCount.add(trimmedByIdle);
evictCount.add(trimmedByGC);
evictCount.add(trimmedByTTL);
evictCount.add(trimmedByLRU);
if (logger.isTraceEnabled()) {
long exeMicros = TimeUnit.MICROSECONDS.convert(System.nanoTime() - startNanos, TimeUnit.NANOSECONDS);
logger.trace("Executed trim of cache {} in [{}]millis idle[{}] timeToLive[{}] accessTime[{}] gc[{}]",
name, exeMicros, trimmedByIdle, trimmedByTTL, trimmedByLRU, trimmedByGC);
} finally {
lock.unlock();
}
}
@@ -293,7 +312,7 @@ public class DefaultServerCache implements ServerCache {
}
/**
* Comparator for sorting by last access time.
* Comparator for sorting by last access sort, a copy of last access time that should not mutate during trim processing.
*/
public static final class CompareByLastAccess implements Comparator<CacheEntry>, Serializable {
@@ -301,7 +320,7 @@ public class DefaultServerCache implements ServerCache {
@Override
public int compare(CacheEntry e1, CacheEntry e2) {
return Long.compare(e1.getLastAccessTime(), e2.getLastAccessTime());
return Long.compare(e1.lastAccessSort, e2.lastAccessSort);
}
}
@@ -314,6 +333,7 @@ public class DefaultServerCache implements ServerCache {
private final Object value;
private final long createTime;
private long lastAccessTime;
private long lastAccessSort;
public CacheEntry(Object key, Object value) {
this.key = key;
@@ -322,6 +342,14 @@ public class DefaultServerCache implements ServerCache {
this.lastAccessTime = createTime;
}
/**
* Store a copy of lastAccessTime used for sorting. This value should not change during trim processing.
*/
public CacheEntry forSort() {
this.lastAccessSort = lastAccessTime;
return this;
}
/**
* Return the entry key.
*/
@@ -76,4 +76,14 @@ public final class DefaultServerCacheConfig {
}
return 0;
}
/**
* Determine the number of mutations/puts required to trigger a runEviction() in the foreground.
*/
public long determineTrimOnPut() {
if (maxSize > 0) {
return maxSize / 10;
}
return 1000;
}
}
@@ -1,6 +1,6 @@
package io.ebeaninternal.server.cluster;
import io.ebean.EbeanServer;
import io.ebean.Database;
import io.ebean.config.ContainerConfig;
import io.ebeaninternal.server.transaction.RemoteTransactionEvent;
import org.slf4j.Logger;
@@ -20,7 +20,7 @@ public class ClusterManager implements ServerLookup {
private final ReentrantLock lock = new ReentrantLock();
private final ConcurrentHashMap<String, EbeanServer> serverMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Database> serverMap = new ConcurrentHashMap<>();
private final Object monitor = new Object();
@@ -53,7 +53,7 @@ public class ClusterManager implements ServerLookup {
return factory;
}
public void registerServer(EbeanServer server) {
public void registerServer(Database server) {
lock.lock();
try {
serverMap.put(server.name(), server);
@@ -66,7 +66,7 @@ public class ClusterManager implements ServerLookup {
}
@Override
public EbeanServer getServer(String name) {
public Database getServer(String name) {
lock.lock();
try {
return serverMap.get(name);
@@ -1,14 +1,14 @@
package io.ebeaninternal.server.cluster;
import io.ebean.EbeanServer;
import io.ebean.Database;
/**
* Returns EbeanServer instances for remote message reading.
* Returns Database instances for remote message reading.
*/
public interface ServerLookup {
/**
* Return the EbeanServer instance by name.
*/
EbeanServer getServer(String name);
Database getServer(String name);
}
@@ -1,6 +1,6 @@
package io.ebeaninternal.server.core;
import io.ebean.EbeanServer;
import io.ebean.Database;
import io.ebeaninternal.api.CoreLog;
import io.ebeaninternal.api.SpiEbeanServer;
import io.ebeaninternal.api.SpiTransaction;
@@ -79,7 +79,7 @@ public abstract class BeanRequest {
* Return the server processing the request. Made available for
* BeanController and BeanFinder.
*/
public EbeanServer getEbeanServer() {
public Database database() {
return server;
}
@@ -5,8 +5,6 @@ import io.ebean.config.ContainerConfig;
import io.ebean.config.DatabaseConfig;
import io.ebean.config.DatabaseConfigProvider;
import io.ebean.config.ModuleInfoLoader;
import io.ebean.config.ServerConfig;
import io.ebean.config.ServerConfigProvider;
import io.ebean.config.TenantMode;
import io.ebean.config.UnderscoreNamingConvention;
import io.ebean.config.dbplatform.DatabasePlatform;
@@ -124,15 +122,8 @@ public final class DefaultContainer implements SpiContainer {
private void applyConfigServices(DatabaseConfig config) {
if (config.isDefaultServer()) {
boolean appliedConfig = false;
for (DatabaseConfigProvider configProvider : ServiceLoader.load(DatabaseConfigProvider.class)) {
configProvider.apply(config);
appliedConfig = true;
}
if (!appliedConfig && config instanceof ServerConfig) {
for (ServerConfigProvider configProvider : ServiceLoader.load(ServerConfigProvider.class)) {
configProvider.apply((ServerConfig)config);
}
}
}
if (config.isAutoLoadModuleInfo()) {
@@ -14,7 +14,6 @@ import javax.sql.DataSource;
*/
final class InitDataSource {
private final JndiDataSourceLookup jndiDataSourceFactory = new JndiDataSourceLookup();
private final DatabaseConfig config;
/**
@@ -41,21 +40,9 @@ final class InitDataSource {
* Initialise the "main" read write DataSource from configuration.
*/
private DataSource initDataSource() {
final String jndiName = config.getDataSourceJndiName();
if (jndiName != null) {
return jndiDataSource(jndiName);
}
return createFromConfig(config.getDataSourceConfig(), false);
}
private DataSource jndiDataSource(String jndiName) {
DataSource ds = jndiDataSourceFactory.lookup(jndiName);
if (ds == null) {
throw new PersistenceException("JNDI lookup for DataSource " + jndiName + " returned null.");
}
return ds;
}
/**
* Initialise the "read only" DataSource from configuration.
*/
@@ -1,33 +0,0 @@
package io.ebeaninternal.server.core;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.PersistenceException;
import javax.sql.DataSource;
/**
* Helper to lookup a DataSource from JNDI.
*/
class JndiDataSourceLookup {
/**
* Return the DataSource by JNDI lookup.
* <p>
* If name is null the 'default' dataSource is returned.
* </p>
*/
public DataSource lookup(String jndiName) {
try {
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup(jndiName);
if (ds == null) {
throw new PersistenceException("JNDI DataSource [" + jndiName + "] not found?");
}
return ds;
} catch (NamingException ex) {
throw new PersistenceException(ex);
}
}
}
@@ -91,7 +91,7 @@ public class BootupClasses implements Predicate<Class<?>> {
public void runServerConfigStartup(DatabaseConfig config) {
for (Class<?> cls : serverConfigStartupCandidates) {
try {
ServerConfigStartup newInstance = (ServerConfigStartup) cls.newInstance();
ServerConfigStartup newInstance = (ServerConfigStartup) cls.getDeclaredConstructor().newInstance();
newInstance.onStart(config);
} catch (Exception e) {
// assume that the desired behavior is to fail - add your own try catch if needed
@@ -22,7 +22,7 @@ class BeanDescriptorElementEmbedded<T> extends BeanDescriptorElement<T> {
BeanDescriptorElementEmbedded(BeanDescriptorMap owner, DeployBeanDescriptor<T> deploy, ElementHelp elementHelp) {
super(owner, deploy, elementHelp);
try {
this.prototype = (EntityBean) beanType.newInstance();
this.prototype = (EntityBean) beanType.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new IllegalStateException("Unable to create entity bean prototype for "+beanType);
}
@@ -119,6 +119,11 @@ public interface DbSqlContext {
*/
boolean isIncludeSoftDelete();
/**
* Return the count of history table AS OF predicates added via joins.
*/
int asOfTableCount();
/**
* Return true if the query is a 'asDraft' query.
*/
@@ -259,15 +259,11 @@ public final class DeployInheritInfo implements Comparable<DeployInheritInfo> {
}
@Override
public int compareTo(DeployInheritInfo o) {
if (o == this || o.discriminatorStringValue == null && discriminatorStringValue == null) {
public int compareTo(DeployInheritInfo other) {
if (other == this) {
return 0;
} else if (o.discriminatorStringValue == null) {
return 1;
} else if (discriminatorStringValue == null) {
return -1;
} else {
return discriminatorStringValue.compareTo(o.discriminatorStringValue);
return type.getName().compareTo(other.type.getName());
}
}
@@ -100,22 +100,11 @@ public final class DefaultBackgroundExecutor implements SpiBackgroundExecutor {
return pool.submit(wrap(task));
}
@Override
public void execute(Runnable task) {
submit(logExceptions(task));
}
@Override
public void executePeriodically(Runnable task, long delay, TimeUnit unit) {
schedulePool.scheduleWithFixedDelay(wrap(logExceptions(task)), delay, delay, unit);
}
@Override
public void executePeriodically(Runnable task, long initialDelay, long delay, TimeUnit unit) {
schedulePool.scheduleWithFixedDelay(wrap(logExceptions(task)), initialDelay, delay, unit);
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long initialDelay, long delay, TimeUnit unit) {
return schedulePool.scheduleWithFixedDelay(wrap(logExceptions(task)), initialDelay, delay, unit);
@@ -1,15 +1,15 @@
package io.ebeaninternal.server.persist;
import io.ebean.EbeanServer;
import io.ebean.Database;
import io.ebean.Transaction;
import io.ebean.event.BeanDeleteIdRequest;
import io.ebeaninternal.api.SpiEbeanServer;
final class DeleteIdRequest implements BeanDeleteIdRequest {
private final EbeanServer server;
private final SpiEbeanServer server;
private final Transaction transaction;
private Class<?> beanType;
private final Class<?> beanType;
private Object id;
DeleteIdRequest(SpiEbeanServer server, Transaction transaction, Class<?> beanType, Object id) {
@@ -24,7 +24,7 @@ final class DeleteIdRequest implements BeanDeleteIdRequest {
}
@Override
public EbeanServer getEbeanServer() {
public Database database() {
return server;
}
@@ -18,7 +18,6 @@ import io.ebeaninternal.server.core.SpiOrmQueryRequest;
import io.ebeaninternal.server.deploy.*;
import javax.persistence.PersistenceException;
import java.lang.ref.WeakReference;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@@ -149,8 +148,6 @@ public final class CQuery<T> implements DbReadContext, CancelableQuery, SpiProfi
private final ProfilingListener profilingListener;
private final WeakReference<NodeUsageListener> profilingListenerRef;
private final Boolean readOnly;
private long profileOffset;
@@ -189,7 +186,6 @@ public final class CQuery<T> implements DbReadContext, CancelableQuery, SpiProfi
this.objectGraphNode = query.getParentNode();
this.profilingListener = query.getProfilingListener();
this.autoTuneProfiling = profilingListener != null;
this.profilingListenerRef = autoTuneProfiling ? new WeakReference<>(profilingListener) : null;
// set the generated sql back to the query
// so its available to the user...
query.setGeneratedSql(queryPlan.getSql());
@@ -673,7 +669,7 @@ public final class CQuery<T> implements DbReadContext, CancelableQuery, SpiProfi
@Override
public void profileBean(EntityBeanIntercept ebi, String prefix) {
ObjectGraphNode node = request.loadContext().getObjectGraphNode(prefix);
ebi.setNodeUsageCollector(new NodeUsageCollector(node, profilingListenerRef));
ebi.setNodeUsageCollector(new NodeUsageCollector(node, profilingListener));
}
@Override
@@ -644,9 +644,12 @@ final class CQueryBuilder {
}
private void appendHistoryAsOfPredicate() {
if (query.isAsOfBaseTable() && !historySupport.isStandardsBased()) {
appendAndOrWhere();
sb.append(historySupport.getAsOfPredicate(request.baseTableAlias()));
if (query.isAsOfBaseTable()) {
query.incrementAsOfTableCount();
if (!historySupport.isStandardsBased()){
appendAndOrWhere();
sb.append(historySupport.getAsOfPredicate(request.baseTableAlias()));
}
}
}
@@ -18,45 +18,27 @@ final class DefaultDbSqlContext implements DbSqlContext {
private static final String tableAliasManyPlaceHolder = "${mta}";
private final String columnAliasPrefix;
private final ArrayStack<String> tableAliasStack = new ArrayStack<>();
private final ArrayStack<String> joinStack = new ArrayStack<>();
private final ArrayStack<String> prefixStack = new ArrayStack<>();
private final String fromForUpdate;
private boolean useColumnAlias;
private int columnIndex;
private int asOfTableCount;
private StringBuilder sb = new StringBuilder(STRING_BUILDER_INITIAL_CAPACITY);
/**
* A Set used to make sure formula joins are only added once to a query.
*/
private HashSet<String> formulaJoins;
private HashSet<String> tableJoins;
private final SqlTreeAlias alias;
private String currentPrefix;
private List<BeanProperty> encryptedProps;
private List<SqlTreeJoin> extraJoins;
private final CQueryDraftSupport draftSupport;
private final CQueryHistorySupport historySupport;
private final boolean historyQuery;
/**
* Construct for SELECT clause (with column alias settings).
*/
DefaultDbSqlContext(SqlTreeAlias alias, String columnAliasPrefix, CQueryHistorySupport historySupport,
CQueryDraftSupport draftSupport, String fromForUpdate) {
this.alias = alias;
@@ -116,7 +98,6 @@ final class DefaultDbSqlContext implements DbSqlContext {
if (encryptedProps == null) {
return null;
}
return encryptedProps.toArray(new BeanProperty[0]);
}
@@ -153,6 +134,9 @@ final class DefaultDbSqlContext implements DbSqlContext {
String asOfView = historySupport.getAsOfView(table);
appendTable(table, asOfView);
if (asOfView != null) {
if (historySupport.isStandardsBased()) {
asOfTableCount++;
}
addAsOfOnClause = !historySupport.isStandardsBased();
}
}
@@ -178,6 +162,7 @@ final class DefaultDbSqlContext implements DbSqlContext {
}
if (addAsOfOnClause) {
sb.append(" and ").append(historySupport.getAsOfPredicate(a2));
asOfTableCount++;
}
if (extraWhere != null && !extraWhere.isEmpty()) {
sb.append(" and ");
@@ -195,6 +180,11 @@ final class DefaultDbSqlContext implements DbSqlContext {
}
}
@Override
public int asOfTableCount() {
return asOfTableCount;
}
@Override
public boolean isDraftQuery() {
return draftSupport != null;
@@ -236,7 +226,7 @@ final class DefaultDbSqlContext implements DbSqlContext {
@Override
public void appendFormulaJoin(String sqlFormulaJoin, SqlJoinType joinType, String manyWhere) {
// replace ${ta} place holder with the real table alias...
// replace ${ta} placeholder with the real table alias...
String tableAlias = manyWhere == null ? tableAliasStack.peek() : getTableAliasManyWhere(manyWhere);
String converted = sqlFormulaJoin.replace(tableAliasPlaceHolder, tableAlias);
if (formulaJoins == null) {
@@ -250,9 +240,9 @@ final class DefaultDbSqlContext implements DbSqlContext {
formulaJoins.add(converted);
sb.append(" ");
if (joinType == SqlJoinType.OUTER) {
if ("join".equals(sqlFormulaJoin.substring(0, 4).toLowerCase())) {
if ("join".equalsIgnoreCase(sqlFormulaJoin.substring(0, 4))) {
// prepend left as we are in the 'many' part
append(" left ");
sb.append("left ");
}
}
sb.append(converted);
@@ -432,26 +432,11 @@ final class DefaultFetchGroupQuery<T> implements SpiFetchGroupQuery<T>, SpiQuery
throw new RuntimeException("EB102: Only select() and fetch() clause is allowed on FetchGroup");
}
@Override
public Query<T> order(String orderByClause) {
throw new RuntimeException("EB102: Only select() and fetch() clause is allowed on FetchGroup");
}
@Override
public OrderBy<T> order() {
throw new RuntimeException("EB102: Only select() and fetch() clause is allowed on FetchGroup");
}
@Override
public OrderBy<T> orderBy() {
throw new RuntimeException("EB102: Only select() and fetch() clause is allowed on FetchGroup");
}
@Override
public Query<T> setOrder(OrderBy<T> orderBy) {
throw new RuntimeException("EB102: Only select() and fetch() clause is allowed on FetchGroup");
}
@Override
public Query<T> setOrderBy(OrderBy<T> orderBy) {
throw new RuntimeException("EB102: Only select() and fetch() clause is allowed on FetchGroup");
@@ -130,6 +130,7 @@ public final class SqlTreeBuilder {
groupBy = buildGroupByClause();
distinctOn = buildDistinctOn();
encryptedProps = ctx.getEncryptedProps();
query.incrementAsOfTableCount(ctx.asOfTableCount());
}
boolean includeJoins = alias != null && alias.isIncludeJoins();
@@ -304,20 +304,7 @@ class SqlTreeNodeBean implements SqlTreeNode {
@Override
public void addAsOfTableAlias(SpiQuery<?> query) {
// if history on this bean type add it's alias
// for each alias we add an effect date predicate
if (desc.isHistorySupport()) {
query.incrementAsOfTableCount();
}
if (lazyLoadParent != null && lazyLoadParent.isManyToManyWithHistory()) {
query.incrementAsOfTableCount();
}
if (intersectionAsOfTableAlias) {
query.incrementAsOfTableCount();
}
for (SqlTreeNode child : children) {
child.addAsOfTableAlias(query);
}
// do nothing for non-root, handled by DbSqlContext for joins
}
@Override
@@ -58,13 +58,6 @@ final class SqlTreeNodeRoot extends SqlTreeNodeBean {
public void addAsOfTableAlias(SpiQuery<?> query) {
if (desc.isHistorySupport()) {
query.setAsOfBaseTable();
query.incrementAsOfTableCount();
}
if (lazyLoadParent != null && lazyLoadParent.isManyToManyWithHistory()) {
query.incrementAsOfTableCount();
}
for (SqlTreeNode aChildren : children) {
aChildren.addAsOfTableAlias(query);
}
}
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,6 @@
package io.ebeaninternal.server.querydefn;
import io.ebean.EbeanServer;
import io.ebean.Database;
import io.ebean.Update;
import io.ebeaninternal.api.BindParams;
import io.ebeaninternal.api.SpiUpdate;
@@ -14,7 +14,7 @@ public final class DefaultOrmUpdate<T> implements SpiUpdate<T>, Serializable {
private static final long serialVersionUID = -8791423602246515438L;
private transient final EbeanServer server;
private transient final Database server;
private final Class<?> beanType;
private final String name;
private String label;
@@ -35,7 +35,7 @@ public final class DefaultOrmUpdate<T> implements SpiUpdate<T>, Serializable {
* Create with a specific server. This means you can use the
* UpdateSql.execute() method.
*/
public DefaultOrmUpdate(Class<?> beanType, EbeanServer server, String baseTable, String updateStatement) {
public DefaultOrmUpdate(Class<?> beanType, Database server, String baseTable, String updateStatement) {
this.beanType = beanType;
this.server = server;
this.baseTable = baseTable;
@@ -378,19 +378,12 @@ final class ImplicitReadOnlyTransaction implements SpiTransaction, TxnProfileEve
/**
* Flush any queued persist requests.
* <p>
* This is general will result in a number of batched PreparedStatements
* executing.
* </p>
* This is general will result in a number of batched PreparedStatements executing.
*/
@Override
public void flush() {
}
@Override
public void flushBatch() {
flush();
}
/**
* Return the persistence context associated with this transaction.
*/
@@ -405,7 +398,6 @@ final class ImplicitReadOnlyTransaction implements SpiTransaction, TxnProfileEve
* This could be considered similar to EJB3 Extended PersistanceContext. In
* that you get the PersistanceContext from a transaction, hold onto it, and
* then set it back later to a second transaction.
* </p>
*/
@Override
public void setPersistenceContext(SpiPersistenceContext context) {
@@ -503,7 +495,6 @@ final class ImplicitReadOnlyTransaction implements SpiTransaction, TxnProfileEve
* <p>
* This leaves the transaction active and expects another commit
* to occur later (which closes the underlying connection etc).
* </p>
*/
@Override
public void commitAndContinue() {
@@ -758,11 +758,6 @@ class JdbcTransaction implements SpiTransaction, TxnProfileEventCodes {
internalBatchFlush();
}
@Override
public final void flushBatch() {
flush();
}
/**
* Flush the JDBC batch and execute derived relationship statements if necessary.
*/
@@ -27,7 +27,7 @@ public final class JtaTransactionManager implements ExternalTransactionManager {
private TransactionScopeManager scope;
/**
* Instantiates a new spring aware transaction scope manager.
* Instantiates a new JTA transaction manager.
*/
public JtaTransactionManager() {
}
@@ -37,10 +37,8 @@ public final class JtaTransactionManager implements ExternalTransactionManager {
*/
@Override
public void setTransactionManager(Object txnMgr) {
// RB: At this stage not exposing TransactionManager to
// the public API and hence the Object type and casting here
this.transactionManager = (TransactionManager) txnMgr;
this.scope = transactionManager.scope();
}
@@ -72,16 +70,13 @@ public final class JtaTransactionManager implements ExternalTransactionManager {
}
/**
* Looks for a current Spring managed transaction and wraps/returns that as a Ebean transaction.
* Looks for a current JTA managed transaction and wraps/returns that as an Ebean transaction.
* <p>
* Returns null if there is no current spring transaction (lazy loading outside a spring txn etc).
* </p>
*/
@Override
public Object getCurrentTransaction() {
TransactionSynchronizationRegistry syncRegistry = getSyncRegistry();
SpiTransaction t = (SpiTransaction) syncRegistry.getResource(EBEAN_TXN_RESOURCE);
if (t != null) {
// we have already seen this transaction
@@ -122,14 +117,10 @@ public final class JtaTransactionManager implements ExternalTransactionManager {
return newTrans;
}
/**
* Create a listener to register with JTA to enable Ebean to be
* notified when transactions commit and rollback.
* Create a listener to register with JTA to enable Ebean to be notified when transactions commit and rollback.
* <p>
* This is used by Ebean to notify it's appropriate listeners and maintain it's server
* cache etc.
* </p>
* This is used by Ebean to notify its appropriate listeners and maintain its server cache etc.
*/
private JtaTxnListener createJtaTxnListener(SpiTransaction t) {
return new JtaTxnListener(transactionManager, t);
@@ -169,7 +160,6 @@ public final class JtaTransactionManager implements ExternalTransactionManager {
* <p>
* When Ebean is notified (of the commit/rollback) it can then manage its
* cache, notify BeanPersistListeners etc.
* </p>
*/
private static class JtaTxnListener implements Synchronization {
@@ -283,10 +283,6 @@ final class NoTransaction implements SpiTransaction {
public void flush() throws PersistenceException {
}
@Override
public void flushBatch() throws PersistenceException {
}
@Override
public Connection connection() {
return null;
@@ -4,7 +4,6 @@ module io.ebean.core {
uses io.ebean.cache.ServerCachePlugin;
uses io.ebean.cache.ServerCacheNotifyPlugin;
uses io.ebean.config.DatabaseConfigProvider;
uses io.ebean.config.ServerConfigProvider;
uses io.ebean.config.ModuleInfoLoader;
uses io.ebean.config.dbplatform.DatabasePlatformProvider;
uses io.ebean.datasource.DataSourceAlertFactory;
@@ -6,8 +6,7 @@ import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DefaultServerCacheConfigTest {
class DefaultServerCacheConfigTest {
private DefaultServerCacheConfig create(int maxSize, int maxIdleSecs, int maxSecsToLive, int trimFreq) {
ServerCacheOptions options = new ServerCacheOptions();
@@ -20,33 +19,45 @@ public class DefaultServerCacheConfigTest {
}
@Test
public void trimFreq_halfIdle() {
void trimFreq_halfIdle() {
assertEquals(create(10000,10,20, 0).determineTrimFrequency(), 4);
}
@Test
public void trimFreq_halfIdle_withRounding() {
void trimFreq_halfIdle_withRounding() {
assertEquals(create(10000,11,20, 0).determineTrimFrequency(), 4);
}
@Test
public void trimFreq_halfTTL() {
void trimFreq_halfTTL() {
assertEquals(create(10000,0,20, 0).determineTrimFrequency(), 9);
}
@Test
public void trimFreq_halfTTL_withRounding() {
void trimFreq_halfTTL_withRounding() {
assertEquals(create(10000,0,21, 0).determineTrimFrequency(), 9);
}
@Test
public void trimFreq_explicit() {
void trimFreq_explicit() {
assertEquals(create(10000,10,20, 42).determineTrimFrequency(), 42);
}
@Test
void trimOnPut_default() {
assertEquals(create(0,0,0, 0).determineTrimOnPut(), 1_000);
}
@Test
void trimOnPut_tenPercent() {
assertEquals(create(10_000,0,0, 0).determineTrimOnPut(), 1_000);
assertEquals(create(9_000,0,0, 0).determineTrimOnPut(), 900);
assertEquals(create(100,0,0, 0).determineTrimOnPut(), 10);
}
@Test
void trimOnPut_roundDown() {
assertEquals(create(9010,0,0, 0).determineTrimOnPut(), 901);
assertEquals(create(9009,0,0, 0).determineTrimOnPut(), 900);
}
}
@@ -10,16 +10,14 @@ import org.junit.jupiter.api.Test;
import java.util.Random;
public class DefaultServerCache_RunEvictionTest {
class DefaultServerCache_RunEvictionTest {
private DefaultServerCache createCache() {
ServerCacheOptions cacheOptions = new ServerCacheOptions();
cacheOptions.setMaxSize(10000);
cacheOptions.setMaxSize(300);
cacheOptions.setMaxIdleSecs(1);
cacheOptions.setMaxSecsToLive(2);
cacheOptions.setTrimFrequency(1);
cacheOptions.setTrimFrequency(5);
ServerCacheConfig con = new ServerCacheConfig(ServerCacheType.BEAN, "foo", "foo", cacheOptions, null, null);
return new DefaultServerCache(new DefaultServerCacheConfig(con));
@@ -35,8 +33,7 @@ public class DefaultServerCache_RunEvictionTest {
@Disabled("test takes long time")
@Test
public void runEvict() throws InterruptedException {
void runEvict() throws InterruptedException {
for (int i = 0; i < 15; i++) {
doStuff();
cache.runEviction();
@@ -47,12 +44,10 @@ public class DefaultServerCache_RunEvictionTest {
}
private void doStuff() {
for (int i = 0; i < 500; i++) {
for (int i = 0; i < 5000; i++) {
String key = "" + random.nextInt(20000);
int mode = random.nextInt(10);
if (mode < 8) {
if (mode < 7) {
cache.get(key);
} else {
cache.put(key, key + "-" + System.currentTimeMillis());
@@ -3,7 +3,7 @@ package io.ebeaninternal.server.core;
import io.ebean.config.DatabaseConfig;
import io.ebean.datasource.DataSourceAlert;
import io.ebean.datasource.DataSourceConfig;
import io.ebean.datasource.pool.ConnectionPool;
import io.ebean.datasource.DataSourcePool;
import org.junit.jupiter.api.Test;
import javax.sql.DataSource;
@@ -137,7 +137,7 @@ public class InitDataSourceTest {
config.getDataSourceConfig().setUrl("jdbc:h2:mem:dsTestOnline");
config.getDataSourceConfig().setDriver("org.h2.Driver");
InitDataSource.init(config);
ConnectionPool pool = (ConnectionPool) config.getDataSource();
DataSourcePool pool = (DataSourcePool) config.getDataSource();
assertThat(pool.isDataSourceUp()).isTrue();
pool.shutdown();
}
@@ -174,7 +174,7 @@ public class InitDataSourceTest {
config.getDataSourceConfig().setAlert(alert);
config.setDatabasePlatformName("h2");
InitDataSource.init(config);
ConnectionPool pool = (ConnectionPool) config.getDataSource();
DataSourcePool pool = (DataSourcePool) config.getDataSource();
assertThat(pool).isNotNull();
// make some additional tests with the pool
assertThat(pool.isDataSourceUp()).isFalse();
@@ -0,0 +1,21 @@
package io.ebeaninternal.server.deploy.parse;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class DeployInheritInfoTest {
@Test
void addChild_when_DiscriminatorValueIsNull() {
DeployInheritInfo root = new DeployInheritInfo(Object.class);
root.addChild(new DeployInheritInfo(Integer.class)); // DiscriminatorValue is null
root.addChild(new DeployInheritInfo(Short.class)); // DiscriminatorValue is null
DeployInheritInfo c2 = new DeployInheritInfo(Long.class);
c2.setDiscriminatorValue("c2");
root.addChild(c2);
assertThat(root.children()).hasSize(3);
}
}
@@ -1,6 +1,6 @@
package io.ebeaninternal.server.expression;
import io.ebean.EbeanServer;
import io.ebean.Database;
import io.ebean.Query;
import io.ebean.Transaction;
import io.ebean.event.BeanQueryRequest;
@@ -62,7 +62,7 @@ public abstract class BaseExpressionTest extends BaseTest {
}
@Override
public EbeanServer getEbeanServer() {
public Database database() {
return null;
}