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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.cps.spi.repository;
24 import java.util.HashMap;
25 import java.util.LinkedList;
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;
43 @RequiredArgsConstructor
46 public class FragmentQueryBuilder {
47 private static final AnchorEntity ACROSS_ALL_ANCHORS = null;
50 private EntityManager entityManager;
52 private final JsonObjectMapper jsonObjectMapper;
55 * Create a sql query to retrieve by anchor(id) and cps path.
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
61 public Query getQueryForAnchorAndCpsPath(final AnchorEntity anchorEntity, final CpsPathQuery cpsPathQuery) {
62 return getQueryForDataspaceOrAnchorAndCpsPath(anchorEntity.getDataspace(), anchorEntity, cpsPathQuery);
66 * Create a sql query to retrieve by cps path.
68 * @param dataspaceEntity the dataspace
69 * @param cpsPathQuery the cps path query to be transformed into a sql query
70 * @return a executable query object
72 public Query getQueryForDataspaceAndCpsPath(final DataspaceEntity dataspaceEntity,
73 final CpsPathQuery cpsPathQuery) {
74 return getQueryForDataspaceOrAnchorAndCpsPath(dataspaceEntity, ACROSS_ALL_ANCHORS, cpsPathQuery);
77 private Query getQueryForDataspaceOrAnchorAndCpsPath(final DataspaceEntity dataspaceEntity,
78 final AnchorEntity anchorEntity,
79 final CpsPathQuery cpsPathQuery) {
80 final StringBuilder sqlStringBuilder = new StringBuilder();
81 final Map<String, Object> queryParameters = new HashMap<>();
83 if (anchorEntity == ACROSS_ALL_ANCHORS) {
84 sqlStringBuilder.append("SELECT fragment.* FROM fragment JOIN anchor ON anchor.id = fragment.anchor_id"
85 + " WHERE dataspace_id = :dataspaceId");
86 queryParameters.put("dataspaceId", dataspaceEntity.getId());
88 sqlStringBuilder.append("SELECT * FROM fragment WHERE anchor_id = :anchorId");
89 queryParameters.put("anchorId", anchorEntity.getId());
91 addXpathSearch(cpsPathQuery, sqlStringBuilder, queryParameters);
92 addLeafConditions(cpsPathQuery, sqlStringBuilder);
93 addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
94 addContainsFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
96 final Query query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
97 setQueryParameters(query, queryParameters);
101 private static void addXpathSearch(final CpsPathQuery cpsPathQuery,
102 final StringBuilder sqlStringBuilder,
103 final Map<String, Object> queryParameters) {
104 sqlStringBuilder.append(" AND (xpath LIKE :escapedXpath OR "
105 + "(xpath LIKE :escapedXpath||'[@%]' AND xpath NOT LIKE :escapedXpath||'[@%]/%[@%]'))");
106 if (CpsPathPrefixType.ABSOLUTE.equals(cpsPathQuery.getCpsPathPrefixType())) {
107 queryParameters.put("escapedXpath", EscapeUtils.escapeForSqlLike(cpsPathQuery.getXpathPrefix()));
109 queryParameters.put("escapedXpath", "%/" + EscapeUtils.escapeForSqlLike(cpsPathQuery.getDescendantName()));
113 private static Integer getTextValueAsInt(final CpsPathQuery cpsPathQuery) {
115 return Integer.parseInt(cpsPathQuery.getTextFunctionConditionValue());
116 } catch (final NumberFormatException e) {
121 private void addLeafConditions(final CpsPathQuery cpsPathQuery, final StringBuilder sqlStringBuilder) {
122 if (cpsPathQuery.hasLeafConditions()) {
123 queryLeafConditions(cpsPathQuery, sqlStringBuilder);
127 private void queryLeafConditions(final CpsPathQuery cpsPathQuery, final StringBuilder sqlStringBuilder) {
128 sqlStringBuilder.append(" AND (");
129 final Queue<String> booleanOperatorsQueue = new LinkedList<>(cpsPathQuery.getBooleanOperators());
130 final Queue<String> comparativeOperatorQueue = new LinkedList<>(cpsPathQuery.getComparativeOperators());
131 cpsPathQuery.getLeavesData().entrySet().forEach(entry -> {
132 final String nextComparativeOperator = comparativeOperatorQueue.poll();
133 if (entry.getValue() instanceof Integer) {
134 sqlStringBuilder.append("(attributes ->> ");
135 sqlStringBuilder.append("'").append(entry.getKey()).append("')\\:\\:int");
136 sqlStringBuilder.append(" ").append(nextComparativeOperator).append(" ");
137 sqlStringBuilder.append("'").append(jsonObjectMapper.asJsonString(entry.getValue())).append("'");
139 if ("=".equals(nextComparativeOperator)) {
140 sqlStringBuilder.append(" attributes @> ");
141 sqlStringBuilder.append("'");
142 sqlStringBuilder.append(jsonObjectMapper.asJsonString(entry));
143 sqlStringBuilder.append("'");
145 throw new CpsPathException(" can use only " + nextComparativeOperator + " with integer ");
148 if (!booleanOperatorsQueue.isEmpty()) {
149 sqlStringBuilder.append(" ");
150 sqlStringBuilder.append(booleanOperatorsQueue.poll());
151 sqlStringBuilder.append(" ");
154 sqlStringBuilder.append(")");
157 private static void addTextFunctionCondition(final CpsPathQuery cpsPathQuery,
158 final StringBuilder sqlStringBuilder,
159 final Map<String, Object> queryParameters) {
160 if (cpsPathQuery.hasTextFunctionCondition()) {
161 sqlStringBuilder.append(" AND (");
162 sqlStringBuilder.append("attributes @> jsonb_build_object(:textLeafName, :textValue)");
164 .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValue))");
165 queryParameters.put("textLeafName", cpsPathQuery.getTextFunctionConditionLeafName());
166 queryParameters.put("textValue", cpsPathQuery.getTextFunctionConditionValue());
167 final Integer textValueAsInt = getTextValueAsInt(cpsPathQuery);
168 if (textValueAsInt != null) {
169 sqlStringBuilder.append(" OR attributes @> jsonb_build_object(:textLeafName, :textValueAsInt)");
171 .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValueAsInt))");
172 queryParameters.put("textValueAsInt", textValueAsInt);
174 sqlStringBuilder.append(")");
178 private static void addContainsFunctionCondition(final CpsPathQuery cpsPathQuery,
179 final StringBuilder sqlStringBuilder,
180 final Map<String, Object> queryParameters) {
181 if (cpsPathQuery.hasContainsFunctionCondition()) {
182 sqlStringBuilder.append(" AND attributes ->> :containsLeafName LIKE CONCAT('%',:containsValue,'%') ");
183 queryParameters.put("containsLeafName", cpsPathQuery.getContainsFunctionConditionLeafName());
184 queryParameters.put("containsValue",
185 EscapeUtils.escapeForSqlLike(cpsPathQuery.getContainsFunctionConditionValue()));
189 private static void setQueryParameters(final Query query, final Map<String, Object> queryParameters) {
190 for (final Map.Entry<String, Object> queryParameter : queryParameters.entrySet()) {
191 query.setParameter(queryParameter.getKey(), queryParameter.getValue());