package com.ankurm.nplusone; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import net.ttddyy.dsproxy.QueryCount; import net.ttddyy.dsproxy.QueryCountHolder; import net.ttddyy.dsproxy.QueryInfo; import net.ttddyy.dsproxy.listener.QueryExecutionListener; import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder; import org.opentest4j.AssertionFailedError; /** * Counts every statement that reaches the JDBC driver, whoever sent it. * *
{@link #wrap(DataSource)} puts datasource-proxy between Hibernate and the real DataSource.
* datasource-proxy keeps per-type counters (select / insert / update / delete) in
* {@link QueryCountHolder}; a small listener additionally remembers the SQL text so a failed
* assertion can print the statements that broke the budget. Counters are per thread: the code
* under test and the assertion must run on the same thread.
*/
public final class QueryGuard {
static final String DATASOURCE_NAME = "guarded";
private static final ThreadLocal> SQL = ThreadLocal.withInitial(ArrayList::new);
private QueryGuard() {
}
/** Wraps a DataSource so every statement is counted and recorded. */
public static DataSource wrap(DataSource real) {
return ProxyDataSourceBuilder.create(real)
.name(DATASOURCE_NAME)
.countQuery()
.listener(new QueryExecutionListener() {
@Override
public void beforeQuery(net.ttddyy.dsproxy.ExecutionInfo execInfo, List