minor
[cdmlib.git] / cdmlib-persistence / src / main / java / eu / etaxonomy / cdm / database / update / CdmUpdater.java
1 // $Id$
2 /**
3 * Copyright (C) 2009 EDIT
4 * European Distributed Institute of Taxonomy
5 * http://www.e-taxonomy.eu
6 *
7 * The contents of this file are subject to the Mozilla Public License Version 1.1
8 * See LICENSE.TXT at the top of this package for the full license terms.
9 */
10 package eu.etaxonomy.cdm.database.update;
11
12 import java.sql.ResultSet;
13
14 import org.apache.log4j.Logger;
15
16 import eu.etaxonomy.cdm.common.monitor.DefaultProgressMonitor;
17 import eu.etaxonomy.cdm.common.monitor.IProgressMonitor;
18 import eu.etaxonomy.cdm.database.CdmDataSource;
19 import eu.etaxonomy.cdm.database.ICdmDataSource;
20 import eu.etaxonomy.cdm.database.update.v31_33.SchemaUpdater_31_33;
21 import eu.etaxonomy.cdm.database.update.v31_33.SchemaUpdater_33_331;
22 import eu.etaxonomy.cdm.database.update.v31_33.TermUpdater_31_33;
23
24 /**
25 * @author a.mueller
26 * @date 10.09.2010
27 *
28 */
29 public class CdmUpdater {
30 private static final Logger logger = Logger.getLogger(CdmUpdater.class);
31
32 public static CdmUpdater NewInstance(){
33 return new CdmUpdater();
34 }
35
36 /**
37 * @param datasource
38 * @param monitor may be <code>null</code>
39 * @return
40 */
41 public boolean updateToCurrentVersion(ICdmDataSource datasource, IProgressMonitor monitor){
42 boolean result = true;
43 if (monitor == null){
44 monitor = DefaultProgressMonitor.NewInstance();
45 }
46 CaseType caseType = CaseType.caseTypeOfDatasource(datasource);
47
48 ISchemaUpdater currentSchemaUpdater = getCurrentSchemaUpdater();
49 // TODO do we really always update the terms??
50 ITermUpdater currentTermUpdater = getCurrentTermUpdater();
51
52 int steps = currentSchemaUpdater.countSteps(datasource, monitor, caseType);
53 steps += currentTermUpdater.countSteps(datasource, monitor, caseType);
54 steps++; //for hibernate_sequences update
55
56 String taskName = "Update to schema version " + currentSchemaUpdater.getTargetVersion() + " and to term version " + currentTermUpdater.getTargetVersion(); //+ currentSchemaUpdater.getVersion();
57 monitor.beginTask(taskName, steps);
58
59 try {
60 datasource.startTransaction();
61 result &= currentSchemaUpdater.invoke(datasource, monitor, caseType);
62 if (result == true){
63 result &= currentTermUpdater.invoke(datasource, monitor, caseType);
64 updateHibernateSequence(datasource, monitor, caseType);
65 }
66 if (result == false){
67 datasource.rollback();
68 }else{
69 datasource.commitTransaction();
70 }
71
72 } catch (Exception e) {
73 result = false;
74 monitor.warning("Stopped schema updater");
75 } finally {
76 String message = "Update finished " + (result ? "successfully" : "with ERRORS");
77 monitor.subTask(message);
78 if (!result){
79 monitor.warning(message);
80 monitor.setCanceled(true);
81 }else{
82 monitor.done();
83 }
84 logger.info(message);
85 }
86
87 return result;
88 }
89
90
91
92 /**
93 * Updating terms often inserts new terms, vocabularies and representations.
94 * Therefore the counter in hibernate_sequences must be increased.
95 * We do this once at the end of term updating.
96 * @param caseType
97 * @return true if update was successful, false otherwise
98 */
99 private boolean updateHibernateSequence(ICdmDataSource datasource, IProgressMonitor monitor, CaseType caseType) {
100 boolean result = true;
101 monitor.subTask("Update hibernate sequences");
102 try {
103 String sql = "SELECT * FROM hibernate_sequences ";
104 ResultSet rs = datasource.executeQuery(sql);
105 while (rs.next()){
106 String table = rs.getString("sequence_name");
107 Integer val = rs.getInt("next_val");
108 result &= updateSingleValue(datasource,monitor, table, val, caseType);
109 }
110 } catch (Exception e) {
111 String message = "Exception occurred when trying to update hibernate_sequences table: " + e.getMessage();
112 monitor.warning(message, e);
113 logger.error(message);
114 result = false;
115 }finally{
116 monitor.worked(1);
117 }
118 return result;
119 }
120
121 /**
122 *
123 * @param datasource
124 * @param monitor
125 * @param table
126 * @param oldVal
127 * @param caseType
128 * @return
129 */
130 private boolean updateSingleValue(ICdmDataSource datasource, IProgressMonitor monitor, String table, Integer oldVal, CaseType caseType){
131 if (table.equals("default")){ //found in flora central africa test database
132 return true;
133 }
134 try {
135 Integer newVal;
136 try {
137 String sql = " SELECT max(id) FROM %s ";
138 newVal = (Integer)datasource.getSingleValue(String.format(sql, caseType.transformTo(table)));
139 } catch (Exception e) {
140 String message = "Could not retrieve max value for table '%s'. Will not update hibernate_sequence for this table. " +
141 "Usually this will not cause problems, however, if new data has been added to " +
142 "this table by the update script one may encounter 'unique identifier' " +
143 "exceptions when trying to add further data.";
144 monitor.warning(String.format(message,table), e);
145 //TODO
146 return true;
147 }
148
149 if (newVal != null){
150 //This is how {@link PooledOptimizer#generate(org.hibernate.id.enhanced.AccessCallback)} works
151 //it substracts the increment size from the value in hibernate_sequences to get the initial value.
152 //Haven't checked why.
153 //For the correct increment size see eu.etaxonomy.cdm.model.common.package-info.java
154 int incrementSize = 10;
155 newVal = newVal + incrementSize;
156 if (newVal != null && newVal >= oldVal){
157 String sql = " UPDATE hibernate_sequences " +
158 " SET next_val = %d " +
159 " WHERE sequence_name = '%s' ";
160 datasource.executeUpdate(String.format(sql, newVal + 1 , table) );
161 }
162 }
163 return true;
164 } catch (Exception e) {
165 String message = "Exception occurred when trying to read or update hibernate_sequences table for value " + table + ": " + e.getMessage();
166 monitor.warning(message, e);
167 logger.error(message);
168 return false;
169 }
170
171 }
172
173
174 private ITermUpdater getCurrentTermUpdater() {
175 return TermUpdater_31_33.NewInstance();
176 }
177
178 /**
179 * Returns the current CDM updater
180 * @return
181 */
182 private ISchemaUpdater getCurrentSchemaUpdater() {
183 return SchemaUpdater_33_331.NewInstance();
184 }
185
186 /**
187 * @param args
188 */
189 public static void main(String[] args) {
190 // logger.warn("main method not yet fully implemented (only works with mysql!!!)");
191 // if(args.length < 2){
192 // logger.error("Arguments missing: server database [username [password]]");
193 // }
194 //TODO better implementation
195 CdmUpdater myUpdater = new CdmUpdater();
196 String server = args[0];
197 String database = args[1];
198 String username = args.length > 2 ? args[2] : null;
199 String password = args.length > 3 ? args[3] : null;
200 int port = 3306;
201 if( args.length > 4){
202 try {
203 port = Integer.parseInt(args[4]);
204 } catch (Exception e) {
205 // ignore
206 }
207 }
208
209 ICdmDataSource dataSource = CdmDataSource.NewMySqlInstance(server, database, 3306, username, password, null);
210 boolean success = myUpdater.updateToCurrentVersion(dataSource, null);
211 System.out.println("DONE " + (success ? "successfully" : "with ERRORS"));
212 }
213
214 }