Project

General

Profile

Download (6.84 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.ResultSet;
12
import java.sql.SQLException;
13
import java.util.ArrayList;
14
import java.util.List;
15
import java.util.UUID;
16

    
17
import org.apache.commons.lang.StringUtils;
18
import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;
19
import org.joda.time.DateTime;
20

    
21
import eu.etaxonomy.cdm.common.monitor.IProgressMonitor;
22
import eu.etaxonomy.cdm.database.DatabaseTypeEnum;
23
import eu.etaxonomy.cdm.database.ICdmDataSource;
24
import eu.etaxonomy.cdm.model.common.Language;
25

    
26
/**
27
 * @author a.mueller
28
 * @since 13.09.2010
29
 */
30
public abstract class SchemaUpdaterStepBase implements ISchemaUpdaterStep {
31
	private static final Logger logger = LogManager.getLogger(SchemaUpdaterStepBase.class);
32

    
33
	protected String stepName;
34

    
35
	private boolean ignoreErrors;
36

    
37
//************************ CONSTRUCTOR ***********************************/
38

    
39
	protected <T extends ISchemaUpdaterStep> SchemaUpdaterStepBase(List<T> stepList, String stepName){
40
		this.setStepName(stepName);
41
		if (stepList != null){
42
		    stepList.add((T)this);
43
		}
44
	}
45

    
46
	@Override
47
	public abstract void invoke (ICdmDataSource datasource, IProgressMonitor monitor,
48
	        CaseType caseType, SchemaUpdateResult result) throws SQLException;
49

    
50
	@Override
51
	public void setStepName(String stepName) {
52
		this.stepName = stepName;
53
	}
54

    
55
	@Override
56
	public String getStepName() {
57
		return stepName;
58
	}
59

    
60
	protected String getBoolean(boolean value, ICdmDataSource datasource) {
61

    
62
		String result;
63
		DatabaseTypeEnum type = datasource.getDatabaseType();
64
		//TODO use
65
//		type.getHibernateDialect().toBooleanValueString(bool);
66
		int intValue = value == true? 1 : 0;
67
		if (type.equals(DatabaseTypeEnum.MySQL)){
68
			result = "b'"+intValue+"'";
69
		}else if (type.equals(DatabaseTypeEnum.PostgreSQL)){
70
			result = "'"+intValue+"'";
71
		}else if (type.equals(DatabaseTypeEnum.H2)){
72
			result = value == true ? "TRUE" : "FALSE";
73
		}else if (type.equals(DatabaseTypeEnum.SqlServer2005)){
74
			logger.warn("SQLServer boolean not tested yet");
75
			result = "b'"+intValue+"'";
76
		}else{
77
			throw new RuntimeException("Database type not supported for boolean" + type.getName());
78
		}
79
		return result;
80
	}
81

    
82
	protected Integer getEnglishLanguageId(ICdmDataSource datasource, IProgressMonitor monitor, CaseType caseType) throws SQLException {
83
		return getLanguageId(Language.uuidEnglish, datasource, monitor, caseType);
84
	}
85

    
86
	protected Integer getLanguageId(UUID uuidLanguage, ICdmDataSource datasource,
87
	        IProgressMonitor monitor, CaseType caseType) throws SQLException {
88

    
89
		ResultSet rs;
90
		Integer langId = null;
91
		String sqlLangId = " SELECT id FROM %s WHERE uuid = '%s'";
92
		sqlLangId = String.format(sqlLangId, caseType.transformTo("DefinedTermBase"), uuidLanguage.toString() );
93
		rs = datasource.executeQuery(sqlLangId);
94
		if (rs.next()){
95
			langId = rs.getInt("id");
96
		}else{
97
			String warning = "Term for language (" +  uuidLanguage + ") does not exist!";
98
			monitor.warning(warning);
99
		}
100
		return langId;
101
	}
102

    
103
    /**
104
     * Returns the smallest next free id, if includeAudit is <code>true</code> the audit
105
     * table is also considered in computation
106
     * @throws NumberFormatException
107
     * @throws SQLException
108
     */
109
    protected int getMaxId1(ICdmDataSource datasource, String tableName, boolean includeAudit, IProgressMonitor monitor, CaseType caseType,
110
            SchemaUpdateResult result) throws SQLException {
111

    
112
        return getMaxIdentifier(datasource, tableName, "id", includeAudit, monitor, caseType, result);
113
    }
114

    
115
    protected int getMaxIdentifier(ICdmDataSource datasource, String tableName, String idAttrName, boolean includeAudit, IProgressMonitor monitor, CaseType caseType,
116
            SchemaUpdateResult result) throws SQLException {
117

    
118
        String sql = "SELECT max("+idAttrName+") FROM " +caseType.transformTo(tableName);
119
        Integer maxId = getInteger(datasource, sql, 0);
120

    
121
        Integer maxIdAud = -1;
122
        if(includeAudit){
123
            sql = "SELECT max("+idAttrName+") FROM " +caseType.transformTo(tableName + "_AUD");
124
            maxIdAud = getInteger(datasource, sql, 0);
125
        }
126
        return Math.max(maxId, maxIdAud) + 1;
127
    }
128

    
129

    
130
    /**
131
     * Creates a new entry in the AuditEvent table
132
     * @return the revision number of the the new audit event
133
     */
134
    protected long createAuditEvent(ICdmDataSource datasource, CaseType caseType, IProgressMonitor monitor,
135
            SchemaUpdateResult result) throws SQLException {
136
        String sql;
137
        long rev;
138
        sql = "INSERT INTO @@AuditEvent@@ (revisionnumber, date, timestamp, uuid) "
139
                + " VALUES (%d, '%s', %d, '%s') ";
140
        int newId = this.getMaxIdentifier(datasource, "AuditEvent", "revisionNumber", false, monitor, caseType, result);
141
        long timeStamp = System.currentTimeMillis();
142
        sql = caseType.replaceTableNames(String.format(sql, newId, this.getNowString(), timeStamp, UUID.randomUUID()));
143
        datasource.executeUpdate(sql);
144
        rev =  newId;
145
        return rev;
146
    }
147

    
148
    private Integer getInteger(ICdmDataSource datasource, String sql, int nullReplace) throws SQLException {
149
        Object value = datasource.getSingleValue(sql);
150
        if (value == null){
151
            return nullReplace;
152
        }else{
153
            return Integer.valueOf(value.toString());
154
        }
155
    }
156

    
157
    @Override
158
	public List<ISchemaUpdaterStep> getInnerSteps(){
159
		return new ArrayList<>();
160
	}
161

    
162
	@Override
163
	public boolean isIgnoreErrors() {
164
		return ignoreErrors;
165
	}
166
	@Override
167
	public void setIgnoreErrors(boolean ignoreErrors) {
168
		this.ignoreErrors = ignoreErrors;
169
	}
170

    
171

    
172
	/**
173
	 * Returns a time string with date and time (without millis) that
174
	 * can be used as a time string for database insert and update
175
	 * @return
176
	 */
177
	protected String getNowString() {
178
		return DateTime.now().toString("YYYY-MM-dd HH:mm:ss");
179
	}
180

    
181
    protected String nullSafeParam(String param) {
182
        return param == null ? "NULL" : "'" + param.replace("'", "''") + "'";
183
    }
184

    
185
    protected Integer nullSafeInt(ResultSet rs, String columnName) throws SQLException {
186
        Object intObject = rs.getObject(columnName);
187
        if (intObject == null){
188
            return null;
189
        }else{
190
            return Integer.valueOf(intObject.toString());
191
        }
192
    }
193

    
194
    protected String escapeSingleQuote(String str) {
195
        return str == null? null : str.replace("'", "''");
196
    }
197

    
198
    protected boolean isNotBlank(String str) {
199
        return StringUtils.isNotBlank(str);
200
    }
201

    
202
    protected boolean isBlank(String str) {
203
        return StringUtils.isBlank(str);
204
    }
205

    
206
	@Override
207
	public String toString(){
208
		if (StringUtils.isNotBlank(stepName)){
209
			return stepName;
210
		}else{
211
			return super.toString();
212
		}
213
	}
214

    
215
}
(27-27/41)