f16eadd019ef7917408bd9ad8cab721566684fb6
[ccsdk/features.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP : ccsdk features
4  * ================================================================================
5  * Copyright (C) 2020 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;
23
24 import java.sql.Connection;
25 import java.sql.DriverManager;
26 import java.sql.PreparedStatement;
27 import java.sql.ResultSet;
28 import java.sql.SQLException;
29 import java.sql.Statement;
30 import java.text.ParseException;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
33 import org.onap.ccsdk.features.sdnr.wt.common.database.Portstatus;
34 import org.onap.ccsdk.features.sdnr.wt.common.database.data.AliasesEntry;
35 import org.onap.ccsdk.features.sdnr.wt.common.database.data.AliasesEntryList;
36 import org.onap.ccsdk.features.sdnr.wt.common.database.data.DatabaseVersion;
37 import org.onap.ccsdk.features.sdnr.wt.common.database.data.IndicesEntryList;
38 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.data.SqlDBIndicesEntry;
39 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.database.SqlDBMapper;
40 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.database.SqlDBMapper.UnableToMapClassException;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.Entity;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 public class SqlDBClient {
46
47     private static final Logger LOG = LoggerFactory.getLogger(SqlDBClient.class);
48
49     // matches:
50     //  1=>type, e.g. mariadb, mysql, ...
51     //  2=>host
52     //  3=>port
53     //  4=>dbname
54     private static final String DBURL_REGEX = "^jdbc:([^:]+):\\/\\/([^:]+):([0-9]+)\\/(.+)$";
55     private static final Pattern DBURL_PATTERN = Pattern.compile(DBURL_REGEX);
56     private static final String DBVERSION_REGEX = "^([\\d]+\\.[\\d]+\\.[\\d]+)";
57     private static final Pattern DBVERSION_PATTERN = Pattern.compile(DBVERSION_REGEX);
58     private static final String SELECT_VERSION_QUERY = "SELECT @@version as version";
59
60     private static final String DBNAME_DEFAULT = "sdnrdb";
61     private final String dbConnectionString;
62     private final String dbName;
63     private final String dbHost;
64     private final int dbPort;
65
66     /**
67      *
68      * @param dbUrl e.g. jdbc:mysql://sdnrdb:3306/sdnrdb
69      * @param username
70      * @param password
71      */
72     public SqlDBClient(String dbUrl, String username, String password) throws IllegalArgumentException {
73         this.dbConnectionString = String.format("%s?user=%s&password=%s", dbUrl, username, password);
74         final Matcher matcher = DBURL_PATTERN.matcher(dbUrl);
75         if(!matcher.find()) {
76             throw new IllegalArgumentException("unable to parse databaseUrl "+dbUrl);
77         }
78         this.dbHost = matcher.group(2);
79         this.dbPort = Integer.parseInt(matcher.group(3));
80         this.dbName = matcher.group(4);
81     }
82
83     public AliasesEntryList readViews() {
84         return this.readViews(DBNAME_DEFAULT);
85     }
86
87     public AliasesEntryList readViews(String dbName) {
88         AliasesEntryList list = new AliasesEntryList();
89         final String query = "SELECT v.`TABLE_NAME` AS vn, t.`TABLE_NAME` AS tn\n"
90                 + "FROM `information_schema`.`TABLES` AS v\n"
91                 + "LEFT JOIN `information_schema`.`TABLES` AS t ON t.`TABLE_NAME` LIKE CONCAT(v.`TABLE_NAME`,'%')"
92                 + " AND t.`TABLE_TYPE`='BASE TABLE'\n" + "WHERE v.`TABLE_SCHEMA`='" + dbName
93                 + "' AND v.`TABLE_TYPE`='VIEW'";
94         ResultSet data = this.read(query);
95         try {
96             while (data.next()) {
97                 list.add(new AliasesEntry(data.getString(2), data.getString(1)));
98             }
99         } catch (SQLException e) {
100             LOG.warn("problem reading views: ", e);
101         }
102         return list;
103     }
104
105     public IndicesEntryList readTables() {
106         final String query = "SHOW FULL TABLES WHERE `Table_type` = 'BASE TABLE'";
107         IndicesEntryList list = new IndicesEntryList();
108         ResultSet data = this.read(query);
109         try {
110             while (data.next()) {
111                 list.add(new SqlDBIndicesEntry(data.getString(1)));
112             }
113         } catch (SQLException e) {
114             LOG.warn("problem reading tables: ", e);
115         }
116         return list;
117     }
118
119     public void waitForYellowStatus(long timeoutms) {
120         Portstatus.waitSecondsTillAvailable(timeoutms/1000, this.dbHost, this.dbPort);
121     }
122
123     public DatabaseVersion readActualVersion() throws SQLException, ParseException {
124         ResultSet data;
125         try {
126             data = this.read(SELECT_VERSION_QUERY);
127             if (data.next()) {
128                 final String s = data.getString(1);
129                 final Matcher matcher = DBVERSION_PATTERN.matcher(s);
130                 data.afterLast();
131                 data.close();
132                 if (matcher.find()) {
133                     return new DatabaseVersion(matcher.group(1));
134                 } else {
135                     throw new ParseException(String.format("unable to extract version out of string '%s'", s), 0);
136                 }
137             }
138         } catch (SQLException e) {
139             LOG.warn("problem reading tables: ", e);
140         }
141         throw new SQLException("unable to read version from database");
142     }
143
144     public boolean createTable(Entity entity, Class<?> clazz, String suffix) throws UnableToMapClassException {
145         String createStatement = SqlDBMapper.createTable(clazz, entity, suffix);
146         return this.createTable(createStatement);
147     }
148
149     public boolean createTable(String tableName, String tableMappings) {
150         final String createStatement = String.format("CREATE TABLE IF NOT EXISTS `%s` (%s)", tableName, tableMappings);
151         return this.createTable(createStatement);
152     }
153
154     public boolean createTable(String query) {
155         try {
156             Connection connection = this.getConnection();
157             PreparedStatement stmt = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
158             stmt.execute();
159             connection.close();
160             return true;
161         } catch (SQLException e) {
162             LOG.warn("problem creating table:", e);
163         }
164         return false;
165     }
166
167     public boolean createView(String tableName, String viewName) throws SQLException {
168         try {
169             this.write(String.format("CREATE VIEW IF NOT EXISTS `%s` AS SELECT * FROM `%s`", viewName, tableName));
170             return true;
171         } catch (SQLException e) {
172             LOG.warn("problem deleting table:", e);
173         }
174         return false;
175     }
176
177     public boolean deleteView(String viewName) throws SQLException {
178         try {
179             this.write(String.format("DROP VIEW IF EXISTS `%s`", viewName));
180             return true;
181         } catch (SQLException e) {
182             LOG.warn("problem deleting view:", e);
183         }
184         return false;
185     }
186
187     public boolean update(String query) throws SQLException {
188         boolean result = false;
189         Connection connection = null;
190         connection = DriverManager.getConnection(this.dbConnectionString);
191         Statement stmt = connection.createStatement();
192         result = stmt.execute(query);
193         return stmt.getUpdateCount() > 0 ? stmt.getUpdateCount() > 0 : result;
194     }
195
196     public boolean write(String query) throws SQLException {
197         Connection connection = this.getConnection();
198         PreparedStatement stmt = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
199         boolean result = stmt.execute();
200         connection.close();
201         return stmt.getUpdateCount() > 0 ? stmt.getUpdateCount() > 0 : result;
202     }
203
204     public String writeAndReturnId(String query) throws SQLException {
205         Connection connection = this.getConnection();
206         PreparedStatement stmt = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
207         stmt.execute();
208         ResultSet generatedKeys = stmt.getGeneratedKeys();
209         connection.close();
210         if (generatedKeys.next()) {
211             return String.valueOf(generatedKeys.getLong(1));
212         }
213         return null;
214     }
215
216     public boolean deleteTable(String tableName) throws SQLException {
217         try {
218             this.write(String.format("DROP TABLE IF EXISTS `%s`", tableName));
219             return true;
220         } catch (SQLException e) {
221             LOG.warn("problem deleting table:", e);
222         }
223         return false;
224     }
225
226     public String getDatabaseName() {
227         return this.dbName;
228     }
229
230     public ResultSet read(String query) {
231         ResultSet data = null;
232         Connection connection = null;
233         Statement stmt = null;
234         try {
235             connection = DriverManager.getConnection(this.dbConnectionString);
236             stmt = connection.createStatement();
237             data = stmt.executeQuery(query);
238         } catch (SQLException e) {
239             LOG.warn("problem reading tables: ", e);
240         } finally {
241             try {
242                 if (connection != null) {
243                     connection.close();
244                 }
245             } catch (SQLException e) {
246                 LOG.warn("problem closing connection: ", e);
247             }
248         }
249
250         return data;
251     }
252
253     public Connection getConnection() throws SQLException {
254         return DriverManager.getConnection(this.dbConnectionString);
255     }
256
257     public boolean delete(String query) throws SQLException {
258         this.write(query);
259         return true;
260     }
261
262
263
264 }