Merge "Cm Subscription: Predicates optional now"
[cps.git] / cps-ri / src / main / java / org / onap / cps / spi / repository / FragmentQueryBuilder.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2022-2024 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 jakarta.persistence.EntityManager;
25 import jakarta.persistence.PersistenceContext;
26 import jakarta.persistence.Query;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.LinkedList;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Queue;
33 import lombok.RequiredArgsConstructor;
34 import lombok.extern.slf4j.Slf4j;
35 import org.onap.cps.cpspath.parser.CpsPathPrefixType;
36 import org.onap.cps.cpspath.parser.CpsPathQuery;
37 import org.onap.cps.spi.PaginationOption;
38 import org.onap.cps.spi.entities.AnchorEntity;
39 import org.onap.cps.spi.entities.DataspaceEntity;
40 import org.onap.cps.spi.entities.FragmentEntity;
41 import org.onap.cps.spi.exceptions.CpsPathException;
42 import org.onap.cps.spi.utils.EscapeUtils;
43 import org.springframework.stereotype.Component;
44
45 @RequiredArgsConstructor
46 @Slf4j
47 @Component
48 public class FragmentQueryBuilder {
49     private static final AnchorEntity ACROSS_ALL_ANCHORS = null;
50
51     @PersistenceContext
52     private EntityManager entityManager;
53
54     /**
55      * Create a sql query to retrieve by anchor(id) and cps path.
56      *
57      * @param anchorEntity the anchor
58      * @param cpsPathQuery the cps path query to be transformed into a sql query
59      * @return a executable query object
60      */
61     public Query getQueryForAnchorAndCpsPath(final AnchorEntity anchorEntity, final CpsPathQuery cpsPathQuery) {
62         return getQueryForDataspaceOrAnchorAndCpsPath(anchorEntity.getDataspace(),
63                 anchorEntity, cpsPathQuery, Collections.emptyList());
64     }
65
66     /**
67      * Create a sql query to retrieve by cps path.
68      *
69      * @param dataspaceEntity the dataspace
70      * @param cpsPathQuery the cps path query to be transformed into a sql query
71      * @return a executable query object
72      */
73     public Query getQueryForDataspaceAndCpsPath(final DataspaceEntity dataspaceEntity,
74                                                 final CpsPathQuery cpsPathQuery,
75                                                 final List<Long> anchorIdsForPagination) {
76         return getQueryForDataspaceOrAnchorAndCpsPath(dataspaceEntity, ACROSS_ALL_ANCHORS,
77                 cpsPathQuery, anchorIdsForPagination);
78     }
79
80     /**
81      * Get query for dataspace, cps path, page index and page size.
82      * @param dataspaceEntity data space entity
83      * @param cpsPathQuery cps path query
84      * @param paginationOption pagination option
85      * @return query for given dataspace, cps path and pagination parameters
86      */
87     public Query getQueryForAnchorIdsForPagination(final DataspaceEntity dataspaceEntity,
88                                                    final CpsPathQuery cpsPathQuery,
89                                                    final PaginationOption paginationOption) {
90         final StringBuilder sqlStringBuilder = new StringBuilder();
91         final Map<String, Object> queryParameters = new HashMap<>();
92         sqlStringBuilder.append("SELECT distinct(fragment.anchor_id) FROM fragment "
93                 + "JOIN anchor ON anchor.id = fragment.anchor_id WHERE dataspace_id = :dataspaceId");
94         queryParameters.put("dataspaceId", dataspaceEntity.getId());
95         addAbsoluteParentXpathSearchCondition(cpsPathQuery, sqlStringBuilder, queryParameters, ACROSS_ALL_ANCHORS);
96         addXpathSearchCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
97         addLeafConditions(cpsPathQuery, sqlStringBuilder);
98         addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
99         addContainsFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
100         if (PaginationOption.NO_PAGINATION != paginationOption) {
101             sqlStringBuilder.append(" ORDER BY fragment.anchor_id");
102             addPaginationCondition(sqlStringBuilder, queryParameters, paginationOption);
103         }
104
105         final Query query = entityManager.createNativeQuery(sqlStringBuilder.toString());
106         setQueryParameters(query, queryParameters);
107         return query;
108     }
109
110     private Query getQueryForDataspaceOrAnchorAndCpsPath(final DataspaceEntity dataspaceEntity,
111                                                          final AnchorEntity anchorEntity,
112                                                          final CpsPathQuery cpsPathQuery,
113                                                          final List<Long> anchorIdsForPagination) {
114         final StringBuilder sqlStringBuilder = new StringBuilder();
115         final Map<String, Object> queryParameters = new HashMap<>();
116
117         if (anchorEntity == ACROSS_ALL_ANCHORS) {
118             sqlStringBuilder.append("SELECT fragment.* FROM fragment JOIN anchor ON anchor.id = fragment.anchor_id"
119                 + " WHERE dataspace_id = :dataspaceId");
120             queryParameters.put("dataspaceId", dataspaceEntity.getId());
121             if (!anchorIdsForPagination.isEmpty()) {
122                 sqlStringBuilder.append(" AND anchor_id IN (:anchorIdsForPagination)");
123                 queryParameters.put("anchorIdsForPagination", anchorIdsForPagination);
124             }
125         } else {
126             sqlStringBuilder.append("SELECT * FROM fragment WHERE anchor_id = :anchorId");
127             queryParameters.put("anchorId", anchorEntity.getId());
128         }
129         addAbsoluteParentXpathSearchCondition(cpsPathQuery, sqlStringBuilder, queryParameters, anchorEntity);
130         addXpathSearchCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
131         addLeafConditions(cpsPathQuery, sqlStringBuilder);
132         addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
133         addContainsFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
134
135         final Query query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
136         setQueryParameters(query, queryParameters);
137         return query;
138     }
139
140     private static void addXpathSearchCondition(final CpsPathQuery cpsPathQuery,
141                                                 final StringBuilder sqlStringBuilder,
142                                                 final Map<String, Object> queryParameters) {
143         sqlStringBuilder.append(" AND (xpath LIKE :escapedXpath OR "
144                 + "(xpath LIKE :escapedXpath||'[@%]' AND xpath NOT LIKE :escapedXpath||'[@%]/%[@%]'))");
145         if (CpsPathPrefixType.ABSOLUTE.equals(cpsPathQuery.getCpsPathPrefixType())) {
146             queryParameters.put("escapedXpath", EscapeUtils.escapeForSqlLike(cpsPathQuery.getXpathPrefix()));
147         } else {
148             queryParameters.put("escapedXpath", "%/" + EscapeUtils.escapeForSqlLike(cpsPathQuery.getDescendantName()));
149         }
150     }
151
152     private static void addAbsoluteParentXpathSearchCondition(final CpsPathQuery cpsPathQuery,
153                                                               final StringBuilder sqlStringBuilder,
154                                                               final Map<String, Object> queryParameters,
155                                                               final AnchorEntity anchorEntity) {
156         if (CpsPathPrefixType.ABSOLUTE.equals(cpsPathQuery.getCpsPathPrefixType())) {
157             if (cpsPathQuery.getNormalizedParentPath().isEmpty()) {
158                 sqlStringBuilder.append(" AND parent_id IS NULL");
159             } else {
160                 if (anchorEntity == ACROSS_ALL_ANCHORS) {
161                     sqlStringBuilder.append(" AND parent_id IN (SELECT id FROM fragment WHERE xpath = :parentXpath)");
162                 } else {
163                     sqlStringBuilder.append(" AND parent_id = (SELECT id FROM fragment WHERE xpath = :parentXpath"
164                             + " AND anchor_id = :anchorId)");
165                 }
166                 queryParameters.put("parentXpath", cpsPathQuery.getNormalizedParentPath());
167             }
168         }
169     }
170
171     private static void addPaginationCondition(final StringBuilder sqlStringBuilder,
172                                                final Map<String, Object> queryParameters,
173                                                final PaginationOption paginationOption) {
174         final Integer offset = (paginationOption.getPageIndex() - 1) * paginationOption.getPageSize();
175         sqlStringBuilder.append(" LIMIT :pageSize OFFSET :offset");
176         queryParameters.put("pageSize", paginationOption.getPageSize());
177         queryParameters.put("offset", offset);
178     }
179
180     private static Integer getTextValueAsInt(final CpsPathQuery cpsPathQuery) {
181         try {
182             return Integer.parseInt(cpsPathQuery.getTextFunctionConditionValue());
183         } catch (final NumberFormatException e) {
184             return null;
185         }
186     }
187
188     private void addLeafConditions(final CpsPathQuery cpsPathQuery, final StringBuilder sqlStringBuilder) {
189         if (cpsPathQuery.hasLeafConditions()) {
190             queryLeafConditions(cpsPathQuery, sqlStringBuilder);
191         }
192     }
193
194     private void queryLeafConditions(final CpsPathQuery cpsPathQuery, final StringBuilder sqlStringBuilder) {
195         sqlStringBuilder.append(" AND (");
196         final Queue<String> booleanOperatorsQueue = new LinkedList<>(cpsPathQuery.getBooleanOperators());
197         final Queue<String> comparativeOperatorQueue = new LinkedList<>(cpsPathQuery.getComparativeOperators());
198         cpsPathQuery.getLeavesData().forEach(leaf -> {
199             final String nextComparativeOperator = comparativeOperatorQueue.poll();
200             if (leaf.getValue() instanceof Integer) {
201                 sqlStringBuilder.append("(attributes ->> '").append(leaf.getName()).append("')\\:\\:int");
202                 sqlStringBuilder.append(nextComparativeOperator);
203                 sqlStringBuilder.append(leaf.getValue());
204             } else {
205                 if ("=".equals(nextComparativeOperator)) {
206                     final String leafValueAsText = leaf.getValue().toString();
207                     sqlStringBuilder.append("attributes ->> '").append(leaf.getName()).append("'");
208                     sqlStringBuilder.append(" = '");
209                     sqlStringBuilder.append(EscapeUtils.escapeForSqlStringLiteral(leafValueAsText));
210                     sqlStringBuilder.append("'");
211                 } else {
212                     throw new CpsPathException(" can use only " + nextComparativeOperator + " with integer ");
213                 }
214             }
215             if (!booleanOperatorsQueue.isEmpty()) {
216                 sqlStringBuilder.append(" ");
217                 sqlStringBuilder.append(booleanOperatorsQueue.poll());
218                 sqlStringBuilder.append(" ");
219             }
220         });
221         sqlStringBuilder.append(")");
222     }
223
224     private static void addTextFunctionCondition(final CpsPathQuery cpsPathQuery,
225                                                  final StringBuilder sqlStringBuilder,
226                                                  final Map<String, Object> queryParameters) {
227         if (cpsPathQuery.hasTextFunctionCondition()) {
228             sqlStringBuilder.append(" AND (");
229             sqlStringBuilder.append("attributes @> jsonb_build_object(:textLeafName, :textValue)");
230             sqlStringBuilder
231                 .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValue))");
232             queryParameters.put("textLeafName", cpsPathQuery.getTextFunctionConditionLeafName());
233             queryParameters.put("textValue", cpsPathQuery.getTextFunctionConditionValue());
234             final Integer textValueAsInt = getTextValueAsInt(cpsPathQuery);
235             if (textValueAsInt != null) {
236                 sqlStringBuilder.append(" OR attributes @> jsonb_build_object(:textLeafName, :textValueAsInt)");
237                 sqlStringBuilder
238                     .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValueAsInt))");
239                 queryParameters.put("textValueAsInt", textValueAsInt);
240             }
241             sqlStringBuilder.append(")");
242         }
243     }
244
245     private static void addContainsFunctionCondition(final CpsPathQuery cpsPathQuery,
246                                                      final StringBuilder sqlStringBuilder,
247                                                      final Map<String, Object> queryParameters) {
248         if (cpsPathQuery.hasContainsFunctionCondition()) {
249             sqlStringBuilder.append(" AND attributes ->> :containsLeafName LIKE CONCAT('%',:containsValue,'%') ");
250             queryParameters.put("containsLeafName", cpsPathQuery.getContainsFunctionConditionLeafName());
251             queryParameters.put("containsValue",
252                     EscapeUtils.escapeForSqlLike(cpsPathQuery.getContainsFunctionConditionValue()));
253         }
254     }
255
256     private static void setQueryParameters(final Query query, final Map<String, Object> queryParameters) {
257         for (final Map.Entry<String, Object> queryParameter : queryParameters.entrySet()) {
258             query.setParameter(queryParameter.getKey(), queryParameter.getValue());
259         }
260     }
261
262 }