a4df26baee231372322f4b3b9b255a300c3bda67
[ccsdk/features.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP : ccsdk features
4  * ================================================================================
5  * Copyright (C) 2021 highstreet technologies GmbH Intellectual Property.
6  * All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  *
21  */
22 package org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.query;
23
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Set;
29 import java.util.stream.Collectors;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.database.SqlDBMapper;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.EntityInput;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.SortOrder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.Filter;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.FilterBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.FilterKey;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.Pagination;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.Sortorder;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.SortorderKey;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 public class SelectQuery implements SqlQuery {
44
45     private static final Logger LOG = LoggerFactory.getLogger(SelectQuery.class);
46
47     private static final long DEFAULT_PAGESIZE = 20;
48     private static final long DEFAULT_PAGE = 1;
49     private final String tableName;
50     private final List<Filter> filters;
51     private final List<String> sortExpressions;
52     private long page;
53     private long pageSize;
54     private final List<String> fields;
55     private final List<String> groups;
56
57     public SelectQuery(String tableName) {
58         this(tableName, (String)null);
59     }
60     public SelectQuery(String tableName, String controllerId) {
61         this(tableName, Arrays.asList("*"), controllerId);
62     }
63     public SelectQuery(String tableName, List<String> fields, String controllerId) {
64         this.tableName = tableName;
65         this.fields = fields;
66         this.filters = new ArrayList<>();
67         this.sortExpressions = new ArrayList<>();
68         this.groups = new ArrayList<>();
69         this.page = DEFAULT_PAGE;
70         this.pageSize = DEFAULT_PAGESIZE;
71         if (controllerId != null) {
72             this.addFilter(SqlDBMapper.ODLID_DBCOL, controllerId);
73         }
74     }
75
76     public SelectQuery(String tableName, String field, String controllerId) {
77         this(tableName, Arrays.asList(field), controllerId);
78     }
79
80     public SelectQuery(String tableName, EntityInput input) {
81         this(tableName, input, null);
82     }
83
84     public SelectQuery(String tableName, EntityInput input, String controllerId) {
85         this(tableName);
86         Map<FilterKey, Filter> filter = input != null ? input.getFilter() : null;
87         if (filter != null && filter.size() > 0) {
88             for (Filter f : filter.values()) {
89                 this.addFilter(f);
90             }
91         }
92         if (controllerId != null) {
93             this.addFilter(SqlDBMapper.ODLID_DBCOL, controllerId);
94         }
95
96         Map<SortorderKey, Sortorder> so = input != null ? input.getSortorder() : null;
97         if (so != null && !so.isEmpty()) {
98             for (Sortorder s : so.values()) {
99                 this.addSortOrder(s.getProperty(), s.getSortorder() == SortOrder.Ascending ? "ASC" : "DESC");
100             }
101         }
102         Pagination pagination = input != null ? input.getPagination() : null;
103         if (pagination != null) {
104             this.setPagination(pagination.getPage().longValue(), pagination.getSize().longValue());
105         } else {
106             this.setPagination(1, 30);
107         }
108
109     }
110
111     public SelectQuery addFilter(String property, String filtervalue) {
112         this.addFilter(new FilterBuilder().setProperty(property).setFiltervalue(filtervalue).build());
113         return this;
114     }
115
116     private static Filter cleanFilter(Filter filter) {
117         final String sFilter = filter.getFiltervalue();
118         final Set<String> sFilters = filter.getFiltervalues();
119         //if only single filter value is set
120         if (sFilter != null && (sFilters == null || sFilter.isEmpty())) {
121             return "*".equals(filter.getFiltervalue()) ? null : filter;
122         } else {
123             List<String> list = new ArrayList<>(filter.getFiltervalues());
124             if (sFilter != null && !sFilter.isEmpty()) {
125                 list.add(sFilter);
126             }
127             if (list.size() == 1 && "*".equals(list.get(0))) {
128                 return null;
129             } ;
130             return new FilterBuilder().setProperty(filter.getProperty()).setFiltervalue(filter.getFiltervalue())
131                     .setFiltervalues(
132                             filter.getFiltervalues().stream().filter(e -> !"*".equals(e)).collect(Collectors.toSet()))
133                     .build();
134         }
135     }
136
137     public void addFilter(Filter filter) {
138         Filter tmp = cleanFilter(filter);
139         if (tmp == null) {
140             LOG.debug("ignore unneccessary filter for {}", filter);
141         } else {
142             this.filters.add(tmp);
143         }
144     }
145
146     public void addSortOrder(String col, String order) {
147         this.sortExpressions.add(String.format("`%s` %s", col, order));
148     }
149
150     public void setPagination(long page, long pageSize) {
151         this.page = page;
152         this.pageSize = pageSize;
153     }
154
155     public void setPagination(@Nullable Pagination pagination) {
156         long page = DEFAULT_PAGE;
157         long pageSize = DEFAULT_PAGESIZE;
158         if (pagination != null) {
159             if (pagination.getPage() != null) {
160                 page = pagination.getPage().longValue();
161             }
162             if (pagination.getSize() != null) {
163                 pageSize = pagination.getSize().longValue();
164             }
165         }
166         this.setPagination(page, pageSize);
167
168     }
169
170     @Override
171     public String toSql() {
172         StringBuilder sb = new StringBuilder();
173         if (this.fields.size() == 1 && this.fields.contains("*")) {
174             sb.append(String.format("SELECT * FROM `%s`", this.tableName));
175         } else {
176             sb.append(String.format("SELECT `%s` FROM `%s`", String.join("`,`", this.fields), this.tableName));
177         }
178         sb.append(SqlQuery.getWhereExpression(this.filters));
179         if (this.groups.size() > 0) {
180             sb.append(String.format(" GROUP BY `%s`", String.join("`,`", this.groups)));
181         }
182         if (this.sortExpressions.size() > 0) {
183             sb.append(" ORDER BY " + String.join(",", this.sortExpressions));
184         }
185         sb.append(String.format(" LIMIT %d,%d;", (this.page - 1) * this.pageSize, this.pageSize));
186         return sb.toString();
187     }
188
189     public long getPage() {
190         return this.page;
191     }
192
193     public long getPageSize() {
194         return this.pageSize;
195     }
196
197     public SelectQuery groupBy(String group) {
198         this.groups.add(group);
199         return this;
200     }
201
202 }