net.java.ao.CachingSqlProcessor Maven / Gradle / Ivy
package net.java.ao;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import net.java.ao.sql.SqlUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import java.util.function.Function;
/**
* This class wraps some of the methods from {@link SqlUtils} with a cache. The rationale for this is as follows:
*
* the regex-based processing of the identifiers done in {@link SqlUtils} is very often more expensive than the call to the database.
* In fact, for simple queries, this is always true. At the same time, the queries are often very similar. Let's cache the results.
*
* @since 3.2.11
*/
public final class CachingSqlProcessor {
/**
* The maximum amount of cached clauses.
*/
private static final long MAXIMUM_CACHED_CLAUSES = Long.parseLong(System.getProperty("net.java.ao.CachingSqlProcessor.MAXIMUM_CACHED_CLAUSES", "100"));
CachingSqlProcessor() {
}
private static final class ClauseAndProcessor extends MutablePair> {
private ClauseAndProcessor(final String clause, final Function processor) {
super(clause, processor);
}
}
@VisibleForTesting
final LoadingCache processedWhereClauses = buildCache(
args -> SqlUtils.processWhereClause(args.getLeft(), args.getRight()::apply)
);
@VisibleForTesting
final LoadingCache processedOnClauses = buildCache(
args -> SqlUtils.processOnClause(args.getLeft(), args.getRight()::apply)
);
public String processWhereClause(final String where, final Function processor) {
return processedWhereClauses.getUnchecked(new ClauseAndProcessor(where, processor));
}
public String processOnClause(final String on, final Function processor) {
return processedOnClauses.getUnchecked(new ClauseAndProcessor(on, processor));
}
private static LoadingCache buildCache(final Function loadingFunction) {
final CacheLoader loader = new CacheLoader() {
@Override
public String load(final ClauseAndProcessor key) {
return loadingFunction.apply(key);
}
};
return CacheBuilder.newBuilder()
.maximumSize(MAXIMUM_CACHED_CLAUSES)
.build(loader);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy