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.tasks;
021
022import ca.uhn.fhir.context.ConfigurationException;
023import ca.uhn.fhir.i18n.Msg;
024import ca.uhn.fhir.jpa.migrate.DriverTypeEnum;
025import ca.uhn.fhir.jpa.migrate.tasks.api.ISchemaInitializationProvider;
026import com.google.common.annotations.VisibleForTesting;
027import com.google.common.base.Charsets;
028import jakarta.annotation.Nonnull;
029import org.apache.commons.io.IOUtils;
030import org.apache.commons.lang3.builder.HashCodeBuilder;
031
032import java.io.IOException;
033import java.io.InputStream;
034import java.util.ArrayList;
035import java.util.Collections;
036import java.util.List;
037
038import static org.apache.commons.lang3.StringUtils.isBlank;
039import static org.apache.commons.lang3.StringUtils.trim;
040
041public class SchemaInitializationProvider implements ISchemaInitializationProvider {
042
043        private final String mySchemaExistsIndicatorTable;
044        private final boolean myCanInitializeSchema;
045        private String mySchemaFileClassPath;
046        private String mySchemaDescription;
047
048        /**
049         * @param theSchemaFileClassPath        pathname to script used to initialize schema
050         * @param theSchemaExistsIndicatorTable a table name we can use to determine if this schema has already been initialized
051         * @param theCanInitializeSchema        this is a "root" schema initializer that creates the primary tables used by this app
052         */
053        public SchemaInitializationProvider(
054                        String theSchemaDescription,
055                        String theSchemaFileClassPath,
056                        String theSchemaExistsIndicatorTable,
057                        boolean theCanInitializeSchema) {
058                mySchemaDescription = theSchemaDescription;
059                mySchemaFileClassPath = theSchemaFileClassPath;
060                mySchemaExistsIndicatorTable = theSchemaExistsIndicatorTable;
061                myCanInitializeSchema = theCanInitializeSchema;
062        }
063
064        @Override
065        public List<String> getSqlStatements(DriverTypeEnum theDriverType) {
066                if (!isEnabled()) {
067                        return Collections.emptyList();
068                }
069
070                List<String> retval = new ArrayList<>();
071
072                String initScript = mySchemaFileClassPath + "/" + getInitScript(theDriverType);
073                try {
074                        InputStream sqlFileInputStream = SchemaInitializationProvider.class.getResourceAsStream(initScript);
075                        if (sqlFileInputStream == null) {
076                                throw new ConfigurationException(
077                                                Msg.code(49) + "Schema initialization script " + initScript + " not found on classpath");
078                        }
079                        // Assumes no escaped semicolons...
080                        String sqlString = IOUtils.toString(sqlFileInputStream, Charsets.UTF_8);
081                        parseSqlFileIntoIndividualStatements(theDriverType, retval, sqlString);
082                } catch (IOException e) {
083                        throw new ConfigurationException(
084                                        Msg.code(50) + "Error reading schema initialization script " + initScript, e);
085                }
086                return retval;
087        }
088
089        @VisibleForTesting
090        void parseSqlFileIntoIndividualStatements(DriverTypeEnum theDriverType, List<String> retval, String theSqlString) {
091                String sqlString = theSqlString.replaceAll("--.*", "");
092
093                String sqlStringNoComments = preProcessSqlString(theDriverType, sqlString);
094                String[] statements = sqlStringNoComments.split("\\;");
095                for (String statement : statements) {
096                        String cleanedStatement = preProcessSqlStatement(theDriverType, statement);
097                        if (!isBlank(cleanedStatement)) {
098                                String next = trim(cleanedStatement);
099                                next = next.replace('\n', ' ');
100                                next = next.replace('\r', ' ');
101                                next = next.replaceAll(" +", " ");
102                                retval.add(next);
103                        }
104                }
105        }
106
107        protected String preProcessSqlString(DriverTypeEnum theDriverType, String sqlString) {
108                return sqlString;
109        }
110
111        protected String preProcessSqlStatement(DriverTypeEnum theDriverType, String sqlStatement) {
112                return sqlStatement;
113        }
114
115        @Nonnull
116        protected String getInitScript(DriverTypeEnum theDriverType) {
117                return theDriverType.getSchemaFilename();
118        }
119
120        @Override
121        public boolean equals(Object theO) {
122                if (this == theO) return true;
123
124                if (theO == null || getClass() != theO.getClass()) return false;
125
126                SchemaInitializationProvider that = (SchemaInitializationProvider) theO;
127
128                return this.getClass().getSimpleName() == that.getClass().getSimpleName();
129        }
130
131        @Override
132        public int hashCode() {
133                return new HashCodeBuilder(17, 37)
134                                .append(this.getClass().getSimpleName())
135                                .toHashCode();
136        }
137
138        @Override
139        public String getSchemaExistsIndicatorTable() {
140                return mySchemaExistsIndicatorTable;
141        }
142
143        public SchemaInitializationProvider setSchemaFileClassPath(String theSchemaFileClassPath) {
144                mySchemaFileClassPath = theSchemaFileClassPath;
145                return this;
146        }
147
148        @Override
149        public String getSchemaDescription() {
150                return mySchemaDescription;
151        }
152
153        @Override
154        public SchemaInitializationProvider setSchemaDescription(String theSchemaDescription) {
155                mySchemaDescription = theSchemaDescription;
156                return this;
157        }
158
159        @Override
160        public boolean canInitializeSchema() {
161                return myCanInitializeSchema;
162        }
163}