io.github.afezeria.freedao.classic.runtime.SqlHelper Maven / Gradle / Ivy
package io.github.afezeria.freedao.classic.runtime;
import io.github.afezeria.freedao.classic.runtime.context.JoinQueryContext;
import io.github.afezeria.freedao.classic.runtime.context.PageQueryContext;
import io.github.afezeria.freedao.classic.runtime.context.ParameterContext;
import java.lang.annotation.Annotation;
import java.util.*;
import java.util.function.Supplier;
/**
* @author afezeria
*/
public class SqlHelper {
public static T join(Supplier block) {
return join(Collections.emptyList(), block);
}
public static T join(List joinIds, Supplier block) {
JoinQueryContext.localJoinIds.set(joinIds);
try {
T t = block.get();
return t;
} finally {
JoinQueryContext.localJoinIds.remove();
}
}
/**
* 设置临时上下文参数
*/
public static T withContextParameter(String key, Object value, Supplier block) {
ParameterContext.ParameterMap parameterMap =
Objects.requireNonNull(ParameterContext.local.get(), "ParameterContext not initialized");
parameterMap.put(key, value);
try {
return block.get();
} finally {
parameterMap.reset();
}
}
/**
* 设置临时上下文参数
*/
public static T withContextParameters(Map params, Supplier block) {
ParameterContext.ParameterMap parameterMap =
Objects.requireNonNull(ParameterContext.local.get(), "ParameterContext not initialized");
parameterMap.putAll(params);
try {
return block.get();
} finally {
parameterMap.reset();
}
}
/**
* {@link SqlHelper#ds(DS, Supplier)}
*/
public static T ds(String name, Supplier supplier) {
return ds(name, true, supplier);
}
/**
* {@link SqlHelper#ds(DS, Supplier)}
*/
public static T ds(String name, boolean isPrefix, Supplier supplier) {
return ds(new DS() {
@Override
public String value() {
return name;
}
@Override
public boolean prefix() {
return isPrefix;
}
@Override
public Class extends Annotation> annotationType() {
return null;
}
}, supplier);
}
/**
* 切换数据源,暂时只支持spring-boot
*
* @param ds {@link DS}
*/
public static T ds(DS ds, Supplier supplier) {
DS outer = DataSourceContextHolder.get();
if (outer != null) {
if (outer.prefix() == ds.prefix() && Objects.equals(outer.value(), ds.value())) {
return supplier.get();
}
}
try {
DataSourceContextHolder.set(ds);
return supplier.get();
} finally {
DataSourceContextHolder.set(outer);
}
}
public static Page page(int pageIndex, int pageSize, Supplier> closure) {
return page(Page.of(pageIndex, pageSize), closure);
}
@SuppressWarnings("unchecked")
public static Page page(Page> page, Supplier> closure) {
if (PageQueryContext.local.get() != null) {
throw new RuntimeException("paging conditions cannot be set repeatedly");
}
PageQueryContext.local.set(page);
try {
closure.get();
return (Page) page;
} finally {
PageQueryContext.local.remove();
}
}
}