SQL解析(Jsqlparser)

Posted on

SQL解析(Jsqlparser)

前段时间主要研究了一下SQL语句的解析,主要的几个开源产品试用了一下。本文大概总结一下个人体会。 首先是ZQL,ZQL有个比较突出的优点是使用起来比较简单,基本上属于拿上手就可以用的。但支持的功能有限,selectItem可以是简单的表达式,但不支持查询作为一个selectItem,对于其他的子查询同样也不支持。 最终我选择使用了Jsqlparser,主要原因有两点: 1)功能强大,基本上能够覆盖所有的SQL语法(没有研究是不是包含了数据库特殊的关键字,如LIMIT ),包含UNION,GROUP BY,HAVING,ORDER BY,JOIN,SUB JOIN,SUB SELECT,FUNCTION等。支持SQL深层嵌套。 2)本身设计不错,使用起来感觉很灵活。Jsqlparser对于SQL的遍历采用了VISITOR模式可以很方便的遍历SQL语句。 下面主要介绍一下Jsqlparser在我的项目中的应用情况。 背景:通过SQL语句的解析,从而增强SQL语句增加特定的查询过滤条件(如:状态过滤、权限过滤等) 1)解析SQL 2)根据SQL中涉及的表增强SQL 3)重新生成ORACLE数据库的SQL Java代码 收藏代码

  1. CCJSqlParserManager parserManager = new CCJSqlParserManager();
  2. try {
  3. Select select = (Select) parserManager.parse(new StringReader(sql)); //解析SQL语句
  4. SelectBody body = select.getSelectBody();
  5. VisitContext vc = new VisitContext(filterContext, params);
  6. vc.setTableFilterFactory(tableFilterFactory);//表的字段过滤
  7. body.accept(new SelectVisitorImpl(vc)); //访问SQL并根据SQL中涉及的表来增强SQL
  8. ExpressionDeParser expressionDeParser = new ExpressionDeParser();
  9. StringBuffer stringBuffer = new StringBuffer();
  10. SelectDeParser deParser = new OracleSelectDeParser(expressionDeParser, stringBuffer); //针对ORACLE的SQL生成
  11. expressionDeParser.setSelectVisitor(deParser);
  12. expressionDeParser.setBuffer(stringBuffer);
  13. body.accept(deParser);
  14. return new FilterResult(deParser.getBuffer().toString(), vc.getResultSqlParams());
  15. } catch (JSQLParserException e) {
  16. throw new FilterException(e);
  17. }

     CCJSqlParserManager parserManager = new CCJSqlParserManager();
    
     try {
         Select select = (Select) parserManager.parse(new StringReader(sql)); //解析SQL语句
    
         SelectBody body = select.getSelectBody();
         VisitContext vc = new VisitContext(filterContext, params);
    
         vc.setTableFilterFactory(tableFilterFactory);//表的字段过滤
         body.accept(new SelectVisitorImpl(vc)); //访问SQL并根据SQL中涉及的表来增强SQL
    
         ExpressionDeParser expressionDeParser = new ExpressionDeParser();
         StringBuffer stringBuffer = new StringBuffer();
    
         SelectDeParser deParser = new OracleSelectDeParser(expressionDeParser, stringBuffer); //针对ORACLE的SQL生成
         expressionDeParser.setSelectVisitor(deParser);
    
         expressionDeParser.setBuffer(stringBuffer);
    
        body.accept(deParser);
        return new FilterResult(deParser.getBuffer().toString(), vc.getResultSqlParams());

    } catch (JSQLParserException e) {
        throw new FilterException(e);

    }

接下去是各个VISITOR,用来访问解析后的SQL Java代码 收藏代码

  1. public class SelectVisitorImpl extends AbstractVisitor implements SelectVisitor {
  2. public SelectVisitorImpl(VisitContext ctx) {
  3. super(ctx);
  4. }
  5. @SuppressWarnings("unchecked")
  6. public void visit(PlainSelect ps) {
  7. //SELECT ITEM访问
  8. List selectItems = ps.getSelectItems();
  9. for (SelectItem item : selectItems) {
  10. item.accept(new SelectItemVisitorImpl(this.getContext()));
  11. }
  12. //FROM访问
  13. FromItem from = ps.getFromItem();
  14. FromItemVisitorImpl fv = new FromItemVisitorImpl(context);
  15. from.accept(fv);
  16. //查询条件访问
  17. if (ps.getWhere() != null) {
  18. ps.getWhere().accept(new ExpressionVisitorImpl(this.getContext()));
  19. }
  20. //过滤增强的条件
  21. if (fv.getEnhancedCondition() != null) {
  22. if (ps.getWhere() != null) {
  23. Expression expr = new Parenthesis(ps.getWhere());
  24. AndExpression and = new AndExpression(fv.getEnhancedCondition(), expr);
  25. ps.setWhere(and);
  26. } else {
  27. ps.setWhere(fv.getEnhancedCondition());
  28. }
  29. }
  30. //JOIN表的访问
  31. List joins = ps.getJoins();
  32. if (CollectionUtil.isNotEmpty(joins)) {
  33. for (Join join : joins) {
  34. FromItemVisitorImpl tempfv = new FromItemVisitorImpl(context);
  35. join.getRightItem().accept(tempfv);
  36. if (join.getOnExpression() != null) {
  37. join.getOnExpression().accept(new ExpressionVisitorImpl(this.getContext()));
  38. if (tempfv.getEnhancedCondition() != null) {
  39. Expression expr = new Parenthesis(join.getOnExpression());
  40. AndExpression and = new AndExpression(tempfv.getEnhancedCondition(), expr);
  41. join.setOnExpression(and);
  42. }
  43. }
  44. }
  45. }
  46. //ORDER BY 访问
  47. List elements = ps.getOrderByElements();
  48. if (CollectionUtil.isNotEmpty(elements)) {
  49. for (OrderByElement e : elements) {
  50. e.getExpression().accept(new ExpressionVisitorImpl(this.getContext()));
  51. }
  52. }
  53. //GROUP BY的HAVING访问
  54. if (ps.getHaving() != null) {
  55. ps.getHaving().accept(new ExpressionVisitorImpl(this.getContext()));
  56. }
  57. }
  58. @SuppressWarnings("unchecked")
  59. public void visit(Union un) {
  60. List selects = un.getPlainSelects();
  61. for (PlainSelect select : selects) {
  62. select.accept(new SelectVisitorImpl(this.getContext()));
  63. }
  64. List elements = un.getOrderByElements();
  65. if (CollectionUtil.isNotEmpty(elements)) {
  66. for (OrderByElement e : elements) {
  67. e.getExpression().accept(new ExpressionVisitorImpl(this.getContext()));
  68. }
  69. }
  70. }
  71. }

