AliDruidCountOptimize.java 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**
  2. * Copyright (c) 2011-2014, hubin (jobob@qq.com).
  3. * <p>
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. * <p>
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. * <p>
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.baomidou.mybatisplus.plugins.pagination.optimize;
  17. import com.alibaba.druid.sql.PagerUtils;
  18. import com.baomidou.mybatisplus.plugins.parser.AbstractSqlParser;
  19. import com.baomidou.mybatisplus.plugins.parser.SqlInfo;
  20. /**
  21. * <p>
  22. * Ali Druid Count Optimize
  23. * </p>
  24. *
  25. * @author hubin
  26. * @Date 2017-06-20
  27. */
  28. public class AliDruidCountOptimize extends AbstractSqlParser {
  29. public AliDruidCountOptimize(String sql, String dbType) {
  30. super(sql, dbType);
  31. }
  32. @Override
  33. public SqlInfo optimizeSql() {
  34. String sql = this.getSql();
  35. String dbType = this.getDbType();
  36. if (logger.isDebugEnabled()) {
  37. logger.debug(" AliDruidCountOptimize sql=" + sql + ", dbType=" + dbType);
  38. }
  39. SqlInfo sqlInfo = SqlInfo.newInstance();
  40. // 调整SQL便于解析
  41. String tempSql = sql.replaceAll("(?i)ORDER[\\s]+BY", "ORDER BY");
  42. int orderByIndex = tempSql.toUpperCase().lastIndexOf("ORDER BY");
  43. sqlInfo.setOrderBy(orderByIndex > -1);
  44. sqlInfo.setSql(PagerUtils.count(sql, dbType));
  45. return sqlInfo;
  46. }
  47. }