2 * ============LICENSE_START=======================================================
3 * ONAP : ccsdk features
4 * ================================================================================
5 * Copyright (C) 2021 highstreet technologies GmbH Intellectual Property.
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.database;
24 import com.fasterxml.jackson.core.JsonProcessingException;
25 import java.lang.reflect.InvocationTargetException;
26 import java.sql.Connection;
27 import java.sql.PreparedStatement;
28 import java.sql.ResultSet;
29 import java.sql.SQLException;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.List;
33 import java.util.Optional;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.SqlDBClient;
36 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.data.rpctypehelper.QueryResult;
37 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.query.DeleteQuery;
38 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.query.InsertQuery;
39 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.query.SelectQuery;
40 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.query.SqlQuery;
41 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.query.UpdateQuery;
42 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.query.UpsertQuery;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.Entity;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.EntityInput;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.Filter;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.FilterBuilder;
47 import org.opendaylight.yangtools.yang.binding.DataObject;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
51 public class SqlDBReaderWriter<T extends DataObject> {
53 private static final Logger LOG = LoggerFactory.getLogger(SqlDBReaderWriter.class);
55 protected final Entity entity;
56 private final Class<T> clazz;
57 protected final SqlDBClient dbService;
58 private final String dbName;
59 protected final String controllerId;
60 protected final String tableName;
62 public SqlDBReaderWriter(SqlDBClient dbService, Entity e, String dbSuffix, Class<T> clazz, String dbName,
63 String controllerId) {
64 this.dbService = dbService;
68 this.tableName = this.entity.getName() + dbSuffix;
69 this.controllerId = controllerId;
72 public long count(List<Filter> filter) throws SQLException {
74 if (filter == null || filter.isEmpty()) {
75 query = String.format("SELECT table_rows FROM `information_schema`.`tables` "
76 + "WHERE `table_schema` = '%s' AND `table_name` = '%s'", this.dbName, this.tableName);
78 query = String.format("SELECT COUNT(`id`) FROM `%s` %s", this.tableName,
79 SqlQuery.getWhereExpression(filter));
81 ResultSet data = this.dbService.read(query);
84 cnt = data.getLong(1);
89 public long count(List<Filter> list, String controllerId) throws SQLException {
91 list = new ArrayList<>();
93 Optional<Filter> cFilter =
94 list.stream().filter(e -> SqlDBMapper.ODLID_DBCOL.equals(e.getProperty())).findFirst();
95 if (!cFilter.isEmpty()) {
96 list.remove(cFilter.get());
98 if (controllerId != null) {
99 list.add(new FilterBuilder().setProperty(SqlDBMapper.ODLID_DBCOL).setFiltervalue(this.controllerId)
102 return this.count(list);
105 public QueryResult<T> getData(EntityInput input) {
106 SelectQuery query = new SelectQuery(this.tableName, input, this.controllerId);
107 LOG.trace("query={}", query.toSql());
109 ResultSet data = this.dbService.read(query.toSql());
110 List<T> mappedData = SqlDBMapper.read(data, clazz);
111 long total = this.count(input.getFilter() != null ? new ArrayList<>(input.getFilter().values()) : null,
113 return new QueryResult<T>(mappedData, query.getPage(), query.getPageSize(), total);
114 } catch (SQLException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
115 | InstantiationException | SecurityException | NoSuchMethodException | JsonProcessingException e) {
116 LOG.warn("problem reading data {}: ", this.entity, e);
118 return QueryResult.createEmpty();
123 public <S extends DataObject> String write(S object, String id) {
125 return this.writeWithoutId(object);
127 InsertQuery<S> query = new InsertQuery<S>(this.entity, object, this.controllerId);
129 boolean success = false;
131 success = this.dbService.write(query.toSql());
132 } catch (SQLException e) {
133 LOG.warn("problem writing data into db: ", e);
136 return success ? id : null;
139 private <S extends DataObject> String writeWithoutId(S object) {
141 InsertQuery<S> query = new InsertQuery<S>(this.entity, object, this.controllerId);
143 return this.dbService.writeAndReturnId(query.toSql());
144 } catch (SQLException e) {
145 LOG.warn("problem writing data into db: ", e);
150 public <S extends DataObject> String update(S object, String id) {
151 UpdateQuery<S> query = new UpdateQuery<S>(this.entity, object, this.controllerId);
153 String insertedId = null;
155 Connection connection = this.dbService.getConnection();
156 PreparedStatement stmt = connection.prepareStatement(query.toSql());
159 int affectedRows = stmt.getUpdateCount();
161 if (affectedRows > 0) {
164 } catch (SQLException e) {
165 LOG.warn("problem writing data into db: ", e);
171 public <S extends DataObject> String updateOrInsert(S object, String id) {
172 UpsertQuery<S> query = new UpsertQuery<S>(this.entity, object, this.controllerId);
174 String insertedId = null;
175 LOG.trace("query={}", query.toSql());
177 Connection connection = this.dbService.getConnection();
178 PreparedStatement stmt = connection.prepareStatement(query.toSql());
181 int affectedRows = stmt.getUpdateCount();
183 if (affectedRows > 0) {
186 } catch (SQLException e) {
187 LOG.warn("problem writing data into db: ", e);
192 public SqlDBReaderWriter<T> setWriteInterface(Class<? extends DataObject> writeInterfaceClazz) {
193 LOG.debug("Set write interface to {}", writeInterfaceClazz);
194 if (writeInterfaceClazz == null) {
195 throw new IllegalArgumentException("Null not allowed here.");
198 // this.writeInterfaceClazz = writeInterfaceClazz;
202 public int remove(List<Filter> filters) {
203 DeleteQuery query = new DeleteQuery(this.entity, filters);
204 int affectedRows = 0;
206 Connection connection = this.dbService.getConnection();
207 PreparedStatement stmt = connection.prepareStatement(query.toSql());
209 affectedRows = stmt.getUpdateCount();
211 } catch (SQLException e) {
212 LOG.warn("problem execute delete query: ", e);
217 public int remove(@Nullable String id) {
218 return this.remove(Arrays.asList(new FilterBuilder().setProperty("id").setFiltervalue(id).build()));
221 public <S extends DataObject> List<S> readAll(Class<S> clazz) {
222 SelectQuery query = new SelectQuery(this.tableName);
224 ResultSet data = this.dbService.read(query.toSql());
225 List<S> mappedData = SqlDBMapper.read(data, clazz);
227 } catch (SQLException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
228 | InstantiationException | SecurityException | NoSuchMethodException | JsonProcessingException e) {
229 LOG.warn("problem reading data {}: ", this.entity, e);
234 public List<String> readAll(String key) {
235 SelectQuery query = new SelectQuery(this.tableName, key, this.controllerId).groupBy(key);
237 ResultSet data = this.dbService.read(query.toSql());
238 List<String> mappedData = SqlDBMapper.read(data, String.class, key);
240 } catch (SQLException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
241 | InstantiationException | SecurityException | NoSuchMethodException | JsonProcessingException e) {
242 LOG.warn("problem reading data {}: ", this.entity, e);