public class SelectVisitorImpl extends AbstractVisitor implements SelectVisitor {

public SelectVisitorImpl(VisitContext ctx) {

    super(ctx);
}


@SuppressWarnings("unchecked")

public void visit(PlainSelect ps) {
    //SELECT ITEM访问

    List<SelectItem> selectItems = ps.getSelectItems();
    for (SelectItem item : selectItems) {

        item.accept(new SelectItemVisitorImpl(this.getContext()));
    }


    //FROM访问

    FromItem from = ps.getFromItem();
    FromItemVisitorImpl fv = new FromItemVisitorImpl(context);

    from.accept(fv);


    //查询条件访问
    if (ps.getWhere() != null) {

        ps.getWhere().accept(new ExpressionVisitorImpl(this.getContext()));
    }


    //过滤增强的条件

    if (fv.getEnhancedCondition() != null) {
        if (ps.getWhere() != null) {

            Expression expr = new Parenthesis(ps.getWhere());
            AndExpression and = new AndExpression(fv.getEnhancedCondition(), expr);

            ps.setWhere(and);
        } else {

            ps.setWhere(fv.getEnhancedCondition());
        }

    }


    //JOIN表的访问
    List<Join> joins = ps.getJoins();

    if (CollectionUtil.isNotEmpty(joins)) {
        for (Join join : joins) {

            FromItemVisitorImpl tempfv = new FromItemVisitorImpl(context);
            join.getRightItem().accept(tempfv);

            if (join.getOnExpression() != null) {
                join.getOnExpression().accept(new ExpressionVisitorImpl(this.getContext()));

                if (tempfv.getEnhancedCondition() != null) {
                    Expression expr = new Parenthesis(join.getOnExpression());

                    AndExpression and = new AndExpression(tempfv.getEnhancedCondition(), expr);
                    join.setOnExpression(and);

                }
            }

        }
    }


    //ORDER BY 访问

    List<OrderByElement> elements = ps.getOrderByElements();
    if (CollectionUtil.isNotEmpty(elements)) {

        for (OrderByElement e : elements) {
            e.getExpression().accept(new ExpressionVisitorImpl(this.getContext()));

        }
    }


    //GROUP BY的HAVING访问

    if (ps.getHaving() != null) {
        ps.getHaving().accept(new ExpressionVisitorImpl(this.getContext()));

    }
}


@SuppressWarnings("unchecked")

public void visit(Union un) {
    List<PlainSelect> selects = un.getPlainSelects();

    for (PlainSelect select : selects) {
        select.accept(new SelectVisitorImpl(this.getContext()));

    }
    List<OrderByElement> elements = un.getOrderByElements();

    if (CollectionUtil.isNotEmpty(elements)) {
        for (OrderByElement e : elements) {

            e.getExpression().accept(new ExpressionVisitorImpl(this.getContext()));
        }

    }
}

} Java代码 收藏代码

  1. public class SelectItemVisitorImpl extends AbstractVisitor implements SelectItemVisitor {
  2. public SelectItemVisitorImpl(VisitContext ctx) {
  3. super(ctx);
  4. }
  5. public void visit(AllColumns ac) {
  6. }
  7. public void visit(AllTableColumns atc) {
  8. }
  9. public void visit(SelectExpressionItem sei) {
  10. sei.getExpression().accept(new ExpressionVisitorImpl(this.getContext()));
  11. }
  12. }

public class SelectItemVisitorImpl extends AbstractVisitor implements SelectItemVisitor {

public SelectItemVisitorImpl(VisitContext ctx) {

    super(ctx);
}


public void visit(AllColumns ac) {

}


public void visit(AllTableColumns atc) {
}


public void visit(SelectExpressionItem sei) {

    sei.getExpression().accept(new ExpressionVisitorImpl(this.getContext()));
}

} Java代码 收藏代码

  1. public class ItemsListVisitorImpl extends AbstractVisitor implements ItemsListVisitor {
  2. public ItemsListVisitorImpl(VisitContext ctx) {
  3. super(ctx);
  4. }
  5. public void visit(SubSelect ss) {
  6. ss.getSelectBody().accept(new SelectVisitorImpl(context));
  7. }
  8. @SuppressWarnings("unchecked")
  9. public void visit(ExpressionList el) {
  10. List list = el.getExpressions();
  11. if (CollectionUtil.isNotEmpty(list)) {
  12. for (Expression expr : list) {
  13. expr.accept(new ExpressionVisitorImpl(context));
  14. }
  15. }
  16. }
  17. }

