Add <,> operators support to cps-path
[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.utils.JsonObjectMapper;
40 import org.springframework.stereotype.Component;
41
42 @RequiredArgsConstructor
43 @Slf4j
44 @Component
45 public class FragmentQueryBuilder {
46     private static final String REGEX_ABSOLUTE_PATH_PREFIX = "^";
47     private static final String REGEX_DESCENDANT_PATH_PREFIX = "^.*\\/";
48     private static final String REGEX_OPTIONAL_LIST_INDEX_POSTFIX = "(\\[@(?!.*\\[).*?])?$";
49     private static final AnchorEntity ACROSS_ALL_ANCHORS = null;
50
51     @PersistenceContext
52     private EntityManager entityManager;
53
54     private final JsonObjectMapper jsonObjectMapper;
55
56     /**
57      * Create a sql query to retrieve by anchor(id) and cps path.
58      *
59      * @param anchorEntity the anchor
60      * @param cpsPathQuery the cps path query to be transformed into a sql query
61      * @return a executable query object
62      */
63     public Query getQueryForAnchorAndCpsPath(final AnchorEntity anchorEntity, final CpsPathQuery cpsPathQuery) {
64         return getQueryForDataspaceOrAnchorAndCpsPath(anchorEntity.getDataspace(), anchorEntity, cpsPathQuery);
65     }
66
67     /**
68      * Create a sql query to retrieve by cps path.
69      *
70      * @param dataspaceEntity the dataspace
71      * @param cpsPathQuery the cps path query to be transformed into a sql query
72      * @return a executable query object
73      */
74     public Query getQueryForDataspaceAndCpsPath(final DataspaceEntity dataspaceEntity,
75                                                 final CpsPathQuery cpsPathQuery) {
76         return getQueryForDataspaceOrAnchorAndCpsPath(dataspaceEntity, ACROSS_ALL_ANCHORS, cpsPathQuery);
77     }
78
79     private static String getXpathSqlRegex(final CpsPathQuery cpsPathQuery) {
80         final StringBuilder xpathRegexBuilder = getRegexStringBuilderWithPrefix(cpsPathQuery);
81         xpathRegexBuilder.append(REGEX_OPTIONAL_LIST_INDEX_POSTFIX);
82         return xpathRegexBuilder.toString();
83     }
84
85     private Query getQueryForDataspaceOrAnchorAndCpsPath(final DataspaceEntity dataspaceEntity,
86                                                          final AnchorEntity anchorEntity,
87                                                          final CpsPathQuery cpsPathQuery) {
88         final StringBuilder sqlStringBuilder = new StringBuilder();
89         final Map<String, Object> queryParameters = new HashMap<>();
90
91         if (anchorEntity == ACROSS_ALL_ANCHORS) {
92             sqlStringBuilder.append("SELECT fragment.* FROM fragment JOIN anchor ON anchor.id = fragment.anchor_id"
93                 + " WHERE dataspace_id = :dataspaceId");
94             queryParameters.put("dataspaceId", dataspaceEntity.getId());
95         } else {
96             sqlStringBuilder.append("SELECT * FROM fragment WHERE anchor_id = :anchorId");
97             queryParameters.put("anchorId", anchorEntity.getId());
98         }
99         addXpathSearch(cpsPathQuery, sqlStringBuilder, queryParameters);
100         addLeafConditions(cpsPathQuery, sqlStringBuilder);
101         addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
102         addContainsFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
103
104         final Query query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
105         setQueryParameters(query, queryParameters);
106         return query;
107     }
108
109     private static void addXpathSearch(final CpsPathQuery cpsPathQuery,
110                                        final StringBuilder sqlStringBuilder,
111                                        final Map<String, Object> queryParameters) {
112         sqlStringBuilder.append(" AND xpath ~ :xpathRegex");
113         final String xpathRegex = getXpathSqlRegex(cpsPathQuery);
114         queryParameters.put("xpathRegex", xpathRegex);
115     }
116
117     private static StringBuilder getRegexStringBuilderWithPrefix(final CpsPathQuery cpsPathQuery) {
118         final StringBuilder xpathRegexBuilder = new StringBuilder();
119         if (CpsPathPrefixType.ABSOLUTE.equals(cpsPathQuery.getCpsPathPrefixType())) {
120             xpathRegexBuilder.append(REGEX_ABSOLUTE_PATH_PREFIX);
121             xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getXpathPrefix()));
122             return xpathRegexBuilder;
123         }
124         xpathRegexBuilder.append(REGEX_DESCENDANT_PATH_PREFIX);
125         xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getDescendantName()));
126         return xpathRegexBuilder;
127     }
128
129     private static String escapeXpath(final String xpath) {
130         // See https://jira.onap.org/browse/CPS-500 for limitations of this basic escape mechanism
131         return xpath.replace("[@", "\\[@");
132     }
133
134     private static Integer getTextValueAsInt(final CpsPathQuery cpsPathQuery) {
135         try {
136             return Integer.parseInt(cpsPathQuery.getTextFunctionConditionValue());
137         } catch (final NumberFormatException e) {
138             return null;
139         }
140     }
141
142     private void addLeafConditions(final CpsPathQuery cpsPathQuery, final StringBuilder sqlStringBuilder) {
143         if (cpsPathQuery.hasLeafConditions()) {
144             queryLeafConditions(cpsPathQuery, sqlStringBuilder);
145         }
146     }
147
148     private void queryLeafConditions(final CpsPathQuery cpsPathQuery, final StringBuilder sqlStringBuilder) {
149         sqlStringBuilder.append(" AND (");
150         final Queue<String> booleanOperatorsQueue = new LinkedList<>(cpsPathQuery.getBooleanOperators());
151         final Queue<String> comparativeOperatorQueue = new LinkedList<>(cpsPathQuery.getComparativeOperators());
152         cpsPathQuery.getLeavesData().entrySet().forEach(entry -> {
153             final String nextComparativeOperator = comparativeOperatorQueue.poll();
154             if (entry.getValue() instanceof Integer) {
155                 sqlStringBuilder.append("(attributes ->> ");
156                 sqlStringBuilder.append("'").append(entry.getKey()).append("')\\:\\:int");
157                 sqlStringBuilder.append(" ").append(nextComparativeOperator).append(" ");
158                 sqlStringBuilder.append("'").append(jsonObjectMapper.asJsonString(entry.getValue())).append("'");
159             } else {
160                 if ("=".equals(nextComparativeOperator)) {
161                     sqlStringBuilder.append(" attributes @> ");
162                     sqlStringBuilder.append("'");
163                     sqlStringBuilder.append(jsonObjectMapper.asJsonString(entry));
164                     sqlStringBuilder.append("'");
165                 } else {
166                     throw new CpsPathException(" can use only " + nextComparativeOperator + " with integer ");
167                 }
168             }
169             if (!booleanOperatorsQueue.isEmpty()) {
170                 sqlStringBuilder.append(" ");
171                 sqlStringBuilder.append(booleanOperatorsQueue.poll());
172                 sqlStringBuilder.append(" ");
173             }
174         });
175         sqlStringBuilder.append(")");
176     }
177
178     private static void addTextFunctionCondition(final CpsPathQuery cpsPathQuery,
179                                                  final StringBuilder sqlStringBuilder,
180                                                  final Map<String, Object> queryParameters) {
181         if (cpsPathQuery.hasTextFunctionCondition()) {
182             sqlStringBuilder.append(" AND (");
183             sqlStringBuilder.append("attributes @> jsonb_build_object(:textLeafName, :textValue)");
184             sqlStringBuilder
185                 .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValue))");
186             queryParameters.put("textLeafName", cpsPathQuery.getTextFunctionConditionLeafName());
187             queryParameters.put("textValue", cpsPathQuery.getTextFunctionConditionValue());
188             final Integer textValueAsInt = getTextValueAsInt(cpsPathQuery);
189             if (textValueAsInt != null) {
190                 sqlStringBuilder.append(" OR attributes @> jsonb_build_object(:textLeafName, :textValueAsInt)");
191                 sqlStringBuilder
192                     .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValueAsInt))");
193                 queryParameters.put("textValueAsInt", textValueAsInt);
194             }
195             sqlStringBuilder.append(")");
196         }
197     }
198
199     private static void addContainsFunctionCondition(final CpsPathQuery cpsPathQuery,
200                                                      final StringBuilder sqlStringBuilder,
201                                                      final Map<String, Object> queryParameters) {
202         if (cpsPathQuery.hasContainsFunctionCondition()) {
203             sqlStringBuilder.append(" AND attributes ->> :containsLeafName LIKE CONCAT('%',:containsValue,'%') ");
204             queryParameters.put("containsLeafName", cpsPathQuery.getContainsFunctionConditionLeafName());
205             queryParameters.put("containsValue", cpsPathQuery.getContainsFunctionConditionValue());
206         }
207     }
208
209     private static void setQueryParameters(final Query query, final Map<String, Object> queryParameters) {
210         for (final Map.Entry<String, Object> queryParameter : queryParameters.entrySet()) {
211             query.setParameter(queryParameter.getKey(), queryParameter.getValue());
212         }
213     }
214
215 }