Remove an expression in JSqlParser

820 Views Asked by At

I'm trying to find the easiest way to remove an expression (for example, a condition) from a query parsed with JSQLParser.

Let's assume I have the following query (no real logic here):

select a,b,c from table where a > 1 and c > 4 and a = b

Assuming that, I would like to remove one of the conditions, say "a = b", what would be the best way?

I used the following code to track down the condition that has two columns in an "EqualTo" expression, but now that I have the expression object in hand, I'm not sure what's the best way to remove it from the where clause.

subselect.getWhere().accept(new ExpressionVisitorAdapter() {
      @Override
      public void visit(EqualsTo expr) {
           if (expr.getLeftExpression() instanceof Column && expr.getRightExpression() instanceof Column &&
                  ((Column)expr.getLeftExpression()).getTable() != ((Column)expr.getRightExpression()).getTable()) {
               // Now what?
           }
      }
});
2

There are 2 best solutions below

3
On BEST ANSWER

The easiest possibility is if you already have implemented a visitor to set this expression to

1 = 1

this would be done with something like

expr.setLeftExpression(new LongValue(1));
expr.setRightExpression(new LongValue(1));

If you want to completly remove this from your sql, you have to implement some kind of stack to keep track of previous visited parts of your sql, to get those objects you have your expression to remove from. But this is not trivial if you take parenthesis, calculations, etc. into account.

IMHO keep it simple and try the simple replacement.

0
On

you can use DeParser to rewrite sql.

final Statement statement = CCJSqlParserUtil.parse(sql);
Select select = (Select) statement;
final SelectBody selectBody = select.getSelectBody();
final PlainSelect plainSelect = (PlainSelect) selectBody;

final StringBuilder buffer = new StringBuilder();
final SelectDeParser selectDeParser = new SelectDeParser();
final ExpressionDeParser expressionDeParser = new ExpressionDeParser(null, buffer) {
    @Override
    public void visit(EqualsTo equalsTo) {
        if (equalsTo.getLeftExpression() instanceof Column && equalsTo.getRightExpression() instanceof Column jdbcParameter) {
            // do nothing
        }else{
            super.visit(equalsTo);
        }
    }
};
selectDeParser.setExpressionVisitor(expressionDeParser);
selectDeParser.setBuffer(buffer);

plainSelect.accept(selectDeParser);

System.out.println(buffer.toString());