001package ca.uhn.fhir.jpa.migrate.taskdef; 002 003/*- 004 * #%L 005 * HAPI FHIR Server - SQL Migration 006 * %% 007 * Copyright (C) 2014 - 2022 Smile CDR, Inc. 008 * %% 009 * Licensed under the Apache License, Version 2.0 (the "License"); 010 * you may not use this file except in compliance with the License. 011 * You may obtain a copy of the License at 012 * 013 * http://www.apache.org/licenses/LICENSE-2.0 014 * 015 * Unless required by applicable law or agreed to in writing, software 016 * distributed under the License is distributed on an "AS IS" BASIS, 017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 018 * See the License for the specific language governing permissions and 019 * limitations under the License. 020 * #L% 021 */ 022 023import ca.uhn.fhir.jpa.migrate.JdbcUtils; 024import org.slf4j.Logger; 025import org.slf4j.LoggerFactory; 026 027import java.sql.SQLException; 028import java.util.Set; 029 030public class AddColumnTask extends BaseTableColumnTypeTask { 031 032 private static final Logger ourLog = LoggerFactory.getLogger(AddColumnTask.class); 033 034 public AddColumnTask(String theProductVersion, String theSchemaVersion) { 035 super(theProductVersion, theSchemaVersion); 036 } 037 038 @Override 039 public void validate() { 040 super.validate(); 041 setDescription("Add column " + getColumnName() + " on table " + getTableName()); 042 } 043 044 @Override 045 public void doExecute() throws SQLException { 046 Set<String> columnNames = JdbcUtils.getColumnNames(getConnectionProperties(), getTableName()); 047 if (columnNames.contains(getColumnName())) { 048 logInfo(ourLog, "Column {} already exists on table {} - No action performed", getColumnName(), getTableName()); 049 return; 050 } 051 052 String typeStatement = getTypeStatement(); 053 054 String sql; 055 switch (getDriverType()) { 056 case MYSQL_5_7: 057 case MARIADB_10_1: 058 // Quote the column name as "SYSTEM" is a reserved word in MySQL 059 sql = "alter table " + getTableName() + " add column `" + getColumnName() + "` " + typeStatement; 060 break; 061 case DERBY_EMBEDDED: 062 case POSTGRES_9_4: 063 sql = "alter table " + getTableName() + " add column " + getColumnName() + " " + typeStatement; 064 break; 065 case MSSQL_2012: 066 case ORACLE_12C: 067 case H2_EMBEDDED: 068 sql = "alter table " + getTableName() + " add " + getColumnName() + " " + typeStatement; 069 break; 070 default: 071 throw new IllegalStateException(); 072 } 073 074 logInfo(ourLog, "Adding column {} of type {} to table {}", getColumnName(), getSqlType(), getTableName()); 075 executeSql(getTableName(), sql); 076 } 077 078 public String getTypeStatement() { 079 String type = getSqlType(); 080 String nullable = getSqlNotNull(); 081 if (isNullable()) { 082 nullable = ""; 083 } 084 return type + " " + nullable; 085 } 086 087}