-
Notifications
You must be signed in to change notification settings - Fork 17
/
Database.java
337 lines (278 loc) · 8.49 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
/**
* This file is part of LWC (https://github.com/Hidendra/LWC)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.griefcraft.sql;
import com.griefcraft.lwc.LWC;
import com.griefcraft.scripting.ModuleException;
import com.griefcraft.util.Updater;
import com.griefcraft.util.config.Configuration;
import org.bukkit.Bukkit;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;
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;
}
}
/**
* The database engine being used for this connection
*/
public Type currentType;
/**
* Store cached prepared statements.
* <p/>
* Since SQLite JDBC doesn't cache them.. we do it ourselves :S
*/
private Map<String, PreparedStatement> statementCache = new HashMap<String, PreparedStatement>();
/**
* The connection to the database
*/
protected Connection connection = null;
/**
* Logging object
*/
protected Logger logger = Logger.getLogger(getClass().getSimpleName());
/**
* The default database engine being used. This is set via config
*
* @default SQLite
*/
public static Type DefaultType = Type.NONE;
/**
* 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);
}
/**
* Connect to MySQL
*
* @return if the connection was succesful
*/
public boolean connect() throws Exception {
if (connection != 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 + "lib/" + currentType.getDriver()).getPath() + "!/")});
} else {
classLoader = Bukkit.getServer().getClass().getClassLoader();
}
// DatabaseClassLoader classLoader = DatabaseClassLoader.getInstance(new URL("jar:file:" + new File(Updater.DEST_LIBRARY_FOLDER + "lib/" + currentType.getDriver()).getAbsolutePath() + "!/"));
String className = "";
if (currentType == Type.MySQL) {
className = "com.mysql.jdbc.Driver";
} else {
className = "org.sqlite.JDBC";
}
Driver driver = (Driver) classLoader.loadClass(className).newInstance();
DriverManager.registerDriver(new DriverStub(driver));
Properties properties = new Properties();
// if we're using mysql, append the database info
if (currentType == Type.MySQL) {
LWC lwc = LWC.getInstance();
properties.put("autoReconnect", "true");
properties.put("user", lwc.getConfiguration().getString("database.username"));
properties.put("password", lwc.getConfiguration().getString("database.password"));
}
connection = DriverManager.getConnection("jdbc:" + currentType.toString().toLowerCase() + ":" + getDatabasePath(), properties);
connected = true;
return true;
}
public void dispose() {
statementCache.clear();
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
connection = null;
}
/**
* @return the connection to the database
*/
public Connection getConnection() {
return connection;
}
/**
* @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;
}
public abstract void load();
/**
* Log a string to stdout
*
* @param str The string to log
*/
public void log(String str) {
logger.info("LWC: " + str);
}
/**
* Called after a statement is prepared
*/
protected void postPrepare() {
}
/**
* Prepare a statement unless it's already cached (and if so, just return it)
*
* @param sql
* @return
*/
public PreparedStatement prepare(String sql) {
if (connection == null) {
return null;
}
if (statementCache.containsKey(sql)) {
postPrepare();
return statementCache.get(sql);
}
try {
PreparedStatement preparedStatement = connection.prepareStatement(sql);
statementCache.put(sql, preparedStatement);
postPrepare();
return 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);
}
/**
* 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) {
Statement statement = null;
boolean exception = false;
try {
statement = connection.createStatement();
statement.executeUpdate(query);
} catch (SQLException e) {
exception = true;
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (SQLException e) {
}
}
return exception;
}
/**
* @return true if connected to the database
*/
public boolean isConnected() {
return connected;
}
}