001/*- 002 * #%L 003 * HAPI FHIR Server - SQL Migration 004 * %% 005 * Copyright (C) 2014 - 2026 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.taskdef; 021 022import ca.uhn.fhir.i18n.Msg; 023import jakarta.annotation.Nonnull; 024import org.slf4j.Logger; 025import org.slf4j.LoggerFactory; 026 027import java.sql.SQLException; 028import java.util.Arrays; 029import java.util.List; 030 031/** 032 * Migration task that handles cross-database logic for adding a new primary key. 033 */ 034public class AddPrimaryKeyTask extends BaseTableTask { 035 private static final Logger ourLog = LoggerFactory.getLogger(AddPrimaryKeyTask.class); 036 037 private final List<String> myPrimaryKeyColumnsInOrder; 038 039 public AddPrimaryKeyTask( 040 String theProductVersion, String theSchemaVersion, String theTableName, String... theColumnsInOrder) { 041 super(theProductVersion, theSchemaVersion); 042 setTableName(theTableName); 043 044 myPrimaryKeyColumnsInOrder = Arrays.asList(theColumnsInOrder); 045 } 046 047 @Nonnull 048 private String generateSql() { 049 switch (getDriverType()) { 050 case MYSQL_5_7: 051 case MARIADB_10_1: 052 case POSTGRES_9_4: 053 case DERBY_EMBEDDED: 054 case H2_EMBEDDED: 055 case ORACLE_12C: 056 case MSSQL_2012: 057 case COCKROACHDB_21_1: 058 return String.format( 059 "ALTER TABLE %s ADD PRIMARY KEY (%s)", 060 getTableName(), String.join(", ", myPrimaryKeyColumnsInOrder)); 061 default: 062 throw new IllegalStateException(String.format( 063 "%s Unknown driver type. Cannot add primary key for task %s", 064 Msg.code(2531), getMigrationVersion())); 065 } 066 } 067 068 @Override 069 protected void doExecute() throws SQLException { 070 logInfo( 071 ourLog, 072 "Going to add a primary key on table {} for columns {}", 073 getTableName(), 074 myPrimaryKeyColumnsInOrder); 075 076 executeSql(getTableName(), generateSql()); 077 } 078}