Project

General

Profile

Download (5.68 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2009 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9
package eu.etaxonomy.cdm.database.update;
10

    
11
import java.sql.SQLException;
12

    
13
import org.apache.commons.lang.StringUtils;
14
import org.apache.log4j.Logger;
15

    
16
import eu.etaxonomy.cdm.common.monitor.IProgressMonitor;
17
import eu.etaxonomy.cdm.database.DatabaseTypeEnum;
18
import eu.etaxonomy.cdm.database.ICdmDataSource;
19
import eu.etaxonomy.cdm.database.update.v33_34.UsernameConstraintUpdater;
20

    
21
/**
22
 * Adds an Index on a string column.
23
 *
24
 * @see {@link UsernameConstraintUpdater}
25
 * @author a.mueller
26
 * @since 2016-10-18
27
 *
28
 */
29
public class IndexAdder extends SchemaUpdaterStepBase {
30
	private static final Logger logger = Logger.getLogger(IndexAdder.class);
31

    
32
	private String tableName;
33

    
34
	private String columnName;
35

    
36
	private Integer length;
37

    
38
// ********************** FACTORY ****************************************/
39

    
40
	public static final IndexAdder NewStringInstance(String stepName, String tableName, String columnName, Integer length){
41
		return new IndexAdder(stepName, tableName, columnName, length == null ? 255 : length);
42
	}
43

    
44
    public static final IndexAdder NewIntegerInstance(String stepName, String tableName, String columnName){
45
        return new IndexAdder(stepName, tableName, columnName, null);
46
    }
47

    
48
// **************************** CONSTRUCTOR *********************************/
49

    
50
	protected IndexAdder(String stepName, String tableName, String columnName, Integer length) {
51
		super(stepName);
52
		this.tableName = tableName;
53
		this.columnName = columnName;
54
		this.length = length;
55
	}
56

    
57
    @Override
58
    public void invoke(ICdmDataSource datasource, IProgressMonitor monitor,
59
            CaseType caseType, SchemaUpdateResult result) throws SQLException {
60
        //remove 2-fold constraint
61
//		result &= removeExistingConstraint(datasource, caseType);
62
		createColumnConstraint(datasource, caseType, result);
63
		return;
64
	}
65

    
66
	private void createColumnConstraint(ICdmDataSource datasource,
67
	        CaseType caseType, SchemaUpdateResult result) {
68
		try {
69
		    String constraintName = StringUtils.uncapitalize(tableName) + columnName + "Index";
70
			if(constraintName.length()>64){
71
			    //MySQL has problems with index names > 64,  https://stackoverflow.com/questions/28615903/error-1059-identifier-name-too-long-on-foreign-key-constraints-from-existing-ta
72
			    constraintName = constraintName.replace("Base", "");
73
			}
74
		    String updateQuery = getCreateQuery(datasource, caseType, tableName, constraintName, columnName);
75
			datasource.executeUpdate(updateQuery);
76
			return;
77
		} catch (Exception e) {
78
		    String message = "Unique index for " + columnName + " could not be created";
79
			logger.warn(message);
80
			result.addException(e, message, "IndexAdder.createColumnConstraint");
81
			return;
82
		}
83
	}
84

    
85
	private String getCreateQuery(ICdmDataSource datasource, CaseType caseType, String tableName, String constraintName, String columnName) {
86
			DatabaseTypeEnum type = datasource.getDatabaseType();
87
//			String indexName = "_UniqueKey";
88
			String updateQuery;
89
			if (type.equals(DatabaseTypeEnum.MySQL)){
90
				//Maybe MySQL also works with the below syntax. Did not check yet.
91
				updateQuery = "ALTER TABLE @@"+ tableName + "@@ ADD INDEX " + constraintName + " ("+columnName+ makeLength()+");";
92
			}else if (type.equals(DatabaseTypeEnum.H2) || type.equals(DatabaseTypeEnum.PostgreSQL) || type.equals(DatabaseTypeEnum.SqlServer2005)){
93
				updateQuery = "CREATE INDEX " + constraintName + " ON "+tableName+"(" + columnName + ")";
94
			}else{
95
				throw new IllegalArgumentException("Datasource type not supported yet: " + type.getName());
96
			}
97
//			updateQuery = updateQuery.replace("@indexName", indexName);
98
			updateQuery = caseType.replaceTableNames(updateQuery);
99
			return updateQuery;
100
	}
101

    
102
	/**
103
     * @param length2
104
     * @return
105
     */
106
    private String makeLength() {
107
        if (length != null){
108
            return "(" + length + ")";
109
        }else{
110
            return "";
111
        }
112
    }
113

    
114
    private boolean removeExistingConstraint(ICdmDataSource datasource, CaseType caseType) {
115
		try {
116
			DatabaseTypeEnum type = datasource.getDatabaseType();
117
			String indexName = "_UniqueKey";
118
			String updateQuery = makeRemoveConstraintUpdateQuery(caseType, type, indexName);
119
			try {
120
				datasource.executeUpdate(updateQuery);
121
			} catch (Exception e) {
122
				indexName = "uuid";
123
				updateQuery = makeRemoveConstraintUpdateQuery(caseType, type, indexName);
124
				datasource.executeUpdate(updateQuery);
125
			}
126
			return true;
127
		} catch (Exception e) {
128
			logger.warn("Old index could not be removed");
129
			return false;
130
		}
131
	}
132

    
133

    
134
	/**
135
	 * @param caseType
136
	 * @param type
137
	 * @param indexName
138
	 * @param updateQuery
139
	 * @return
140
	 */
141
	private String makeRemoveConstraintUpdateQuery(CaseType caseType,
142
			DatabaseTypeEnum type, String indexName) {
143
		String updateQuery;
144
		if (type.equals(DatabaseTypeEnum.MySQL)){
145
			updateQuery = "ALTER TABLE @@" + tableName + "@@ DROP INDEX @indexName";
146
		}else if (type.equals(DatabaseTypeEnum.H2)){
147
			updateQuery = "ALTER TABLE @@" + tableName + "@@ DROP CONSTRAINT IF EXISTS @indexName";
148
		}else if (type.equals(DatabaseTypeEnum.PostgreSQL)){
149
			updateQuery = "ALTER TABLE @@" + tableName + "@@ DROP CONSTRAINT @indexName";
150
		}else if (type.equals(DatabaseTypeEnum.SqlServer2005)){
151
			//TODO
152
			throw new RuntimeException("Remove index not yet supported for SQLServer");
153
		}else{
154
			throw new IllegalArgumentException("Datasource type not supported: " + type.getName());
155
		}
156
		updateQuery = updateQuery.replace("@indexName", indexName);
157
		updateQuery = caseType.replaceTableNames(updateQuery);
158
		return updateQuery;
159
	}
160
}
(14-14/36)