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.context.ConfigurationException;
023import ca.uhn.fhir.i18n.Msg;
024import org.hibernate.cfg.AvailableSettings;
025import org.slf4j.Logger;
026import org.slf4j.LoggerFactory;
027
028import java.sql.Connection;
029import java.sql.SQLException;
030import java.util.Collections;
031import java.util.List;
032import java.util.Properties;
033import javax.sql.DataSource;
034
035public class SchemaMigrator {
036        public static final String HAPI_FHIR_MIGRATION_TABLENAME = "FLY_HFJ_MIGRATION";
037        private static final Logger ourLog = LoggerFactory.getLogger(SchemaMigrator.class);
038        private final String mySchemaName;
039        private final DataSource myDataSource;
040        private final boolean mySkipValidation;
041        private final String myMigrationTableName;
042        private final MigrationTaskList myMigrationTasks;
043        private DriverTypeEnum myDriverType;
044        private List<IHapiMigrationCallback> myCallbacks = Collections.emptyList();
045        private final HapiMigrationStorageSvc myHapiMigrationStorageSvc;
046
047        /**
048         * Constructor
049         */
050        public SchemaMigrator(
051                        String theSchemaName,
052                        String theMigrationTableName,
053                        DataSource theDataSource,
054                        Properties jpaProperties,
055                        MigrationTaskList theMigrationTasks,
056                        HapiMigrationStorageSvc theHapiMigrationStorageSvc) {
057                mySchemaName = theSchemaName;
058                myDataSource = theDataSource;
059                myMigrationTableName = theMigrationTableName;
060                myMigrationTasks = theMigrationTasks;
061
062                mySkipValidation = jpaProperties.containsKey(AvailableSettings.HBM2DDL_AUTO)
063                                && "update".equals(jpaProperties.getProperty(AvailableSettings.HBM2DDL_AUTO));
064                myHapiMigrationStorageSvc = theHapiMigrationStorageSvc;
065        }
066
067        public void validate() {
068                if (mySkipValidation) {
069                        ourLog.warn("Database running in hibernate auto-update mode.  Skipping schema validation.");
070                        return;
071                }
072                try (Connection connection = myDataSource.getConnection()) {
073                        MigrationTaskList unappliedMigrations = myHapiMigrationStorageSvc.diff(myMigrationTasks);
074
075                        if (unappliedMigrations.size() > 0) {
076
077                                String url = connection.getMetaData().getURL();
078                                throw new ConfigurationException(Msg.code(27) + "The database schema for " + url + " is out of date.  "
079                                                + "Current database schema version is "
080                                                + myHapiMigrationStorageSvc.getLatestAppliedVersion()
081                                                + ".  Schema version required by application is " + unappliedMigrations.getLastVersion()
082                                                + ".  Please run the database migrator.");
083                        }
084                        ourLog.info("Database schema confirmed at expected version "
085                                        + myHapiMigrationStorageSvc.getLatestAppliedVersion());
086                } catch (SQLException e) {
087                        throw new ConfigurationException(Msg.code(28) + "Unable to connect to " + myDataSource, e);
088                }
089        }
090
091        public MigrationResult migrate() {
092                if (mySkipValidation) {
093                        ourLog.warn("Database running in hibernate auto-update mode.  Skipping schema migration.");
094                        return null;
095                }
096                try {
097                        ourLog.info("Migrating " + mySchemaName);
098                        MigrationResult retval = newMigrator().migrate();
099                        ourLog.info(mySchemaName + " migrated successfully: {}", retval.summary());
100                        return retval;
101                } catch (Exception e) {
102                        ourLog.error("Failed to migrate " + mySchemaName, e);
103                        throw e;
104                }
105        }
106
107        private HapiMigrator newMigrator() {
108                HapiMigrator migrator;
109                migrator = new HapiMigrator(myMigrationTableName, myDataSource, myDriverType);
110                migrator.addTasks(myMigrationTasks);
111                migrator.setCallbacks(myCallbacks);
112                return migrator;
113        }
114
115        public void setDriverType(DriverTypeEnum theDriverType) {
116                myDriverType = theDriverType;
117        }
118
119        public void setCallbacks(List<IHapiMigrationCallback> theCallbacks) {
120                myCallbacks = theCallbacks;
121        }
122
123        public boolean createMigrationTableIfRequired() {
124                return myHapiMigrationStorageSvc.createMigrationTableIfRequired();
125        }
126}