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.binding.dbquery.internal.domain;
15 import java.util.Objects;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.openhab.binding.dbquery.internal.config.QueryConfiguration;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
24 * Extracts a result from {@link QueryResult} to a single value to be used in channels
25 * (after being converted that it's not responsability of this class)
27 * @author Joan Pujol - Initial contribution
30 public class QueryResultExtractor {
31 private final Logger logger = LoggerFactory.getLogger(QueryResultExtractor.class);
32 private final QueryConfiguration config;
34 public QueryResultExtractor(QueryConfiguration config) {
38 public ResultValue extractResult(QueryResult queryResult) {
39 if (queryResult.isCorrect()) {
40 if (config.isScalarResult()) {
41 return getScalarValue(queryResult);
43 return ResultValue.of(queryResult);
46 return ResultValue.incorrect();
50 private ResultValue getScalarValue(QueryResult queryResult) {
51 if (validateHasScalarValue(queryResult)) {
52 var row = queryResult.getData().get(0);
55 if (config.isScalarColumnDefined()) {
56 value = row.getValue(Objects.requireNonNull(config.getScalarColumn()));
58 value = row.getValue(row.getColumnNames().iterator().next());
60 return ResultValue.of(value);
62 return ResultValue.incorrect();
66 private boolean validateHasScalarValue(QueryResult queryResult) {
67 boolean valid = false;
68 String baseErrorMessage = "Can't get scalar value for result: ";
69 if (queryResult.isCorrect()) {
70 if (queryResult.getData().size() == 1) {
71 boolean oneColumn = queryResult.getData().get(0).getColumnsSize() == 1;
72 if (oneColumn || config.isScalarColumnDefined()) {
75 logger.warn("{} Columns size is {} and scalarColumn isn't defined", baseErrorMessage,
76 queryResult.getData().get(0).getColumnNames().size());
79 logger.warn("{} Rows size is {}", baseErrorMessage, queryResult.getData().size());
82 logger.debug("{} Incorrect result", baseErrorMessage);