Remove duplicated parenthesis in SQL statement

General SQL Parser can be use to remove duplicated parenthesis in SQL statement. After parsing sql query, all detailed parse tree information was available for further processing.

Take this sql for example:

select * from ((select f from t1) union ((select f from t2)))

you can easily remove duplicated parenthesis in this subquery

((select f from t2))

with code like this:

    private static int removeDuplicatedParenthesis(TSourceTokenList sourceTokenList){
        int cnt = 0;
        TSourceToken st = null, prevEndToken = null;
        boolean inParenthesis = false;
        for(int i=0;i<sourceTokenList.size();i++){
            st = sourceTokenList.get(i);
            if (st.isnonsolidtoken()) continue;
            if ((st.tokencode == '(')&&(st.getLinkToken() != null)){
               if (inParenthesis){
                  if (st.getLinkToken() == prevEndToken.prevSolidToken()){
                      //this is duplicated token, remove this token
                  prevEndToken = st.getLinkToken();
               }else {
                   inParenthesis = true;
                   prevEndToken = st.getLinkToken();
            }else {
                inParenthesis = false;
                prevEndToken = null;
        return cnt;

and the result sql will be like this:

select * from ((select f from t1) union (select f from t2))

For predicate in where clause, the same rule applied.

select * from user_table where ((username like '%admin%'));

will be turned into this one:

select * from user_table where (username like '%admin%');

For SQL like this:

select * from user_table where (f1 > 1 or f2 > 2) and f3 > 3;

this tool will not remove parenthesis which will change semantic of the original sql.

Download this demo, Java version