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 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
049        /**
050         * @param theSchemaFileClassPath        pathname to script used to initialize schema
051         * @param theSchemaExistsIndicatorTable a table name we can use to determine if this schema has already been initialized
052         * @param theCanInitializeSchema        this is a "root" schema initializer that creates the primary tables used by this app
053         */
054        public SchemaInitializationProvider(
055                        String theSchemaDescription,
056                        String theSchemaFileClassPath,
057                        String theSchemaExistsIndicatorTable,
058                        boolean theCanInitializeSchema) {
059                mySchemaDescription = theSchemaDescription;
060                mySchemaFileClassPath = theSchemaFileClassPath;
061                mySchemaExistsIndicatorTable = theSchemaExistsIndicatorTable;
062                myCanInitializeSchema = theCanInitializeSchema;
063        }
064
065        @Override
066        public List<String> getSqlStatements(DriverTypeEnum theDriverType) {
067                if (!isEnabled()) {
068                        return Collections.emptyList();
069                }
070
071                List<String> retval = new ArrayList<>();
072
073                String initScript = mySchemaFileClassPath + "/" + getInitScript(theDriverType);
074                try {
075                        InputStream sqlFileInputStream = ClasspathUtil.loadResourceAsStream(initScript);
076                        // Assumes no escaped semicolons...
077                        String sqlString = IOUtils.toString(sqlFileInputStream, Charsets.UTF_8);
078                        parseSqlFileIntoIndividualStatements(theDriverType, retval, sqlString);
079                } catch (IOException e) {
080                        throw new ConfigurationException(
081                                        Msg.code(50) + "Error reading schema initialization script " + initScript, e);
082                }
083                return retval;
084        }
085
086        @VisibleForTesting
087        void parseSqlFileIntoIndividualStatements(DriverTypeEnum theDriverType, List<String> retval, String theSqlString) {
088                String sqlString = theSqlString.replaceAll("--.*", "");
089
090                String sqlStringNoComments = preProcessSqlString(theDriverType, sqlString);
091                String[] statements = sqlStringNoComments.split(";");
092                for (String statement : statements) {
093                        String cleanedStatement = preProcessSqlStatement(theDriverType, statement);
094                        if (!isBlank(cleanedStatement)) {
095                                String next = trim(cleanedStatement);
096                                next = next.replace('\n', ' ');
097                                next = next.replace('\r', ' ');
098                                next = next.replaceAll(" +", " ");
099                                retval.add(next);
100                        }
101                }
102        }
103
104        protected String preProcessSqlString(DriverTypeEnum theDriverType, String sqlString) {
105                return sqlString;
106        }
107
108        protected String preProcessSqlStatement(DriverTypeEnum theDriverType, String sqlStatement) {
109                return sqlStatement;
110        }
111
112        @Nonnull
113        protected String getInitScript(DriverTypeEnum theDriverType) {
114                return theDriverType.getSchemaFilename();
115        }
116
117        @Override
118        public boolean equals(Object theO) {
119                if (this == theO) return true;
120
121                if (theO == null || getClass() != theO.getClass()) return false;
122
123                SchemaInitializationProvider that = (SchemaInitializationProvider) theO;
124
125                return this.getClass().getSimpleName() == that.getClass().getSimpleName();
126        }
127
128        @Override
129        public int hashCode() {
130                return new HashCodeBuilder(17, 37)
131                                .append(this.getClass().getSimpleName())
132                                .toHashCode();
133        }
134
135        @Override
136        public String getSchemaExistsIndicatorTable() {
137                return mySchemaExistsIndicatorTable;
138        }
139
140        public SchemaInitializationProvider setSchemaFileClassPath(String theSchemaFileClassPath) {
141                mySchemaFileClassPath = theSchemaFileClassPath;
142                return this;
143        }
144
145        @Override
146        public String getSchemaDescription() {
147                return mySchemaDescription;
148        }
149
150        @Override
151        public SchemaInitializationProvider setSchemaDescription(String theSchemaDescription) {
152                mySchemaDescription = theSchemaDescription;
153                return this;
154        }
155
156        @Override
157        public boolean canInitializeSchema() {
158                return myCanInitializeSchema;
159        }
160}