package org.jdbi.v3.sqlobject.customizer.internal;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
import org.jdbi.v3.core.statement.Query;
import org.jdbi.v3.sqlobject.customizer.MaxRows;
import org.jdbi.v3.sqlobject.customizer.SqlStatementCustomizer;
import org.jdbi.v3.sqlobject.customizer.SqlStatementCustomizerFactory;
import org.jdbi.v3.sqlobject.customizer.SqlStatementParameterCustomizer;
public class MaxRowsFactory implements SqlStatementCustomizerFactory {
public static final int DEFAULT_MAX_ROWS = -1;
@Override
public SqlStatementCustomizer createForMethod(Annotation annotation, Class<?> sqlObjectType, Method method) {
final int maxRows = ((MaxRows) annotation).value();
if (maxRows == DEFAULT_MAX_ROWS) {
throw new IllegalArgumentException(String.format(
"no value given for @%s on %s:%s",
MaxRows.class.getSimpleName(),
sqlObjectType.getName(),
method.getName())
);
}
if (maxRows <= 0) {
throw new IllegalArgumentException(String.format(
"@%s value given on %s:%s is %s, which is negative or 0. This makes no sense.",
MaxRows.class.getSimpleName(),
sqlObjectType.getName(),
method.getName(),
maxRows)
);
}
return stmt -> ((Query) stmt).setMaxRows(maxRows);
}
@Override
public SqlStatementParameterCustomizer createForParameter(Annotation annotation,
Class<?> sqlObjectType,
Method method,
Parameter param,
int index,
Type type) {
int value = ((MaxRows) annotation).value();
if (value != DEFAULT_MAX_ROWS) {
throw new IllegalArgumentException(String.format(
"You've specified a value for @%s on %s:%s(%s) — this value won't do anything, the parameter value will be used instead. Remove the value to prevent confusion.",
MaxRows.class.getSimpleName(),
sqlObjectType.getName(),
method.getName(),
param.getName())
);
}
return (stmt, arg) -> {
int maxRows = (int) arg;
if (maxRows <= 0) {
throw new IllegalArgumentException(String.format(
"@%s value given on %s:%s(%s) is %s, which is negative or 0. This makes no sense.",
MaxRows.class.getSimpleName(),
sqlObjectType.getName(),
method.getName(),
param.getName(),
maxRows)
);
}
((Query) stmt).setMaxRows(maxRows);
};
}
}