View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.shardingsphere.infra.hint;
19  
20  import com.cedarsoftware.util.CaseInsensitiveMap;
21  import com.google.common.base.Splitter;
22  import lombok.AccessLevel;
23  import lombok.NoArgsConstructor;
24  
25  import java.math.BigInteger;
26  import java.util.Collection;
27  import java.util.Collections;
28  import java.util.HashSet;
29  import java.util.List;
30  import java.util.Map;
31  import java.util.Map.Entry;
32  import java.util.Objects;
33  
34  /**
35   * SQL hint utility class.
36   */
37  @NoArgsConstructor(access = AccessLevel.PRIVATE)
38  public final class SQLHintUtils {
39      
40      private static final String SQL_COMMENT_PREFIX = "/*";
41      
42      private static final String SQL_COMMENT_SUFFIX = "*/";
43      
44      private static final String SQL_HINT_SPLIT = ",";
45      
46      private static final String SQL_HINT_VALUE_SPLIT = "=";
47      
48      private static final String SQL_HINT_VALUE_COLLECTION_SPLIT = " ";
49      
50      private static final int SQL_HINT_VALUE_SIZE = 2;
51      
52      /**
53       * Extract SQL hint.
54       *
55       * @param sql SQL
56       * @return hint value context
57       */
58      public static HintValueContext extractHint(final String sql) {
59          if (!containsSQLHint(sql)) {
60              return new HintValueContext();
61          }
62          HintValueContext result = new HintValueContext();
63          int hintKeyValueBeginIndex = getHintKeyValueBeginIndex(sql);
64          String hintKeyValueText = sql.substring(hintKeyValueBeginIndex, sql.indexOf(SQL_COMMENT_SUFFIX, hintKeyValueBeginIndex));
65          Map<String, String> hintKeyValues = getSQLHintKeyValues(hintKeyValueText);
66          if (containsHintKey(hintKeyValues, SQLHintPropertiesKey.DATASOURCE_NAME_KEY)) {
67              result.setDataSourceName(getHintValue(hintKeyValues, SQLHintPropertiesKey.DATASOURCE_NAME_KEY));
68          }
69          if (containsHintKey(hintKeyValues, SQLHintPropertiesKey.WRITE_ROUTE_ONLY_KEY)) {
70              result.setWriteRouteOnly(Boolean.parseBoolean(getHintValue(hintKeyValues, SQLHintPropertiesKey.WRITE_ROUTE_ONLY_KEY)));
71          }
72          if (containsHintKey(hintKeyValues, SQLHintPropertiesKey.SKIP_SQL_REWRITE_KEY)) {
73              result.setSkipSQLRewrite(Boolean.parseBoolean(getHintValue(hintKeyValues, SQLHintPropertiesKey.SKIP_SQL_REWRITE_KEY)));
74          }
75          if (containsHintKey(hintKeyValues, SQLHintPropertiesKey.SKIP_METADATA_VALIDATE_KEY)) {
76              result.setSkipMetadataValidate(Boolean.parseBoolean(getHintValue(hintKeyValues, SQLHintPropertiesKey.SKIP_METADATA_VALIDATE_KEY)));
77          }
78          if (containsHintKey(hintKeyValues, SQLHintPropertiesKey.DISABLE_AUDIT_NAMES_KEY)) {
79              String property = getHintValue(hintKeyValues, SQLHintPropertiesKey.DISABLE_AUDIT_NAMES_KEY);
80              result.getDisableAuditNames().addAll(getSplitterSQLHintValue(property));
81          }
82          if (containsHintKey(hintKeyValues, SQLHintPropertiesKey.SHADOW_KEY)) {
83              result.setShadow(Boolean.parseBoolean(getHintValue(hintKeyValues, SQLHintPropertiesKey.SHADOW_KEY)));
84          }
85          for (Entry<String, String> entry : hintKeyValues.entrySet()) {
86              Object value = convert(entry.getValue());
87              Comparable<?> comparable = value instanceof Comparable ? (Comparable<?>) value : Objects.toString(value);
88              if (containsHintKey(Objects.toString(entry.getKey()), SQLHintPropertiesKey.SHARDING_DATABASE_VALUE_KEY)) {
89                  result.getShardingDatabaseValues().put(Objects.toString(entry.getKey()).toUpperCase(), comparable);
90              }
91              if (containsHintKey(Objects.toString(entry.getKey()), SQLHintPropertiesKey.SHARDING_TABLE_VALUE_KEY)) {
92                  result.getShardingTableValues().put(Objects.toString(entry.getKey()).toUpperCase(), comparable);
93              }
94          }
95          return result;
96      }
97      
98      private static int getHintKeyValueBeginIndex(final String sql) {
99          int tokenBeginIndex = sql.contains(SQLHintTokenType.SQL_START_HINT_TOKEN.getKey()) ? sql.indexOf(SQLHintTokenType.SQL_START_HINT_TOKEN.getKey())
100                 : sql.indexOf(SQLHintTokenType.SQL_START_HINT_TOKEN.getAlias());
101         return sql.indexOf(":", tokenBeginIndex) + 1;
102     }
103     
104     private static boolean containsSQLHint(final String sql) {
105         return (sql.contains(SQLHintTokenType.SQL_START_HINT_TOKEN.getKey()) || sql.contains(SQLHintTokenType.SQL_START_HINT_TOKEN.getAlias()))
106                 && sql.contains(SQL_COMMENT_PREFIX) && sql.contains(SQL_COMMENT_SUFFIX);
107     }
108     
109     private static Map<String, String> getSQLHintKeyValues(final String hintKeyValueText) {
110         Collection<String> sqlHints = Splitter.on(SQL_HINT_SPLIT).trimResults().splitToList(hintKeyValueText.trim());
111         Map<String, String> result = new CaseInsensitiveMap<>(sqlHints.size(), 1F);
112         for (String each : sqlHints) {
113             List<String> hintValues = Splitter.on(SQL_HINT_VALUE_SPLIT).trimResults().splitToList(each);
114             if (SQL_HINT_VALUE_SIZE == hintValues.size()) {
115                 result.put(hintValues.get(0), hintValues.get(1));
116             }
117         }
118         return result;
119     }
120     
121     private static Object convert(final String value) {
122         try {
123             return new BigInteger(value);
124         } catch (final NumberFormatException ignored) {
125             return value;
126         }
127     }
128     
129     private static boolean containsHintKey(final Map<String, String> hintKeyValues, final SQLHintPropertiesKey sqlHintPropsKey) {
130         return hintKeyValues.containsKey(sqlHintPropsKey.getKey()) || hintKeyValues.containsKey(sqlHintPropsKey.getAlias());
131     }
132     
133     private static boolean containsHintKey(final String hintPropKey, final SQLHintPropertiesKey sqlHintPropsKey) {
134         return hintPropKey.contains(sqlHintPropsKey.getKey()) || hintPropKey.contains(sqlHintPropsKey.getAlias());
135     }
136     
137     private static String getHintValue(final Map<String, String> hintKeyValues, final SQLHintPropertiesKey sqlHintPropsKey) {
138         String result = hintKeyValues.get(sqlHintPropsKey.getKey());
139         return null == result ? hintKeyValues.get(sqlHintPropsKey.getAlias()) : result;
140     }
141     
142     private static Collection<String> getSplitterSQLHintValue(final String property) {
143         return property.isEmpty() ? Collections.emptySet() : new HashSet<>(Splitter.on(SQL_HINT_VALUE_COLLECTION_SPLIT).omitEmptyStrings().trimResults().splitToList(property));
144     }
145     
146     /**
147      * Remove SQL hint.
148      *
149      * @param sql SQL
150      * @return SQL after remove hint
151      */
152     public static String removeHint(final String sql) {
153         if (containsSQLHint(sql)) {
154             int hintKeyValueBeginIndex = getHintKeyValueBeginIndex(sql);
155             int sqlHintBeginIndex = sql.substring(0, hintKeyValueBeginIndex).lastIndexOf(SQL_COMMENT_PREFIX, hintKeyValueBeginIndex);
156             int sqlHintEndIndex = sql.indexOf(SQL_COMMENT_SUFFIX, hintKeyValueBeginIndex) + SQL_COMMENT_SUFFIX.length();
157             String removedHintSQL = sql.substring(0, sqlHintBeginIndex) + sql.substring(sqlHintEndIndex);
158             return removedHintSQL.trim();
159         }
160         return sql;
161     }
162 }