001/*-
002 * #%L
003 * HAPI FHIR Server - SQL Migration
004 * %%
005 * Copyright (C) 2014 - 2023 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 org.apache.commons.io.IOUtils;
029import org.apache.commons.lang3.builder.HashCodeBuilder;
030
031import javax.annotation.Nonnull;
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(String theSchemaDescription, String theSchemaFileClassPath, String theSchemaExistsIndicatorTable, boolean theCanInitializeSchema) {
054                mySchemaDescription = theSchemaDescription;
055                mySchemaFileClassPath = theSchemaFileClassPath;
056                mySchemaExistsIndicatorTable = theSchemaExistsIndicatorTable;
057                myCanInitializeSchema = theCanInitializeSchema;
058        }
059
060        @Override
061        public List<String> getSqlStatements(DriverTypeEnum theDriverType) {
062                if (!isEnabled()) {
063                        return Collections.emptyList();
064                }
065
066                List<String> retval = new ArrayList<>();
067
068                String initScript = mySchemaFileClassPath + "/" + getInitScript(theDriverType);
069                try {
070                        InputStream sqlFileInputStream = SchemaInitializationProvider.class.getResourceAsStream(initScript);
071                        if (sqlFileInputStream == null) {
072                                throw new ConfigurationException(Msg.code(49) + "Schema initialization script " + initScript + " not found on classpath");
073                        }
074                        // Assumes no escaped semicolons...
075                        String sqlString = IOUtils.toString(sqlFileInputStream, Charsets.UTF_8);
076                        parseSqlFileIntoIndividualStatements(theDriverType, retval, sqlString);
077                } catch (IOException e) {
078                        throw new ConfigurationException(Msg.code(50) + "Error reading schema initialization script " + initScript, e);
079                }
080                return retval;
081        }
082
083        @VisibleForTesting
084        void parseSqlFileIntoIndividualStatements(DriverTypeEnum theDriverType, List<String> retval, String theSqlString) {
085                String sqlString = theSqlString.replaceAll("--.*", "");
086                
087                String sqlStringNoComments = preProcessSqlString(theDriverType, sqlString);
088                String[] statements = sqlStringNoComments.split("\\;");
089                for (String statement : statements) {
090                        String cleanedStatement = preProcessSqlStatement(theDriverType, statement);
091                        if (!isBlank(cleanedStatement)) {
092                                String next = trim(cleanedStatement);
093                                next = next.replace('\n', ' ');
094                                next = next.replace('\r', ' ');
095                                next = next.replaceAll(" +", " ");
096                                retval.add(next);
097                        }
098                }
099        }
100
101        protected String preProcessSqlString(DriverTypeEnum theDriverType, String sqlString) {
102                return sqlString;
103        }
104
105        protected String preProcessSqlStatement(DriverTypeEnum theDriverType, String sqlStatement) {
106                return sqlStatement;
107        }
108
109        @Nonnull
110        protected String getInitScript(DriverTypeEnum theDriverType) {
111                return theDriverType.getSchemaFilename();
112        }
113
114        @Override
115        public boolean equals(Object theO) {
116                if (this == theO) return true;
117
118                if (theO == null || getClass() != theO.getClass()) return false;
119
120                SchemaInitializationProvider that = (SchemaInitializationProvider) theO;
121
122                return this.getClass().getSimpleName() == that.getClass().getSimpleName();
123        }
124
125        @Override
126        public int hashCode() {
127                return new HashCodeBuilder(17, 37)
128                        .append(this.getClass().getSimpleName())
129                        .toHashCode();
130        }
131
132        @Override
133        public String getSchemaExistsIndicatorTable() {
134                return mySchemaExistsIndicatorTable;
135        }
136
137        public SchemaInitializationProvider setSchemaFileClassPath(String theSchemaFileClassPath) {
138                mySchemaFileClassPath = theSchemaFileClassPath;
139                return this;
140        }
141
142        @Override
143        public String getSchemaDescription() {
144                return mySchemaDescription;
145        }
146
147        @Override
148        public SchemaInitializationProvider setSchemaDescription(String theSchemaDescription) {
149                mySchemaDescription = theSchemaDescription;
150                return this;
151        }
152
153        @Override
154        public boolean canInitializeSchema() {
155                return myCanInitializeSchema;
156        }
157}
158