JSqlParser icon indicating copy to clipboard operation
JSqlParser copied to clipboard

How to convert Statement to Expression

Open kevin2000 opened this issue 3 years ago • 2 comments

the target sql is "select * from table2 where id in (SELECT id FROM table1 WHERE find_in_set(100, ancestors))"

the follow code will throw exception that Statement cant convert to Expression InExpression expression = new InExpression(); expression.setLeftExpression(new Column(deptColumn)); Statement subSelect = CCJSqlParserUtil.parse("SELECT id FROM table1 WHERE find_in_set(100, ancestors)"); expression.setRightExpression((Expression) subSelect);

kevin2000 avatar Apr 14 '23 09:04 kevin2000

Greetings.

Yes, your observation is correct because SubSelect is an Expression, but not a Statement. So you have to options:

  1. Build a new SubSelect using the Java API.
  2. Parse the SubSelect as an Expression:
SubSelect subSelect = (SubSelect) CCJSqlParserUtil.parseExpression("SELECT id FROM table1 WHERE find_in_set(100, ancestors)");
InExpression expression = new InExpression();
expression.setLeftExpression(new Column(deptColumn));
expression.setRightExpression( subSelect );

manticore-projects avatar Apr 14 '23 10:04 manticore-projects

It's just pure coincidence, that I have provided PR #1754 which changes exactly that behaviour and makes the former SubSelect a normal Statement (and Expression).

So when you checkout this PR #1754, the following will work:

    @Test
    void testSubJoinParsing() throws JSQLParserException {
        String sqlStr = "(SELECT id FROM table1 WHERE find_in_set(100, ancestors))";
        Select select = (Select)  CCJSqlParserUtil.parse(sqlStr);

        InExpression inExpression = new InExpression();
        inExpression.setLeftExpression(new Column("id"));
        inExpression.setRightExpression( select );

        Assertions.assertEquals("id IN (SELECT id FROM table1 WHERE find_in_set(100, ancestors))", inExpression.toString());
    }

manticore-projects avatar Apr 14 '23 10:04 manticore-projects