package com.ediagnosis.cdr.dao.sqlutil; import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.expression.Function; import net.sf.jsqlparser.expression.LongValue; import net.sf.jsqlparser.parser.CCJSqlParserUtil; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.select.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.Optional; public class SqlParser { private static final Logger log = LoggerFactory.getLogger(SqlParser.class); public static Optional getCountSql(String sql) { Optional plainSelectOptional = detectSelectSql(sql); if (plainSelectOptional.isEmpty()) { return Optional.empty(); } PlainSelect plainSelect = plainSelectOptional.get(); List> selectItems = plainSelect.getSelectItems(); selectItems.clear(); selectItems.add(new SelectItem<>( new Function("count", new AllColumns()) ) ); String newSql = plainSelect.toString(); log.info("change to count sql: {}", newSql); return Optional.of(newSql); } public static String addLimitClause(String sql) { String newSql = sql; Optional plainSelectOptional = detectSelectSql(sql); if (plainSelectOptional.isEmpty()) { return newSql; } PlainSelect plainSelect = plainSelectOptional.get(); Limit limit = plainSelect.getLimit(); if (limit == null) { Select select = plainSelect.withLimit( new Limit() .withRowCount(new LongValue(10)) .withOffset(new LongValue(0)) ); newSql = select.toString(); log.info("原始sql没有limit从句,添加limit从句,新sql语句:{}", newSql); } else { log.info("原始sql存在limit从句,不做处理"); } return newSql; } private static Optional detectSelectSql(String sql) { Statement statement = null; try { statement = CCJSqlParserUtil.parse(sql); log.debug("sql语句语法正确"); } catch (JSQLParserException e) { log.error("解析sql失败", e); return Optional.empty(); } if ((statement instanceof PlainSelect plainSelect)) { log.debug("原始sql是select语句"); return Optional.of(plainSelect); } else { log.warn("原始sql不是select语句"); return Optional.empty(); } } }