public class ItemsListVisitorImpl extends AbstractVisitor implements ItemsListVisitor {

public ItemsListVisitorImpl(VisitContext ctx) {

    super(ctx);
}


public void visit(SubSelect ss) {

    ss.getSelectBody().accept(new SelectVisitorImpl(context));
}


@SuppressWarnings("unchecked")

public void visit(ExpressionList el) {
    List<Expression> list = el.getExpressions();

    if (CollectionUtil.isNotEmpty(list)) {
        for (Expression expr : list) {

            expr.accept(new ExpressionVisitorImpl(context));
        }

    }
}

} 如果FROM的内容是table的话,则根据table的增强配置对SQL增强 Java代码 收藏代码

  1. public class FromItemVisitorImpl extends AbstractVisitor implements FromItemVisitor {
  2. private String varPattern = "@\{\s/?(\w+)\s/?\}";
  3. private Expression enhancedCondition;
  4. public FromItemVisitorImpl(VisitContext ctx) {
  5. super(ctx);
  6. }
  7. public void visit(Table table) {
  8. Set filters = context.getTableFilterFactory().getTableFilter(table.getName());
  9. if (filters == null) {
  10. filters = Collections.emptySet();
  11. }
  12. for (FieldFilter ff : filters) {
  13. Column c = new Column(new Table(null, table.getAlias()), ff.getFieldName());
  14. JdbcParameter param = new JdbcParameter();
  15. Object fieldValue = getRawValue(ff.getFieldValue(), this.context.getFilterContext());
  16. Expression[] exps;
  17. if ("between".equalsIgnoreCase(ff.getOperator()) || "not between".equalsIgnoreCase(ff.getOperator())) {
  18. Object[] objs = (Object[]) fieldValue;
  19. this.getContext().getResultSqlParams().add(objs[0]);
  20. this.getContext().getResultSqlParams().add(objs[1]);
  21. exps = new Expression[] { c, param, param };
  22. } else if ("is null".equalsIgnoreCase(ff.getOperator()) || "is not null".equalsIgnoreCase(ff.getOperator())) {
  23. exps = new Expression[] { c };
  24. } else {
  25. this.getContext().getResultSqlParams().add(fieldValue);
  26. exps = new Expression[] { c, param };
  27. }
  28. Expression operator = this.getOperator(ff.getOperator(), exps);
  29. if (this.enhancedCondition != null) {
  30. enhancedCondition = new AndExpression(enhancedCondition, operator);
  31. } else {
  32. enhancedCondition = operator;
  33. }
  34. }
  35. }
  36. public void visit(SubSelect ss) {
  37. ss.getSelectBody().accept(new SelectVisitorImpl(this.getContext()));
  38. }
  39. public void visit(SubJoin sj) {
  40. Join join = sj.getJoin();
  41. join.getRightItem().accept(new FromItemVisitorImpl(this.getContext()));
  42. join.getOnExpression().accept(new ExpressionVisitorImpl(this.getContext()));
  43. }
  44. private Expression getOperator(String op, Expression[] exp) {
  45. if ("=".equals(op)) {
  46. EqualsTo eq = new EqualsTo();
  47. eq.setLeftExpression(exp[0]);
  48. eq.setRightExpression(exp[1]);
  49. return eq;
  50. } else if (">".equals(op)) {
  51. GreaterThan gt = new GreaterThan();
  52. gt.setLeftExpression(exp[0]);
  53. gt.setRightExpression(exp[1]);
  54. return gt;
  55. } else if (">=".equals(op)) {
  56. GreaterThanEquals geq = new GreaterThanEquals();
  57. geq.setLeftExpression(exp[0]);
  58. geq.setRightExpression(exp[1]);
  59. return geq;
  60. } else if ("<".equals(op)) {
  61. MinorThan mt = new MinorThan();
  62. mt.setLeftExpression(exp[0]);
  63. mt.setRightExpression(exp[1]);
  64. return mt;
  65. } else if ("<=".equals(op)) {
  66. MinorThanEquals leq = new MinorThanEquals();
  67. leq.setLeftExpression(exp[0]);
  68. leq.setRightExpression(exp[1]);
  69. return leq;
  70. } else if ("<>".equals(op)) {
  71. NotEqualsTo neq = new NotEqualsTo();
  72. neq.setLeftExpression(exp[0]);
  73. neq.setRightExpression(exp[1]);
  74. return neq;
  75. } else if ("is null".equalsIgnoreCase(op)) {
  76. IsNullExpression isNull = new IsNullExpression();
  77. isNull.setNot(false);
  78. isNull.setLeftExpression(exp[0]);
  79. return isNull;
  80. } else if ("is not null".equalsIgnoreCase(op)) {
  81. IsNullExpression isNull = new IsNullExpression();
  82. isNull.setNot(true);
  83. isNull.setLeftExpression(exp[0]);
  84. return isNull;
  85. } else if ("like".equalsIgnoreCase(op)) {
  86. LikeExpression like = new LikeExpression();
  87. like.setNot(false);
  88. like.setLeftExpression(exp[0]);
  89. like.setRightExpression(exp[1]);
  90. return like;
  91. } else if ("not like".equalsIgnoreCase(op)) {
  92. LikeExpression nlike = new LikeExpression();
  93. nlike.setNot(true);
  94. nlike.setLeftExpression(exp[0]);
  95. nlike.setRightExpression(exp[1]);
  96. return nlike;
  97. } else if ("between".equalsIgnoreCase(op)) {
  98. Between bt = new Between();
  99. bt.setNot(false);
  100. bt.setLeftExpression(exp[0]);
  101. bt.setBetweenExpressionStart(exp[1]);
  102. bt.setBetweenExpressionEnd(exp[2]);
  103. return bt;
  104. } else if ("not between".equalsIgnoreCase(op)) {
  105. Between bt = new Between();
  106. bt.setNot(true);
  107. bt.setLeftExpression(exp[0]);
  108. bt.setBetweenExpressionStart(exp[1]);
  109. bt.setBetweenExpressionEnd(exp[2]);
  110. return bt;
  111. }
  112. throw new FilterException("Unknown operator:" + op);
  113. }
  114. protected Object getRawValue(Object value, Map context) {
  115. if (context == null) {
  116. return value;
  117. }
  118. if (value instanceof String) {
  119. String v = (String) value;
  120. Pattern pattern = Pattern.compile(varPattern);
  121. Matcher matcher = pattern.matcher(v);
  122. if (matcher.find()) {
  123. return context.get(matcher.group(1));
  124. }
  125. }
  126. return value;
  127. }
  128. public Expression getEnhancedCondition() {
  129. return enhancedCondition;
  130. }
  131. }

