实体类:
@Data
public class SqlFlowEntity {
/*
表名称
*/
private String tableName;
/*
表操作类型
*/
private String type;
/*
涉及字段
*/
private List<String> columnList;
}
核心代码:
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 com.alibaba.druid.util.JdbcConstants;
import com.alibaba.fastjson.JSON;
import java.util.*;
public class test {
public static void main(String args[]) {
String sql = "select name from student union select name from employees;";
List<SQLStatement> sqlStatements = SQLUtils.parseStatements(sql.toLowerCase(), JdbcConstants.HIVE);
List<SqlFlowEntity> sqlFlowEntityList = new ArrayList<>();
for (SQLStatement sqlStatement : sqlStatements) {
SchemaStatVisitor schemaStatVisitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.HIVE);
sqlStatement.accept(schemaStatVisitor);
Map<TableStat.Name, TableStat> tables = schemaStatVisitor.getTables();
Collection<TableStat.Column> columns = schemaStatVisitor.getColumns();
if (Objects.nonNull(tables)) {
tables.forEach(((name, tableStat) -> {
SqlFlowEntity sqlFlowEntity = new SqlFlowEntity();
sqlFlowEntity.setTableName(name.toString());
sqlFlowEntity.setType(tableStat.toString());
List<String> columnList = new ArrayList<>();
if (tableStat.getCreateCount() > 0 || tableStat.getInsertCount() > 0) {
columns.stream().filter(column -> Objects.equals(column.getTable().toLowerCase(), name.getName().toLowerCase())).forEach(column -> {
columnList.add(column.getName().toLowerCase());
});
} else if (tableStat.getSelectCount() > 0) {
columns.stream().filter(column -> Objects.equals(column.getTable().toLowerCase(), name.getName().toLowerCase())).forEach(column -> {
columnList.add(column.getName().toLowerCase());
});
}
sqlFlowEntity.setColumnList(columnList);
sqlFlowEntityList.add(sqlFlowEntity);
}));
}
System.out.println(JSON.toJSON(sqlFlowEntityList));
}
}
}
返回的结果集:
[{
"columnList": ["name"],
"type": "select",
"tableName": "student"
}, {
"columnList": ["name"],
"type": "select",
"tableName": "employees"
}]