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;
15 import java.util.List;
16 import java.util.Locale;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.openhab.core.config.core.ConfigurableService;
23 import org.openhab.core.i18n.TimeZoneProvider;
24 import org.openhab.core.items.GroupItem;
25 import org.openhab.core.items.Item;
26 import org.openhab.core.items.ItemNotFoundException;
27 import org.openhab.core.items.ItemRegistry;
28 import org.openhab.core.persistence.FilterCriteria;
29 import org.openhab.core.persistence.HistoricItem;
30 import org.openhab.core.persistence.PersistenceItemInfo;
31 import org.openhab.core.persistence.PersistenceService;
32 import org.openhab.core.persistence.QueryablePersistenceService;
33 import org.openhab.core.persistence.strategy.PersistenceStrategy;
34 import org.openhab.core.types.UnDefType;
35 import org.osgi.framework.BundleContext;
36 import org.osgi.framework.Constants;
37 import org.osgi.service.component.annotations.Activate;
38 import org.osgi.service.component.annotations.Component;
39 import org.osgi.service.component.annotations.Deactivate;
40 import org.osgi.service.component.annotations.Reference;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
45 * This is the implementation of the JDBC {@link PersistenceService}.
47 * @author Helmut Lehmeyer - Initial contribution
48 * @author Kai Kreuzer - Migration to 3.x
51 @Component(service = { PersistenceService.class,
52 QueryablePersistenceService.class }, configurationPid = "org.openhab.jdbc", //
53 property = Constants.SERVICE_PID + "=org.openhab.jdbc")
54 @ConfigurableService(category = "persistence", label = "JDBC Persistence Service", description_uri = JdbcPersistenceService.CONFIG_URI)
55 public class JdbcPersistenceService extends JdbcMapper implements QueryablePersistenceService {
57 protected static final String CONFIG_URI = "persistence:jdbc";
59 private final Logger logger = LoggerFactory.getLogger(JdbcPersistenceService.class);
61 private final ItemRegistry itemRegistry;
64 public JdbcPersistenceService(final @Reference ItemRegistry itemRegistry,
65 final @Reference TimeZoneProvider timeZoneProvider) {
66 super(timeZoneProvider);
67 this.itemRegistry = itemRegistry;
71 * Called by the SCR to activate the component with its configuration read
74 * @param bundleContext
75 * BundleContext of the Bundle that defines this component
76 * @param configuration
77 * Configuration properties for this component obtained from the
81 public void activate(BundleContext bundleContext, Map<Object, Object> configuration) {
82 logger.debug("JDBC::activate: persistence service activated");
83 updateConfig(configuration);
87 * Called by the SCR to deactivate the component when either the
88 * configuration is removed or mandatory references are no longer satisfied
89 * or the component has simply been stopped.
92 * Reason code for the deactivation:<br>
95 * <li>1 – The component was disabled
96 * <li>2 – A reference became unsatisfied
97 * <li>3 – A configuration was changed
98 * <li>4 – A configuration was deleted
99 * <li>5 – The component was disposed
100 * <li>6 – The bundle was stopped
104 public void deactivate(final int reason) {
105 logger.debug("JDBC::deactivate: persistence bundle stopping. Disconnecting from database. reason={}", reason);
106 // closeConnection();
111 public String getId() {
112 logger.debug("JDBC::getName: returning name 'jdbc' for queryable persistence service.");
117 public String getLabel(@Nullable Locale locale) {
122 public void store(Item item) {
130 public void store(Item item, @Nullable String alias) {
131 // Do not store undefined/uninitialized data
132 if (item.getState() instanceof UnDefType) {
133 logger.debug("JDBC::store: ignore Item '{}' because it is UnDefType", item.getName());
136 if (!checkDBAccessability()) {
138 "JDBC::store: No connection to database. Cannot persist item '{}'! Will retry connecting to database when error count:{} equals errReconnectThreshold:{}",
139 item, errCnt, conf.getErrReconnectThreshold());
142 long timerStart = System.currentTimeMillis();
143 storeItemValue(item);
144 logger.debug("JDBC: Stored item '{}' as '{}' in SQL database at {} in {} ms.", item.getName(), item.getState(),
145 new java.util.Date(), System.currentTimeMillis() - timerStart);
149 public Set<PersistenceItemInfo> getItemInfo() {
154 * Queries the {@link PersistenceService} for data with a given filter
158 * the filter to apply to the query
159 * @return a time series of items
162 public Iterable<HistoricItem> query(FilterCriteria filter) {
163 if (!checkDBAccessability()) {
164 logger.warn("JDBC::query: database not connected, query aborted for item '{}'", filter.getItemName());
168 // Get the item name from the filter
169 // Also get the Item object so we can determine the type
171 String itemName = filter.getItemName();
172 logger.debug("JDBC::query: item is {}", itemName);
174 item = itemRegistry.getItem(itemName);
175 } catch (ItemNotFoundException e1) {
176 logger.error("JDBC::query: unable to get item for itemName: '{}'. Ignore and give up!", itemName);
180 if (item instanceof GroupItem) {
181 // For Group Item is BaseItem needed to get correct Type of Value.
182 item = GroupItem.class.cast(item).getBaseItem();
183 logger.debug("JDBC::query: item is instanceof GroupItem '{}'", itemName);
185 logger.debug("JDBC::query: BaseItem of GroupItem is null. Ignore and give up!");
188 if (item instanceof GroupItem) {
189 logger.debug("JDBC::query: BaseItem of GroupItem is a GroupItem too. Ignore and give up!");
194 String table = sqlTables.get(itemName);
196 logger.debug("JDBC::query: unable to find table for item with name: '{}', no data in database.", itemName);
200 long timerStart = System.currentTimeMillis();
201 List<HistoricItem> items = getHistItemFilterQuery(filter, conf.getNumberDecimalcount(), table, item);
202 if (logger.isDebugEnabled()) {
203 logger.debug("JDBC: Query for item '{}' returned {} rows in {} ms", itemName, items.size(),
204 System.currentTimeMillis() - timerStart);
212 public void updateConfig(Map<Object, Object> configuration) {
213 logger.debug("JDBC::updateConfig");
215 conf = new JdbcConfiguration(configuration);
216 if (conf.valid && checkDBAccessability()) {
218 // connection has been established ... initialization completed!
224 logger.debug("JDBC::updateConfig: configuration complete for service={}.", getId());
228 public List<PersistenceStrategy> getDefaultStrategies() {
229 return List.of(PersistenceStrategy.Globals.CHANGE);