-
Notifications
You must be signed in to change notification settings - Fork 89
/
DatabaseManager.java
252 lines (236 loc) · 5.99 KB
/
DatabaseManager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
/*
* Copyright 2015 Patrick Ahlbrecht
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.onyxbits.raccoon.db;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Stack;
import org.hsqldb.jdbc.JDBCConnection;
import org.hsqldb.persist.HsqlProperties;
/**
* Takes care of setting up a database connection and coordinates Java/SQL
* bridging via DAOs.
*
* @author patrick
*
*/
public final class DatabaseManager {
/**
* Filename for the database
*/
public static final String DBNAME = "raccoondb_4";
private Stack<Connection> pool;
private HsqlProperties props;
private HashMap<Class<?>, Object> daos;
private HashMap<String, Integer> daoversions;
/**
* Create a new manager.
*
* @param databaseDir
* directory to keep the files in.
* @throws SQLException
* if the DAO table cannot be initialized.
*/
public DatabaseManager(File databaseDir) throws SQLException {
pool = new Stack<Connection>();
props = new HsqlProperties();
props.setProperty("connection_type", "file:");
props.setProperty("database",
new File(databaseDir, DBNAME).getAbsolutePath());
daos = new HashMap<Class<?>, Object>();
daoversions = new HashMap<String, Integer>();
Connection c = new JDBCConnection(props);
Statement st = null;
ResultSet res = null;
try {
// Load the DAO version table
st = c.createStatement();
st.execute("CREATE TABLE IF NOT EXISTS versions (dao VARCHAR(255), version INT)");
st.close();
st = c.createStatement();
st.execute("SELECT dao, version FROM versions");
res = st.getResultSet();
while (res.next()) {
daoversions.put(res.getString(1), res.getInt(2));
}
}
finally {
if (res != null) {
res.close();
}
if (st != null) {
st.close();
}
pool.push(c);
}
}
/**
* Lookup a DAO by class. Tables are automatically created/updated if
* necessary. Trying to access a table from a database file that is newer than
* it's dao will result in an {@link IllegalStateException}.
*
* @param daoclass
* class of the database object to get
* @return the DAO
*/
@SuppressWarnings("unchecked")
public <T extends DataAccessObject> T get(Class<T> daoclass) {
T ret = (T) daos.get(daoclass);
if (ret == null) {
try {
ret = daoclass.newInstance();
}
catch (Exception e) {
throw new RuntimeException(e);
}
// Make sure DAO and TABLE versions match!
int codeVer = ret.getVersion();
int dbVer = 0; // 0: Table not yet created
Integer tmp = daoversions.get(daoclass.getSimpleName());
if (tmp != null) {
dbVer = tmp.intValue();
}
if (codeVer > dbVer) {
Connection c = null;
try {
c = connect();
c.setAutoCommit(false);
ret.upgradeFrom(dbVer, c);
versionTo(codeVer, daoclass.getSimpleName(), c);
c.commit();
}
catch (SQLException e) {
try {
c.rollback();
}
catch (SQLException e1) {
throw new RuntimeException(e1);
}
}
finally {
try {
c.setAutoCommit(true);
}
catch (SQLException e) {
throw new RuntimeException(e);
}
disconnect(c);
}
}
if (dbVer > codeVer) {
throw new IllegalStateException("Database version conflict!");
}
ret.setManager(this);
daos.put(daoclass, ret);
}
return ret;
}
/**
* Set the version of a DAO in the version table
*
* @param version
* @param dao
* @param c
* @throws SQLException
*/
private static void versionTo(int version, String dao, Connection c)
throws SQLException {
PreparedStatement st = null;
try {
st = c.prepareStatement("MERGE INTO versions USING (VALUES (?, ?)) AS vals(x,y) ON versions.dao = vals.x WHEN MATCHED THEN UPDATE SET versions.version=vals.y WHEN NOT MATCHED THEN INSERT VALUES vals.x , vals.y");
st.setString(1, dao);
st.setInt(2, version);
st.execute();
}
finally {
if (st != null) {
st.close();
}
}
}
/**
* Release resources
*
* @throws SQLException
*/
public void shutdown() {
try {
Connection c = connect();
Statement st = c.createStatement();
st.execute("SHUTDOWN");
st.close();
c.close();
while (!pool.isEmpty()) {
pool.pop().close();
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Called by DAOs to get a connection object
*
* @return a connection connection from the pool. The connection should be
* returned using disconnect() after doing it's unit of work.
*/
public Connection connect() {
if (pool.isEmpty()) {
try {
// Speedhack: The proper way of creating a connection is by looking it
// up via JDBC url. However, that's time consuming and we need the
// connection ASAP.
return new JDBCConnection(props);
}
catch (SQLException e) {
e.printStackTrace();
return null;
}
}
return pool.pop();
}
/**
* Called by DAOs to return a connection after they have finished with it.
*
* @param c
* connection to return to the pool (do not close it).
*/
public void disconnect(Connection c) {
try {
if (!c.getAutoCommit()) {
throw new RuntimeException(
"Connection must be set to autocommit before returning it to the pool!");
}
else {
pool.push(c);
}
return;
}
catch (SQLException e) {
// The connection is beyond repair. Just abandon it.
}
try {
c.close();
}
catch (SQLException e) {
// Don't care.
}
}
}