6403a5c1d291f46e1d70ea761961de0db7efda0f
[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.stream.Collectors;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.database.SqlDBMapper;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.EntityInput;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.SortOrder;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.Filter;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.FilterBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.FilterKey;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.Pagination;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.Sortorder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.SortorderKey;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 public class SelectQuery implements SqlQuery {
43
44     private static final Logger LOG = LoggerFactory.getLogger(SelectQuery.class);
45
46     private static final long DEFAULT_PAGESIZE = 20;
47     private static final long DEFAULT_PAGE = 1;
48     private final String tableName;
49     private final List<Filter> filters;
50     private final List<String> sortExpressions;
51     private long page;
52     private long pageSize;
53     private final List<String> fields;
54     private final List<String> groups;
55
56     public SelectQuery(String tableName) {
57         this(tableName, (String)null);
58     }
59     public SelectQuery(String tableName, String controllerId) {
60         this(tableName, Arrays.asList("*"), controllerId);
61     }
62     public SelectQuery(String tableName, List<String> fields, String controllerId) {
63         this.tableName = tableName;
64         this.fields = fields;
65         this.filters = new ArrayList<>();
66         this.sortExpressions = new ArrayList<>();
67         this.groups = new ArrayList<>();
68         this.page = DEFAULT_PAGE;
69         this.pageSize = DEFAULT_PAGESIZE;
70         if (controllerId != null) {
71             this.addFilter(SqlDBMapper.ODLID_DBCOL, controllerId);
72         }
73     }
74
75     public SelectQuery(String tableName, String field, String controllerId) {
76         this(tableName, Arrays.asList(field), controllerId);
77     }
78
79     public SelectQuery(String tableName, EntityInput input) {
80         this(tableName, input, null);
81     }
82
83     public SelectQuery(String tableName, EntityInput input, String controllerId) {
84         this(tableName);
85         Map<FilterKey, Filter> filter = input != null ? input.getFilter() : null;
86         if (filter != null && filter.size() > 0) {
87             for (Filter f : filter.values()) {
88                 this.addFilter(f);
89             }
90         }
91         if (controllerId != null) {
92             this.addFilter(SqlDBMapper.ODLID_DBCOL, controllerId);
93         }
94
95         Map<SortorderKey, Sortorder> so = input != null ? input.getSortorder() : null;
96         if (so != null && !so.isEmpty()) {
97             for (Sortorder s : so.values()) {
98                 this.addSortOrder(s.getProperty(), s.getSortorder() == SortOrder.Ascending ? "ASC" : "DESC");
99             }
100         }
101         Pagination pagination = input != null ? input.getPagination() : null;
102         if (pagination != null) {
103             this.setPagination(pagination.getPage().longValue(), pagination.getSize().longValue());
104         } else {
105             this.setPagination(1, 30);
106         }
107
108     }
109
110     public SelectQuery addFilter(String property, String filtervalue) {
111         this.addFilter(new FilterBuilder().setProperty(property).setFiltervalue(filtervalue).build());
112         return this;
113     }
114
115     private static Filter cleanFilter(Filter filter) {
116         final String sFilter = filter.getFiltervalue();
117         final List<String> sFilters = filter.getFiltervalues();
118         //if only single filter value is set
119         if (sFilter != null && (sFilters == null || sFilter.isEmpty())) {
120             return "*".equals(filter.getFiltervalue()) ? null : filter;
121         } else {
122             List<String> list = new ArrayList<>(filter.getFiltervalues());
123             if (sFilter != null && !sFilter.isEmpty()) {
124                 list.add(sFilter);
125             }
126             if (list.size() == 1 && "*".equals(list.get(0))) {
127                 return null;
128             } ;
129             return new FilterBuilder().setProperty(filter.getProperty()).setFiltervalue(filter.getFiltervalue())
130                     .setFiltervalues(
131                             filter.getFiltervalues().stream().filter(e -> !"*".equals(e)).collect(Collectors.toList()))
132                     .build();
133         }
134     }
135
136     public void addFilter(Filter filter) {
137         Filter tmp = cleanFilter(filter);
138         if (tmp == null) {
139             LOG.debug("ignore unneccessary filter for {}", filter);
140         } else {
141             this.filters.add(tmp);
142         }
143     }
144
145     public void addSortOrder(String col, String order) {
146         this.sortExpressions.add(String.format("`%s` %s", col, order));
147     }
148
149     public void setPagination(long page, long pageSize) {
150         this.page = page;
151         this.pageSize = pageSize;
152     }
153
154     public void setPagination(@Nullable Pagination pagination) {
155         long page = DEFAULT_PAGE;
156         long pageSize = DEFAULT_PAGESIZE;
157         if (pagination != null) {
158             if (pagination.getPage() != null) {
159                 page = pagination.getPage().longValue();
160             }
161             if (pagination.getSize() != null) {
162                 pageSize = pagination.getSize().longValue();
163             }
164         }
165         this.setPagination(page, pageSize);
166
167     }
168
169     @Override
170     public String toSql() {
171         StringBuilder sb = new StringBuilder();
172         if (this.fields.size() == 1 && this.fields.contains("*")) {
173             sb.append(String.format("SELECT * FROM `%s`", this.tableName));
174         } else {
175             sb.append(String.format("SELECT `%s` FROM `%s`", String.join("`,`", this.fields), this.tableName));
176         }
177         sb.append(SqlQuery.getWhereExpression(this.filters));
178         if (this.groups.size() > 0) {
179             sb.append(String.format(" GROUP BY `%s`", String.join("`,`", this.groups)));
180         }
181         if (this.sortExpressions.size() > 0) {
182             sb.append(" ORDER BY " + String.join(",", this.sortExpressions));
183         }
184         sb.append(String.format(" LIMIT %d,%d;", (this.page - 1) * this.pageSize, this.pageSize));
185         return sb.toString();
186     }
187
188     public long getPage() {
189         return this.page;
190     }
191
192     public long getPageSize() {
193         return this.pageSize;
194     }
195
196     public SelectQuery groupBy(String group) {
197         this.groups.add(group);
198         return this;
199     }
200
201 }