001/*- 002 * #%L 003 * HAPI FHIR Server - SQL Migration 004 * %% 005 * Copyright (C) 2014 - 2026 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.dao; 021 022import ca.uhn.fhir.i18n.Msg; 023import ca.uhn.fhir.jpa.migrate.DriverTypeEnum; 024import ca.uhn.fhir.jpa.migrate.entity.HapiMigrationEntity; 025import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; 026import ca.uhn.fhir.util.VersionEnum; 027import org.apache.commons.lang3.Validate; 028import org.flywaydb.core.api.MigrationVersion; 029import org.slf4j.Logger; 030import org.slf4j.LoggerFactory; 031import org.springframework.jdbc.core.JdbcTemplate; 032 033import java.sql.Connection; 034import java.sql.ResultSet; 035import java.sql.SQLException; 036import java.util.Date; 037import java.util.List; 038import java.util.Optional; 039import java.util.Set; 040import java.util.stream.Collectors; 041import javax.sql.DataSource; 042 043public class HapiMigrationDao { 044 private static final Logger ourLog = LoggerFactory.getLogger(HapiMigrationDao.class); 045 046 private final JdbcTemplate myJdbcTemplate; 047 private final String myMigrationTablename; 048 private final MigrationQueryBuilder myMigrationQueryBuilder; 049 private final DataSource myDataSource; 050 051 public HapiMigrationDao(DataSource theDataSource, DriverTypeEnum theDriverType, String theMigrationTablename) { 052 myDataSource = theDataSource; 053 myJdbcTemplate = new JdbcTemplate(theDataSource); 054 myMigrationTablename = theMigrationTablename; 055 myMigrationQueryBuilder = new MigrationQueryBuilder(theDriverType, theMigrationTablename); 056 } 057 058 public String getMigrationTablename() { 059 return myMigrationTablename; 060 } 061 062 public Set<MigrationVersion> fetchSuccessfulMigrationVersions() { 063 List<HapiMigrationEntity> allEntries = findAll(); 064 return allEntries.stream() 065 .filter(HapiMigrationEntity::getSuccess) 066 .map(HapiMigrationEntity::getVersion) 067 .map(MigrationVersion::fromVersion) 068 .collect(Collectors.toSet()); 069 } 070 071 public void deleteAll() { 072 myJdbcTemplate.execute(myMigrationQueryBuilder.deleteAll()); 073 } 074 075 /** 076 * 077 * @param theEntity to save. If the pid is null, the next available pid will be set 078 * @return true if any database records were changed 079 */ 080 public boolean save(HapiMigrationEntity theEntity) { 081 Validate.notNull(theEntity.getDescription(), "Description may not be null"); 082 Validate.notNull(theEntity.getExecutionTime(), "Execution time may not be null"); 083 Validate.notNull(theEntity.getSuccess(), "Success may not be null"); 084 085 if (theEntity.getPid() == null) { 086 Integer highestKey = getHighestKey(); 087 if (highestKey == null || highestKey < 0) { 088 highestKey = 0; 089 } 090 Integer nextAvailableKey = highestKey + 1; 091 theEntity.setPid(nextAvailableKey); 092 } 093 theEntity.setType("JDBC"); 094 theEntity.setScript("HAPI FHIR"); 095 theEntity.setInstalledBy(VersionEnum.latestVersion().name()); 096 theEntity.setInstalledOn(new Date()); 097 String insertRecordStatement = myMigrationQueryBuilder.insertPreparedStatement(); 098 int changedRecordCount = myJdbcTemplate.update(insertRecordStatement, theEntity.asPreparedStatementSetter()); 099 return changedRecordCount > 0; 100 } 101 102 private Integer getHighestKey() { 103 String highestKeyQuery = myMigrationQueryBuilder.getHighestKeyQuery(); 104 return myJdbcTemplate.queryForObject(highestKeyQuery, Integer.class); 105 } 106 107 public boolean createMigrationTableIfRequired() { 108 if (migrationTableExists()) { 109 if (!columnExists("result")) { 110 String addResultColumnStatement = myMigrationQueryBuilder.addResultColumnStatement(); 111 ourLog.info(addResultColumnStatement); 112 myJdbcTemplate.execute(addResultColumnStatement); 113 } 114 return false; 115 } 116 ourLog.info("Creating table {}", myMigrationTablename); 117 118 String createTableStatement = myMigrationQueryBuilder.createTableStatement(); 119 ourLog.info(createTableStatement); 120 myJdbcTemplate.execute(createTableStatement); 121 122 String createIndexStatement = myMigrationQueryBuilder.createIndexStatement(); 123 ourLog.info(createIndexStatement); 124 myJdbcTemplate.execute(createIndexStatement); 125 126 HapiMigrationEntity entity = HapiMigrationEntity.tableCreatedRecord(); 127 myJdbcTemplate.update(myMigrationQueryBuilder.insertPreparedStatement(), entity.asPreparedStatementSetter()); 128 129 return true; 130 } 131 132 private boolean migrationTableExists() { 133 try { 134 try (Connection connection = myDataSource.getConnection()) { 135 ResultSet tables = 136 connection.getMetaData().getTables(connection.getCatalog(), connection.getSchema(), null, null); 137 138 while (tables.next()) { 139 String tableName = tables.getString("TABLE_NAME"); 140 141 if (myMigrationTablename.equalsIgnoreCase(tableName)) { 142 return true; 143 } 144 } 145 return false; 146 } 147 } catch (SQLException e) { 148 throw new InternalErrorException(Msg.code(2141) + e); 149 } 150 } 151 152 private boolean columnExists(String theColumnName) { 153 try (Connection connection = myDataSource.getConnection()) { 154 ResultSet columnsUpper = connection 155 .getMetaData() 156 .getColumns( 157 connection.getCatalog(), 158 connection.getSchema(), 159 myMigrationTablename, 160 theColumnName.toUpperCase()); 161 ResultSet columnsLower = connection 162 .getMetaData() 163 .getColumns( 164 connection.getCatalog(), 165 connection.getSchema(), 166 myMigrationTablename, 167 theColumnName.toLowerCase()); 168 169 return columnsUpper.next() || columnsLower.next(); // If there's a row, the column exists 170 } catch (SQLException e) { 171 throw new InternalErrorException(Msg.code(2615) + "Error checking column existence: " + e.getMessage(), e); 172 } 173 } 174 175 public List<HapiMigrationEntity> findAll() { 176 String allQuery = myMigrationQueryBuilder.findAllQuery(); 177 ourLog.debug("Executing query: [{}]", allQuery); 178 return myJdbcTemplate.query(allQuery, HapiMigrationEntity.rowMapper()); 179 } 180 181 /** 182 * @return true if the record was successfully deleted 183 */ 184 public boolean deleteLockRecord(Integer theLockPid, String theLockDescription) { 185 int recordsChanged = myJdbcTemplate.update( 186 myMigrationQueryBuilder.deleteLockRecordStatement(theLockPid, theLockDescription)); 187 return recordsChanged > 0; 188 } 189 190 public Optional<HapiMigrationEntity> findFirstByPidAndNotDescription( 191 Integer theLockPid, String theLockDescription) { 192 String query = myMigrationQueryBuilder.findByPidAndNotDescriptionQuery(theLockPid, theLockDescription); 193 194 return myJdbcTemplate.query(query, HapiMigrationEntity.rowMapper()).stream() 195 .findFirst(); 196 } 197}