db.sql.api.impl.cmd.executor.DbSelectorCall Maven / Gradle / Ivy
package db.sql.api.impl.cmd.executor;
import db.sql.api.DbType;
import db.sql.api.impl.tookit.Objects;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
public class DbSelectorCall implements SelectorCall {
private final Map consumers = new HashMap<>();
private Callable otherwise;
@Override
public DbSelectorCall when(DbType dbType, Callable runnable) {
consumers.put(dbType, runnable);
return this;
}
@Override
public DbSelectorCall when(DbType[] dbTypes, Callable runnable) {
for (DbType dbType : dbTypes) {
consumers.put(dbType, runnable);
}
return this;
}
@Override
public DbSelectorCall otherwise(Callable runnable) {
if (Objects.nonNull(this.otherwise)) {
throw new RuntimeException("The method of 'otherwise' has already called");
}
this.otherwise = runnable;
return this;
}
@Override
public DbSelectorCall otherwise() {
return this.otherwise(() -> {
return null;
});
}
private R execute(Callable callable) {
try {
return callable.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public R dbExecute(DbType dbType) {
Callable runnable = consumers.get(dbType);
if (Objects.nonNull(runnable)) {
return this.execute(runnable);
}
if (Objects.nonNull(this.otherwise)) {
return this.execute(this.otherwise);
}
throw new RuntimeException("Not adapted to DbType " + dbType);
}
}