I would like to completely, and succinctly, parse a SQL where clause using JSqlParser. It's easy to parse it into individual conditional statements like so
String whereClause = "a=3 AND b=4 AND c=5";
Expression expr = CCJSqlParserUtil.parseCondExpression(whereClause);
expr.accept(new ExpressionVisitorAdapter() {
@Override
public void visit(AndExpression expr) {
if (expr.getLeftExpression() instanceof AndExpression) {
expr.getLeftExpression().accept(this);
} else if ((expr.getLeftExpression() instanceof EqualsTo)){
System.out.println(expr.getLeftExpression());
}
System.out.println(expr.getRightExpression());
}
});
Which will produce the output:
a=3
b=4
c=5
What I want is to get left side, operator and right side of each individual expression so that I can put the values in some existing filter objects.
I know you can override the visit function for every type of operator like so:
expr.accept(new ExpressionVisitorAdapter() {
@Override
public void visit(AndExpression expr) {
if (expr.getLeftExpression() instanceof AndExpression) {
expr.getLeftExpression().accept(this);
} else if ((expr.getLeftExpression() instanceof EqualsTo)){
expr.getLeftExpression().accept(this);
System.out.println(expr.getLeftExpression());
}
expr.getRightExpression().accept(this);
System.out.println(expr.getRightExpression());
}
@Override
public void visit(EqualsTo expr) {
System.out.println(expr.getLeftExpression());
System.out.println(expr.getStringExpression());
System.out.println(expr.getRightExpression());
}
});
Which will get you this output:
a
=
3
a=3
b
=
4
b=4
c
=
5
c=5
But that only covers EqualsTo condition statements that are ANDed together. As you can see, you would have to create an if statement for every logical operator and override the visit() function for every comparison operator. Is there a simpler way of doing this?