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 final Logger logger = LoggerFactory.getLogger(JdbcPostgresqlDAO.class);
44 public JdbcPostgresqlDAO() {
51 private void initSqlQueries() {
52 logger.debug("JDBC::initSqlQueries: '{}'", this.getClass().getSimpleName());
53 // System Information Functions: https://www.postgresql.org/docs/9.2/static/functions-info.html
54 sqlGetDB = "SELECT CURRENT_DATABASE()";
55 sqlIfTableExists = "SELECT * FROM PG_TABLES WHERE TABLENAME='#searchTable#'";
56 sqlCreateItemsTableIfNot = "CREATE TABLE IF NOT EXISTS #itemsManageTable# (itemid SERIAL NOT NULL, #colname# #coltype# NOT NULL, CONSTRAINT #itemsManageTable#_pkey PRIMARY KEY (itemid))";
57 sqlCreateNewEntryInItemsTable = "INSERT INTO items (itemname) SELECT itemname FROM #itemsManageTable# UNION VALUES ('#itemname#') EXCEPT SELECT itemname FROM items";
58 sqlGetItemTables = "SELECT table_name FROM information_schema.tables WHERE table_type='BASE TABLE' AND table_schema=(SELECT table_schema "
59 + "FROM information_schema.tables WHERE table_type='BASE TABLE' AND table_name='#itemsManageTable#') AND NOT table_name='#itemsManageTable#'";
60 // http://stackoverflow.com/questions/17267417/how-do-i-do-an-upsert-merge-insert-on-duplicate-update-in-postgresql
61 // for later use, PostgreSql > 9.5 to prevent PRIMARY key violation use:
62 // SQL_INSERT_ITEM_VALUE = "INSERT INTO #tableName# (TIME, VALUE) VALUES( NOW(), CAST( ? as #dbType#) ) ON
63 // CONFLICT DO NOTHING";
64 sqlInsertItemValue = "INSERT INTO #tableName# (TIME, VALUE) VALUES( #tablePrimaryValue#, CAST( ? as #dbType#) )";
68 * INFO: http://www.java2s.com/Code/Java/Database-SQL-JDBC/StandardSQLDataTypeswithTheirJavaEquivalents.htm
70 private void initSqlTypes() {
71 // Initialize the type array
72 sqlTypes.put("CALLITEM", "VARCHAR");
73 sqlTypes.put("COLORITEM", "VARCHAR");
74 sqlTypes.put("CONTACTITEM", "VARCHAR");
75 sqlTypes.put("DATETIMEITEM", "TIMESTAMP");
76 sqlTypes.put("DIMMERITEM", "SMALLINT");
77 sqlTypes.put("IMAGEITEM", "VARCHAR");
78 sqlTypes.put("LOCATIONITEM", "VARCHAR");
79 sqlTypes.put("NUMBERITEM", "DOUBLE PRECISION");
80 sqlTypes.put("PLAYERITEM", "VARCHAR");
81 sqlTypes.put("ROLLERSHUTTERITEM", "SMALLINT");
82 sqlTypes.put("STRINGITEM", "VARCHAR");
83 sqlTypes.put("SWITCHITEM", "VARCHAR");
84 logger.debug("JDBC::initSqlTypes: Initialized the type array sqlTypes={}", sqlTypes.values());
88 * INFO: https://github.com/brettwooldridge/HikariCP
90 private void initDbProps() {
92 // databaseProps.setProperty("dataSource.cachePrepStmts", "true");
93 // databaseProps.setProperty("dataSource.prepStmtCacheSize", "250");
94 // databaseProps.setProperty("dataSource.prepStmtCacheSqlLimit", "2048");
96 // Properties for HikariCP
97 databaseProps.setProperty("driverClassName", "org.postgresql.Driver");
98 // driverClassName OR BETTER USE dataSourceClassName
99 // databaseProps.setProperty("dataSourceClassName", "org.postgresql.ds.PGSimpleDataSource");
100 // databaseProps.setProperty("maximumPoolSize", "3");
101 // databaseProps.setProperty("minimumIdle", "2");
108 public ItemsVO doCreateItemsTableIfNot(ItemsVO vo) {
109 String sql = StringUtilsExt.replaceArrayMerge(sqlCreateItemsTableIfNot,
110 new String[] { "#itemsManageTable#", "#colname#", "#coltype#", "#itemsManageTable#" },
111 new String[] { vo.getItemsManageTable(), vo.getColname(), vo.getColtype(), vo.getItemsManageTable() });
112 logger.debug("JDBC::doCreateItemsTableIfNot sql={}", sql);
113 Yank.execute(sql, null);
118 public Long doCreateNewEntryInItemsTable(ItemsVO vo) {
119 String sql = StringUtilsExt.replaceArrayMerge(sqlCreateNewEntryInItemsTable,
120 new String[] { "#itemsManageTable#", "#itemname#" },
121 new String[] { vo.getItemsManageTable(), vo.getItemname() });
122 logger.debug("JDBC::doCreateNewEntryInItemsTable sql={}", sql);
123 return Yank.insert(sql, null);
127 public List<ItemsVO> doGetItemTables(ItemsVO vo) {
128 String sql = StringUtilsExt.replaceArrayMerge(this.sqlGetItemTables,
129 new String[] { "#itemsManageTable#", "#itemsManageTable#" },
130 new String[] { vo.getItemsManageTable(), vo.getItemsManageTable() });
131 this.logger.debug("JDBC::doGetItemTables sql={}", sql);
132 return Yank.queryBeanList(sql, ItemsVO.class, null);
139 public void doStoreItemValue(Item item, State itemState, ItemVO vo) {
140 ItemVO storedVO = storeItemValueProvider(item, itemState, vo);
141 String sql = StringUtilsExt.replaceArrayMerge(sqlInsertItemValue,
142 new String[] { "#tableName#", "#dbType#", "#tablePrimaryValue#" },
143 new String[] { storedVO.getTableName(), storedVO.getDbType(), sqlTypes.get("tablePrimaryValue") });
144 Object[] params = new Object[] { storedVO.getValue() };
145 logger.debug("JDBC::doStoreItemValue sql={} value='{}'", sql, storedVO.getValue());
146 Yank.execute(sql, params);
149 /****************************
150 * SQL generation Providers *
151 ****************************/
154 protected String histItemFilterQueryProvider(FilterCriteria filter, int numberDecimalcount, String table,
155 String simpleName, ZoneId timeZone) {
157 "JDBC::getHistItemFilterQueryProvider filter = {}, numberDecimalcount = {}, table = {}, simpleName = {}",
158 filter.toString(), numberDecimalcount, table, simpleName);
160 String filterString = "";
161 if (filter.getBeginDate() != null) {
162 filterString += filterString.isEmpty() ? " WHERE" : " AND";
163 filterString += " TIME>'" + JDBC_DATE_FORMAT.format(filter.getBeginDate().withZoneSameInstant(timeZone))
166 if (filter.getEndDate() != null) {
167 filterString += filterString.isEmpty() ? " WHERE" : " AND";
168 filterString += " TIME<'" + JDBC_DATE_FORMAT.format(filter.getEndDate().withZoneSameInstant(timeZone))
171 filterString += (filter.getOrdering() == Ordering.ASCENDING) ? " ORDER BY time ASC" : " ORDER BY time DESC";
172 if (filter.getPageSize() != 0x7fffffff) {
174 // http://www.jooq.org/doc/3.5/manual/sql-building/sql-statements/select-statement/limit-clause/
175 filterString += " OFFSET " + filter.getPageNumber() * filter.getPageSize() + " LIMIT "
176 + filter.getPageSize();
178 String queryString = "NUMBERITEM".equalsIgnoreCase(simpleName) && numberDecimalcount > -1
179 ? "SELECT time, ROUND(CAST (value AS numeric)," + numberDecimalcount + ") FROM " + table
180 : "SELECT time, value FROM " + table;
181 if (!filterString.isEmpty()) {
182 queryString += filterString;
184 logger.debug("JDBC::query queryString = {}", queryString);
192 /******************************
193 * public Getters and Setters *
194 ******************************/