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                        // remove skippable tasks
076                        MigrationTaskList unappliedUnskippable = unappliedMigrations.getUnskippableTasks();
077
078                        if (unappliedUnskippable.size() > 0) {
079                                String url = connection.getMetaData().getURL();
080                                throw new ConfigurationException(Msg.code(27) + "The database schema for " + url + " is out of date.  "
081                                                + "Current database schema version is "
082                                                + myHapiMigrationStorageSvc.getLatestAppliedVersion()
083                                                + ".  Schema version required by application is " + unappliedMigrations.getLastVersion()
084                                                + ".  Please run the database migrator.");
085                        }
086                        ourLog.info("Database schema confirmed at expected version "
087                                        + myHapiMigrationStorageSvc.getLatestAppliedVersion());
088                } catch (SQLException e) {
089                        throw new ConfigurationException(Msg.code(28) + "Unable to connect to " + myDataSource, e);
090                }
091        }
092
093        public MigrationResult migrate() {
094                if (mySkipValidation) {
095                        ourLog.warn("Database running in hibernate auto-update mode.  Skipping schema migration.");
096                        return null;
097                }
098                try {
099                        ourLog.info("Migrating " + mySchemaName);
100                        MigrationResult retval = newMigrator().migrate();
101                        ourLog.info(mySchemaName + " migrated successfully: {}", retval.summary());
102                        return retval;
103                } catch (Exception e) {
104                        ourLog.error("Failed to migrate " + mySchemaName, e);
105                        throw e;
106                }
107        }
108
109        private HapiMigrator newMigrator() {
110                HapiMigrator migrator;
111                migrator = new HapiMigrator(myMigrationTableName, myDataSource, myDriverType);
112                migrator.addTasks(myMigrationTasks);
113                migrator.setCallbacks(myCallbacks);
114                return migrator;
115        }
116
117        public void setDriverType(DriverTypeEnum theDriverType) {
118                myDriverType = theDriverType;
119        }
120
121        public void setCallbacks(List<IHapiMigrationCallback> theCallbacks) {
122                myCallbacks = theCallbacks;
123        }
124
125        public boolean createMigrationTableIfRequired() {
126                return myHapiMigrationStorageSvc.createMigrationTableIfRequired();
127        }
128}