public class FromItemVisitorImpl extends AbstractVisitor implements FromItemVisitor {

private String varPattern = "@\\{\\s/*?(\\w+)\\s/*?\\}";
private Expression enhancedCondition;


public FromItemVisitorImpl(VisitContext ctx) {

    super(ctx);
}


public void visit(Table table) {

    Set<FieldFilter> filters = context.getTableFilterFactory().getTableFilter(table.getName());
    if (filters == null) {

        filters = Collections.emptySet();
    }

    for (FieldFilter ff : filters) {
        Column c = new Column(new Table(null, table.getAlias()), ff.getFieldName());

        JdbcParameter param = new JdbcParameter();
        Object fieldValue = getRawValue(ff.getFieldValue(), this.context.getFilterContext());

        Expression[] exps;
        if ("between".equalsIgnoreCase(ff.getOperator()) || "not between".equalsIgnoreCase(ff.getOperator())) {

            Object[] objs = (Object[]) fieldValue;
            this.getContext().getResultSqlParams().add(objs[0]);

            this.getContext().getResultSqlParams().add(objs[1]);
            exps = new Expression[] { c, param, param };

        } else if ("is null".equalsIgnoreCase(ff.getOperator()) || "is not null".equalsIgnoreCase(ff.getOperator())) {
            exps = new Expression[] { c };

        } else {
            this.getContext().getResultSqlParams().add(fieldValue);

            exps = new Expression[] { c, param };
        }

        Expression operator = this.getOperator(ff.getOperator(), exps);
        if (this.enhancedCondition != null) {

            enhancedCondition = new AndExpression(enhancedCondition, operator);
        } else {

            enhancedCondition = operator;
        }

    }
}


public void visit(SubSelect ss) {

    ss.getSelectBody().accept(new SelectVisitorImpl(this.getContext()));
}


public void visit(SubJoin sj) {

    Join join = sj.getJoin();
    join.getRightItem().accept(new FromItemVisitorImpl(this.getContext()));

    join.getOnExpression().accept(new ExpressionVisitorImpl(this.getContext()));
}


private Expression getOperator(String op, Expression[] exp) {

    if ("=".equals(op)) {
        EqualsTo eq = new EqualsTo();

        eq.setLeftExpression(exp[0]);
        eq.setRightExpression(exp[1]);

        return eq;
    } else if (">".equals(op)) {

        GreaterThan gt = new GreaterThan();
        gt.setLeftExpression(exp[0]);

        gt.setRightExpression(exp[1]);
        return gt;

    } else if (">=".equals(op)) {
        GreaterThanEquals geq = new GreaterThanEquals();

        geq.setLeftExpression(exp[0]);
        geq.setRightExpression(exp[1]);

        return geq;
    } else if ("<".equals(op)) {

        MinorThan mt = new MinorThan();
        mt.setLeftExpression(exp[0]);

        mt.setRightExpression(exp[1]);
        return mt;

    } else if ("<=".equals(op)) {
        MinorThanEquals leq = new MinorThanEquals();

        leq.setLeftExpression(exp[0]);
        leq.setRightExpression(exp[1]);

        return leq;
    } else if ("<>".equals(op)) {

        NotEqualsTo neq = new NotEqualsTo();
        neq.setLeftExpression(exp[0]);

        neq.setRightExpression(exp[1]);
        return neq;

    } else if ("is null".equalsIgnoreCase(op)) {
        IsNullExpression isNull = new IsNullExpression();

        isNull.setNot(false);
        isNull.setLeftExpression(exp[0]);

        return isNull;
    } else if ("is not null".equalsIgnoreCase(op)) {

        IsNullExpression isNull = new IsNullExpression();
        isNull.setNot(true);

        isNull.setLeftExpression(exp[0]);
        return isNull;

    } else if ("like".equalsIgnoreCase(op)) {
        LikeExpression like = new LikeExpression();

        like.setNot(false);
        like.setLeftExpression(exp[0]);

        like.setRightExpression(exp[1]);
        return like;

    } else if ("not like".equalsIgnoreCase(op)) {
        LikeExpression nlike = new LikeExpression();

        nlike.setNot(true);
        nlike.setLeftExpression(exp[0]);

        nlike.setRightExpression(exp[1]);
        return nlike;

    } else if ("between".equalsIgnoreCase(op)) {
        Between bt = new Between();

        bt.setNot(false);
        bt.setLeftExpression(exp[0]);

        bt.setBetweenExpressionStart(exp[1]);
        bt.setBetweenExpressionEnd(exp[2]);

        return bt;
    } else if ("not between".equalsIgnoreCase(op)) {

        Between bt = new Between();
        bt.setNot(true);

        bt.setLeftExpression(exp[0]);
        bt.setBetweenExpressionStart(exp[1]);

        bt.setBetweenExpressionEnd(exp[2]);
        return bt;

    }
    throw new FilterException("Unknown operator:" + op);

}


protected Object getRawValue(Object value, Map<String, Object> context) {
    if (context == null) {

        return value;
    }

    if (value instanceof String) {
        String v = (String) value;

        Pattern pattern = Pattern.compile(varPattern);
        Matcher matcher = pattern.matcher(v);

        if (matcher.find()) {
            return context.get(matcher.group(1));

        }
    }

    return value;
}


public Expression getEnhancedCondition() {

    return enhancedCondition;
}

} 1)对JDBC parameter做了处理,如果参数为NULL则自动忽略该parameter,忽略后需要处理and or between 等情况 如:where name=? and age=? ,假如name对应的参数为null,则条件改为where 1=1 and age=?,如果是or的话则改为 where 1=0 or age=? Java代码 收藏代码

  1. public class ExpressionVisitorImpl extends AbstractVisitor implements ExpressionVisitor {
  2. public ExpressionVisitorImpl(VisitContext ctx) {
  3. super(ctx);
  4. }
  5. public void visit(NullValue nv) {
  6. }
  7. public void visit(Function f) {
  8. }
  9. public void visit(InverseExpression ie) {
  10. }
  11. public void visit(JdbcParameter jp) {
  12. this.getContext().getResultSqlParams().add(context.removeFirstParam());
  13. }
  14. public void visit(DoubleValue dv) {
  15. }
  16. public void visit(LongValue lv) {
  17. }
  18. public void visit(DateValue dv) {
  19. }
  20. public void visit(TimeValue tv) {
  21. }
  22. public void visit(TimestampValue tv) {
  23. }
  24. public void visit(Parenthesis parenthesis) {
  25. ExpressionVisitorImpl ev = new ExpressionVisitorImpl(context);
  26. parenthesis.getExpression().accept(ev);
  27. if (ev.isNotValid()) {
  28. parenthesis.setExpression(this.createTrueEquals());
  29. }
  30. }
  31. public void visit(StringValue s) {
  32. }
  33. public void visit(Addition a) {
  34. }
  35. public void visit(Division d) {
  36. }
  37. public void visit(Multiplication m) {
  38. }
  39. public void visit(Subtraction s) {
  40. }
  41. public void visit(AndExpression and) {
  42. ExpressionVisitorImpl left = new ExpressionVisitorImpl(this.getContext());
  43. and.getLeftExpression().accept(left);
  44. if (left.isNotValid()) {
  45. and.setLeftExpression(this.createTrueEquals());
  46. }
  47. ExpressionVisitorImpl right = new ExpressionVisitorImpl(this.getContext());
  48. and.getRightExpression().accept(right);
  49. if (right.isNotValid()) {
  50. and.setRightExpression(this.createTrueEquals());
  51. }
  52. }
  53. public void visit(OrExpression or) {
  54. ExpressionVisitorImpl left = new ExpressionVisitorImpl(this.getContext());
  55. or.getLeftExpression().accept(left);
  56. if (left.isNotValid()) {
  57. or.setLeftExpression(this.createFalseEquals());
  58. }
  59. ExpressionVisitorImpl right = new ExpressionVisitorImpl(this.getContext());
  60. or.getRightExpression().accept(right);
  61. if (right.isNotValid()) {
  62. or.setRightExpression(this.createFalseEquals());
  63. }
  64. }
  65. public void visit(Between btw) {
  66. Expression start = btw.getBetweenExpressionStart();
  67. Expression end = btw.getBetweenExpressionEnd();
  68. if (start instanceof JdbcParameter && end instanceof JdbcParameter) {
  69. Object o1 = this.context.getFirstParam();
  70. Object o2 = this.context.getParam(1);
  71. if (o1 == null || o2 == null) {
  72. this.context.removeFirstParam();
  73. this.context.removeFirstParam();
  74. this.setValid(false);
  75. return;
  76. }
  77. } else if (start instanceof JdbcParameter || end instanceof JdbcParameter) {
  78. Object o1 = this.context.getFirstParam();
  79. if (o1 == null) {
  80. this.context.removeFirstParam();
  81. this.setValid(false);
  82. return;
  83. }
  84. }
  85. btw.getLeftExpression().accept(new ExpressionVisitorImpl(context));
  86. btw.getBetweenExpressionStart().accept(new ExpressionVisitorImpl(context));
  87. btw.getBetweenExpressionEnd().accept(new ExpressionVisitorImpl(context));
  88. }
  89. public void visit(EqualsTo eq) {
  90. if (eq.getRightExpression() instanceof JdbcParameter) {
  91. Object o = this.context.getFirstParam();
  92. if (o == null) {
  93. this.setValid(false);
  94. this.getContext().removeFirstParam();
  95. return;
  96. }
  97. }
  98. eq.getLeftExpression().accept(new ExpressionVisitorImpl(this.getContext()));
  99. eq.getRightExpression().accept(new ExpressionVisitorImpl(this.getContext()));
  100. }
  101. public void visit(GreaterThan gt) {
  102. if (gt.getRightExpression() instanceof JdbcParameter) {
  103. Object o = this.context.getFirstParam();
  104. if (o == null) {
  105. this.setValid(false);
  106. this.getContext().removeFirstParam();
  107. }
  108. }
  109. gt.getLeftExpression().accept(new ExpressionVisitorImpl(this.getContext()));
  110. gt.getRightExpression().accept(new ExpressionVisitorImpl(this.getContext()));
  111. }
  112. public void visit(GreaterThanEquals gte) {
  113. if (gte.getRightExpression() instanceof JdbcParameter) {
  114. Object o = this.context.getFirstParam();
  115. if (o == null) {
  116. this.setValid(false);
  117. this.getContext().removeFirstParam();
  118. }
  119. }
  120. gte.getLeftExpression().accept(new ExpressionVisitorImpl(this.getContext()));
  121. gte.getRightExpression().accept(new ExpressionVisitorImpl(this.getContext()));
  122. }
  123. public void visit(InExpression in) {
  124. ItemsList list = in.getItemsList();
  125. list.accept(new ItemsListVisitorImpl(context));
  126. }
  127. public void visit(IsNullExpression ine) {
  128. }
  129. public void visit(LikeExpression le) {
  130. if (le.getRightExpression() instanceof JdbcParameter) {
  131. Object o = this.context.getFirstParam();
  132. if (o == null) {
  133. this.setValid(false);
  134. this.getContext().removeFirstParam();
  135. }
  136. }
  137. le.getLeftExpression().accept(new ExpressionVisitorImpl(this.getContext()));
  138. le.getRightExpression().accept(new ExpressionVisitorImpl(this.getContext()));
  139. }
  140. public void visit(MinorThan mt) {
  141. if (mt.getRightExpression() instanceof JdbcParameter) {
  142. Object o = this.context.getFirstParam();
  143. if (o == null) {
  144. this.setValid(false);
  145. this.getContext().removeFirstParam();
  146. }
  147. }
  148. mt.getLeftExpression().accept(new ExpressionVisitorImpl(this.getContext()));
  149. mt.getRightExpression().accept(new ExpressionVisitorImpl(this.getContext()));
  150. }
  151. public void visit(MinorThanEquals mte) {
  152. if (mte.getRightExpression() instanceof JdbcParameter) {
  153. Object o = this.context.getFirstParam();
  154. if (o == null) {
  155. this.setValid(false);
  156. this.getContext().removeFirstParam();
  157. }
  158. }
  159. mte.getLeftExpression().accept(new ExpressionVisitorImpl(this.getContext()));
  160. mte.getRightExpression().accept(new ExpressionVisitorImpl(this.getContext()));
  161. }
  162. public void visit(NotEqualsTo neq) {
  163. if (neq.getRightExpression() instanceof JdbcParameter) {
  164. Object o = this.context.getFirstParam();
  165. if (o == null) {
  166. this.setValid(false);
  167. this.getContext().removeFirstParam();
  168. return;
  169. }
  170. }
  171. neq.getLeftExpression().accept(new ExpressionVisitorImpl(this.getContext()));
  172. neq.getRightExpression().accept(new ExpressionVisitorImpl(this.getContext()));
  173. }
  174. public void visit(Column c) {
  175. }
  176. public void visit(SubSelect ss) {
  177. ss.getSelectBody().accept(new SelectVisitorImpl(context));
  178. }
  179. public void visit(CaseExpression ce) {
  180. }
  181. public void visit(WhenClause wc) {
  182. }
  183. public void visit(ExistsExpression ee) {
  184. }
  185. public void visit(AllComparisonExpression ace) {
  186. }
  187. public void visit(AnyComparisonExpression ace) {
  188. }
  189. public void visit(Concat c) {
  190. }
  191. public void visit(Matches m) {
  192. }
  193. public void visit(BitwiseAnd ba) {
  194. }
  195. public void visit(BitwiseOr bo) {
  196. }
  197. public void visit(BitwiseXor bx) {
  198. }
  199. private EqualsTo createTrueEquals() {
  200. EqualsTo eq = new EqualsTo();
  201. eq.setLeftExpression(new LongValue("1"));
  202. eq.setRightExpression(new LongValue("1"));
  203. return eq;
  204. }
  205. private EqualsTo createFalseEquals() {
  206. EqualsTo eq = new EqualsTo();
  207. eq.setLeftExpression(new LongValue("1"));
  208. eq.setRightExpression(new LongValue("0"));
  209. return eq;
  210. }
  211. }

