2 * ============LICENSE_START=======================================================
3 * ONAP : ccsdk features
4 * ================================================================================
5 * Copyright (C) 2020 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;
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;
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;
48 import javax.sql.ConnectionPoolDataSource;
50 public class SqlDBClient {
52 private static final Logger LOG = LoggerFactory.getLogger(SqlDBClient.class);
55 // 1=>type, e.g. mariadb, mysql, ...
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";
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;
71 private final HikariDataSource connectionPool;
74 * @param dbUrl e.g. jdbc:mysql://sdnrdb:3306/sdnrdb
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);
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);
93 public AliasesEntryList readViews() {
94 return this.readViews(DBNAME_DEFAULT);
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);
106 while (data.next()) {
107 list.add(new AliasesEntry(data.getString(2), data.getString(1)));
109 } catch (SQLException e) {
110 LOG.warn("problem reading views: ", e);
112 try { data.close(); } catch (SQLException ignore) { }
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);
121 while (data.next()) {
122 list.add(new SqlDBIndicesEntry(data.getString(1)));
124 } catch (SQLException e) {
125 LOG.warn("problem reading tables: ", e);
127 try { data.close(); } catch (SQLException ignore) { }
131 public void waitForYellowStatus(long timeoutms) {
132 Portstatus.waitSecondsTillAvailable(timeoutms / 1000, this.dbHost, this.dbPort);
135 public DatabaseVersion readActualVersion() throws SQLException, ParseException {
138 data = this.read(SELECT_VERSION_QUERY);
140 final String s = data.getString(1);
141 final Matcher matcher = DBVERSION_PATTERN.matcher(s);
144 if (matcher.find()) {
145 return new DatabaseVersion(matcher.group(1));
147 throw new ParseException(String.format("unable to extract version out of string '%s'", s), 0);
150 } catch (SQLException e) {
151 LOG.warn("problem reading actual version: ", e);
153 throw new SQLException("unable to read version from database");
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);
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);
166 public boolean createTable(String query) {
167 boolean result = false;
168 PreparedStatement stmt = null;
169 Connection connection = null;
171 connection = this.getConnection();
172 stmt = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
176 } catch (SQLException e) {
177 LOG.warn("problem creating table:", e);
179 if (stmt != null) try { stmt.close(); } catch (SQLException logOrIgnore) {}
180 if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
185 public boolean createView(String tableName, String viewName) throws SQLException {
187 this.write(String.format("CREATE VIEW IF NOT EXISTS `%s` AS SELECT * FROM `%s`", viewName, tableName));
189 } catch (SQLException e) {
190 LOG.warn("problem deleting table:", e);
195 public boolean deleteView(String viewName) throws SQLException {
197 this.write(String.format("DROP VIEW IF EXISTS `%s`", viewName));
199 } catch (SQLException e) {
200 LOG.warn("problem deleting view:", e);
205 public boolean update(String query) throws SQLException {
206 boolean result = false;
207 SQLException innerE = null;
208 Statement stmt = null;
209 Connection connection = null;
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) {
218 if (stmt != null) try { stmt.close(); } catch (SQLException ignore) {}
219 if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
221 if (innerE != null) {
227 public boolean write(String query) throws SQLException {
228 boolean result = false;
229 SQLException innerE = null;
230 PreparedStatement stmt = null;
231 Connection connection = null;
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) {
240 if (stmt != null) try { stmt.close(); } catch (SQLException ignore) {}
241 if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
243 if (innerE != null) {
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;
256 connection = this.getConnection();
257 stmt = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
259 generatedKeys = stmt.getGeneratedKeys();
260 if (generatedKeys.next()) {
261 result = String.valueOf(generatedKeys.getLong(1));
263 } catch (SQLException e) {
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) {}
270 if (innerE != null) {
276 public boolean deleteTable(String tableName) throws SQLException {
278 this.write(String.format("DROP TABLE IF EXISTS `%s`", tableName));
280 } catch (SQLException e) {
281 LOG.warn("problem deleting table:", e);
286 public String getDatabaseName() {
290 public ResultSet read(String query) {
291 ResultSet data = null;
292 Statement stmt = null;
293 Connection connection = null;
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);
301 if (stmt != null) try { stmt.close(); } catch (SQLException ignore) {}
302 if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
307 public Connection getConnection() throws SQLException {
308 return this.connectionPool.getConnection();
309 //return DriverManager.getConnection(this.dbConnectionString);
312 public boolean delete(String query) throws SQLException {