1. 实现自己的Visitor

1.1 Oracle版本

  1. public static class ExportTableAliasVisitor extends OracleASTVisitorAdapter {
  2. private Map<String, SQLTableSource> aliasMap = new HashMap<String, SQLTableSource>();
  3. public boolean visit(OracleSelectTableReference x) {
  4. String alias = x.getAlias();
  5. aliasMap.put(alias, x);
  6. return true;
  7. }
  8.  
  9. public Map<String, SQLTableSource> getAliasMap() {
  10. return aliasMap;
  11. }
  12. }

1.2 MySql版本

  1. public static class ExportTableAliasVisitor extends MySqlASTVisitorAdapter {
  2. private Map<String, SQLTableSource> aliasMap = new HashMap<String, SQLTableSource>();
  3. public boolean visit(SQLExprTableSource x) {
  4. String alias = x.getAlias();
  5. aliasMap.put(alias, x);
  6. return true;
  7. }
  8.  
  9. public Map<String, SQLTableSource> getAliasMap() {
  10. return aliasMap;
  11. }
  12. }

1.3 POSTGRESQL版本

  1. public static class ExportTableAliasVisitor extends PGASTVisitorAdapter {
  2. private Map<String, SQLTableSource> aliasMap = new HashMap<String, SQLTableSource>();
  3. public boolean visit(SQLExprTableSource x) {
  4. String alias = x.getAlias();
  5. aliasMap.put(alias, x);
  6. return true;
  7. }
  8.  
  9. public Map<String, SQLTableSource> getAliasMap() {
  10. return aliasMap;
  11. }
  12. }

2. 使用Visitor

  1. finnal String dbType = JdbcConstants.ORACLE; // JdbcConstants.MYSQL或者JdbcConstants.POSTGRESQL
  2. String sql = "select * from mytable a where a.id = 3";
  3. List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);
  4.  
  5. ExportTableAliasVisitor visitor = new ExportTableAliasVisitor();
  6. for (SQLStatement stmt : stmtList) {
  7. stmt.accept(visitor);
  8. }
  9.  
  10. SQLTableSource tableSource = visitor.getAliasMap().get("a");
  11. System.out.println(tableSource);