public class ExpressionVisitorImpl extends AbstractVisitor implements ExpressionVisitor {

public ExpressionVisitorImpl(VisitContext ctx) {

    super(ctx);
}


public void visit(NullValue nv) {

}


public void visit(Function f) {
}


public void visit(InverseExpression ie) {

}


public void visit(JdbcParameter jp) {
    this.getContext().getResultSqlParams().add(context.removeFirstParam());

}


public void visit(DoubleValue dv) {
}


public void visit(LongValue lv) {

}


public void visit(DateValue dv) {
}


public void visit(TimeValue tv) {

}


public void visit(TimestampValue tv) {
}


public void visit(Parenthesis parenthesis) {

    ExpressionVisitorImpl ev = new ExpressionVisitorImpl(context);
    parenthesis.getExpression().accept(ev);

    if (ev.isNotValid()) {
        parenthesis.setExpression(this.createTrueEquals());

    }
}


public void visit(StringValue s) {

}


public void visit(Addition a) {
}


public void visit(Division d) {

}


public void visit(Multiplication m) {
}


public void visit(Subtraction s) {

}


public void visit(AndExpression and) {
    ExpressionVisitorImpl left = new ExpressionVisitorImpl(this.getContext());

    and.getLeftExpression().accept(left);
    if (left.isNotValid()) {

        and.setLeftExpression(this.createTrueEquals());
    }

    ExpressionVisitorImpl right = new ExpressionVisitorImpl(this.getContext());
    and.getRightExpression().accept(right);

    if (right.isNotValid()) {
        and.setRightExpression(this.createTrueEquals());

    }
}


public void visit(OrExpression or) {

    ExpressionVisitorImpl left = new ExpressionVisitorImpl(this.getContext());
    or.getLeftExpression().accept(left);

    if (left.isNotValid()) {
        or.setLeftExpression(this.createFalseEquals());

    }
    ExpressionVisitorImpl right = new ExpressionVisitorImpl(this.getContext());

    or.getRightExpression().accept(right);
    if (right.isNotValid()) {

        or.setRightExpression(this.createFalseEquals());
    }

}


public void visit(Between btw) {
    Expression start = btw.getBetweenExpressionStart();

    Expression end = btw.getBetweenExpressionEnd();
    if (start instanceof JdbcParameter && end instanceof JdbcParameter) {

        Object o1 = this.context.getFirstParam();
        Object o2 = this.context.getParam(1);

        if (o1 == null || o2 == null) {
            this.context.removeFirstParam();

            this.context.removeFirstParam();
            this.setValid(false);

            return;
        }

    } else if (start instanceof JdbcParameter || end instanceof JdbcParameter) {
        Object o1 = this.context.getFirstParam();

        if (o1 == null) {
            this.context.removeFirstParam();

            this.setValid(false);
            return;

        }
    }

    btw.getLeftExpression().accept(new ExpressionVisitorImpl(context));
    btw.getBetweenExpressionStart().accept(new ExpressionVisitorImpl(context));

    btw.getBetweenExpressionEnd().accept(new ExpressionVisitorImpl(context));
}


public void visit(EqualsTo eq) {

    if (eq.getRightExpression() instanceof JdbcParameter) {
        Object o = this.context.getFirstParam();

        if (o == null) {
            this.setValid(false);

            this.getContext().removeFirstParam();
            return;

        }
    }

    eq.getLeftExpression().accept(new ExpressionVisitorImpl(this.getContext()));
    eq.getRightExpression().accept(new ExpressionVisitorImpl(this.getContext()));

}


public void visit(GreaterThan gt) {
    if (gt.getRightExpression() instanceof JdbcParameter) {

        Object o = this.context.getFirstParam();
        if (o == null) {

            this.setValid(false);
            this.getContext().removeFirstParam();

        }
    }

    gt.getLeftExpression().accept(new ExpressionVisitorImpl(this.getContext()));
    gt.getRightExpression().accept(new ExpressionVisitorImpl(this.getContext()));

}


public void visit(GreaterThanEquals gte) {
    if (gte.getRightExpression() instanceof JdbcParameter) {

        Object o = this.context.getFirstParam();
        if (o == null) {

            this.setValid(false);
            this.getContext().removeFirstParam();

        }
    }

    gte.getLeftExpression().accept(new ExpressionVisitorImpl(this.getContext()));
    gte.getRightExpression().accept(new ExpressionVisitorImpl(this.getContext()));

}


public void visit(InExpression in) {
    ItemsList list = in.getItemsList();

    list.accept(new ItemsListVisitorImpl(context));
}


public void visit(IsNullExpression ine) {

}


public void visit(LikeExpression le) {
    if (le.getRightExpression() instanceof JdbcParameter) {

        Object o = this.context.getFirstParam();
        if (o == null) {

            this.setValid(false);
            this.getContext().removeFirstParam();

        }
    }

    le.getLeftExpression().accept(new ExpressionVisitorImpl(this.getContext()));
    le.getRightExpression().accept(new ExpressionVisitorImpl(this.getContext()));

}


public void visit(MinorThan mt) {
    if (mt.getRightExpression() instanceof JdbcParameter) {

        Object o = this.context.getFirstParam();
        if (o == null) {

            this.setValid(false);
            this.getContext().removeFirstParam();

        }
    }

    mt.getLeftExpression().accept(new ExpressionVisitorImpl(this.getContext()));
    mt.getRightExpression().accept(new ExpressionVisitorImpl(this.getContext()));

}


public void visit(MinorThanEquals mte) {
    if (mte.getRightExpression() instanceof JdbcParameter) {

        Object o = this.context.getFirstParam();
        if (o == null) {

            this.setValid(false);
            this.getContext().removeFirstParam();

        }
    }

    mte.getLeftExpression().accept(new ExpressionVisitorImpl(this.getContext()));
    mte.getRightExpression().accept(new ExpressionVisitorImpl(this.getContext()));

}


public void visit(NotEqualsTo neq) {
    if (neq.getRightExpression() instanceof JdbcParameter) {

        Object o = this.context.getFirstParam();
        if (o == null) {

            this.setValid(false);
            this.getContext().removeFirstParam();

            return;
        }

    }
    neq.getLeftExpression().accept(new ExpressionVisitorImpl(this.getContext()));

    neq.getRightExpression().accept(new ExpressionVisitorImpl(this.getContext()));
}


public void visit(Column c) {

}


public void visit(SubSelect ss) {
    ss.getSelectBody().accept(new SelectVisitorImpl(context));

}


public void visit(CaseExpression ce) {
}


public void visit(WhenClause wc) {

}


public void visit(ExistsExpression ee) {
}


public void visit(AllComparisonExpression ace) {

}


public void visit(AnyComparisonExpression ace) {
}


public void visit(Concat c) {

}


public void visit(Matches m) {
}


public void visit(BitwiseAnd ba) {

}


public void visit(BitwiseOr bo) {
}


public void visit(BitwiseXor bx) {

}


private EqualsTo createTrueEquals() {
    EqualsTo eq = new EqualsTo();

    eq.setLeftExpression(new LongValue("1"));
    eq.setRightExpression(new LongValue("1"));

    return eq;
}


private EqualsTo createFalseEquals() {

    EqualsTo eq = new EqualsTo();
    eq.setLeftExpression(new LongValue("1"));

    eq.setRightExpression(new LongValue("0"));
    return eq;

}

} 增强后SQL语句的重新生成,根据ORACLE的语法重写了几个生成的方法 Java代码 收藏代码

  1. public class OracleSelectDeParser extends SelectDeParser {
  2. public OracleSelectDeParser(ExpressionDeParser expressionDeParser, StringBuffer sb) {
  3. super(expressionDeParser, sb);
  4. }
  5. ///
  6. /* 重写父类方法,去掉父类方法中table前的as
  7. /*/
  8. public void visit(Table tableName) {
  9. buffer.append(tableName.getWholeTableName());
  10. String alias = tableName.getAlias();
  11. if (alias != null && StringUtil.isNotEmpty(alias)) {
  12. buffer.append(" ");
  13. buffer.append(alias);
  14. }
  15. }
  16. ///
  17. /* 重写父类方法,在JOIN之前增加空格
  18. /*/
  19. @SuppressWarnings("unchecked")
  20. public void deparseJoin(Join join) {
  21. if (join.isSimple()) {
  22. buffer.append(", ");
  23. } else {
  24. buffer.append(" ");
  25. if (join.isRight()) {
  26. buffer.append("RIGHT ");
  27. } else if (join.isNatural()) {
  28. buffer.append("NATURAL ");
  29. } else if (join.isFull()) {
  30. buffer.append("FULL ");
  31. } else if (join.isLeft()) {
  32. buffer.append("LEFT ");
  33. }
  34. if (join.isOuter()) {
  35. buffer.append("OUTER ");
  36. } else if (join.isInner()) {
  37. buffer.append("INNER ");
  38. }
  39. buffer.append("JOIN ");
  40. }
  41. FromItem fromItem = join.getRightItem();
  42. fromItem.accept(this);
  43. if (join.getOnExpression() != null) {
  44. buffer.append(" ON ");
  45. join.getOnExpression().accept(expressionVisitor);
  46. }
  47. if (join.getUsingColumns() != null) {
  48. buffer.append(" USING ( ");
  49. for (Iterator iterator = join.getUsingColumns().iterator(); iterator.hasNext();) {
  50. Column column = iterator.next();
  51. buffer.append(column.getWholeColumnName());
  52. if (iterator.hasNext()) {
  53. buffer.append(" ,");
  54. }
  55. }
  56. buffer.append(")");
  57. }
  58. }
  59. }

