/
DatabaseStorage.java
697 lines (637 loc) · 24.1 KB
/
DatabaseStorage.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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
package net.citizensnpcs.api.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* Implements a traversable tree-view database, which can be accessed with
* simple keys, and is dynamic, meaning that any necessary tables or columns
* must be created when needed.
*
* Keys are formatted using a general node-subnode format x.x.x...x, and will be
* treated by this object according to a set of rules.
* <ul>
* <li>1. The first node is treated as the name of the initial table.
*
* <li>2. The second node is treated as the primary key of the given table name,
* and will be fetched or created from the database as necessary.
*
* <p>
* A combination of the first two rules gives us the initial starting point to
* traverse the key. We have a table and a valid starting point to begin at.
* </p>
*
* <li>3. The last node of the key is treated as the table field to fetch or set
* the requested value from.
*
* <li>4. Any other subnodes are traversed by creating foreign keys between the
* current table and the next table.
* </ul>
*
* <p>
* For example, the user sets a string at the key
* <code>npcs.Bob.location.x</code>
* </p>
* <ul>
* <li>The table <code>npcs</code> is created.
*
* <li>The primary key field must also be created, and as <code>Bob</code> does
* not match any other validation patterns, it is treated as a varchar, so a
* primary key <code>npcs_id varchar(255)</code> is created.
*
* <li>The table <code>location</code> is created and a foreign key
* <code>fk_location</code> is inserted into <code>npcs</code> which references
* <code>location_id</code> (integer). A row is created in location and the
* fk_location field is updated with the generated id.
*
* <li>The field <code>x varchar(255)</code> is created for
* <code>location</code> and the value inserted.
* </ul>
*/
public class DatabaseStorage implements Storage {
private Connection conn;
private final QueryRunner queryRunner = new QueryRunner();
private final Map<String, Table> tables = Maps.newHashMap();
private final Map<String, Traversed> traverseCache = Maps.newHashMap();
private final DatabaseType type;
private final String url, username, password;
public DatabaseStorage(String driver, String url, String username, String password) throws SQLException {
this.url = "jdbc:" + url;
this.username = username;
this.password = password;
this.type = DatabaseType.match(driver);
boolean success = this.type.load();
if (success == false)
throw new SQLException("Couldn't load driver");
}
private void createForeignKey(Table from, Table to) {
String fk = "fk_" + to.name;
Connection conn = getConnection();
try {
for (String sql : type.prepareForeignKeySQL(from, to, fk)) {
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.execute();
stmt.close();
}
from.addForeignKey(fk);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
private Table createTable(String name, int type, boolean autoIncrement) {
if (name == null)
throw new IllegalArgumentException("name cannot be null");
Table t = tables.get(name);
if (t != null)
return t;
String pk = name + "_id";
String directType, primaryType = " NOT NULL PRIMARY KEY";
switch (type) {
case Types.INTEGER:
directType = "INTEGER";
if (autoIncrement)
primaryType += " AUTO_INCREMENT";
break;
case Types.VARCHAR:
directType = "VARCHAR(255)";
break;
default:
throw new IllegalArgumentException("type not supported");
}
Connection conn = getConnection();
PreparedStatement stmt = null;
Table created = null;
try {
stmt = conn.prepareStatement("CREATE TABLE IF NOT EXISTS `" + name + "` (`" + pk + "` " + directType
+ primaryType + ")");
stmt.execute();
created = new Table().setName(name).setPrimaryKey(pk).setPrimaryKeyType(directType);
tables.put(name, created);
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
closeQuietly(stmt);
}
return created;
}
private String ensureRelation(String pk, Table from, final Table to) {
Connection conn = getConnection();
try {
String existing = queryRunner.query(conn, "SELECT `fk_" + to.name + "` FROM `" + from.name + "` WHERE `"
+ from.primaryKey + "` = ?", new ResultSetHandler<String>() {
@Override
public String handle(ResultSet rs) throws SQLException {
return rs.next() ? rs.getString("fk_" + to.name) : null;
}
}, pk);
if (existing == null) {
String generated = to.generateRow();
queryRunner.update(conn, "UPDATE `" + from.name + "` SET `fk_" + to.name + "`=?", generated);
return generated;
} else {
return existing;
}
} catch (SQLException ex) {
ex.printStackTrace();
return null;
}
}
private Connection getConnection() {
if (conn != null) {
// Make a dummy query to check the connection is alive.
try {
if (conn.isClosed()) {
conn = null;
} else {
conn.prepareStatement("SELECT 1;").execute();
}
} catch (SQLException ex) {
if ("08S01".equals(ex.getSQLState())) {
closeQuietly(conn);
}
}
}
try {
if (conn == null || conn.isClosed()) {
conn = (username.isEmpty() && password.isEmpty()) ? DriverManager.getConnection(url) : DriverManager
.getConnection(url, username, password);
return conn;
}
} catch (SQLException ex) {
ex.printStackTrace();
return null;
}
return conn;
}
@Override
public DataKey getKey(String root) {
return new DatabaseKey(root);
}
@Override
public boolean load() {
tables.clear();
traverseCache.clear();
Connection conn = getConnection();
try {
ResultSet rs = conn.getMetaData().getTables(null, null, null, new String[] { "TABLE" });
while (rs.next()) {
tables.put(rs.getString("TABLE_NAME"), new Table());
}
rs.close();
for (Entry<String, Table> entry : tables.entrySet()) {
Table table = entry.getValue();
table.name = entry.getKey();
rs = conn.getMetaData().getColumns(null, null, table.name, null);
while (rs.next()) {
table.addColumn(rs.getString("COLUMN_NAME"));
}
rs.close();
rs = conn.getMetaData().getPrimaryKeys(null, null, table.name);
while (rs.next()) {
table.primaryKey = rs.getString("COLUMN_NAME");
table.setPrimaryKeyType(rs.getMetaData().getColumnTypeName(4));
}
rs.close();
rs = conn.getMetaData().getImportedKeys(null, null, table.name);
while (rs.next()) {
table.addForeignKey(rs.getString("PKCOLUMN_NAME"));
}
rs.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
return false;
}
return true;
}
@Override
public void save() {
commitAndCloseQuietly(conn);
}
@Override
public String toString() {
return "DatabaseStorage [tables=" + tables + ", url=" + url + ", username=" + username + ", password="
+ password + "]";
}
public class DatabaseKey extends DataKey {
private DatabaseKey() {
super("");
}
private DatabaseKey(String root) {
super(root);
}
@Override
protected String createRelativeKey(String from) {
return super.createRelativeKey(from.replace("-", ""));
}
@Override
public boolean getBoolean(String key) {
final Traversed t = traverse(createRelativeKey(key), false);
if (t == INVALID_TRAVERSAL)
return false;
Boolean value = getValue(t, new ResultSetHandler<Boolean>() {
@Override
public Boolean handle(ResultSet rs) throws SQLException {
return rs.next() ? rs.getBoolean(t.column) : null;
}
});
return value == null ? false : value;
}
@Override
public double getDouble(String key) {
final Traversed t = traverse(createRelativeKey(key), false);
if (t == INVALID_TRAVERSAL)
return 0;
Double value = getValue(t, new ResultSetHandler<Double>() {
@Override
public Double handle(ResultSet rs) throws SQLException {
return rs.next() ? rs.getDouble(t.column) : null;
}
});
return value == null ? 0 : value;
}
@Override
public int getInt(String key) {
final Traversed t = traverse(createRelativeKey(key), false);
if (t == INVALID_TRAVERSAL)
return 0;
Integer value = getValue(t, new ResultSetHandler<Integer>() {
@Override
public Integer handle(ResultSet rs) throws SQLException {
return rs.next() ? rs.getInt(t.column) : null;
}
});
return value == null ? 0 : value;
}
@Override
public long getLong(String key) {
final Traversed t = traverse(createRelativeKey(key), false);
if (t == INVALID_TRAVERSAL)
return 0;
Long value = getValue(t, new ResultSetHandler<Long>() {
@Override
public Long handle(ResultSet rs) throws SQLException {
return rs.next() ? rs.getLong(t.column) : null;
}
});
return value == null ? 0 : value;
}
@Override
public Object getRaw(String key) {
final Traversed t = traverse(createRelativeKey(key), false);
if (t == INVALID_TRAVERSAL)
return null;
Object value = getValue(t, new ResultSetHandler<Object>() {
@Override
public Object handle(ResultSet rs) throws SQLException {
return rs.next() ? rs.getObject(t.column) : null;
}
});
return value;
}
@Override
public DataKey getRelative(String relative) {
if (relative == null || relative.isEmpty())
return this;
return new DatabaseKey(createRelativeKey(relative));
}
protected Traversed getRoot() {
return null;
}
private Iterable<DataKey> getSingleKeys(List<DataKey> keys) {
if (!tables.containsKey(path))
return keys;
Table table = tables.get(path);
if (table.primaryKey == null)
return keys;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
Connection conn = getConnection();
stmt = conn.prepareStatement("SELECT `" + table.primaryKey + "` FROM `" + path + "`");
rs = stmt.executeQuery();
while (rs.next()) {
final Traversed found = new Traversed(table, rs.getString(table.primaryKey), table.primaryKey);
keys.add(new DatabaseKey() {
@Override
public Traversed getRoot() {
return found;
}
});
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeQuietly(stmt);
closeQuietly(rs);
}
return keys;
}
@Override
public String getString(String key) {
final Traversed t = traverse(createRelativeKey(key), false);
if (t == INVALID_TRAVERSAL)
return "";
String value = getValue(t, new ResultSetHandler<String>() {
@Override
public String handle(ResultSet rs) throws SQLException {
return rs.next() ? rs.getString(t.column) : null;
}
});
return value == null ? "" : value;
}
@Override
public Iterable<DataKey> getSubKeys() {
List<DataKey> keys = Lists.newArrayList();
if (path.split("\\.").length == 1) {
return getSingleKeys(keys);
}
// TODO: handle longer case
return keys;
}
private <T> T getValue(Traversed t, ResultSetHandler<T> resultSetHandler) {
if (!t.found.hasColumn(t.column))
return null;
try {
return queryRunner.query(getConnection(), "SELECT `" + t.column + "` FROM " + t.found.name + " WHERE `"
+ t.found.primaryKey + "`=?", resultSetHandler, t.key);
} catch (SQLException ex) {
ex.printStackTrace();
return null;
}
}
@Override
public Map<String, Object> getValuesDeep() {
throw new UnsupportedOperationException(); // TODO
}
@Override
public boolean keyExists(String key) {
return traverse(createRelativeKey(key), false) != INVALID_TRAVERSAL;
}
@Override
public String name() {
Traversed t = traverse(path, true);
return t.key != null ? t.key : t.found != null ? t.found.name : "";
}
@Override
public void removeKey(String key) {
Traversed t = traverse(createRelativeKey(key), false);
if (t == INVALID_TRAVERSAL)
return;
Connection conn = getConnection();
try {
if (t.found.hasColumn(t.column)) {
queryRunner.update(conn, "UPDATE `" + t.found.name + "` SET `" + t.column + "`=? WHERE `"
+ t.found.primaryKey + "`=?", null, t.key);
} else {
queryRunner.update(conn, "DELETE FROM `" + t.found.name + "` WHERE `" + t.found.primaryKey + "=?",
t.key);
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
@Override
public void setBoolean(String key, final boolean value) {
setValue("SMALLINT", key, value);
}
@Override
public void setDouble(String key, final double value) {
setValue("DOUBLE", key, value);
}
@Override
public void setInt(String key, final int value) {
setValue("INT", key, value);
}
@Override
public void setLong(String key, final long value) {
setValue("BIGINT", key, value);
}
@Override
public void setRaw(String key, final Object value) {
setValue("JAVA_OBJECT", key, value);
}
@Override
public void setString(String key, final String value) {
setValue("VARCHAR", key, value);
}
private void setValue(String type, String key, Object value) {
Traversed t = traverse(createRelativeKey(key), true);
if (t == INVALID_TRAVERSAL) {
System.err.println("Could not set " + value + " at " + key);
return;
}
Connection conn = getConnection();
try {
if (!t.found.hasColumn(t.column)) {
PreparedStatement stmt = conn.prepareStatement("ALTER TABLE `" + t.found.name + "` ADD `"
+ t.column + "` " + type);
stmt.execute();
closeQuietly(stmt);
t.found.addColumn(t.column);
}
queryRunner.update(conn, "UPDATE `" + t.found.name + "` SET `" + t.column + "`=? WHERE `"
+ t.found.primaryKey + "`=?", value, t.key);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
private Traversed traverse(String path, boolean createRelations) {
Traversed prev = traverseCache.get(path);
if (prev != null)
return prev;
String[] parts = Iterables.toArray(Splitter.on('.').omitEmptyStrings().trimResults().split(path),
String.class);
Traversed root = getRoot();
Table table;
String pk;
int i = 0;
if (root == null) {
if (parts.length < 2)
return INVALID_TRAVERSAL;
// we need a primary key, but we weren't given one!
table = tables.get(parts[0]);
pk = parts[1];
if (table == null) {
if (!createRelations)
return INVALID_TRAVERSAL;
int type = INTEGER.matcher(pk).matches() ? Types.INTEGER : Types.VARCHAR;
table = createTable(parts[0], type, false);
if (table == null)
return INVALID_TRAVERSAL;
table.insert(pk);
}
i = 2; // skip the initial table/primary key
} else {
table = root.found;
pk = root.key;
}
for (; i < parts.length - 1; ++i) {
final String part = parts[i];
Table next = tables.get(part);
boolean missingTable = next == null;
if (missingTable) {
next = createTable(part, Types.INTEGER, true);
if (next == null)
return INVALID_TRAVERSAL;
}
boolean needRelationToNext = !table.hasColumn("fk_" + next.name);
if (needRelationToNext) {
if (!createRelations) {
return INVALID_TRAVERSAL;
}
createForeignKey(table, next);
}
pk = ensureRelation(pk, table, next);
if (pk == null)
return INVALID_TRAVERSAL;
table = next;
}
String setColumn = parts.length == 0 ? null : parts[parts.length - 1];
Traversed t = new Traversed(table, pk, setColumn);
traverseCache.put(path, t);
return t;
}
}
public class Table {
private final List<String> columns = Lists.newArrayList();
String name;
String primaryKey;
String primaryKeyType;
public void addColumn(String column) {
if (columns.contains(column))
throw new IllegalArgumentException(column + " already exists in " + name);
if (column.equalsIgnoreCase(primaryKey) || column.equalsIgnoreCase(name))
return;
columns.add(column);
}
public void addForeignKey(String fk) {
if (columns.contains(fk))
throw new IllegalArgumentException(fk + " already exists in " + name);
columns.add(fk);
}
public String generateRow() {
StringBuilder nullBuilder = new StringBuilder();
int size = columns.size() + 1; // add 1 to account for primary key
for (int i = 0; i < size; ++i) {
nullBuilder.append("NULL,");
}
String nulls = nullBuilder.substring(0, nullBuilder.length() - 1);
Connection conn = getConnection();
PreparedStatement stmt = null;
ResultSet rs = null;
try {
stmt = conn.prepareStatement("INSERT INTO `" + name + "` VALUES (" + nulls + ")",
Statement.RETURN_GENERATED_KEYS);
stmt.execute();
rs = stmt.getGeneratedKeys();
if (!rs.next())
return null;
return rs.getString(1);
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
closeQuietly(stmt);
closeQuietly(rs);
}
return null;
}
public boolean hasColumn(String column) {
return columns.contains(column);
}
public void insert(String primary) {
Connection conn = getConnection();
try {
queryRunner.update(conn, "INSERT INTO `" + name + "` (`" + primaryKey + "`) VALUES (?)", primary);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public Table setName(String tableName) {
name = tableName;
return this;
}
public Table setPrimaryKey(String pk) {
this.primaryKey = pk;
return this;
}
public Table setPrimaryKeyType(String type) {
primaryKeyType = type;
return this;
}
@Override
public String toString() {
return "Table {name=" + name + ", primaryKey=" + primaryKey + ", columns=" + columns + "}";
}
}
private static class Traversed {
private final String column;
private final Table found;
private final String key;
Traversed(Table found, String pk, String column) {
this.found = found;
this.key = pk;
this.column = column;
}
@Override
public String toString() {
return "Traversed [column=" + column + ", found=" + found + ", key=" + key + "]";
}
}
// methods from Apache's DbUtils
private static void closeQuietly(Connection conn) {
try {
if (conn != null)
conn.close();
} catch (SQLException e) {
}
}
private static void closeQuietly(ResultSet rs) {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
}
}
private static void closeQuietly(Statement stmt) {
try {
if (stmt != null)
stmt.close();
} catch (SQLException e) {
}
}
private static void commitAndCloseQuietly(Connection conn) {
try {
try {
conn.commit();
} finally {
conn.close();
}
} catch (SQLException e) {
}
}
public static boolean loadDriver(ClassLoader classLoader, String driverClassName) {
try {
classLoader.loadClass(driverClassName).newInstance();
return true;
} catch (IllegalAccessException e) {
// Constructor is private, OK for DriverManager contract
return true;
} catch (Exception e) {
return false;
}
}
private static final Pattern INTEGER = Pattern.compile("([\\+-]?\\d+)([eE][\\+-]?\\d+)?");
private static final Traversed INVALID_TRAVERSAL = new Traversed(null, null, null);
}