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              Comparable<?> value = convert(entry.getValue());
87              if (containsHintKey(Objects.toString(entry.getKey()), SQLHintPropertiesKey.SHARDING_DATABASE_VALUE_KEY)) {
88                  result.getShardingDatabaseValues().put(Objects.toString(entry.getKey()).toUpperCase(), value);
89              }
90              if (containsHintKey(Objects.toString(entry.getKey()), SQLHintPropertiesKey.SHARDING_TABLE_VALUE_KEY)) {
91                  result.getShardingTableValues().put(Objects.toString(entry.getKey()).toUpperCase(), value);
92              }
93          }
94          return result;
95      }
96      
97      private static int getHintKeyValueBeginIndex(final String sql) {
98          int tokenBeginIndex = sql.contains(SQLHintTokenType.SQL_START_HINT_TOKEN.getKey()) ? sql.indexOf(SQLHintTokenType.SQL_START_HINT_TOKEN.getKey())
99                  : sql.indexOf(SQLHintTokenType.SQL_START_HINT_TOKEN.getAlias());
100         return sql.indexOf(":", tokenBeginIndex) + 1;
101     }
102     
103     private static boolean containsSQLHint(final String sql) {
104         return (sql.contains(SQLHintTokenType.SQL_START_HINT_TOKEN.getKey()) || sql.contains(SQLHintTokenType.SQL_START_HINT_TOKEN.getAlias()))
105                 && sql.contains(SQL_COMMENT_PREFIX) && sql.contains(SQL_COMMENT_SUFFIX);
106     }
107     
108     private static Map<String, String> getSQLHintKeyValues(final String hintKeyValueText) {
109         Collection<String> sqlHints = Splitter.on(SQL_HINT_SPLIT).trimResults().splitToList(hintKeyValueText.trim());
110         Map<String, String> result = new CaseInsensitiveMap<>(sqlHints.size(), 1F);
111         for (String each : sqlHints) {
112             List<String> hintValues = Splitter.on(SQL_HINT_VALUE_SPLIT).trimResults().splitToList(each);
113             if (SQL_HINT_VALUE_SIZE == hintValues.size()) {
114                 result.put(hintValues.get(0), hintValues.get(1));
115             }
116         }
117         return result;
118     }
119     
120     private static Comparable<?> convert(final String value) {
121         try {
122             return new BigInteger(value);
123         } catch (final NumberFormatException ignored) {
124             return value;
125         }
126     }
127     
128     private static boolean containsHintKey(final Map<String, String> hintKeyValues, final SQLHintPropertiesKey sqlHintPropsKey) {
129         return hintKeyValues.containsKey(sqlHintPropsKey.getKey()) || hintKeyValues.containsKey(sqlHintPropsKey.getAlias());
130     }
131     
132     private static boolean containsHintKey(final String hintPropKey, final SQLHintPropertiesKey sqlHintPropsKey) {
133         return hintPropKey.contains(sqlHintPropsKey.getKey()) || hintPropKey.contains(sqlHintPropsKey.getAlias());
134     }
135     
136     private static String getHintValue(final Map<String, String> hintKeyValues, final SQLHintPropertiesKey sqlHintPropsKey) {
137         String result = hintKeyValues.get(sqlHintPropsKey.getKey());
138         return null == result ? hintKeyValues.get(sqlHintPropsKey.getAlias()) : result;
139     }
140     
141     private static Collection<String> getSplitterSQLHintValue(final String property) {
142         return property.isEmpty() ? Collections.emptySet() : new HashSet<>(Splitter.on(SQL_HINT_VALUE_COLLECTION_SPLIT).omitEmptyStrings().trimResults().splitToList(property));
143     }
144     
145     /**
146      * Remove SQL hint.
147      *
148      * @param sql SQL
149      * @return SQL after remove hint
150      */
151     public static String removeHint(final String sql) {
152         if (containsSQLHint(sql)) {
153             int hintKeyValueBeginIndex = getHintKeyValueBeginIndex(sql);
154             int sqlHintBeginIndex = sql.substring(0, hintKeyValueBeginIndex).lastIndexOf(SQL_COMMENT_PREFIX, hintKeyValueBeginIndex);
155             int sqlHintEndIndex = sql.indexOf(SQL_COMMENT_SUFFIX, hintKeyValueBeginIndex) + SQL_COMMENT_SUFFIX.length();
156             String removedHintSQL = sql.substring(0, sqlHintBeginIndex) + sql.substring(sqlHintEndIndex);
157             return removedHintSQL.trim();
158         }
159         return sql;
160     }
161 }