public class OracleSelectDeParser extends SelectDeParser {

public OracleSelectDeParser(ExpressionDeParser expressionDeParser, StringBuffer sb) {

    super(expressionDeParser, sb);
}


//*/*

 /* 重写父类方法,去掉父类方法中table前的as
 /*/

public void visit(Table tableName) {
    buffer.append(tableName.getWholeTableName());

    String alias = tableName.getAlias();
    if (alias != null && StringUtil.isNotEmpty(alias)) {

        buffer.append(" ");
        buffer.append(alias);

    }
}


//*/*

 /* 重写父类方法,在JOIN之前增加空格
 /*/

@SuppressWarnings("unchecked")
public void deparseJoin(Join join) {

    if (join.isSimple()) {
        buffer.append(", ");

    } else {
        buffer.append(" ");

        if (join.isRight()) {
            buffer.append("RIGHT ");

        } else if (join.isNatural()) {
            buffer.append("NATURAL ");

        } else if (join.isFull()) {
            buffer.append("FULL ");

        } else if (join.isLeft()) {
            buffer.append("LEFT ");

        }
        if (join.isOuter()) {

            buffer.append("OUTER ");
        } else if (join.isInner()) {

            buffer.append("INNER ");
        }

        buffer.append("JOIN ");
    }


    FromItem fromItem = join.getRightItem();

    fromItem.accept(this);
    if (join.getOnExpression() != null) {

        buffer.append(" ON ");
        join.getOnExpression().accept(expressionVisitor);

    }
    if (join.getUsingColumns() != null) {

        buffer.append(" USING ( ");
        for (Iterator<Column> iterator = join.getUsingColumns().iterator(); iterator.hasNext();) {

            Column column = iterator.next();
            buffer.append(column.getWholeColumnName());

            if (iterator.hasNext()) {
                buffer.append(" ,");

            }
        }

        buffer.append(")");
    }

}

}

希望本站内容对您有点用处,有什么疑问或建议请在后面留言评论
转载请注明作者(RobinChia)和出处 It so life ,请勿用于任何商业用途
本文链接: SQL解析(Jsqlparser)