2 * Copyright (c) 2010-2021 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.knowm.yank.Yank;
19 import org.openhab.core.items.Item;
20 import org.openhab.core.persistence.FilterCriteria;
21 import org.openhab.core.persistence.FilterCriteria.Ordering;
22 import org.openhab.persistence.jdbc.dto.ItemVO;
23 import org.openhab.persistence.jdbc.dto.ItemsVO;
24 import org.openhab.persistence.jdbc.utils.StringUtilsExt;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
29 * Extended Database Configuration class. Class represents
30 * the extended database-specific configuration. Overrides and supplements the
31 * default settings from JdbcBaseDAO. Enter only the differences to JdbcBaseDAO here.
33 * @author Helmut Lehmeyer - Initial contribution
35 public class JdbcPostgresqlDAO extends JdbcBaseDAO {
36 private final Logger logger = LoggerFactory.getLogger(JdbcPostgresqlDAO.class);
41 public JdbcPostgresqlDAO() {
48 private void initSqlQueries() {
49 logger.debug("JDBC::initSqlQueries: '{}'", this.getClass().getSimpleName());
50 // System Information Functions: https://www.postgresql.org/docs/9.2/static/functions-info.html
51 sqlGetDB = "SELECT CURRENT_DATABASE()";
52 sqlIfTableExists = "SELECT * FROM PG_TABLES WHERE TABLENAME='#searchTable#'";
53 sqlCreateItemsTableIfNot = "CREATE TABLE IF NOT EXISTS #itemsManageTable# (itemid SERIAL NOT NULL, #colname# #coltype# NOT NULL, CONSTRAINT #itemsManageTable#_pkey PRIMARY KEY (itemid))";
54 sqlCreateNewEntryInItemsTable = "INSERT INTO items (itemname) SELECT itemname FROM #itemsManageTable# UNION VALUES ('#itemname#') EXCEPT SELECT itemname FROM items";
55 sqlGetItemTables = "SELECT table_name FROM information_schema.tables WHERE table_type='BASE TABLE' AND table_schema=(SELECT table_schema "
56 + "FROM information_schema.tables WHERE table_type='BASE TABLE' AND table_name='#itemsManageTable#') AND NOT table_name='#itemsManageTable#'";
57 // http://stackoverflow.com/questions/17267417/how-do-i-do-an-upsert-merge-insert-on-duplicate-update-in-postgresql
58 // for later use, PostgreSql > 9.5 to prevent PRIMARY key violation use:
59 // SQL_INSERT_ITEM_VALUE = "INSERT INTO #tableName# (TIME, VALUE) VALUES( NOW(), CAST( ? as #dbType#) ) ON
60 // CONFLICT DO NOTHING";
61 sqlInsertItemValue = "INSERT INTO #tableName# (TIME, VALUE) VALUES( #tablePrimaryValue#, CAST( ? as #dbType#) )";
65 * INFO: http://www.java2s.com/Code/Java/Database-SQL-JDBC/StandardSQLDataTypeswithTheirJavaEquivalents.htm
67 private void initSqlTypes() {
68 // Initialize the type array
69 sqlTypes.put("CALLITEM", "VARCHAR");
70 sqlTypes.put("COLORITEM", "VARCHAR");
71 sqlTypes.put("CONTACTITEM", "VARCHAR");
72 sqlTypes.put("DATETIMEITEM", "TIMESTAMP");
73 sqlTypes.put("DIMMERITEM", "SMALLINT");
74 sqlTypes.put("IMAGEITEM", "VARCHAR");
75 sqlTypes.put("LOCATIONITEM", "VARCHAR");
76 sqlTypes.put("NUMBERITEM", "DOUBLE PRECISION");
77 sqlTypes.put("PLAYERITEM", "VARCHAR");
78 sqlTypes.put("ROLLERSHUTTERITEM", "SMALLINT");
79 sqlTypes.put("STRINGITEM", "VARCHAR");
80 sqlTypes.put("SWITCHITEM", "VARCHAR");
81 logger.debug("JDBC::initSqlTypes: Initialized the type array sqlTypes={}", sqlTypes.values());
85 * INFO: https://github.com/brettwooldridge/HikariCP
87 private void initDbProps() {
89 // databaseProps.setProperty("dataSource.cachePrepStmts", "true");
90 // databaseProps.setProperty("dataSource.prepStmtCacheSize", "250");
91 // databaseProps.setProperty("dataSource.prepStmtCacheSqlLimit", "2048");
93 // Properties for HikariCP
94 databaseProps.setProperty("driverClassName", "org.postgresql.Driver");
95 // driverClassName OR BETTER USE dataSourceClassName
96 // databaseProps.setProperty("dataSourceClassName", "org.postgresql.ds.PGSimpleDataSource");
97 // databaseProps.setProperty("maximumPoolSize", "3");
98 // databaseProps.setProperty("minimumIdle", "2");
105 public ItemsVO doCreateItemsTableIfNot(ItemsVO vo) {
106 String sql = StringUtilsExt.replaceArrayMerge(sqlCreateItemsTableIfNot,
107 new String[] { "#itemsManageTable#", "#colname#", "#coltype#", "#itemsManageTable#" },
108 new String[] { vo.getItemsManageTable(), vo.getColname(), vo.getColtype(), vo.getItemsManageTable() });
109 logger.debug("JDBC::doCreateItemsTableIfNot sql={}", sql);
110 Yank.execute(sql, null);
115 public Long doCreateNewEntryInItemsTable(ItemsVO vo) {
116 String sql = StringUtilsExt.replaceArrayMerge(sqlCreateNewEntryInItemsTable,
117 new String[] { "#itemsManageTable#", "#itemname#" },
118 new String[] { vo.getItemsManageTable(), vo.getItemname() });
119 logger.debug("JDBC::doCreateNewEntryInItemsTable sql={}", sql);
120 return Yank.insert(sql, null);
124 public List<ItemsVO> doGetItemTables(ItemsVO vo) {
125 String sql = StringUtilsExt.replaceArrayMerge(this.sqlGetItemTables,
126 new String[] { "#itemsManageTable#", "#itemsManageTable#" },
127 new String[] { vo.getItemsManageTable(), vo.getItemsManageTable() });
128 this.logger.debug("JDBC::doGetItemTables sql={}", sql);
129 return Yank.queryBeanList(sql, ItemsVO.class, null);
136 public void doStoreItemValue(Item item, ItemVO vo) {
137 vo = storeItemValueProvider(item, vo);
138 String sql = StringUtilsExt.replaceArrayMerge(sqlInsertItemValue,
139 new String[] { "#tableName#", "#dbType#", "#tablePrimaryValue#" },
140 new String[] { vo.getTableName(), vo.getDbType(), sqlTypes.get("tablePrimaryValue") });
141 Object[] params = new Object[] { vo.getValue() };
142 logger.debug("JDBC::doStoreItemValue sql={} value='{}'", sql, vo.getValue());
143 Yank.execute(sql, params);
146 /****************************
147 * SQL generation Providers *
148 ****************************/
151 protected String histItemFilterQueryProvider(FilterCriteria filter, int numberDecimalcount, String table,
152 String simpleName, ZoneId timeZone) {
154 "JDBC::getHistItemFilterQueryProvider filter = {}, numberDecimalcount = {}, table = {}, simpleName = {}",
155 filter.toString(), numberDecimalcount, table, simpleName);
157 String filterString = "";
158 if (filter.getBeginDate() != null) {
159 filterString += filterString.isEmpty() ? " WHERE" : " AND";
160 filterString += " TIME>'" + JDBC_DATE_FORMAT.format(filter.getBeginDate().withZoneSameInstant(timeZone))
163 if (filter.getEndDate() != null) {
164 filterString += filterString.isEmpty() ? " WHERE" : " AND";
165 filterString += " TIME<'" + JDBC_DATE_FORMAT.format(filter.getEndDate().withZoneSameInstant(timeZone))
168 filterString += (filter.getOrdering() == Ordering.ASCENDING) ? " ORDER BY time ASC" : " ORDER BY time DESC";
169 if (filter.getPageSize() != 0x7fffffff) {
171 // http://www.jooq.org/doc/3.5/manual/sql-building/sql-statements/select-statement/limit-clause/
172 filterString += " OFFSET " + filter.getPageNumber() * filter.getPageSize() + " LIMIT "
173 + filter.getPageSize();
175 String queryString = "NUMBERITEM".equalsIgnoreCase(simpleName) && numberDecimalcount > -1
176 ? "SELECT time, ROUND(CAST (value AS numeric)," + numberDecimalcount + ") FROM " + table
177 : "SELECT time, value FROM " + table;
178 if (!filterString.isEmpty()) {
179 queryString += filterString;
181 logger.debug("JDBC::query queryString = {}", queryString);
189 /******************************
190 * public Getters and Setters *
191 ******************************/