Skip to content

SQL_Parser_Demo_visitor

LiZongbo edited this page Apr 6, 2024 · 6 revisions

1. 实现自己的Visitor

1.1 Oracle版本

public static class ExportTableAliasVisitor extends OracleASTVisitorAdapter {
    private Map<String, SQLTableSource> aliasMap = new HashMap<String, SQLTableSource>();
    public boolean visit(OracleSelectTableReference x) {
        String alias = x.getAlias();
        aliasMap.put(alias, x);
        return true;
    }

    public Map<String, SQLTableSource> getAliasMap() {
        return aliasMap;
    }
}

1.2 MySql版本

public static class ExportTableAliasVisitor extends MySqlASTVisitorAdapter {
    private Map<String, SQLTableSource> aliasMap = new HashMap<String, SQLTableSource>();
    public boolean visit(SQLExprTableSource x) {
        String alias = x.getAlias();
        aliasMap.put(alias, x);
        return true;
    }

    public Map<String, SQLTableSource> getAliasMap() {
        return aliasMap;
    }
}

1.3 POSTGRESQL版本

public static class ExportTableAliasVisitor extends PGASTVisitorAdapter {
    private Map<String, SQLTableSource> aliasMap = new HashMap<String, SQLTableSource>();
    public boolean visit(SQLExprTableSource x) {
        String alias = x.getAlias();
        aliasMap.put(alias, x);
        return true;
    }

    public Map<String, SQLTableSource> getAliasMap() {
        return aliasMap;
    }
}

2. 使用Visitor

final String dbType = JdbcConstants.ORACLE; // JdbcConstants.MYSQL或者JdbcConstants.POSTGRESQL
String sql = "select * from mytable a where a.id = 3";
List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);

ExportTableAliasVisitor visitor = new ExportTableAliasVisitor();
for (SQLStatement stmt : stmtList) {
    stmt.accept(visitor);
}

SQLTableSource tableSource = visitor.getAliasMap().get("a");
System.out.println(tableSource);
Clone this wiki locally