]> git.basschouten.com Git - openhab-addons.git/blob
339b40ecb198717c32a6523054de7045587af752
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.persistence.jdbc.internal;
14
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;
21 import java.util.Map;
22 import java.util.Map.Entry;
23 import java.util.Set;
24 import java.util.stream.Collectors;
25
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;
56
57 /**
58  * This is the implementation of the JDBC {@link PersistenceService}.
59  *
60  * @author Helmut Lehmeyer - Initial contribution
61  * @author Kai Kreuzer - Migration to 3.x
62  */
63 @NonNullByDefault
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 {
69
70     private final Logger logger = LoggerFactory.getLogger(JdbcPersistenceService.class);
71
72     private final ItemRegistry itemRegistry;
73
74     @Activate
75     public JdbcPersistenceService(final @Reference ItemRegistry itemRegistry,
76             final @Reference TimeZoneProvider timeZoneProvider) {
77         super(timeZoneProvider);
78         this.itemRegistry = itemRegistry;
79     }
80
81     /**
82      * Called by the SCR to activate the component with its configuration read
83      * from CAS
84      *
85      * @param bundleContext
86      *            BundleContext of the Bundle that defines this component
87      * @param configuration
88      *            Configuration properties for this component obtained from the
89      *            ConfigAdmin service
90      */
91     @Activate
92     public void activate(BundleContext bundleContext, Map<Object, Object> configuration) {
93         logger.debug("JDBC::activate: persistence service activated");
94         updateConfig(configuration);
95     }
96
97     /**
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.
101      *
102      * @param reason
103      *            Reason code for the deactivation:<br>
104      *            <ul>
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
112      *            </ul>
113      */
114     @Deactivate
115     public void deactivate(final int reason) {
116         logger.debug("JDBC::deactivate:  persistence bundle stopping. Disconnecting from database. reason={}", reason);
117         // closeConnection();
118         initialized = false;
119     }
120
121     @Override
122     public String getId() {
123         logger.debug("JDBC::getName: returning name 'jdbc' for queryable persistence service.");
124         return JdbcPersistenceServiceConstants.SERVICE_ID;
125     }
126
127     @Override
128     public String getLabel(@Nullable Locale locale) {
129         return JdbcPersistenceServiceConstants.SERVICE_LABEL;
130     }
131
132     @Override
133     public void store(Item item) {
134         internalStore(item, null, item.getState());
135     }
136
137     @Override
138     public void store(Item item, @Nullable String alias) {
139         // alias is not supported
140         internalStore(item, null, item.getState());
141     }
142
143     @Override
144     public void store(Item item, ZonedDateTime date, State state) {
145         internalStore(item, date, state);
146     }
147
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());
152             return;
153         }
154         if (!checkDBAccessability()) {
155             logger.warn(
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());
158             return;
159         }
160         try {
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);
166             }
167         } catch (JdbcException e) {
168             logger.warn("JDBC::store: Unable to store item", e);
169         }
170     }
171
172     @Override
173     public Set<PersistenceItemInfo> getItemInfo() {
174         return getItems();
175     }
176
177     /**
178      * Queries the {@link PersistenceService} for data with a given filter
179      * criteria
180      *
181      * @param filter
182      *            the filter to apply to the query
183      * @return a time series of items
184      */
185     @Override
186     public Iterable<HistoricItem> query(FilterCriteria filter) {
187         if (!checkDBAccessability()) {
188             logger.warn("JDBC::query: database not connected, query aborted for item '{}'", filter.getItemName());
189             return List.of();
190         }
191
192         // Get the item name from the filter
193         // Also get the Item object so we can determine the type
194         Item item = null;
195         String itemName = filter.getItemName();
196         logger.debug("JDBC::query: item is {}", itemName);
197         try {
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);
201             return List.of();
202         }
203
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);
208             if (item == null) {
209                 logger.debug("JDBC::query: BaseItem of GroupItem is null. Ignore and give up!");
210                 return List.of();
211             }
212             if (item instanceof GroupItem) {
213                 logger.debug("JDBC::query: BaseItem of GroupItem is a GroupItem too. Ignore and give up!");
214                 return List.of();
215             }
216         }
217
218         String table = itemNameToTableNameMap.get(itemName);
219         if (table == null) {
220             logger.debug("JDBC::query: unable to find table for item with name: '{}', no data in database.", itemName);
221             return List.of();
222         }
223
224         try {
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);
230             }
231             // Success
232             errCnt = 0;
233             return items;
234         } catch (JdbcSQLException e) {
235             logger.warn("JDBC::query: Unable to query item", e);
236             return List.of();
237         }
238     }
239
240     public void updateConfig(Map<Object, Object> configuration) {
241         logger.debug("JDBC::updateConfig");
242
243         conf = new JdbcConfiguration(configuration);
244         if (conf.valid && checkDBAccessability()) {
245             namingStrategy = new NamingStrategy(conf);
246             try {
247                 checkDBSchema();
248                 // connection has been established ... initialization completed!
249                 initialized = true;
250             } catch (JdbcSQLException e) {
251                 logger.error("Failed to check database schema", e);
252                 initialized = false;
253             }
254         } else {
255             initialized = false;
256         }
257
258         logger.debug("JDBC::updateConfig: configuration complete for service={}.", getId());
259     }
260
261     @Override
262     public List<PersistenceStrategy> getDefaultStrategies() {
263         return List.of(PersistenceStrategy.Globals.CHANGE);
264     }
265
266     @Override
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());
270             return false;
271         }
272
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");
279         }
280
281         String table = itemNameToTableNameMap.get(itemName);
282         if (table == null) {
283             logger.debug("JDBC::remove: unable to find table for item with name: '{}', no data in database.", itemName);
284             return false;
285         }
286
287         try {
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);
293             }
294             return true;
295         } catch (JdbcSQLException e) {
296             logger.debug("JDBC::remove: Unable to remove values for item", e);
297             return false;
298         }
299     }
300
301     /**
302      * Get a list of names of persisted items.
303      */
304     public Collection<String> getItemNames() {
305         return itemNameToTableNameMap.keySet();
306     }
307
308     /**
309      * Get a map of item names to table names.
310      */
311     public Map<String, String> getItemNameToTableNameMap() {
312         return itemNameToTableNameMap;
313     }
314
315     /**
316      * Check schema for integrity issues.
317      *
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
322      */
323     public Collection<String> getSchemaIssues(String tableName, String itemName) throws JdbcSQLException {
324         List<String> issues = new ArrayList<>();
325
326         if (!checkDBAccessability()) {
327             logger.warn("JDBC::getSchemaIssues: database not connected");
328             return issues;
329         }
330
331         Item item;
332         try {
333             item = itemRegistry.getItem(itemName);
334         } catch (ItemNotFoundException e) {
335             return issues;
336         }
337         JdbcBaseDAO dao = conf.getDBDAO();
338         String timeDataType = dao.sqlTypes.get("tablePrimaryKey");
339         if (timeDataType == null) {
340             return issues;
341         }
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 + "'");
349                 }
350                 if (!timeDataType.equalsIgnoreCase(column.getColumnType())) {
351                     issues.add("Column type '" + timeDataType + "' expected, but is '"
352                             + column.getColumnType().toUpperCase() + "'");
353                 }
354                 if (column.getIsNullable()) {
355                     issues.add("Column 'time' expected to be NOT NULL, but is nullable");
356                 }
357             } else if ("value".equalsIgnoreCase(columnName)) {
358                 if (!"value".equals(columnName)) {
359                     issues.add("Column name 'value' expected, but is '" + columnName + "'");
360                 }
361                 if (!valueDataType.equalsIgnoreCase(column.getColumnType())) {
362                     issues.add("Column type '" + valueDataType + "' expected, but is '"
363                             + column.getColumnType().toUpperCase() + "'");
364                 }
365                 if (!column.getIsNullable()) {
366                     issues.add("Column 'value' expected to be nullable, but is NOT NULL");
367                 }
368             } else {
369                 issues.add("Column '" + columnName + "' not expected");
370             }
371         }
372         return issues;
373     }
374
375     /**
376      * Fix schema issues.
377      *
378      * @param tableName for which columns should be repaired
379      * @param itemName that corresponds to table
380      * @return true if table was altered, otherwise false
381      * @throws JdbcSQLException on SQL errors
382      */
383     public boolean fixSchemaIssues(String tableName, String itemName) throws JdbcSQLException {
384         if (!checkDBAccessability()) {
385             logger.warn("JDBC::fixSchemaIssues: database not connected");
386             return false;
387         }
388
389         Item item;
390         try {
391             item = itemRegistry.getItem(itemName);
392         } catch (ItemNotFoundException e) {
393             return false;
394         }
395         JdbcBaseDAO dao = conf.getDBDAO();
396         String timeDataType = dao.sqlTypes.get("tablePrimaryKey");
397         if (timeDataType == null) {
398             return false;
399         }
400         String valueDataType = dao.getDataType(item);
401         List<Column> columns = getTableColumns(tableName);
402         boolean isFixed = false;
403         for (Column column : columns) {
404             String columnName = column.getColumnName();
405             if ("time".equalsIgnoreCase(columnName)) {
406                 if (!"time".equals(columnName) || !timeDataType.equalsIgnoreCase(column.getColumnType())
407                         || column.getIsNullable()) {
408                     alterTableColumn(tableName, "time", timeDataType, false);
409                     isFixed = true;
410                 }
411             } else if ("value".equalsIgnoreCase(columnName)) {
412                 if (!"value".equals(columnName) || !valueDataType.equalsIgnoreCase(column.getColumnType())
413                         || !column.getIsNullable()) {
414                     alterTableColumn(tableName, "value", valueDataType, true);
415                     isFixed = true;
416                 }
417             }
418         }
419         return isFixed;
420     }
421
422     /**
423      * Get a list of all items with corresponding tables and an {@link ItemTableCheckEntryStatus} indicating
424      * its condition.
425      *
426      * @return list of {@link ItemTableCheckEntry}
427      */
428     public List<ItemTableCheckEntry> getCheckedEntries() throws JdbcSQLException {
429         List<ItemTableCheckEntry> entries = new ArrayList<>();
430
431         if (!checkDBAccessability()) {
432             logger.warn("JDBC::getCheckedEntries: database not connected");
433             return entries;
434         }
435
436         var orphanTables = getItemTables().stream().map(ItemsVO::getTableName).collect(Collectors.toSet());
437         for (Entry<String, String> entry : itemNameToTableNameMap.entrySet()) {
438             String itemName = entry.getKey();
439             String tableName = entry.getValue();
440             entries.add(getCheckedEntry(itemName, tableName, orphanTables.contains(tableName)));
441             orphanTables.remove(tableName);
442         }
443         for (String orphanTable : orphanTables) {
444             entries.add(new ItemTableCheckEntry("", orphanTable, ItemTableCheckEntryStatus.ORPHAN_TABLE));
445         }
446         return entries;
447     }
448
449     private ItemTableCheckEntry getCheckedEntry(String itemName, String tableName, boolean tableExists) {
450         boolean itemExists;
451         try {
452             itemRegistry.getItem(itemName);
453             itemExists = true;
454         } catch (ItemNotFoundException e) {
455             itemExists = false;
456         }
457
458         ItemTableCheckEntryStatus status;
459         if (!tableExists) {
460             if (itemExists) {
461                 status = ItemTableCheckEntryStatus.TABLE_MISSING;
462             } else {
463                 status = ItemTableCheckEntryStatus.ITEM_AND_TABLE_MISSING;
464             }
465         } else if (itemExists) {
466             status = ItemTableCheckEntryStatus.VALID;
467         } else {
468             status = ItemTableCheckEntryStatus.ITEM_MISSING;
469         }
470         return new ItemTableCheckEntry(itemName, tableName, status);
471     }
472
473     /**
474      * Clean up inconsistent item: Remove from index and drop table.
475      * Tables with any rows are skipped, unless force is set.
476      *
477      * @param itemName Name of item to clean
478      * @param force If true, non-empty tables will be dropped too
479      * @return true if item was cleaned up
480      * @throws JdbcSQLException
481      */
482     public boolean cleanupItem(String itemName, boolean force) throws JdbcSQLException {
483         if (!checkDBAccessability()) {
484             logger.warn("JDBC::cleanupItem: database not connected");
485             return false;
486         }
487
488         String tableName = itemNameToTableNameMap.get(itemName);
489         if (tableName == null) {
490             return false;
491         }
492         ItemTableCheckEntry entry = getCheckedEntry(itemName, tableName, ifTableExists(tableName));
493         return cleanupItem(entry, force);
494     }
495
496     /**
497      * Clean up inconsistent item: Remove from index and drop table.
498      * Tables with any rows are skipped.
499      *
500      * @param entry
501      * @return true if item was cleaned up
502      * @throws JdbcSQLException
503      */
504     public boolean cleanupItem(ItemTableCheckEntry entry) throws JdbcSQLException {
505         return cleanupItem(entry, false);
506     }
507
508     private boolean cleanupItem(ItemTableCheckEntry entry, boolean force) throws JdbcSQLException {
509         if (!checkDBAccessability()) {
510             logger.warn("JDBC::cleanupItem: database not connected");
511             return false;
512         }
513
514         ItemTableCheckEntryStatus status = entry.getStatus();
515         String tableName = entry.getTableName();
516         switch (status) {
517             case ITEM_MISSING:
518                 if (!force && getRowCount(tableName) > 0) {
519                     return false;
520                 }
521                 dropTable(tableName);
522                 // Fall through to remove from index.
523             case TABLE_MISSING:
524             case ITEM_AND_TABLE_MISSING:
525                 if (!conf.getTableUseRealCaseSensitiveItemNames()) {
526                     ItemsVO itemsVo = new ItemsVO();
527                     itemsVo.setItemName(entry.getItemName());
528                     itemsVo.setItemsManageTable(conf.getItemsManageTable());
529                     deleteItemsEntry(itemsVo);
530                 }
531                 itemNameToTableNameMap.remove(entry.getItemName());
532                 return true;
533             case ORPHAN_TABLE:
534             case VALID:
535             default:
536                 // Nothing to clean.
537                 return false;
538         }
539     }
540 }