001/*-
002 * #%L
003 * HAPI FHIR Server - SQL Migration
004 * %%
005 * Copyright (C) 2014 - 2024 Smile CDR, Inc.
006 * %%
007 * Licensed under the Apache License, Version 2.0 (the "License");
008 * you may not use this file except in compliance with the License.
009 * You may obtain a copy of the License at
010 *
011 *      http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 * #L%
019 */
020package ca.uhn.fhir.jpa.migrate;
021
022import ca.uhn.fhir.i18n.Msg;
023import org.slf4j.Logger;
024import org.slf4j.LoggerFactory;
025import org.springframework.jdbc.core.JdbcTemplate;
026import org.springframework.jdbc.core.RowMapper;
027
028import java.util.List;
029import java.util.Optional;
030
031/**
032 * Utility methods to be used by migrator functionality that needs to invoke JDBC directly.
033 */
034public class MigrationJdbcUtils {
035        private static final Logger ourLog = LoggerFactory.getLogger(MigrationJdbcUtils.class);
036
037        public static boolean queryForSingleBooleanResultMultipleThrowsException(
038                        String theSql, JdbcTemplate theJdbcTemplate) {
039                final RowMapper<Boolean> booleanRowMapper = (theResultSet, theRowNumber) -> theResultSet.getBoolean(1);
040                return queryForSingle(theSql, theJdbcTemplate, booleanRowMapper).orElse(false);
041        }
042
043        private static <T> Optional<T> queryForSingle(
044                        String theSql, JdbcTemplate theJdbcTemplate, RowMapper<T> theRowMapper) {
045                final List<T> results = queryForMultiple(theSql, theJdbcTemplate, theRowMapper);
046
047                if (results.isEmpty()) {
048                        return Optional.empty();
049                }
050
051                if (results.size() > 1) {
052                        // Presumably other callers may want different behaviour but in this case more than one result should be
053                        // considered a hard failure distinct from an empty result, which is one expected outcome.
054                        throw new IllegalArgumentException(Msg.code(2474)
055                                        + String.format(
056                                                        "Failure due to query returning more than one result: %s for SQL: [%s].", results, theSql));
057                }
058
059                return Optional.ofNullable(results.get(0));
060        }
061
062        private static <T> List<T> queryForMultiple(
063                        String theSql, JdbcTemplate theJdbcTemplate, RowMapper<T> theRowMapper) {
064                return theJdbcTemplate.query(theSql, theRowMapper);
065        }
066}