AbstractJsqlParser.java 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /**
  2. * Copyright (c) 2011-2020, 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.parser;
  17. import org.apache.ibatis.logging.Log;
  18. import org.apache.ibatis.logging.LogFactory;
  19. import org.apache.ibatis.reflection.MetaObject;
  20. import com.baomidou.mybatisplus.exceptions.MybatisPlusException;
  21. import net.sf.jsqlparser.JSQLParserException;
  22. import net.sf.jsqlparser.parser.CCJSqlParserUtil;
  23. import net.sf.jsqlparser.statement.Statement;
  24. /**
  25. * <p>
  26. * 抽象 SQL 解析类
  27. * </p>
  28. *
  29. * @author hubin
  30. * @Date 2017-06-20
  31. */
  32. public abstract class AbstractJsqlParser implements ISqlParser {
  33. // 日志
  34. protected final Log logger = LogFactory.getLog(this.getClass());
  35. /**
  36. * <p>
  37. * 获取优化 SQL 方法
  38. * </p>
  39. *
  40. * @param metaObject 元对象
  41. * @param sql SQL 语句
  42. * @return SQL 信息
  43. */
  44. @Override
  45. public SqlInfo optimizeSql(MetaObject metaObject, String sql) {
  46. if (this.allowProcess(metaObject)) {
  47. try {
  48. Statement statement = CCJSqlParserUtil.parse(sql);
  49. logger.debug("Original SQL: " + sql);
  50. if (null != statement) {
  51. return this.processParser(statement);
  52. }
  53. } catch (JSQLParserException e) {
  54. throw new MybatisPlusException("Failed to process, please exclude the tableName or statementId.\n Error SQL: " + sql, e);
  55. }
  56. }
  57. return null;
  58. }
  59. /**
  60. * <p>
  61. * 执行 SQL 解析
  62. * </p>
  63. *
  64. * @param statement JsqlParser Statement
  65. * @return
  66. */
  67. public abstract SqlInfo processParser(Statement statement);
  68. /**
  69. * <p>
  70. * 判断是否允许执行<br>
  71. * 例如:逻辑删除只解析 delete , update 操作
  72. * </p>
  73. *
  74. * @param metaObject 元对象
  75. * @return true
  76. */
  77. public boolean allowProcess(MetaObject metaObject) {
  78. return true;
  79. }
  80. }