Skip to content

Commit

Permalink
✨feat: 优化日志查询逻辑及添加参数绑定
Browse files Browse the repository at this point in the history
- 优化 LoggersService 中的搜索与分页查询逻辑
- 添加 LoggerRequest 绑定参数 SQL 功能
- 更新 QueryJson 处理空参数情况及优化 JSON 路径构建
  • Loading branch information
vnobo committed Sep 5, 2024
1 parent c89797f commit 52e25e0
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,13 @@ public static Sort sortJson(Sort sort, String prefix) {
}

public static ParamSql queryJson(Map<String, Object> params, String prefix) {
if (ObjectUtils.isEmpty(params)) {
return ParamSql.of(new StringJoiner(" and "), Maps.newHashMap());
}
Map<String, Object> bindParams = Maps.newHashMap();
StringJoiner whereSql = new StringJoiner(" and ");

if (ObjectUtils.isEmpty(params)) {
return ParamSql.of(whereSql, bindParams);
}

for (Map.Entry<String, Object> entry : params.entrySet()) {
String[] keys = StringUtils.delimitedListToStringArray(entry.getKey(), ".");
Map.Entry<String, List<String>> exps = jsonPathKeyAndParamName(keys, prefix);
Expand All @@ -97,41 +99,54 @@ public static ParamSql queryJson(Map<String, Object> params, String prefix) {
}

private static Map.Entry<String, List<String>> jsonPathKeyAndParamName(String[] keys, String prefix) {
if (keys == null || keys.length < 1) {
throw new IllegalArgumentException("Keys array cannot be null or empty.");
}

int lastIndex = keys.length - 1;
String lastKey = keys[lastIndex];
Map.Entry<String, String> exps = findKeyWord(lastKey);
String key = lastKey.substring(0, lastKey.length() - exps.getKey().length());

// 处理第一个键
String column = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, keys[0]);
if (StringUtils.hasLength(prefix)) {
column = prefix + "." + keys[0];
}

// 构建 JSON 路径
StringBuilder jsonPath = new StringBuilder("(" + column);
String[] joinKeys = Arrays.copyOfRange(keys, 1, lastIndex);
jsonPath.append(appendIntermediateKeys(joinKeys));

// 处理中间键
if (lastIndex > 1) {
String[] joinKeys = Arrays.copyOfRange(keys, 1, lastIndex);
jsonPath.append(appendIntermediateKeys(joinKeys));
}

List<String> paramNames = new ArrayList<>();
String paramName = StringUtils.arrayToDelimitedString(keys, "_");
if (!ObjectUtils.isEmpty(exps)) {

Map.Entry<String, String> exps = findKeyWord(lastKey);
if (exps != null && !exps.getKey().isEmpty()) {
String key = lastKey.substring(0, lastKey.length() - exps.getKey().length());
jsonPath.append("->>'").append(key).append("' ");

if ("Between".equals(exps.getKey()) || "NotBetween".equals(exps.getKey())) {
jsonPath.append("->>'").append(key).append("' ");
String startKey = paramName + "_start";
String endKey = paramName + "_end";
jsonPath.append(exps.getValue()).append(" :").append(startKey).append(" and :").append(endKey);
paramNames.add(startKey);
paramNames.add(endKey);
} else {
jsonPath.append("->>'").append(key).append("' ");
jsonPath.append(exps.getValue()).append(" :").append(paramName);
paramNames.add(paramName);
}
} else {
jsonPath.append("=").append(" :").append(paramName);
jsonPath.append("->>'").append(lastKey).append("' ").append("=").append(" :").append(paramName);
paramNames.add(paramName);
}
return Map.entry(jsonPath.append(")").toString(), paramNames);
}


private static StringBuilder appendIntermediateKeys(String[] joinKeys) {
StringBuilder jsonPath = new StringBuilder();
for (String path : joinKeys) {
Expand All @@ -147,6 +162,6 @@ private static Map.Entry<String, String> findKeyWord(String inputStr) {
int entry1Length = entry1.getKey().length();
int entry2Length = entry2.getKey().length();
return Integer.compare(entry1Length, entry2Length);
}).orElse(KEYWORDS.entrySet().iterator().next());
}).orElse(null);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@

import com.fasterxml.jackson.databind.JsonNode;
import com.plate.boot.commons.utils.BeanUtils;
import com.plate.boot.commons.utils.query.CriteriaUtils;
import com.plate.boot.commons.utils.query.ParamSql;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.springframework.data.relational.core.query.Criteria;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
Expand All @@ -18,6 +22,8 @@
@ToString(callSuper = true)
public class LoggerRequest extends Logger {

private Map<String, Object> query;

private String securityCode;

public static LoggerRequest of(String tenantCode, String operator, String prefix, String method,
Expand All @@ -36,10 +42,12 @@ public static LoggerRequest of(String tenantCode, String operator, String prefix
public Logger toLogger() {
return BeanUtils.copyProperties(this, Logger.class);
}

public ParamSql bindParamSql() {
return CriteriaUtils.buildParamSql(this, List.of(), null);
}
public Criteria toCriteria() {

Criteria criteria = criteria(Set.of("securityCode", "context"));
Criteria criteria = criteria(Set.of("securityCode", "context","query"));

if (StringUtils.hasLength(this.getSecurityCode())) {
criteria = criteria.and("tenantCode").is(this.getSecurityCode());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

import com.plate.boot.commons.base.AbstractDatabase;
import com.plate.boot.commons.utils.BeanUtils;
import com.plate.boot.commons.utils.query.CriteriaUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.relational.core.query.Query;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
Expand All @@ -26,20 +26,28 @@ public class LoggersService extends AbstractDatabase {
private final LoggersRepository loggersRepository;

public Flux<Logger> search(LoggerRequest request, Pageable pageable) {
Query query = Query.query(request.toCriteria()).with(pageable);
return this.queryWithCache(BeanUtils.cacheKey(request, pageable), query, Logger.class);
String querySql = "select * from se_loggers";
var paramSql = request.bindParamSql();
var query = this.databaseClient.sql(() -> querySql + paramSql.whereSql() + CriteriaUtils.applyPage(pageable))
.bindValues(paramSql.params())
.map((row, rowMetadata) -> r2dbcConverter.read(Logger.class, row, rowMetadata)).all();
return this.queryWithCache(BeanUtils.cacheKey(request, pageable), query);
}

public Mono<Page<Logger>> page(LoggerRequest request, Pageable pageable) {
var searchMono = this.search(request, pageable).collectList();
var countMono = this.countWithCache(BeanUtils.cacheKey(request),
Query.query(request.toCriteria()), Logger.class);
String querySql = "select count(*) from se_loggers";
var paramSql = request.bindParamSql();
var query = this.databaseClient.sql(() -> querySql + paramSql.whereSql())
.bindValues(paramSql.params()).mapValue(Long.class).one();
var countMono = this.countWithCache(BeanUtils.cacheKey(request), query);
return searchMono.zipWith(countMono)
.map(tuple2 -> new PageImpl<>(tuple2.getT1(), pageable, tuple2.getT2()));
}

/**
* 操作日志记录器请求,将请求转换为日志记录器对象,保存并在完成后清除缓存。
*
* @param request 请求对象,包含创建或更新日志记录器所需的数据。
* @return 一个 Mono<Logger> 对象,代表保存操作的结果。
*/
Expand Down

0 comments on commit 52e25e0

Please sign in to comment.