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.db;
15 import java.time.ZoneId;
16 import java.util.List;
17 import java.util.Objects;
18 import java.util.stream.Collectors;
20 import javax.measure.Quantity;
21 import javax.measure.Unit;
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.knowm.yank.Yank;
26 import org.knowm.yank.exceptions.YankSQLException;
27 import org.openhab.core.items.Item;
28 import org.openhab.core.library.items.NumberItem;
29 import org.openhab.core.persistence.FilterCriteria;
30 import org.openhab.core.persistence.FilterCriteria.Ordering;
31 import org.openhab.core.persistence.HistoricItem;
32 import org.openhab.core.types.State;
33 import org.openhab.persistence.jdbc.internal.dto.ItemVO;
34 import org.openhab.persistence.jdbc.internal.dto.ItemsVO;
35 import org.openhab.persistence.jdbc.internal.dto.JdbcHistoricItem;
36 import org.openhab.persistence.jdbc.internal.exceptions.JdbcSQLException;
37 import org.openhab.persistence.jdbc.internal.utils.StringUtilsExt;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
42 * Extended Database Configuration class. Class represents
43 * the extended database-specific configuration. Overrides and supplements the
44 * default settings from JdbcBaseDAO. Enter only the differences to JdbcBaseDAO here.
46 * @author Helmut Lehmeyer - Initial contribution
49 public class JdbcDerbyDAO extends JdbcBaseDAO {
50 private static final String DRIVER_CLASS_NAME = org.apache.derby.jdbc.EmbeddedDriver.class.getName();
51 @SuppressWarnings("unused")
52 private static final String DATA_SOURCE_CLASS_NAME = org.apache.derby.jdbc.EmbeddedDataSource.class.getName();
54 private final Logger logger = LoggerFactory.getLogger(JdbcDerbyDAO.class);
59 public JdbcDerbyDAO() {
65 private void initSqlQueries() {
66 logger.debug("JDBC::initSqlQueries: '{}'", this.getClass().getSimpleName());
67 sqlPingDB = "values 1";
68 sqlGetDB = "VALUES SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY( 'DataDictionaryVersion' )"; // returns version
69 sqlIfTableExists = "SELECT * FROM SYS.SYSTABLES WHERE TABLENAME='#searchTable#'";
70 sqlCreateItemsTableIfNot = "CREATE TABLE #itemsManageTable# ( ItemId INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), #colname# #coltype# NOT NULL)";
71 sqlCreateItemTable = "CREATE TABLE #tableName# (time #tablePrimaryKey# NOT NULL, value #dbType#, PRIMARY KEY(time))";
72 // Prevent error against duplicate time value (seldom): No powerful Merge found:
73 // http://www.codeproject.com/Questions/162627/how-to-insert-new-record-in-my-table-if-not-exists
74 sqlInsertItemValue = "INSERT INTO #tableName# (TIME, VALUE) VALUES( #tablePrimaryValue#, CAST( ? as #dbType#) )";
75 sqlAlterTableColumn = "ALTER TABLE #tableName# ALTER COLUMN #columnName# SET DATA TYPE #columnType#";
78 private void initSqlTypes() {
79 sqlTypes.put("DATETIMEITEM", "TIMESTAMP");
80 sqlTypes.put("DIMMERITEM", "SMALLINT");
81 sqlTypes.put("IMAGEITEM", "VARCHAR(32000)");
82 sqlTypes.put("ROLLERSHUTTERITEM", "SMALLINT");
83 sqlTypes.put("STRINGITEM", "VARCHAR(32000)");
84 sqlTypes.put("tablePrimaryValue", "CURRENT_TIMESTAMP");
85 logger.debug("JDBC::initSqlTypes: Initialized the type array sqlTypes={}", sqlTypes.values());
89 * INFO: https://github.com/brettwooldridge/HikariCP
91 private void initDbProps() {
92 // Properties for HikariCP
93 // Use driverClassName
94 databaseProps.setProperty("driverClassName", DRIVER_CLASS_NAME);
95 // OR dataSourceClassName
96 // databaseProps.setProperty("dataSourceClassName", DATA_SOURCE_CLASS_NAME);
97 databaseProps.setProperty("maximumPoolSize", "1");
98 databaseProps.setProperty("minimumIdle", "1");
102 public void initAfterFirstDbConnection() {
103 logger.debug("JDBC::initAfterFirstDbConnection: Initializing step, after db is connected.");
104 // Initialize sqlTypes, depending on DB version for example
105 // derby does not like this... dbMeta = new DbMetaData();// get DB information
112 public @Nullable Integer doPingDB() throws JdbcSQLException {
114 return Yank.queryScalar(sqlPingDB, Integer.class, null);
115 } catch (YankSQLException e) {
116 throw new JdbcSQLException(e);
121 public boolean doIfTableExists(ItemsVO vo) throws JdbcSQLException {
122 String sql = StringUtilsExt.replaceArrayMerge(sqlIfTableExists, new String[] { "#searchTable#" },
123 new String[] { vo.getItemsManageTable().toUpperCase() });
124 logger.debug("JDBC::doIfTableExists sql={}", sql);
126 final @Nullable String result = Yank.queryScalar(sql, String.class, null);
127 return Objects.nonNull(result);
128 } catch (YankSQLException e) {
129 throw new JdbcSQLException(e);
134 public Long doCreateNewEntryInItemsTable(ItemsVO vo) throws JdbcSQLException {
135 String sql = StringUtilsExt.replaceArrayMerge(sqlCreateNewEntryInItemsTable,
136 new String[] { "#itemsManageTable#", "#itemname#" },
137 new String[] { vo.getItemsManageTable().toUpperCase(), vo.getItemName() });
138 logger.debug("JDBC::doCreateNewEntryInItemsTable sql={}", sql);
140 return Yank.insert(sql, null);
141 } catch (YankSQLException e) {
142 throw new JdbcSQLException(e);
147 public ItemsVO doCreateItemsTableIfNot(ItemsVO vo) throws JdbcSQLException {
148 boolean tableExists = doIfTableExists(vo);
150 String sql = StringUtilsExt.replaceArrayMerge(sqlCreateItemsTableIfNot,
151 new String[] { "#itemsManageTable#", "#colname#", "#coltype#" },
152 new String[] { vo.getItemsManageTable().toUpperCase(), vo.getColname(), vo.getColtype() });
153 logger.debug("JDBC::doCreateItemsTableIfNot tableExists={} therefore sql={}", tableExists, sql);
155 Yank.execute(sql, null);
156 } catch (YankSQLException e) {
157 throw new JdbcSQLException(e);
160 logger.debug("JDBC::doCreateItemsTableIfNot tableExists={}, did not CREATE TABLE", tableExists);
169 public void doCreateItemTable(ItemVO vo) throws JdbcSQLException {
170 String sql = StringUtilsExt.replaceArrayMerge(sqlCreateItemTable,
171 new String[] { "#tableName#", "#dbType#", "#tablePrimaryKey#" },
172 new String[] { vo.getTableName(), vo.getDbType(), sqlTypes.get("tablePrimaryKey") });
174 Yank.execute(sql, null);
175 } catch (YankSQLException e) {
176 throw new JdbcSQLException(e);
181 public void doStoreItemValue(Item item, State itemState, ItemVO vo) throws JdbcSQLException {
182 ItemVO storedVO = storeItemValueProvider(item, itemState, vo);
183 String sql = StringUtilsExt.replaceArrayMerge(sqlInsertItemValue,
184 new String[] { "#tableName#", "#dbType#", "#tablePrimaryValue#" },
185 new String[] { storedVO.getTableName().toUpperCase(), storedVO.getDbType(),
186 sqlTypes.get("tablePrimaryValue") });
187 Object[] params = { storedVO.getValue() };
188 logger.debug("JDBC::doStoreItemValue sql={} value='{}'", sql, storedVO.getValue());
190 Yank.execute(sql, params);
191 } catch (YankSQLException e) {
192 throw new JdbcSQLException(e);
197 public List<HistoricItem> doGetHistItemFilterQuery(Item item, FilterCriteria filter, int numberDecimalcount,
198 String table, String name, ZoneId timeZone) throws JdbcSQLException {
199 String sql = histItemFilterQueryProvider(filter, numberDecimalcount, table, name, timeZone);
202 m = Yank.queryObjectArrays(sql, null);
203 } catch (YankSQLException e) {
204 throw new JdbcSQLException(e);
206 logger.debug("JDBC::doGetHistItemFilterQuery got Array length={}", m.size());
207 // we already retrieve the unit here once as it is a very costly operation
208 String itemName = item.getName();
209 Unit<? extends Quantity<?>> unit = item instanceof NumberItem ? ((NumberItem) item).getUnit() : null;
210 return m.stream().map(o -> {
211 logger.debug("JDBC::doGetHistItemFilterQuery 0='{}' 1='{}'", o[0], o[1]);
212 return new JdbcHistoricItem(itemName, objectAsState(item, unit, o[1]), objectAsZonedDateTime(o[0]));
213 }).collect(Collectors.<HistoricItem> toList());
216 /****************************
217 * SQL generation Providers *
218 ****************************/
221 protected String histItemFilterQueryProvider(FilterCriteria filter, int numberDecimalcount, String table,
222 String simpleName, ZoneId timeZone) {
224 "JDBC::getHistItemFilterQueryProvider filter = {}, numberDecimalcount = {}, table = {}, simpleName = {}",
225 StringUtilsExt.filterToString(filter), numberDecimalcount, table, simpleName);
227 String filterString = "";
228 if (filter.getBeginDate() != null) {
229 filterString += filterString.isEmpty() ? " WHERE" : " AND";
230 filterString += " TIME>'" + JDBC_DATE_FORMAT.format(filter.getBeginDate().withZoneSameInstant(timeZone))
233 if (filter.getEndDate() != null) {
234 filterString += filterString.isEmpty() ? " WHERE" : " AND";
235 filterString += " TIME<'" + JDBC_DATE_FORMAT.format(filter.getEndDate().withZoneSameInstant(timeZone))
238 filterString += (filter.getOrdering() == Ordering.ASCENDING) ? " ORDER BY time ASC" : " ORDER BY time DESC";
239 if (filter.getPageSize() != 0x7fffffff) {
241 // filterString += " LIMIT " + filter.getPageNumber() *
242 // filter.getPageSize() + "," + filter.getPageSize();
243 // SELECT time, value FROM ohscriptfiles_sw_ace_paths_0001 ORDER BY
244 // time DESC OFFSET 1 ROWS FETCH NEXT 0 ROWS ONLY
245 // filterString += " OFFSET " + filter.getPageSize() +" ROWS FETCH
246 // FIRST||NEXT " + filter.getPageNumber() * filter.getPageSize() + "
248 filterString += " OFFSET " + filter.getPageSize() + " ROWS FETCH FIRST "
249 + (filter.getPageNumber() * filter.getPageSize() + 1) + " ROWS ONLY";
252 // http://www.seemoredata.com/en/showthread.php?132-Round-function-in-Apache-Derby
253 // simulated round function in Derby: CAST(value 0.0005 AS DECIMAL(15,3))
254 // simulated round function in Derby: "CAST(value 0.0005 AS DECIMAL(15,"+numberDecimalcount+"))"
256 String queryString = "SELECT time,";
257 if ("NUMBERITEM".equalsIgnoreCase(simpleName) && numberDecimalcount > -1) {
259 queryString += "CAST(value 0.";
260 for (int i = 0; i < numberDecimalcount; i++) {
263 queryString += "5 AS DECIMAL(31," + numberDecimalcount + "))"; // 31 is DECIMAL max precision
264 // https://db.apache.org/derby/docs/10.0/manuals/develop/develop151.html
266 queryString += " value FROM " + table.toUpperCase();
269 if (!filterString.isEmpty()) {
270 queryString += filterString;
272 logger.debug("JDBC::query queryString = {}", queryString);
280 /******************************
281 * public Getters and Setters *
282 ******************************/