2 * Copyright (c) 2010-2022 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.persistence.jdbc.internal;
15 import java.util.ArrayList;
16 import java.util.HashMap;
17 import java.util.List;
20 import java.util.stream.Collectors;
22 import org.knowm.yank.Yank;
23 import org.openhab.core.i18n.TimeZoneProvider;
24 import org.openhab.core.items.Item;
25 import org.openhab.core.persistence.FilterCriteria;
26 import org.openhab.core.persistence.HistoricItem;
27 import org.openhab.core.persistence.PersistenceItemInfo;
28 import org.openhab.persistence.jdbc.dto.ItemVO;
29 import org.openhab.persistence.jdbc.dto.ItemsVO;
30 import org.openhab.persistence.jdbc.dto.JdbcPersistenceItemInfo;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
37 * @author Helmut Lehmeyer - Initial contribution
39 public class JdbcMapper {
40 private final Logger logger = LoggerFactory.getLogger(JdbcMapper.class);
42 private final TimeZoneProvider timeZoneProvider;
44 // Error counter - used to reconnect to database on error
46 protected boolean initialized = false;
47 protected JdbcConfiguration conf = null;
48 protected final Map<String, String> sqlTables = new HashMap<>();
49 private long afterAccessMin = 10000;
50 private long afterAccessMax = 0;
51 private static final String ITEM_NAME_PATTERN = "[^a-zA-Z_0-9\\-]";
53 public JdbcMapper(TimeZoneProvider timeZoneProvider) {
54 this.timeZoneProvider = timeZoneProvider;
60 public boolean pingDB() {
61 logger.debug("JDBC::pingDB");
63 long timerStart = System.currentTimeMillis();
64 if (openConnection()) {
65 if (conf.getDbName() == null) {
67 "JDBC::pingDB asking db for name as absolutely first db action, after connection is established.");
68 String dbName = conf.getDBDAO().doGetDB();
69 conf.setDbName(dbName);
70 ret = dbName.length() > 0;
72 ret = conf.getDBDAO().doPingDB() > 0;
75 logTime("pingDB", timerStart, System.currentTimeMillis());
79 public String getDB() {
80 logger.debug("JDBC::getDB");
81 long timerStart = System.currentTimeMillis();
82 String res = conf.getDBDAO().doGetDB();
83 logTime("pingDB", timerStart, System.currentTimeMillis());
87 public ItemsVO createNewEntryInItemsTable(ItemsVO vo) {
88 logger.debug("JDBC::createNewEntryInItemsTable");
89 long timerStart = System.currentTimeMillis();
90 Long i = conf.getDBDAO().doCreateNewEntryInItemsTable(vo);
91 vo.setItemid(i.intValue());
92 logTime("doCreateNewEntryInItemsTable", timerStart, System.currentTimeMillis());
96 public boolean createItemsTableIfNot(ItemsVO vo) {
97 logger.debug("JDBC::createItemsTableIfNot");
98 long timerStart = System.currentTimeMillis();
99 conf.getDBDAO().doCreateItemsTableIfNot(vo);
100 logTime("doCreateItemsTableIfNot", timerStart, System.currentTimeMillis());
104 public ItemsVO deleteItemsEntry(ItemsVO vo) {
105 logger.debug("JDBC::deleteItemsEntry");
106 long timerStart = System.currentTimeMillis();
107 conf.getDBDAO().doDeleteItemsEntry(vo);
108 logTime("deleteItemsEntry", timerStart, System.currentTimeMillis());
112 public List<ItemsVO> getItemIDTableNames() {
113 logger.debug("JDBC::getItemIDTableNames");
114 long timerStart = System.currentTimeMillis();
115 List<ItemsVO> vo = conf.getDBDAO().doGetItemIDTableNames(new ItemsVO());
116 logTime("getItemIDTableNames", timerStart, System.currentTimeMillis());
120 public List<ItemsVO> getItemTables() {
121 logger.debug("JDBC::getItemTables");
122 long timerStart = System.currentTimeMillis();
123 ItemsVO vo = new ItemsVO();
124 vo.setJdbcUriDatabaseName(conf.getDbName());
125 List<ItemsVO> vol = conf.getDBDAO().doGetItemTables(vo);
126 logTime("getItemTables", timerStart, System.currentTimeMillis());
133 public void updateItemTableNames(List<ItemVO> vol) {
134 logger.debug("JDBC::updateItemTableNames");
135 long timerStart = System.currentTimeMillis();
136 conf.getDBDAO().doUpdateItemTableNames(vol);
137 logTime("updateItemTableNames", timerStart, System.currentTimeMillis());
140 public ItemVO createItemTable(ItemVO vo) {
141 logger.debug("JDBC::createItemTable");
142 long timerStart = System.currentTimeMillis();
143 conf.getDBDAO().doCreateItemTable(vo);
144 logTime("createItemTable", timerStart, System.currentTimeMillis());
148 public Item storeItemValue(Item item) {
149 logger.debug("JDBC::storeItemValue: item={}", item);
150 String tableName = getTable(item);
151 if (tableName == null) {
152 logger.error("JDBC::store: Unable to store item '{}'.", item.getName());
155 long timerStart = System.currentTimeMillis();
156 conf.getDBDAO().doStoreItemValue(item, new ItemVO(tableName, null));
157 logTime("storeItemValue", timerStart, System.currentTimeMillis());
162 public List<HistoricItem> getHistItemFilterQuery(FilterCriteria filter, int numberDecimalcount, String table,
165 "JDBC::getHistItemFilterQuery filter='{}' numberDecimalcount='{}' table='{}' item='{}' itemName='{}'",
166 (filter != null), numberDecimalcount, table, item, item.getName());
168 long timerStart = System.currentTimeMillis();
169 List<HistoricItem> result = conf.getDBDAO().doGetHistItemFilterQuery(item, filter, numberDecimalcount,
170 table, item.getName(), timeZoneProvider.getTimeZone());
171 logTime("getHistItemFilterQuery", timerStart, System.currentTimeMillis());
175 logger.error("JDBC::getHistItemFilterQuery: TABLE is NULL; cannot get data from non-existent table.");
180 /***********************
181 * DATABASE CONNECTION *
182 ***********************/
183 protected boolean openConnection() {
184 logger.debug("JDBC::openConnection isDriverAvailable: {}", conf.isDriverAvailable());
185 if (conf.isDriverAvailable() && !conf.isDbConnected()) {
186 logger.info("JDBC::openConnection: Driver is available::Yank setupDataSource");
187 Yank.setupDefaultConnectionPool(conf.getHikariConfiguration());
188 conf.setDbConnected(true);
190 } else if (!conf.isDriverAvailable()) {
191 logger.warn("JDBC::openConnection: no driver available!");
198 protected void closeConnection() {
199 logger.debug("JDBC::closeConnection");
200 // Closes all open connection pools
201 Yank.releaseDefaultConnectionPool();
202 conf.setDbConnected(false);
205 protected boolean checkDBAccessability() {
206 // Check if connection is valid
211 boolean p = pingDB();
213 logger.debug("JDBC::checkDBAcessability, first try connection: {}", p);
214 return (p && !(conf.getErrReconnectThreshold() > 0 && errCnt <= conf.getErrReconnectThreshold()));
218 logger.debug("JDBC::checkDBAcessability, second try connection: {}", p);
219 return (p && !(conf.getErrReconnectThreshold() > 0 && errCnt <= conf.getErrReconnectThreshold()));
223 /**************************
224 * DATABASE TABLEHANDLING *
225 **************************/
226 protected void checkDBSchema() {
227 // Create Items Table if does not exist
228 createItemsTableIfNot(new ItemsVO());
229 if (conf.getRebuildTableNames()) {
232 "JDBC::checkDBSchema: Rebuild complete, configure the 'rebuildTableNames' setting to 'false' to stop rebuilds on startup");
234 // Reset the error counter
236 for (ItemsVO vo : getItemIDTableNames()) {
237 sqlTables.put(vo.getItemname(), getTableName(vo.getItemid(), vo.getItemname()));
242 protected String getTable(Item item) {
247 String itemName = item.getName();
248 String tableName = sqlTables.get(itemName);
250 // Table already exists - return the name
251 if (tableName != null) {
255 logger.debug("JDBC::getTable: no table found for item '{}' in sqlTables", itemName);
257 // Create a new entry in items table
258 isvo = new ItemsVO();
259 isvo.setItemname(itemName);
260 isvo = createNewEntryInItemsTable(isvo);
261 rowId = isvo.getItemid();
263 logger.error("JDBC::getTable: Creating table for item '{}' failed.", itemName);
265 // Create the table name
266 logger.debug("JDBC::getTable: getTableName with rowId={} itemName={}", rowId, itemName);
267 tableName = getTableName(rowId, itemName);
269 // An error occurred adding the item name into the index list!
270 if (tableName == null) {
271 logger.error("JDBC::getTable: tableName was null; could not create a table for item '{}'", itemName);
275 // Create table for item
276 String dataType = conf.getDBDAO().getDataType(item);
277 ivo = new ItemVO(tableName, itemName);
278 ivo.setDbType(dataType);
279 ivo = createItemTable(ivo);
280 logger.debug("JDBC::getTable: Table created for item '{}' with dataType {} in SQL database.", itemName,
282 sqlTables.put(itemName, tableName);
284 // Check if the new entry is in the table list
285 // If it's not in the list, then there was an error and we need to do
287 // The item needs to be removed from the index table to avoid duplicates
288 if (sqlTables.get(itemName) == null) {
289 logger.error("JDBC::getTable: Item '{}' was not added to the table - removing index", itemName);
290 isvo = new ItemsVO();
291 isvo.setItemname(itemName);
292 deleteItemsEntry(isvo);
298 private void formatTableNames() {
299 boolean tmpinit = initialized;
304 Map<Integer, String> tableIds = new HashMap<>();
307 for (ItemsVO vo : getItemIDTableNames()) {
308 String t = getTableName(vo.getItemid(), vo.getItemname());
309 sqlTables.put(vo.getItemname(), t);
310 tableIds.put(vo.getItemid(), t);
314 List<ItemsVO> al = getItemTables();
318 List<ItemVO> oldNewTablenames = new ArrayList<>();
319 for (int i = 0; i < al.size(); i++) {
321 oldName = al.get(i).getTable_name();
322 logger.info("JDBC::formatTableNames: found Table Name= {}", oldName);
324 if (oldName.startsWith(conf.getTableNamePrefix()) && !oldName.contains("_")) {
325 id = Integer.parseInt(oldName.substring(conf.getTableNamePrefix().length()));
326 logger.info("JDBC::formatTableNames: found Table with Prefix '{}' Name= {} id= {}",
327 conf.getTableNamePrefix(), oldName, (id));
328 } else if (oldName.contains("_")) {
329 id = Integer.parseInt(oldName.substring(oldName.lastIndexOf("_") + 1));
330 logger.info("JDBC::formatTableNames: found Table Name= {} id= {}", oldName, (id));
332 logger.info("JDBC::formatTableNames: found Table id= {}", id);
334 newName = tableIds.get(id);
335 logger.info("JDBC::formatTableNames: found Table newName= {}", newName);
337 if (newName != null) {
338 if (!oldName.equalsIgnoreCase(newName)) {
339 oldNewTablenames.add(new ItemVO(oldName, newName));
340 logger.info("JDBC::formatTableNames: Table '{}' will be renamed to '{}'", oldName, newName);
342 logger.info("JDBC::formatTableNames: Table oldName='{}' newName='{}' nothing to rename", oldName,
346 logger.error("JDBC::formatTableNames: Table '{}' could NOT be renamed to '{}'", oldName, newName);
351 updateItemTableNames(oldNewTablenames);
352 logger.info("JDBC::formatTableNames: Finished updating {} item table names", oldNewTablenames.size());
354 initialized = tmpinit;
357 private String getTableName(int rowId, String itemName) {
358 return getTableNamePrefix(itemName) + formatRight(rowId, conf.getTableIdDigitCount());
361 private String getTableNamePrefix(String itemName) {
362 String name = conf.getTableNamePrefix();
363 if (conf.getTableUseRealItemNames()) {
364 // Create the table name with real Item Names
365 name = (itemName.replaceAll(ITEM_NAME_PATTERN, "") + "_").toLowerCase();
370 public Set<PersistenceItemInfo> getItems() {
371 // TODO: in general it would be possible to query the count, earliest and latest values for each item too but it
372 // would be a very costly operation
373 return sqlTables.keySet().stream().map(itemName -> new JdbcPersistenceItemInfo(itemName))
374 .collect(Collectors.<PersistenceItemInfo> toSet());
377 private static String formatRight(final Object value, final int len) {
378 final String valueAsString = String.valueOf(value);
379 if (valueAsString.length() < len) {
380 final StringBuffer result = new StringBuffer(len);
381 for (int i = len - valueAsString.length(); i > 0; i--) {
384 result.append(valueAsString);
385 return result.toString();
387 return valueAsString;
394 private void logTime(String me, long timerStart, long timerStop) {
395 if (conf.enableLogTime && logger.isInfoEnabled()) {
397 int timerDiff = (int) (timerStop - timerStart);
398 if (timerDiff < afterAccessMin) {
399 afterAccessMin = timerDiff;
401 if (timerDiff > afterAccessMax) {
402 afterAccessMax = timerDiff;
404 conf.timeAverage50arr.add(timerDiff);
405 conf.timeAverage100arr.add(timerDiff);
406 conf.timeAverage200arr.add(timerDiff);
407 if (conf.timerCount == 1) {
408 conf.timer1000 = System.currentTimeMillis();
410 if (conf.timerCount == 1001) {
411 conf.time1000Statements = Math.round(((int) (System.currentTimeMillis() - conf.timer1000)) / 1000);// Seconds
415 "JDBC::logTime: '{}':\n afterAccess = {} ms\n timeAverage50 = {} ms\n timeAverage100 = {} ms\n timeAverage200 = {} ms\n afterAccessMin = {} ms\n afterAccessMax = {} ms\n 1000Statements = {} sec\n statementCount = {}\n",
416 me, timerDiff, conf.timeAverage50arr.getAverageInteger(),
417 conf.timeAverage100arr.getAverageInteger(), conf.timeAverage200arr.getAverageInteger(),
418 afterAccessMin, afterAccessMax, conf.time1000Statements, conf.timerCount);