ParseUtils(SQL解析)

本文介绍了ParseUtils工具类在SQL解析中的应用,并探讨了如何根据需求自定义工具类和SchemaStatVisitor。建议查看GitHub上的API以获取更多详情。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、ParseUtils

package com.example.util;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.visitor.SchemaStatVisitor;
import com.alibaba.druid.stat.TableStat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

import static com.alibaba.druid.util.JdbcConstants.*;

@Slf4j
public abstract class ParseUtil {

    /**
     * sql格式化
     *
     * @param sql    sql语句
     * @param dbType 数据库类型
     */
    public static void format(String sql, String dbType) {
        String sqlFormat = SQLUtils.format(sql, dbType);
        if (sql.equals(sqlFormat)) {
            throw new RuntimeException("SQL格式错误");
        }
    }

    /**
     * 校验结尾是否含有;
     *
     * @param sql sql语句
     */
    public static void checkSymbol(String sql) {
        Arrays.stream(sql.toUpperCase().split("DROP|CREATE|INSERT|UPDATE"))
                .filter(sqlStr -> !StringUtils.isEmpty(sqlStr))
                .filter(sqlStr -> !sqlStr.contains(";"))
                .forEach(sqlStr -> {
                    throw new RuntimeException("SQL缺失;");
                });
    }

    /**
     * sql解析
     *
     * @param sql    sql语句
     * @param dbType 数据库类型
     * @return 解析树
     */
    public static List<SQLStatement> parseStatements(String sql, String dbType) {
        try {
            return SQLUtils.parseStatements(sql, dbType);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("SQL格式错误");
        }
    }

    /**
     * 血缘关系解析
     *
     * @param sqlStatements sql语句
     * @param tableList     关系集合
     * @param dbType        数据库类型
     * @return k(table_target) - v(list<table_source>)
     */
    public static List<Map<String, List<String>>> bloodRelationship(List<SQLStatement> sqlStatements
            , List<Map<String, List<String>>> tableList, String dbType) {

        SchemaStatVisitor visitor;
        for (SQLStatement sqlStatement : sqlStatements) {

            //切入操作
            Map<String, List<String>> tableMap = new HashMap<>();
            visitor = SQLUtils.createSchemaStatVisitor(dbType);
            sqlStatement.accept(visitor);

            //过滤 DML
            visitor.getTables().forEach((key, value) -> {
                if (!"Select".equals(value.toString())) {
                    throw new RuntimeException("禁止进行其他DML操作!");
                }
            });

            //结果集封装
            List<String> tables = visitor.getTables()
                    .keySet()
                    .stream()
                    .map(TableStat.Name::getName)
                    .collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(tables) && tables.size() > 1) {
                tableMap.put(tables.remove(0), tables);
                tableList.add(tableMap);
            }

        }
        return tableList;
    }


    static class OdpsParseUtil extends ParseUtil {

        /**
         * sql 解析(ODPS)
         *
         * @param sql sql语句
         * @return 血缘关系
         */
        public static List<Map<String, List<String>>> parse(String sql) {
            return bloodRelationship(checkSqlFormatByOdps(sql), new ArrayList<>(), ODPS);
        }

        public static List<SQLStatement> checkSqlFormatByOdps(String sql) {
            checkSymbol(sql);
            format(sql, ODPS);
            return parseStatements(sql, ODPS);
        }

    }

    static class HiveParseUtil extends ParseUtil {

        /**
         * sql 解析(HIVE)
         *
         * @param sql sql语句
         * @return 血缘关系
         */
        public static List<Map<String, List<String>>> parse(String sql) {
            return bloodRelationship(checkSqlFormatByHive(sql), new ArrayList<>(), HIVE);
        }

        public static List<SQLStatement> checkSqlFormatByHive(String sql) {
            checkSymbol(sql);
            format(sql, HIVE);
            return parseStatements(sql, HIVE);
        }

    }

    static class MysqlParseUtil extends ParseUtil {

        /**
         * sql 解析(MYSQL)
         *
         * @param sql sql语句
         * @return 血缘关系
         */
        public static List<Map<String, List<String>>> parse(String sql) {
            return bloodRelationship(checkSqlFormatByMysql(sql), new ArrayList<>(), MYSQL);
        }

        public static List<SQLStatement> checkSqlFormatByMysql(String sql) {
            checkSymbol(sql);
            format(sql, MYSQL);
            return parseStatements(sql, MYSQL);
        }

    }
}

2、源码分析

public class SchemaStatVisitor extends SQLASTVisitorAdapter {

    protected SchemaRepository repository;

    //SQL中所有的表
    protected final HashMap<TableStat.Name, TableStat> tableStats     = new LinkedHashMap<TableStat.Name, TableStat>();

    //SQL中所有的列
    protected final Map<Long, Column>                  columns        = new LinkedHashMap<Long, Column>();

    //SQL中条件
    protected final List<Condition>                    conditions     = new ArrayList<Condition>();

    //SQL中关系
    protected final Set<Relationship>                  relationships  = new LinkedHashSet<Relationship>();

    //SQL中排序
    protected final List<Column>                       orderByColumns = new ArrayList<Column>();

    //SQL中分组
    protected final Set<Column>                        groupByColumns = new LinkedHashSet<Column>();

     //SQL中函数
    protected final List<SQLAggregateExpr>             aggregateFunctions = new ArrayList<SQLAggregateExpr>();

    //SQL中方法
    protected final List<SQLMethodInvokeExpr>          functions          = new ArrayList<SQLMethodInvokeExpr>(2);
    ......
}
  • 可以根据自己的功能动态的修改工具类,也可以实现自己的SchemaStatVisitor ,githup的api上有,可以去查看一下
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值