One need a parser to only change table references from the "from" part. Some databases do not accept a fully qualified name within an expression.
This code uses JSqlParser 0.9.5-SNAPSHOT and prints out a modified SQL:
public class SimpleTableReplacer {
public static void main(String args[]) throws JSQLParserException {
String sql = "select t1.name, t2.address from Table1 t1 inner join Table2 t2 on t1.id = t2.id";
Select select = (Select)CCJSqlParserUtil.parse(sql);
//Replace Table1 with hive.DB1.Table1 and Table2 with mongo.DB2.Table2
StringBuilder buffer = new StringBuilder();
ExpressionDeParser expressionDeParser = new ExpressionDeParser();
SelectDeParser deparser = new SelectDeParser(expressionDeParser,buffer ) {
@Override
public void visit(Table tableName) {
switch (tableName.getName()) {
case "Table1": getBuffer().append("hive.DB1.Table1").append(' ').append(tableName.getAlias().getName());break;
case "Table2": getBuffer().append("mongo.DB2.Table2").append(' ').append(tableName.getAlias().getName());break;
default:
super.visit(tableName);
}
}
};
expressionDeParser.setSelectVisitor(deparser);
expressionDeParser.setBuffer(buffer);
select.getSelectBody().accept(deparser);
//End of value modification
System.out.println(buffer.toString());
}
}
Results in: SELECT t1.name, t2.address FROM hive.DB1.Table1 t1 INNER JOIN mongo.DB2.Table2 t2 ON t1.id = t2.id
.
For sure you could use this code to modify the class hierarchy itself, meaning changing the Table - objects name.
Additionally you could use a new feature of JSqlParser to deliver AST nodes for some parts of your SQL. You could extract the exact position of the table names within your SQL and make a text replace there. This could be coded this way:
SimpleNode node = (SimpleNode) CCJSqlParserUtil.parseAST(sql);
node.childrenAccept(new CCJSqlParserDefaultVisitor() {
@Override
public Object visit(SimpleNode node, Object data) {
if (node.getId() == CCJSqlParserTreeConstants.JJTTABLE) {
System.out.println("table name '" + node.jjtGetValue() + "' found at " + node.jjtGetFirstToken().beginColumn + "-" + node.jjtGetLastToken().endColumn);
}
return super.visit(node, data);
}
}, null);