001/*- 002 * #%L 003 * HAPI FHIR Server - SQL Migration 004 * %% 005 * Copyright (C) 2014 - 2023 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 javax.sql.DataSource; 034import java.sql.Connection; 035import java.sql.ResultSet; 036import java.sql.SQLException; 037import java.util.Date; 038import java.util.List; 039import java.util.Optional; 040import java.util.Set; 041import java.util.stream.Collectors; 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 void createMigrationTableIfRequired() { 108 if (migrationTableExists()) { 109 return; 110 } 111 ourLog.info("Creating table {}", myMigrationTablename); 112 113 String createTableStatement = myMigrationQueryBuilder.createTableStatement(); 114 ourLog.info(createTableStatement); 115 myJdbcTemplate.execute(createTableStatement); 116 117 String createIndexStatement = myMigrationQueryBuilder.createIndexStatement(); 118 ourLog.info(createIndexStatement); 119 myJdbcTemplate.execute(createIndexStatement); 120 121 HapiMigrationEntity entity = HapiMigrationEntity.tableCreatedRecord(); 122 myJdbcTemplate.update(myMigrationQueryBuilder.insertPreparedStatement(), entity.asPreparedStatementSetter()); 123 } 124 125 private boolean migrationTableExists() { 126 try { 127 try (Connection connection = myDataSource.getConnection()) { 128 ResultSet tables = connection.getMetaData().getTables(connection.getCatalog(), connection.getSchema(), null, null); 129 130 while (tables.next()) { 131 String tableName = tables.getString("TABLE_NAME"); 132 133 if (myMigrationTablename.equalsIgnoreCase(tableName)) { 134 return true; 135 } 136 } 137 return false; 138 } 139 } catch (SQLException e) { 140 throw new InternalErrorException(Msg.code(2141) + e); 141 } 142 } 143 144 public List<HapiMigrationEntity> findAll() { 145 String allQuery = myMigrationQueryBuilder.findAllQuery(); 146 ourLog.debug("Executing query: [{}]", allQuery); 147 return myJdbcTemplate.query(allQuery, HapiMigrationEntity.rowMapper()); 148 } 149 150 /** 151 * @return true if the record was successfully deleted 152 */ 153 public boolean deleteLockRecord(Integer theLockPid, String theLockDescription) { 154 int recordsChanged = myJdbcTemplate.update(myMigrationQueryBuilder.deleteLockRecordStatement(theLockPid, theLockDescription)); 155 return recordsChanged > 0; 156 } 157 158 public Optional<HapiMigrationEntity> findFirstByPidAndNotDescription(Integer theLockPid, String theLockDescription) { 159 String query = myMigrationQueryBuilder.findByPidAndNotDescriptionQuery(theLockPid, theLockDescription); 160 161 return myJdbcTemplate.query(query, HapiMigrationEntity.rowMapper()).stream().findFirst(); 162 } 163}