Menu

Patch for a bug in CASE (expressions)

wundzun
2010-12-29
2012-12-07
  • wundzun

    wundzun - 2010-12-29

    Hi!
    I discovered a bug in JSqlParser. It is not possible to use arithmetic expressions in CASE; only simple values are permitted. To be precise, it only affects the "switch-like" variation of CASE, not the "if-like" variation. For example, this works:

    CASE WHEN a > 1 THEN 2 + 3 ELSE 4 END
    

    but this doesn't (because of the "2 + 3" part):

    CASE b WHEN 1 THEN 2 + 3 ELSE 4 END
    

    I fixed it like this:

    Index: svn/jsqlparser/trunk/src/net/sf/jsqlparser/parser/JSqlParserCC.jj
    ===================================================================
    --- svn/jsqlparser/trunk/src/net/sf/jsqlparser/parser/JSqlParserCC.jj   (wersja 186)
    +++ svn/jsqlparser/trunk/src/net/sf/jsqlparser/parser/JSqlParserCC.jj   (kopia robocza)
    @@ -1388,7 +1388,7 @@
        Expression thenExp = null;
      }
      {
    -   <K_WHEN> whenExp=PrimaryExpression() <K_THEN> thenExp=PrimaryExpression()
    +   <K_WHEN> whenExp=PrimaryExpression() <K_THEN> thenExp=SimpleExpression()
        {
           whenThen.setWhenExpression(whenExp);
           whenThen.setThenExpression(thenExp);
    

    I also added a test case for the fix:

    Index: svn/jsqlparser/trunk/testsrc/net/sf/jsqlparser/test/select/SelectTest.java
    ===================================================================
    --- svn/jsqlparser/trunk/testsrc/net/sf/jsqlparser/test/select/SelectTest.java  (wersja 186)
    +++ svn/jsqlparser/trunk/testsrc/net/sf/jsqlparser/test/select/SelectTest.java  (kopia robocza)
    @@ -453,6 +453,10 @@
            parsed = parserManager.parse(new StringReader(statement));
            assertEquals(statement, ""+parsed);
    
    +       statement = "SELECT a FROM tab1 WHERE CASE b WHEN 1 THEN 2 + 3 ELSE 4 END > 34";
    +       parsed = parserManager.parse(new StringReader(statement));
    +       assertEquals(statement, ""+parsed);
    +
    
    
            statement = "SELECT a, (CASE " +
    

    To the author of JSqlParser: I would appreciate it if you reviewed this patch and committed it if it's acceptable. Or I could commit it myself if you added me to the list of developers.

     
  • Leonardo Francalanci

    I added you to the list of developers; please commit it and I'll make a package. Thank you!

     
  • Leonardo Francalanci

    added to 0.6.6, thank you very much

     

Log in to post a comment.