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