package com.jay.monitor.data.client.ext;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.postgresql.visitor.PGSchemaStatVisitor;
import com.alibaba.druid.stat.TableStat;

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

/**
 * @author liukaixiong
 * @date 2022/7/13 - 17:26
 */
public class SqlCase {
    public static void main(String[] args) {
        String sql =
            "SELECT id,service_name,business_code,executor_code,executor_description,deleted,status,create_time,update_time,create_by,update_by FROM expression_executor_base_info WHERE (deleted = '0' AND deleted = 'false') and id = 1 ORDER BY create_time DESC";
        List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, "Mysql");
        //解析出的独立语句的个数
        System.out.println("size is:" + stmtList.size());
        for (int i = 0; i < stmtList.size(); i++) {

            SQLStatement stmt = stmtList.get(i);

            PGSchemaStatVisitor visitor = new PGSchemaStatVisitor();
            stmt.accept(visitor);
            Map<TableStat.Name, TableStat> tables = visitor.getTables();
            for (Iterator iterator = tables.keySet().iterator(); iterator.hasNext(); ) {
                TableStat.Name key = (TableStat.Name)iterator.next();
                System.out.println("[ALIAS]" + key + " - " + tables.get(key));
            }
            Set<TableStat.Column> groupby_col = visitor.getGroupByColumns();
            //
            for (Iterator iterator = groupby_col.iterator(); iterator.hasNext(); ) {
                TableStat.Column column = (TableStat.Column)iterator.next();
                System.out.println("[GROUP]" + column.toString());
            }
            //获取表名称
            System.out.println("table names:");
            Map<TableStat.Name, TableStat> tabmap = visitor.getTables();
            for (Iterator iterator = tabmap.keySet().iterator(); iterator.hasNext(); ) {
                TableStat.Name name = (TableStat.Name)iterator.next();
                System.out.println(name.toString() + " - " + tabmap.get(name).toString());
            }
            //System.out.println("Tables : " + visitor.getCurrentTable());
            //获取操作方法名称,依赖于表名称
            System.out.println("Manipulation : " + visitor.getTables());
            //获取字段名称
            System.out.println("fields : " + visitor.getColumns());
        }

    }
}
