-
Notifications
You must be signed in to change notification settings - Fork 17
/
Database.java
419 lines (361 loc) · 11.7 KB
/
Database.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/*
* Copyright 2011 Tyler Blair. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and contributors and should not be interpreted as representing official policies,
* either expressed or implied, of anybody else.
*/
package com.griefcraft.sql;
import com.griefcraft.lwc.LWC;
import com.griefcraft.scripting.ModuleException;
import com.griefcraft.util.Statistics;
import com.griefcraft.util.Updater;
import com.griefcraft.util.config.Configuration;
import org.bukkit.Bukkit;
import snaq.db.ConnectionPool;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public abstract class Database {
public enum Type {
MySQL("mysql.jar"), //
SQLite("sqlite.jar"), //
NONE("nil"); //
private String driver;
Type(String driver) {
this.driver = driver;
}
public String getDriver() {
return driver;
}
/**
* Match the given string to a database type
*
* @param str
* @return
*/
public static Type matchType(String str) {
for (Type type : values()) {
if (type.toString().equalsIgnoreCase(str)) {
return type;
}
}
return null;
}
}
/**
* The database engine being used for this connection
*/
public Type currentType;
/**
* The default database engine being used. This is set via config
*
* @default SQLite
*/
public static Type DefaultType = Type.NONE;
/**
* The connection pool
*/
private ConnectionPool pool;
/**
* If we are connected to sqlite
*/
private boolean connected = false;
/**
* If the database has been loaded
*/
protected boolean loaded = false;
/**
* The database prefix (only if we're using MySQL.)
*/
protected String prefix = "";
public Database() {
currentType = DefaultType;
prefix = LWC.getInstance().getConfiguration().getString("database.prefix", "");
if (prefix == null) {
prefix = "";
}
}
public Database(Type currentType) {
this();
this.currentType = currentType;
}
/**
* @return the table prefix
*/
public String getPrefix() {
return prefix;
}
/**
* Print an exception to stdout
*
* @param exception
*/
protected void printException(Exception exception) {
throw new ModuleException(exception);
}
/**
* Safe a connection safely by not leaking connection objects
*/
protected void safeClose(PreparedStatement statement) {
if (statement != null) {
try {
statement.close();
} catch (Exception e) {
e.printStackTrace();
try {
statement.close();
} catch (Exception ex) { }
}
}
// TODO force close in the connection pool if possible
}
/**
* Get the connection pool object
*
* @return
*/
public ConnectionPool getConnectionPool() {
return pool;
}
/**
* Create a connection in the database pool
*
* @return
*/
public Connection createConnection() {
try {
return pool.getConnection();
} catch (SQLException e) {
return null;
}
}
/**
* Connect to MySQL
*
* @return if the connection was succesful
*/
public boolean connect() throws Exception {
if (pool != null) {
return true;
}
if (currentType == null || currentType == Type.NONE) {
log("Invalid database engine");
return false;
}
// load the database jar
ClassLoader classLoader;
if (currentType == Type.SQLite) {
classLoader = new URLClassLoader(new URL[]{new URL("jar:file:" + new File(Updater.DEST_LIBRARY_FOLDER + currentType.getDriver()).getPath() + "!/")});
} else {
classLoader = Bukkit.getServer().getClass().getClassLoader();
}
// What class should we try to load?
String className = "";
if (currentType == Type.MySQL) {
className = "com.mysql.jdbc.Driver";
} else {
className = "org.sqlite.JDBC";
}
// Load the driver class
classLoader.loadClass(className).newInstance();
try {
Class.forName(className);
} catch (Exception e) { }
// Create the pool
LWC lwc = LWC.getInstance();
String connectionString = "jdbc:" + currentType.toString().toLowerCase() + ":" + getDatabasePath();
if (currentType == Type.MySQL) {
pool = new ConnectionPool("lwc", 2 /* minPool */, 15 /* maxPool */, 15 /* maxSize */, 180000 /* idleTimeout */,
connectionString, lwc.getConfiguration().getString("database.username"), lwc.getConfiguration().getString("database.password"));
} else { // safe method -- only 1 connection
pool = new ConnectionPool("lwc", 1 /* minPool */, 1 /* maxPool */, 1 /* maxSize */, 180000 /* idleTimeout */,
connectionString, lwc.getConfiguration().getString("database.username"), lwc.getConfiguration().getString("database.password"));
}
pool.setCaching(true);
pool.init();
// Connect to the database
try {
Connection connection = pool.getConnection();
Statement stmt = connection.createStatement();
stmt.executeQuery("SELECT 1;");
stmt.close();
connection.close();
return true;
} catch (SQLException e) {
log("###########################");
log("###########################");
log("### NOTE: LWC has failed to connect to the database (" + currentType + ")");
log("### The error received from the server is: \"" + e.getMessage() + "\"");
log("###");
log("### RESOLVING: Once you have fixed this error, simply restart the server again");
log("###########################");
log("###########################");
connected = false;
return false;
}
}
public void dispose() {
if (pool != null) {
pool.release();
}
pool = null;
}
/**
* @return the path where the database file should be saved
*/
public String getDatabasePath() {
Configuration lwcConfiguration = LWC.getInstance().getConfiguration();
if (currentType == Type.MySQL) {
return "//" + lwcConfiguration.getString("database.host") + "/" + lwcConfiguration.getString("database.database");
}
return lwcConfiguration.getString("database.path");
}
/**
* @return the database engine type
*/
public Type getType() {
return currentType;
}
/**
* Load the database
*/
public abstract void load();
/**
* Log a string to stdout
*
* @param str The string to log
*/
public void log(String str) {
LWC.getInstance().log(str);
}
/**
* Prepare a statement unless it's already cached (and if so, just return it)
*
* @param sql
* @return
*/
public PreparedStatement prepare(String sql) {
return prepare(sql, false);
}
/**
* Prepare a statement unless it's already cached (and if so, just return it)
*
* @param sql
* @param returnGeneratedKeys
* @return
*/
public PreparedStatement prepare(String sql, boolean returnGeneratedKeys) {
try {
Connection connection = createConnection();
PreparedStatement preparedStatement;
if (connection == null) {
throw new DatabaseException("Connection pool is full!");
}
if (returnGeneratedKeys) {
preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
} else {
preparedStatement = connection.prepareStatement(sql);
}
Statistics.addQuery();
return new AutoClosingPreparedStatement(connection, preparedStatement);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Add a column to a table
*
* @param table
* @param column
*/
public boolean addColumn(String table, String column, String type) {
return executeUpdateNoException("ALTER TABLE " + table + " ADD " + column + " " + type);
}
/**
* Add a column to a table
*
* @param table
* @param column
*/
public boolean dropColumn(String table, String column) {
return executeUpdateNoException("ALTER TABLE " + table + " DROP COLUMN " + column);
}
/**
* Rename a table
*
* @param table
* @param newName
*/
public boolean renameTable(String table, String newName) {
return executeUpdateNoException("ALTER TABLE " + table + " RENAME TO " + newName);
}
/**
* Drop a table
*
* @param table
*/
public boolean dropTable(String table) {
return executeUpdateNoException("DROP TABLE " + table);
}
/**
* Execute an update, ignoring any exceptions
*
* @param query
* @return true if an exception was thrown
*/
public boolean executeUpdateNoException(String query) {
Connection connection = createConnection();
Statement statement = null;
boolean exception = false;
if (connection == null) {
return true; // could not create
}
try {
statement = connection.createStatement();
statement.executeUpdate(query);
} catch (SQLException e) {
exception = true;
} finally {
try {
if (statement != null) {
statement.close();
}
connection.close();
} catch (SQLException e) {
}
}
return exception;
}
/**
* @return true if connected to the database
*/
public boolean isConnected() {
return connected;
}
}