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.db;
15 import java.time.ZoneId;
16 import java.util.List;
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.knowm.yank.Yank;
20 import org.openhab.core.items.Item;
21 import org.openhab.core.persistence.FilterCriteria;
22 import org.openhab.core.persistence.FilterCriteria.Ordering;
23 import org.openhab.core.types.State;
24 import org.openhab.persistence.jdbc.dto.ItemVO;
25 import org.openhab.persistence.jdbc.dto.ItemsVO;
26 import org.openhab.persistence.jdbc.utils.StringUtilsExt;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
31 * Extended Database Configuration class. Class represents
32 * the extended database-specific configuration. Overrides and supplements the
33 * default settings from JdbcBaseDAO. Enter only the differences to JdbcBaseDAO here.
35 * @author Helmut Lehmeyer - Initial contribution
38 public class JdbcPostgresqlDAO extends JdbcBaseDAO {
39 private static final String DRIVER_CLASS_NAME = org.postgresql.Driver.class.getName();
40 @SuppressWarnings("unused")
41 private static final String DATA_SOURCE_CLASS_NAME = org.postgresql.ds.PGSimpleDataSource.class.getName();
43 private final Logger logger = LoggerFactory.getLogger(JdbcPostgresqlDAO.class);
48 public JdbcPostgresqlDAO() {
54 private void initSqlQueries() {
55 logger.debug("JDBC::initSqlQueries: '{}'", this.getClass().getSimpleName());
56 // System Information Functions: https://www.postgresql.org/docs/9.2/static/functions-info.html
57 sqlGetDB = "SELECT CURRENT_DATABASE()";
58 sqlIfTableExists = "SELECT * FROM PG_TABLES WHERE TABLENAME='#searchTable#'";
59 sqlCreateItemsTableIfNot = "CREATE TABLE IF NOT EXISTS #itemsManageTable# (itemid SERIAL NOT NULL, #colname# #coltype# NOT NULL, CONSTRAINT #itemsManageTable#_pkey PRIMARY KEY (itemid))";
60 sqlCreateNewEntryInItemsTable = "INSERT INTO items (itemname) SELECT itemname FROM #itemsManageTable# UNION VALUES ('#itemname#') EXCEPT SELECT itemname FROM items";
61 sqlGetItemTables = "SELECT table_name FROM information_schema.tables WHERE table_type='BASE TABLE' AND table_schema=(SELECT table_schema "
62 + "FROM information_schema.tables WHERE table_type='BASE TABLE' AND table_name='#itemsManageTable#') AND NOT table_name='#itemsManageTable#'";
63 // http://stackoverflow.com/questions/17267417/how-do-i-do-an-upsert-merge-insert-on-duplicate-update-in-postgresql
64 // for later use, PostgreSql > 9.5 to prevent PRIMARY key violation use:
65 // SQL_INSERT_ITEM_VALUE = "INSERT INTO #tableName# (TIME, VALUE) VALUES( NOW(), CAST( ? as #dbType#) ) ON
66 // CONFLICT DO NOTHING";
67 sqlInsertItemValue = "INSERT INTO #tableName# (TIME, VALUE) VALUES( #tablePrimaryValue#, CAST( ? as #dbType#) )";
71 * INFO: http://www.java2s.com/Code/Java/Database-SQL-JDBC/StandardSQLDataTypeswithTheirJavaEquivalents.htm
73 private void initSqlTypes() {
74 // Initialize the type array
75 sqlTypes.put("CALLITEM", "VARCHAR");
76 sqlTypes.put("COLORITEM", "VARCHAR");
77 sqlTypes.put("CONTACTITEM", "VARCHAR");
78 sqlTypes.put("DATETIMEITEM", "TIMESTAMP");
79 sqlTypes.put("DIMMERITEM", "SMALLINT");
80 sqlTypes.put("IMAGEITEM", "VARCHAR");
81 sqlTypes.put("LOCATIONITEM", "VARCHAR");
82 sqlTypes.put("NUMBERITEM", "DOUBLE PRECISION");
83 sqlTypes.put("PLAYERITEM", "VARCHAR");
84 sqlTypes.put("ROLLERSHUTTERITEM", "SMALLINT");
85 sqlTypes.put("STRINGITEM", "VARCHAR");
86 sqlTypes.put("SWITCHITEM", "VARCHAR");
87 logger.debug("JDBC::initSqlTypes: Initialized the type array sqlTypes={}", sqlTypes.values());
91 * INFO: https://github.com/brettwooldridge/HikariCP
93 private void initDbProps() {
95 // databaseProps.setProperty("dataSource.cachePrepStmts", "true");
96 // databaseProps.setProperty("dataSource.prepStmtCacheSize", "250");
97 // databaseProps.setProperty("dataSource.prepStmtCacheSqlLimit", "2048");
99 // Properties for HikariCP
100 databaseProps.setProperty("driverClassName", DRIVER_CLASS_NAME);
101 // driverClassName OR BETTER USE dataSourceClassName
102 // databaseProps.setProperty("dataSourceClassName", DATA_SOURCE_CLASS_NAME);
103 // databaseProps.setProperty("maximumPoolSize", "3");
104 // databaseProps.setProperty("minimumIdle", "2");
111 public ItemsVO doCreateItemsTableIfNot(ItemsVO vo) {
112 String sql = StringUtilsExt.replaceArrayMerge(sqlCreateItemsTableIfNot,
113 new String[] { "#itemsManageTable#", "#colname#", "#coltype#", "#itemsManageTable#" },
114 new String[] { vo.getItemsManageTable(), vo.getColname(), vo.getColtype(), vo.getItemsManageTable() });
115 logger.debug("JDBC::doCreateItemsTableIfNot sql={}", sql);
116 Yank.execute(sql, null);
121 public Long doCreateNewEntryInItemsTable(ItemsVO vo) {
122 String sql = StringUtilsExt.replaceArrayMerge(sqlCreateNewEntryInItemsTable,
123 new String[] { "#itemsManageTable#", "#itemname#" },
124 new String[] { vo.getItemsManageTable(), vo.getItemname() });
125 logger.debug("JDBC::doCreateNewEntryInItemsTable sql={}", sql);
126 return Yank.insert(sql, null);
130 public List<ItemsVO> doGetItemTables(ItemsVO vo) {
131 String sql = StringUtilsExt.replaceArrayMerge(this.sqlGetItemTables,
132 new String[] { "#itemsManageTable#", "#itemsManageTable#" },
133 new String[] { vo.getItemsManageTable(), vo.getItemsManageTable() });
134 this.logger.debug("JDBC::doGetItemTables sql={}", sql);
135 return Yank.queryBeanList(sql, ItemsVO.class, null);
142 public void doStoreItemValue(Item item, State itemState, ItemVO vo) {
143 ItemVO storedVO = storeItemValueProvider(item, itemState, vo);
144 String sql = StringUtilsExt.replaceArrayMerge(sqlInsertItemValue,
145 new String[] { "#tableName#", "#dbType#", "#tablePrimaryValue#" },
146 new String[] { storedVO.getTableName(), storedVO.getDbType(), sqlTypes.get("tablePrimaryValue") });
147 Object[] params = { storedVO.getValue() };
148 logger.debug("JDBC::doStoreItemValue sql={} value='{}'", sql, storedVO.getValue());
149 Yank.execute(sql, params);
152 /****************************
153 * SQL generation Providers *
154 ****************************/
157 protected String histItemFilterQueryProvider(FilterCriteria filter, int numberDecimalcount, String table,
158 String simpleName, ZoneId timeZone) {
160 "JDBC::getHistItemFilterQueryProvider filter = {}, numberDecimalcount = {}, table = {}, simpleName = {}",
161 filter.toString(), numberDecimalcount, table, simpleName);
163 String filterString = "";
164 if (filter.getBeginDate() != null) {
165 filterString += filterString.isEmpty() ? " WHERE" : " AND";
166 filterString += " TIME>'" + JDBC_DATE_FORMAT.format(filter.getBeginDate().withZoneSameInstant(timeZone))
169 if (filter.getEndDate() != null) {
170 filterString += filterString.isEmpty() ? " WHERE" : " AND";
171 filterString += " TIME<'" + JDBC_DATE_FORMAT.format(filter.getEndDate().withZoneSameInstant(timeZone))
174 filterString += (filter.getOrdering() == Ordering.ASCENDING) ? " ORDER BY time ASC" : " ORDER BY time DESC";
175 if (filter.getPageSize() != 0x7fffffff) {
177 // http://www.jooq.org/doc/3.5/manual/sql-building/sql-statements/select-statement/limit-clause/
178 filterString += " OFFSET " + filter.getPageNumber() * filter.getPageSize() + " LIMIT "
179 + filter.getPageSize();
181 String queryString = "NUMBERITEM".equalsIgnoreCase(simpleName) && numberDecimalcount > -1
182 ? "SELECT time, ROUND(CAST (value AS numeric)," + numberDecimalcount + ") FROM " + table
183 : "SELECT time, value FROM " + table;
184 if (!filterString.isEmpty()) {
185 queryString += filterString;
187 logger.debug("JDBC::query queryString = {}", queryString);
195 /******************************
196 * public Getters and Setters *
197 ******************************/