Escape SQL LIKE wildcards in queries (CPS-1760 #1)
[cps.git] / cps-ri / src / main / java / org / onap / cps / spi / repository / FragmentQueryBuilder.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2022-2023 Nordix Foundation
4  *  Modifications Copyright (C) 2023 TechMahindra Ltd.
5  *  ================================================================================
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  *  SPDX-License-Identifier: Apache-2.0
19  *  ============LICENSE_END=========================================================
20  */
21
22 package org.onap.cps.spi.repository;
23
24 import java.util.HashMap;
25 import java.util.LinkedList;
26 import java.util.Map;
27 import java.util.Queue;
28 import javax.persistence.EntityManager;
29 import javax.persistence.PersistenceContext;
30 import javax.persistence.Query;
31 import lombok.RequiredArgsConstructor;
32 import lombok.extern.slf4j.Slf4j;
33 import org.onap.cps.cpspath.parser.CpsPathPrefixType;
34 import org.onap.cps.cpspath.parser.CpsPathQuery;
35 import org.onap.cps.spi.entities.AnchorEntity;
36 import org.onap.cps.spi.entities.DataspaceEntity;
37 import org.onap.cps.spi.entities.FragmentEntity;
38 import org.onap.cps.spi.exceptions.CpsPathException;
39 import org.onap.cps.spi.utils.EscapeUtils;
40 import org.onap.cps.utils.JsonObjectMapper;
41 import org.springframework.stereotype.Component;
42
43 @RequiredArgsConstructor
44 @Slf4j
45 @Component
46 public class FragmentQueryBuilder {
47     private static final String REGEX_ABSOLUTE_PATH_PREFIX = "^";
48     private static final String REGEX_DESCENDANT_PATH_PREFIX = "^.*\\/";
49     private static final String REGEX_OPTIONAL_LIST_INDEX_POSTFIX = "(\\[@(?!.*\\[).*?])?$";
50     private static final AnchorEntity ACROSS_ALL_ANCHORS = null;
51
52     @PersistenceContext
53     private EntityManager entityManager;
54
55     private final JsonObjectMapper jsonObjectMapper;
56
57     /**
58      * Create a sql query to retrieve by anchor(id) and cps path.
59      *
60      * @param anchorEntity the anchor
61      * @param cpsPathQuery the cps path query to be transformed into a sql query
62      * @return a executable query object
63      */
64     public Query getQueryForAnchorAndCpsPath(final AnchorEntity anchorEntity, final CpsPathQuery cpsPathQuery) {
65         return getQueryForDataspaceOrAnchorAndCpsPath(anchorEntity.getDataspace(), anchorEntity, cpsPathQuery);
66     }
67
68     /**
69      * Create a sql query to retrieve by cps path.
70      *
71      * @param dataspaceEntity the dataspace
72      * @param cpsPathQuery the cps path query to be transformed into a sql query
73      * @return a executable query object
74      */
75     public Query getQueryForDataspaceAndCpsPath(final DataspaceEntity dataspaceEntity,
76                                                 final CpsPathQuery cpsPathQuery) {
77         return getQueryForDataspaceOrAnchorAndCpsPath(dataspaceEntity, ACROSS_ALL_ANCHORS, cpsPathQuery);
78     }
79
80     private static String getXpathSqlRegex(final CpsPathQuery cpsPathQuery) {
81         final StringBuilder xpathRegexBuilder = getRegexStringBuilderWithPrefix(cpsPathQuery);
82         xpathRegexBuilder.append(REGEX_OPTIONAL_LIST_INDEX_POSTFIX);
83         return xpathRegexBuilder.toString();
84     }
85
86     private Query getQueryForDataspaceOrAnchorAndCpsPath(final DataspaceEntity dataspaceEntity,
87                                                          final AnchorEntity anchorEntity,
88                                                          final CpsPathQuery cpsPathQuery) {
89         final StringBuilder sqlStringBuilder = new StringBuilder();
90         final Map<String, Object> queryParameters = new HashMap<>();
91
92         if (anchorEntity == ACROSS_ALL_ANCHORS) {
93             sqlStringBuilder.append("SELECT fragment.* FROM fragment JOIN anchor ON anchor.id = fragment.anchor_id"
94                 + " WHERE dataspace_id = :dataspaceId");
95             queryParameters.put("dataspaceId", dataspaceEntity.getId());
96         } else {
97             sqlStringBuilder.append("SELECT * FROM fragment WHERE anchor_id = :anchorId");
98             queryParameters.put("anchorId", anchorEntity.getId());
99         }
100         addXpathSearch(cpsPathQuery, sqlStringBuilder, queryParameters);
101         addLeafConditions(cpsPathQuery, sqlStringBuilder);
102         addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
103         addContainsFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
104
105         final Query query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
106         setQueryParameters(query, queryParameters);
107         return query;
108     }
109
110     private static void addXpathSearch(final CpsPathQuery cpsPathQuery,
111                                        final StringBuilder sqlStringBuilder,
112                                        final Map<String, Object> queryParameters) {
113         sqlStringBuilder.append(" AND xpath ~ :xpathRegex");
114         final String xpathRegex = getXpathSqlRegex(cpsPathQuery);
115         queryParameters.put("xpathRegex", xpathRegex);
116     }
117
118     private static StringBuilder getRegexStringBuilderWithPrefix(final CpsPathQuery cpsPathQuery) {
119         final StringBuilder xpathRegexBuilder = new StringBuilder();
120         if (CpsPathPrefixType.ABSOLUTE.equals(cpsPathQuery.getCpsPathPrefixType())) {
121             xpathRegexBuilder.append(REGEX_ABSOLUTE_PATH_PREFIX);
122             xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getXpathPrefix()));
123             return xpathRegexBuilder;
124         }
125         xpathRegexBuilder.append(REGEX_DESCENDANT_PATH_PREFIX);
126         xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getDescendantName()));
127         return xpathRegexBuilder;
128     }
129
130     private static String escapeXpath(final String xpath) {
131         // See https://jira.onap.org/browse/CPS-500 for limitations of this basic escape mechanism
132         return xpath.replace("[@", "\\[@");
133     }
134
135     private static Integer getTextValueAsInt(final CpsPathQuery cpsPathQuery) {
136         try {
137             return Integer.parseInt(cpsPathQuery.getTextFunctionConditionValue());
138         } catch (final NumberFormatException e) {
139             return null;
140         }
141     }
142
143     private void addLeafConditions(final CpsPathQuery cpsPathQuery, final StringBuilder sqlStringBuilder) {
144         if (cpsPathQuery.hasLeafConditions()) {
145             queryLeafConditions(cpsPathQuery, sqlStringBuilder);
146         }
147     }
148
149     private void queryLeafConditions(final CpsPathQuery cpsPathQuery, final StringBuilder sqlStringBuilder) {
150         sqlStringBuilder.append(" AND (");
151         final Queue<String> booleanOperatorsQueue = new LinkedList<>(cpsPathQuery.getBooleanOperators());
152         final Queue<String> comparativeOperatorQueue = new LinkedList<>(cpsPathQuery.getComparativeOperators());
153         cpsPathQuery.getLeavesData().entrySet().forEach(entry -> {
154             final String nextComparativeOperator = comparativeOperatorQueue.poll();
155             if (entry.getValue() instanceof Integer) {
156                 sqlStringBuilder.append("(attributes ->> ");
157                 sqlStringBuilder.append("'").append(entry.getKey()).append("')\\:\\:int");
158                 sqlStringBuilder.append(" ").append(nextComparativeOperator).append(" ");
159                 sqlStringBuilder.append("'").append(jsonObjectMapper.asJsonString(entry.getValue())).append("'");
160             } else {
161                 if ("=".equals(nextComparativeOperator)) {
162                     sqlStringBuilder.append(" attributes @> ");
163                     sqlStringBuilder.append("'");
164                     sqlStringBuilder.append(jsonObjectMapper.asJsonString(entry));
165                     sqlStringBuilder.append("'");
166                 } else {
167                     throw new CpsPathException(" can use only " + nextComparativeOperator + " with integer ");
168                 }
169             }
170             if (!booleanOperatorsQueue.isEmpty()) {
171                 sqlStringBuilder.append(" ");
172                 sqlStringBuilder.append(booleanOperatorsQueue.poll());
173                 sqlStringBuilder.append(" ");
174             }
175         });
176         sqlStringBuilder.append(")");
177     }
178
179     private static void addTextFunctionCondition(final CpsPathQuery cpsPathQuery,
180                                                  final StringBuilder sqlStringBuilder,
181                                                  final Map<String, Object> queryParameters) {
182         if (cpsPathQuery.hasTextFunctionCondition()) {
183             sqlStringBuilder.append(" AND (");
184             sqlStringBuilder.append("attributes @> jsonb_build_object(:textLeafName, :textValue)");
185             sqlStringBuilder
186                 .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValue))");
187             queryParameters.put("textLeafName", cpsPathQuery.getTextFunctionConditionLeafName());
188             queryParameters.put("textValue", cpsPathQuery.getTextFunctionConditionValue());
189             final Integer textValueAsInt = getTextValueAsInt(cpsPathQuery);
190             if (textValueAsInt != null) {
191                 sqlStringBuilder.append(" OR attributes @> jsonb_build_object(:textLeafName, :textValueAsInt)");
192                 sqlStringBuilder
193                     .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValueAsInt))");
194                 queryParameters.put("textValueAsInt", textValueAsInt);
195             }
196             sqlStringBuilder.append(")");
197         }
198     }
199
200     private static void addContainsFunctionCondition(final CpsPathQuery cpsPathQuery,
201                                                      final StringBuilder sqlStringBuilder,
202                                                      final Map<String, Object> queryParameters) {
203         if (cpsPathQuery.hasContainsFunctionCondition()) {
204             sqlStringBuilder.append(" AND attributes ->> :containsLeafName LIKE CONCAT('%',:containsValue,'%') ");
205             queryParameters.put("containsLeafName", cpsPathQuery.getContainsFunctionConditionLeafName());
206             queryParameters.put("containsValue",
207                     EscapeUtils.escapeForSqlLike(cpsPathQuery.getContainsFunctionConditionValue()));
208         }
209     }
210
211     private static void setQueryParameters(final Query query, final Map<String, Object> queryParameters) {
212         for (final Map.Entry<String, Object> queryParameter : queryParameters.entrySet()) {
213             query.setParameter(queryParameter.getKey(), queryParameter.getValue());
214         }
215     }
216
217 }