• SQL解析


     1     private static String getCountSql(String sql) {
     2         return "select count(*) from "+cutOrderByOrGroupBy(getFromHql(sql));
     3     }
     4     
     5     private static String cutOrderByOrGroupBy(String hql) {
     6         int lastFromIndex = hql.lastIndexOf(" from ");
     7         int lastOG = hql.lastIndexOf(" order by ");
     8         if (lastOG < 0) {
     9             lastOG = hql.lastIndexOf(" group by ");
    10         }
    11         if (lastFromIndex < lastOG) {
    12             return hql.substring(0, lastOG);
    13         }
    14         return hql;
    15     }
    16     
    17     private static String getFromHql(String sql) {
    18         String tmpSql = sql;
    19         int fIndex = tmpSql.indexOf(" from ");
    20         tmpSql = tmpSql.substring(fIndex+5);
    21         //确保from没被( 和 )包裹起来,即为该语句主from
    22         if (!equalOpenAndCloseParenthesis(tmpSql)) {
    23             tmpSql = getFromHql(tmpSql);
    24         }
    25         return tmpSql;
    26     }
    27 
    28     private static Boolean equalOpenAndCloseParenthesis(String subSql) {
    29         final Pattern opPattern = Pattern.compile("\(");
    30         final Matcher opMatch = opPattern.matcher(subSql);
    31         final List<String> opMatches = new ArrayList<String>();
    32         while (opMatch.find()) {
    33             opMatches.add(opMatch.group(0));
    34         }
    35         final Pattern cpPattern = Pattern.compile("\)");
    36         final Matcher cpMatch = cpPattern.matcher(subSql);
    37         final List<String> cpMatches = new ArrayList<String>();
    38         while (cpMatch.find()) {
    39             cpMatches.add(cpMatch.group(0));
    40         }
    41         return opMatches.size() == cpMatches.size();
    42     }

    根据from左右两侧括号情况判断某个from是否是主sql的from关键字。

  • 相关阅读:
    DirectX11 With Windows SDK--14 深度测试
    DirectX11 With Windows SDK--12 深度/模板状态、平面镜反射绘制
    DirectX11--深入理解HLSL常量缓冲区打包规则
    JS学习笔记7_表单脚本
    JS学习笔记6_事件
    JS学习笔记5_DOM
    JS学习笔记4_BOM
    JS学习笔记3_函数表达式
    JS学习笔记2_面向对象
    JS学习笔记1_基础与常识
  • 原文地址:https://www.cnblogs.com/justbeginning/p/10606030.html
Copyright © 2020-2023  润新知