001package ca.uhn.fhir.jpa.migrate.dao;
002
003/*-
004 * #%L
005 * HAPI FHIR Server - SQL Migration
006 * %%
007 * Copyright (C) 2014 - 2023 Smile CDR, Inc.
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 *
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 *
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023import ca.uhn.fhir.i18n.Msg;
024import ca.uhn.fhir.jpa.migrate.DriverTypeEnum;
025import ca.uhn.fhir.jpa.migrate.entity.HapiMigrationEntity;
026import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
027import ca.uhn.fhir.util.VersionEnum;
028import org.apache.commons.lang3.Validate;
029import org.flywaydb.core.api.MigrationVersion;
030import org.slf4j.Logger;
031import org.slf4j.LoggerFactory;
032import org.springframework.jdbc.core.JdbcTemplate;
033
034import javax.sql.DataSource;
035import java.sql.Connection;
036import java.sql.ResultSet;
037import java.sql.SQLException;
038import java.util.Date;
039import java.util.List;
040import java.util.Optional;
041import java.util.Set;
042import java.util.stream.Collectors;
043
044public class HapiMigrationDao {
045        private static final Logger ourLog = LoggerFactory.getLogger(HapiMigrationDao.class);
046
047        private final JdbcTemplate myJdbcTemplate;
048        private final String myMigrationTablename;
049        private final MigrationQueryBuilder myMigrationQueryBuilder;
050        private final DataSource myDataSource;
051
052        public HapiMigrationDao(DataSource theDataSource, DriverTypeEnum theDriverType, String theMigrationTablename) {
053                myDataSource = theDataSource;
054                myJdbcTemplate = new JdbcTemplate(theDataSource);
055                myMigrationTablename = theMigrationTablename;
056                myMigrationQueryBuilder = new MigrationQueryBuilder(theDriverType, theMigrationTablename);
057        }
058
059        public String getMigrationTablename() {
060                return myMigrationTablename;
061        }
062
063        public Set<MigrationVersion> fetchSuccessfulMigrationVersions() {
064                List<HapiMigrationEntity> allEntries = findAll();
065                return allEntries.stream()
066                        .filter(HapiMigrationEntity::getSuccess)
067                        .map(HapiMigrationEntity::getVersion)
068                        .map(MigrationVersion::fromVersion)
069                        .collect(Collectors.toSet());
070        }
071
072        public void deleteAll() {
073                myJdbcTemplate.execute(myMigrationQueryBuilder.deleteAll());
074        }
075
076        /**
077         *
078         * @param theEntity to save.  If the pid is null, the next available pid will be set
079         * @return true if any database records were changed
080         */
081        public boolean save(HapiMigrationEntity theEntity) {
082                Validate.notNull(theEntity.getDescription(), "Description may not be null");
083                Validate.notNull(theEntity.getExecutionTime(), "Execution time may not be null");
084                Validate.notNull(theEntity.getSuccess(), "Success may not be null");
085
086                if (theEntity.getPid() == null) {
087                        Integer highestKey = getHighestKey();
088                        if (highestKey == null || highestKey < 0) {
089                                highestKey = 0;
090                        }
091                        Integer nextAvailableKey = highestKey + 1;
092                        theEntity.setPid(nextAvailableKey);
093                }
094                theEntity.setType("JDBC");
095                theEntity.setScript("HAPI FHIR");
096                theEntity.setInstalledBy(VersionEnum.latestVersion().name());
097                theEntity.setInstalledOn(new Date());
098                String insertRecordStatement = myMigrationQueryBuilder.insertPreparedStatement();
099                int changedRecordCount = myJdbcTemplate.update(insertRecordStatement, theEntity.asPreparedStatementSetter());
100                return changedRecordCount > 0;
101        }
102
103        private Integer getHighestKey() {
104                String highestKeyQuery = myMigrationQueryBuilder.getHighestKeyQuery();
105                return myJdbcTemplate.queryForObject(highestKeyQuery, Integer.class);
106        }
107
108        public void createMigrationTableIfRequired() {
109                if (migrationTableExists()) {
110                        return;
111                }
112                ourLog.info("Creating table {}", myMigrationTablename);
113
114                String createTableStatement = myMigrationQueryBuilder.createTableStatement();
115                ourLog.info(createTableStatement);
116                myJdbcTemplate.execute(createTableStatement);
117
118                String createIndexStatement = myMigrationQueryBuilder.createIndexStatement();
119                ourLog.info(createIndexStatement);
120                myJdbcTemplate.execute(createIndexStatement);
121
122                HapiMigrationEntity entity = HapiMigrationEntity.tableCreatedRecord();
123                myJdbcTemplate.update(myMigrationQueryBuilder.insertPreparedStatement(), entity.asPreparedStatementSetter());
124        }
125
126        private boolean migrationTableExists() {
127                try {
128                        try (Connection connection = myDataSource.getConnection()) {
129                                ResultSet tables = connection.getMetaData().getTables(connection.getCatalog(), connection.getSchema(), null, null);
130
131                                while (tables.next()) {
132                                        String tableName = tables.getString("TABLE_NAME");
133
134                                        if (myMigrationTablename.equalsIgnoreCase(tableName)) {
135                                                return true;
136                                        }
137                                }
138                                return false;
139                        }
140                } catch (SQLException e) {
141                        throw new InternalErrorException(Msg.code(2141) + e);
142                }
143        }
144
145        public List<HapiMigrationEntity> findAll() {
146                String allQuery = myMigrationQueryBuilder.findAllQuery();
147                ourLog.debug("Executing query: [{}]", allQuery);
148                return myJdbcTemplate.query(allQuery, HapiMigrationEntity.rowMapper());
149        }
150
151        /**
152         * @return true if the record was successfully deleted
153         */
154        public boolean deleteLockRecord(Integer theLockPid, String theLockDescription) {
155                int recordsChanged = myJdbcTemplate.update(myMigrationQueryBuilder.deleteLockRecordStatement(theLockPid, theLockDescription));
156                return recordsChanged > 0;
157        }
158
159        public Optional<HapiMigrationEntity> findFirstByPidAndNotDescription(Integer theLockPid, String theLockDescription) {
160                String query = myMigrationQueryBuilder.findByPidAndNotDescriptionQuery(theLockPid, theLockDescription);
161
162                return myJdbcTemplate.query(query, HapiMigrationEntity.rowMapper()).stream().findFirst();
163        }
164}