1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.bitrepository.service.database;
23
24 import java.sql.Connection;
25 import java.sql.PreparedStatement;
26 import java.sql.ResultSet;
27 import java.sql.SQLException;
28 import java.util.HashMap;
29 import java.util.Map;
30
31
32
33
34
35
36
37
38
39
40
41
42 public abstract class DatabaseMigrator extends DatabaseMaintainer {
43
44 protected final DBConnector connector;
45
46
47 protected static final String TABLEVERSIONS_TABLE = "tableversions";
48
49 protected static final String TV_TABLENAME = "tablename";
50
51 protected static final String TV_VERSION = "version";
52
53
54
55
56
57 protected DatabaseMigrator(DBConnector connector) {
58 this.connector = connector;
59 }
60
61
62
63
64
65 protected Map<String, Integer> getTableVersions() {
66 Map<String, Integer> resultMap = new HashMap<String, Integer>();
67
68
69 String sql = "SELECT " + TV_TABLENAME + " , " + TV_VERSION + " FROM " + TABLEVERSIONS_TABLE;
70 int tablenameColoumn = 1;
71 int versionColoumn = 2;
72
73 try {
74 PreparedStatement ps = null;
75 ResultSet res = null;
76 Connection conn = null;
77 try {
78 conn = connector.getConnection();
79 ps = DatabaseUtils.createPreparedStatement(conn, sql, new Object[0]);
80 res = ps.executeQuery();
81
82 while (res.next()) {
83 resultMap.put(res.getString(tablenameColoumn), res.getInt(versionColoumn));
84 }
85 } finally {
86 if(res != null) {
87 res.close();
88 }
89 if(ps != null) {
90 ps.close();
91 }
92 if(conn != null) {
93 conn.close();
94 }
95 }
96 } catch (SQLException e) {
97 throw new IllegalStateException("Cannot extract the table versions.", e);
98 }
99
100 return resultMap;
101 }
102
103
104
105
106
107
108
109
110 protected void updateTable(String tablename, Integer newVersion, String updateSql, Object ... args) {
111 String migrateSql = "UPDATE " + TABLEVERSIONS_TABLE + " SET " + TV_VERSION + " = ? WHERE " + TV_TABLENAME
112 + " = ?";
113
114 DatabaseUtils.executeStatement(connector, updateSql, args);
115 DatabaseUtils.executeStatement(connector, migrateSql, newVersion, tablename);
116 }
117
118
119
120
121
122
123 protected void migrateDerbyDatabase(String migrateScriptName) {
124 if(connector.getDatabaseDriverClass().equals(DatabaseUtils.DERBY_EMBEDDED_DRIVER)) {
125 try {
126 runScript(connector, migrateScriptName);
127 } catch (Exception e) {
128 throw new IllegalStateException("Cannot migrate the database with the script '" + migrateScriptName
129 + "'. It is very possible that the database has to be migrated by manually running "
130 + "migrate-scripts.", e);
131 }
132 } else {
133 throw new IllegalStateException("Can only perform database migrations on embedded derby databases. "
134 + "Migration of other databases must be performed manually. Your database had the drivers: "
135 + connector.getDatabaseDriverClass());
136 }
137 }
138
139
140
141
142 abstract public void migrate();
143
144
145
146
147
148 public abstract boolean needsMigration();
149
150 }