package org.jdbi.v3.core.statement;
import java.io.Closeable;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import org.jdbi.v3.core.Handle;
import org.jdbi.v3.core.config.ConfigRegistry;
import org.jdbi.v3.core.config.Configurable;
import org.jdbi.v3.core.generic.GenericTypes;
abstract class BaseStatement<This> implements Closeable, Configurable<This> {
@SuppressWarnings("unchecked")
final This typedThis = (This) this;
private final Handle handle;
private final StatementContext ctx;
private final Collection<StatementCustomizer> customizers = new ArrayList<>();
BaseStatement(Handle handle) {
this.handle = handle;
this.ctx = new StatementContext(handle.getConfig().createCopy(), handle.getExtensionMethod());
if (GenericTypes.findGenericParameter(getClass(), BaseStatement.class)
.map(GenericTypes::getErasedType)
.map(type -> !type.isAssignableFrom(getClass()))
.orElse(false)) {
throw new IllegalStateException("inconsistent SqlStatement hierarchy");
}
}
public Handle getHandle() {
return handle;
}
@Override
public ConfigRegistry getConfig() {
return ctx.getConfig();
}
public final StatementContext getContext() {
return ctx;
}
This addCleanable(Cleanable cleanable) {
getContext().addCleanable(cleanable);
return typedThis;
}
void addCustomizers(final Collection<StatementCustomizer> customizers) {
this.customizers.addAll(customizers);
}
public final This addCustomizer(final StatementCustomizer customizer) {
this.customizers.add(customizer);
return typedThis;
}
final void beforeBinding(final PreparedStatement stmt) {
for (StatementCustomizer customizer : customizers) {
try {
customizer.beforeBinding(stmt, ctx);
} catch (SQLException e) {
throw new UnableToExecuteStatementException("Exception thrown in statement customization", e, ctx);
}
}
}
final void beforeExecution(final PreparedStatement stmt) {
for (StatementCustomizer customizer : customizers) {
try {
customizer.beforeExecution(stmt, ctx);
} catch (SQLException e) {
throw new UnableToExecuteStatementException("Exception thrown in statement customization", e, ctx);
}
}
}
final void afterExecution(final PreparedStatement stmt) {
for (StatementCustomizer customizer : customizers) {
try {
customizer.afterExecution(stmt, ctx);
} catch (SQLException e) {
throw new UnableToExecuteStatementException("Exception thrown in statement customization", e, ctx);
}
}
}
@Override
public void close() {
getContext().close();
}
}