]> git.basschouten.com Git - openhab-addons.git/blob
ee7abd7781368910164022e37b3ad05f6098509b
[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 of specific item table 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                         && !timeDataType.equalsIgnoreCase(column.getColumnTypeAlias())) {
352                     issues.add("Column type '" + timeDataType + "' expected, but is '"
353                             + column.getColumnType().toUpperCase() + "'");
354                 }
355                 if (column.getIsNullable()) {
356                     issues.add("Column 'time' expected to be NOT NULL, but is nullable");
357                 }
358             } else if ("value".equalsIgnoreCase(columnName)) {
359                 if (!"value".equals(columnName)) {
360                     issues.add("Column name 'value' expected, but is '" + columnName + "'");
361                 }
362                 if (!valueDataType.equalsIgnoreCase(column.getColumnType())
363                         && !valueDataType.equalsIgnoreCase(column.getColumnTypeAlias())) {
364                     issues.add("Column type '" + valueDataType + "' expected, but is '"
365                             + column.getColumnType().toUpperCase() + "'");
366                 }
367                 if (!column.getIsNullable()) {
368                     issues.add("Column 'value' expected to be nullable, but is NOT NULL");
369                 }
370             } else {
371                 issues.add("Column '" + columnName + "' not expected");
372             }
373         }
374         return issues;
375     }
376
377     /**
378      * Fix schema issues.
379      *
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
384      */
385     public boolean fixSchemaIssues(String tableName, String itemName) throws JdbcSQLException {
386         if (!checkDBAccessability()) {
387             logger.warn("JDBC::fixSchemaIssues: database not connected");
388             return false;
389         }
390
391         Item item;
392         try {
393             item = itemRegistry.getItem(itemName);
394         } catch (ItemNotFoundException e) {
395             return false;
396         }
397         JdbcBaseDAO dao = conf.getDBDAO();
398         String timeDataType = dao.sqlTypes.get("tablePrimaryKey");
399         if (timeDataType == null) {
400             return false;
401         }
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);
413                     isFixed = true;
414                 }
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);
421                     isFixed = true;
422                 }
423             }
424         }
425         return isFixed;
426     }
427
428     /**
429      * Get a list of all items with corresponding tables and an {@link ItemTableCheckEntryStatus} indicating
430      * its condition.
431      *
432      * @return list of {@link ItemTableCheckEntry}
433      */
434     public List<ItemTableCheckEntry> getCheckedEntries() throws JdbcSQLException {
435         List<ItemTableCheckEntry> entries = new ArrayList<>();
436
437         if (!checkDBAccessability()) {
438             logger.warn("JDBC::getCheckedEntries: database not connected");
439             return entries;
440         }
441
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);
448         }
449         for (String orphanTable : orphanTables) {
450             entries.add(new ItemTableCheckEntry("", orphanTable, ItemTableCheckEntryStatus.ORPHAN_TABLE));
451         }
452         return entries;
453     }
454
455     private ItemTableCheckEntry getCheckedEntry(String itemName, String tableName, boolean tableExists) {
456         boolean itemExists;
457         try {
458             itemRegistry.getItem(itemName);
459             itemExists = true;
460         } catch (ItemNotFoundException e) {
461             itemExists = false;
462         }
463
464         ItemTableCheckEntryStatus status;
465         if (!tableExists) {
466             if (itemExists) {
467                 status = ItemTableCheckEntryStatus.TABLE_MISSING;
468             } else {
469                 status = ItemTableCheckEntryStatus.ITEM_AND_TABLE_MISSING;
470             }
471         } else if (itemExists) {
472             status = ItemTableCheckEntryStatus.VALID;
473         } else {
474             status = ItemTableCheckEntryStatus.ITEM_MISSING;
475         }
476         return new ItemTableCheckEntry(itemName, tableName, status);
477     }
478
479     /**
480      * Clean up inconsistent item: Remove from index and drop table.
481      * Tables with any rows are skipped, unless force is set.
482      *
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
487      */
488     public boolean cleanupItem(String itemName, boolean force) throws JdbcSQLException {
489         if (!checkDBAccessability()) {
490             logger.warn("JDBC::cleanupItem: database not connected");
491             return false;
492         }
493
494         String tableName = itemNameToTableNameMap.get(itemName);
495         if (tableName == null) {
496             return false;
497         }
498         ItemTableCheckEntry entry = getCheckedEntry(itemName, tableName, ifTableExists(tableName));
499         return cleanupItem(entry, force);
500     }
501
502     /**
503      * Clean up inconsistent item: Remove from index and drop table.
504      * Tables with any rows are skipped.
505      *
506      * @param entry
507      * @return true if item was cleaned up
508      * @throws JdbcSQLException
509      */
510     public boolean cleanupItem(ItemTableCheckEntry entry) throws JdbcSQLException {
511         return cleanupItem(entry, false);
512     }
513
514     private boolean cleanupItem(ItemTableCheckEntry entry, boolean force) throws JdbcSQLException {
515         if (!checkDBAccessability()) {
516             logger.warn("JDBC::cleanupItem: database not connected");
517             return false;
518         }
519
520         ItemTableCheckEntryStatus status = entry.getStatus();
521         String tableName = entry.getTableName();
522         switch (status) {
523             case ITEM_MISSING:
524                 if (!force && getRowCount(tableName) > 0) {
525                     return false;
526                 }
527                 dropTable(tableName);
528                 // Fall through to remove from index.
529             case TABLE_MISSING:
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);
536                 }
537                 itemNameToTableNameMap.remove(entry.getItemName());
538                 return true;
539             case ORPHAN_TABLE:
540             case VALID:
541             default:
542                 // Nothing to clean.
543                 return false;
544         }
545     }
546 }