2 * Copyright (c) 2010-2023 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.time.ZonedDateTime;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Date;
19 import java.util.List;
20 import java.util.Locale;
22 import java.util.Map.Entry;
24 import java.util.stream.Collectors;
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.core.config.core.ConfigurableService;
29 import org.openhab.core.i18n.TimeZoneProvider;
30 import org.openhab.core.items.GroupItem;
31 import org.openhab.core.items.Item;
32 import org.openhab.core.items.ItemNotFoundException;
33 import org.openhab.core.items.ItemRegistry;
34 import org.openhab.core.persistence.FilterCriteria;
35 import org.openhab.core.persistence.HistoricItem;
36 import org.openhab.core.persistence.ModifiablePersistenceService;
37 import org.openhab.core.persistence.PersistenceItemInfo;
38 import org.openhab.core.persistence.PersistenceService;
39 import org.openhab.core.persistence.QueryablePersistenceService;
40 import org.openhab.core.persistence.strategy.PersistenceStrategy;
41 import org.openhab.core.types.State;
42 import org.openhab.core.types.UnDefType;
43 import org.openhab.persistence.jdbc.internal.db.JdbcBaseDAO;
44 import org.openhab.persistence.jdbc.internal.dto.Column;
45 import org.openhab.persistence.jdbc.internal.dto.ItemsVO;
46 import org.openhab.persistence.jdbc.internal.exceptions.JdbcException;
47 import org.openhab.persistence.jdbc.internal.exceptions.JdbcSQLException;
48 import org.osgi.framework.BundleContext;
49 import org.osgi.framework.Constants;
50 import org.osgi.service.component.annotations.Activate;
51 import org.osgi.service.component.annotations.Component;
52 import org.osgi.service.component.annotations.Deactivate;
53 import org.osgi.service.component.annotations.Reference;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
58 * This is the implementation of the JDBC {@link PersistenceService}.
60 * @author Helmut Lehmeyer - Initial contribution
61 * @author Kai Kreuzer - Migration to 3.x
64 @Component(service = { PersistenceService.class,
65 QueryablePersistenceService.class }, configurationPid = "org.openhab.jdbc", //
66 property = Constants.SERVICE_PID + "=org.openhab.jdbc")
67 @ConfigurableService(category = "persistence", label = "JDBC Persistence Service", description_uri = JdbcPersistenceServiceConstants.CONFIG_URI)
68 public class JdbcPersistenceService extends JdbcMapper implements ModifiablePersistenceService {
70 private final Logger logger = LoggerFactory.getLogger(JdbcPersistenceService.class);
72 private final ItemRegistry itemRegistry;
75 public JdbcPersistenceService(final @Reference ItemRegistry itemRegistry,
76 final @Reference TimeZoneProvider timeZoneProvider) {
77 super(timeZoneProvider);
78 this.itemRegistry = itemRegistry;
82 * Called by the SCR to activate the component with its configuration read
85 * @param bundleContext
86 * BundleContext of the Bundle that defines this component
87 * @param configuration
88 * Configuration properties for this component obtained from the
92 public void activate(BundleContext bundleContext, Map<Object, Object> configuration) {
93 logger.debug("JDBC::activate: persistence service activated");
94 updateConfig(configuration);
98 * Called by the SCR to deactivate the component when either the
99 * configuration is removed or mandatory references are no longer satisfied
100 * or the component has simply been stopped.
103 * Reason code for the deactivation:<br>
105 * <li>0 – Unspecified
106 * <li>1 – The component was disabled
107 * <li>2 – A reference became unsatisfied
108 * <li>3 – A configuration was changed
109 * <li>4 – A configuration was deleted
110 * <li>5 – The component was disposed
111 * <li>6 – The bundle was stopped
115 public void deactivate(final int reason) {
116 logger.debug("JDBC::deactivate: persistence bundle stopping. Disconnecting from database. reason={}", reason);
117 // closeConnection();
122 public String getId() {
123 logger.debug("JDBC::getName: returning name 'jdbc' for queryable persistence service.");
124 return JdbcPersistenceServiceConstants.SERVICE_ID;
128 public String getLabel(@Nullable Locale locale) {
129 return JdbcPersistenceServiceConstants.SERVICE_LABEL;
133 public void store(Item item) {
134 internalStore(item, null, item.getState());
138 public void store(Item item, @Nullable String alias) {
139 // alias is not supported
140 internalStore(item, null, item.getState());
144 public void store(Item item, ZonedDateTime date, State state) {
145 internalStore(item, date, state);
148 private void internalStore(Item item, @Nullable ZonedDateTime date, State state) {
149 // Do not store undefined/uninitialized data
150 if (state instanceof UnDefType) {
151 logger.debug("JDBC::store: ignore Item '{}' because it is UnDefType", item.getName());
154 if (!checkDBAccessability()) {
156 "JDBC::store: No connection to database. Cannot persist state '{}' for item '{}'! Will retry connecting to database when error count:{} equals errReconnectThreshold:{}",
157 state, item, errCnt, conf.getErrReconnectThreshold());
161 long timerStart = System.currentTimeMillis();
162 storeItemValue(item, state, date);
163 if (logger.isDebugEnabled()) {
164 logger.debug("JDBC: Stored item '{}' as '{}' in SQL database at {} in {} ms.", item.getName(), state,
165 new Date(), System.currentTimeMillis() - timerStart);
167 } catch (JdbcException e) {
168 logger.warn("JDBC::store: Unable to store item", e);
173 public Set<PersistenceItemInfo> getItemInfo() {
178 * Queries the {@link PersistenceService} for data with a given filter
182 * the filter to apply to the query
183 * @return a time series of items
186 public Iterable<HistoricItem> query(FilterCriteria filter) {
187 if (!checkDBAccessability()) {
188 logger.warn("JDBC::query: database not connected, query aborted for item '{}'", filter.getItemName());
192 // Get the item name from the filter
193 // Also get the Item object so we can determine the type
195 String itemName = filter.getItemName();
196 logger.debug("JDBC::query: item is {}", itemName);
198 item = itemRegistry.getItem(itemName);
199 } catch (ItemNotFoundException e1) {
200 logger.error("JDBC::query: unable to get item for itemName: '{}'. Ignore and give up!", itemName);
204 if (item instanceof GroupItem) {
205 // For Group Item is BaseItem needed to get correct Type of Value.
206 item = GroupItem.class.cast(item).getBaseItem();
207 logger.debug("JDBC::query: item is instanceof GroupItem '{}'", itemName);
209 logger.debug("JDBC::query: BaseItem of GroupItem is null. Ignore and give up!");
212 if (item instanceof GroupItem) {
213 logger.debug("JDBC::query: BaseItem of GroupItem is a GroupItem too. Ignore and give up!");
218 String table = itemNameToTableNameMap.get(itemName);
220 logger.debug("JDBC::query: unable to find table for item with name: '{}', no data in database.", itemName);
225 long timerStart = System.currentTimeMillis();
226 List<HistoricItem> items = getHistItemFilterQuery(filter, conf.getNumberDecimalcount(), table, item);
227 if (logger.isDebugEnabled()) {
228 logger.debug("JDBC: Query for item '{}' returned {} rows in {} ms", itemName, items.size(),
229 System.currentTimeMillis() - timerStart);
234 } catch (JdbcSQLException e) {
235 logger.warn("JDBC::query: Unable to query item", e);
240 public void updateConfig(Map<Object, Object> configuration) {
241 logger.debug("JDBC::updateConfig");
243 conf = new JdbcConfiguration(configuration);
244 if (conf.valid && checkDBAccessability()) {
245 namingStrategy = new NamingStrategy(conf);
248 // connection has been established ... initialization completed!
250 } catch (JdbcSQLException e) {
251 logger.error("Failed to check database schema", e);
258 logger.debug("JDBC::updateConfig: configuration complete for service={}.", getId());
262 public List<PersistenceStrategy> getDefaultStrategies() {
263 return List.of(PersistenceStrategy.Globals.CHANGE);
267 public boolean remove(FilterCriteria filter) throws IllegalArgumentException {
268 if (!checkDBAccessability()) {
269 logger.warn("JDBC::remove: database not connected, remove aborted for item '{}'", filter.getItemName());
273 // Get the item name from the filter
274 // Also get the Item object so we can determine the type
275 String itemName = filter.getItemName();
276 logger.debug("JDBC::remove: item is {}", itemName);
277 if (itemName == null) {
278 throw new IllegalArgumentException("Item name must not be null");
281 String table = itemNameToTableNameMap.get(itemName);
283 logger.debug("JDBC::remove: unable to find table for item with name: '{}', no data in database.", itemName);
288 long timerStart = System.currentTimeMillis();
289 deleteItemValues(filter, table);
290 if (logger.isDebugEnabled()) {
291 logger.debug("JDBC: Deleted values for item '{}' in SQL database at {} in {} ms.", itemName, new Date(),
292 System.currentTimeMillis() - timerStart);
295 } catch (JdbcSQLException e) {
296 logger.debug("JDBC::remove: Unable to remove values for item", e);
302 * Get a list of names of persisted items.
304 public Collection<String> getItemNames() {
305 return itemNameToTableNameMap.keySet();
309 * Get a map of item names to table names.
311 public Map<String, String> getItemNameToTableNameMap() {
312 return itemNameToTableNameMap;
316 * Check schema of specific item table for integrity issues.
318 * @param tableName for which columns should be checked
319 * @param itemName that corresponds to table
320 * @return Collection of strings, each describing an identified issue
321 * @throws JdbcSQLException on SQL errors
323 public Collection<String> getSchemaIssues(String tableName, String itemName) throws JdbcSQLException {
324 List<String> issues = new ArrayList<>();
326 if (!checkDBAccessability()) {
327 logger.warn("JDBC::getSchemaIssues: database not connected");
333 item = itemRegistry.getItem(itemName);
334 } catch (ItemNotFoundException e) {
337 JdbcBaseDAO dao = conf.getDBDAO();
338 String timeDataType = dao.sqlTypes.get("tablePrimaryKey");
339 if (timeDataType == null) {
342 String valueDataType = dao.getDataType(item);
343 List<Column> columns = getTableColumns(tableName);
344 for (Column column : columns) {
345 String columnName = column.getColumnName();
346 if ("time".equalsIgnoreCase(columnName)) {
347 if (!"time".equals(columnName)) {
348 issues.add("Column name 'time' expected, but is '" + columnName + "'");
350 if (!timeDataType.equalsIgnoreCase(column.getColumnType())
351 && !timeDataType.equalsIgnoreCase(column.getColumnTypeAlias())) {
352 issues.add("Column type '" + timeDataType + "' expected, but is '"
353 + column.getColumnType().toUpperCase() + "'");
355 if (column.getIsNullable()) {
356 issues.add("Column 'time' expected to be NOT NULL, but is nullable");
358 } else if ("value".equalsIgnoreCase(columnName)) {
359 if (!"value".equals(columnName)) {
360 issues.add("Column name 'value' expected, but is '" + columnName + "'");
362 if (!valueDataType.equalsIgnoreCase(column.getColumnType())
363 && !valueDataType.equalsIgnoreCase(column.getColumnTypeAlias())) {
364 issues.add("Column type '" + valueDataType + "' expected, but is '"
365 + column.getColumnType().toUpperCase() + "'");
367 if (!column.getIsNullable()) {
368 issues.add("Column 'value' expected to be nullable, but is NOT NULL");
371 issues.add("Column '" + columnName + "' not expected");
380 * @param tableName for which columns should be repaired
381 * @param itemName that corresponds to table
382 * @return true if table was altered, otherwise false
383 * @throws JdbcSQLException on SQL errors
385 public boolean fixSchemaIssues(String tableName, String itemName) throws JdbcSQLException {
386 if (!checkDBAccessability()) {
387 logger.warn("JDBC::fixSchemaIssues: database not connected");
393 item = itemRegistry.getItem(itemName);
394 } catch (ItemNotFoundException e) {
397 JdbcBaseDAO dao = conf.getDBDAO();
398 String timeDataType = dao.sqlTypes.get("tablePrimaryKey");
399 if (timeDataType == null) {
402 String valueDataType = dao.getDataType(item);
403 List<Column> columns = getTableColumns(tableName);
404 boolean isFixed = false;
405 for (Column column : columns) {
406 String columnName = column.getColumnName();
407 if ("time".equalsIgnoreCase(columnName)) {
408 if (!"time".equals(columnName)
409 || (!timeDataType.equalsIgnoreCase(column.getColumnType())
410 && !timeDataType.equalsIgnoreCase(column.getColumnTypeAlias()))
411 || column.getIsNullable()) {
412 alterTableColumn(tableName, "time", timeDataType, false);
415 } else if ("value".equalsIgnoreCase(columnName)) {
416 if (!"value".equals(columnName)
417 || (!valueDataType.equalsIgnoreCase(column.getColumnType())
418 && !valueDataType.equalsIgnoreCase(column.getColumnTypeAlias()))
419 || !column.getIsNullable()) {
420 alterTableColumn(tableName, "value", valueDataType, true);
429 * Get a list of all items with corresponding tables and an {@link ItemTableCheckEntryStatus} indicating
432 * @return list of {@link ItemTableCheckEntry}
434 public List<ItemTableCheckEntry> getCheckedEntries() throws JdbcSQLException {
435 List<ItemTableCheckEntry> entries = new ArrayList<>();
437 if (!checkDBAccessability()) {
438 logger.warn("JDBC::getCheckedEntries: database not connected");
442 var orphanTables = getItemTables().stream().map(ItemsVO::getTableName).collect(Collectors.toSet());
443 for (Entry<String, String> entry : itemNameToTableNameMap.entrySet()) {
444 String itemName = entry.getKey();
445 String tableName = entry.getValue();
446 entries.add(getCheckedEntry(itemName, tableName, orphanTables.contains(tableName)));
447 orphanTables.remove(tableName);
449 for (String orphanTable : orphanTables) {
450 entries.add(new ItemTableCheckEntry("", orphanTable, ItemTableCheckEntryStatus.ORPHAN_TABLE));
455 private ItemTableCheckEntry getCheckedEntry(String itemName, String tableName, boolean tableExists) {
458 itemRegistry.getItem(itemName);
460 } catch (ItemNotFoundException e) {
464 ItemTableCheckEntryStatus status;
467 status = ItemTableCheckEntryStatus.TABLE_MISSING;
469 status = ItemTableCheckEntryStatus.ITEM_AND_TABLE_MISSING;
471 } else if (itemExists) {
472 status = ItemTableCheckEntryStatus.VALID;
474 status = ItemTableCheckEntryStatus.ITEM_MISSING;
476 return new ItemTableCheckEntry(itemName, tableName, status);
480 * Clean up inconsistent item: Remove from index and drop table.
481 * Tables with any rows are skipped, unless force is set.
483 * @param itemName Name of item to clean
484 * @param force If true, non-empty tables will be dropped too
485 * @return true if item was cleaned up
486 * @throws JdbcSQLException
488 public boolean cleanupItem(String itemName, boolean force) throws JdbcSQLException {
489 if (!checkDBAccessability()) {
490 logger.warn("JDBC::cleanupItem: database not connected");
494 String tableName = itemNameToTableNameMap.get(itemName);
495 if (tableName == null) {
498 ItemTableCheckEntry entry = getCheckedEntry(itemName, tableName, ifTableExists(tableName));
499 return cleanupItem(entry, force);
503 * Clean up inconsistent item: Remove from index and drop table.
504 * Tables with any rows are skipped.
507 * @return true if item was cleaned up
508 * @throws JdbcSQLException
510 public boolean cleanupItem(ItemTableCheckEntry entry) throws JdbcSQLException {
511 return cleanupItem(entry, false);
514 private boolean cleanupItem(ItemTableCheckEntry entry, boolean force) throws JdbcSQLException {
515 if (!checkDBAccessability()) {
516 logger.warn("JDBC::cleanupItem: database not connected");
520 ItemTableCheckEntryStatus status = entry.getStatus();
521 String tableName = entry.getTableName();
524 if (!force && getRowCount(tableName) > 0) {
527 dropTable(tableName);
528 // Fall through to remove from index.
530 case ITEM_AND_TABLE_MISSING:
531 if (!conf.getTableUseRealCaseSensitiveItemNames()) {
532 ItemsVO itemsVo = new ItemsVO();
533 itemsVo.setItemName(entry.getItemName());
534 itemsVo.setItemsManageTable(conf.getItemsManageTable());
535 deleteItemsEntry(itemsVo);
537 itemNameToTableNameMap.remove(entry.getItemName());