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