0

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?
           }
      }
});
Oguz
  • 1,867
  • 1
  • 17
  • 24
Tomer Shay
  • 771
  • 6
  • 17

2 Answers2

1

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.

wumpz
  • 8,257
  • 3
  • 30
  • 25
  • Thank you for the suggestion. My concern is that the output of this change (the modified query) is seen by other people, who might not understand why their modified query now includes "1=1" conditions. Said that, unless I'll find a better solution, I will go for that :) Thanks! – Tomer Shay Sep 28 '17 at 11:30
0

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());
muk
  • 69
  • 1
  • 3