DatabaseManager.java 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. package com.gmail.nossr50.database;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.PreparedStatement;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.util.ArrayList;
  8. import java.util.HashMap;
  9. import java.util.Map;
  10. import java.util.Properties;
  11. import org.bukkit.entity.Player;
  12. import com.gmail.nossr50.mcMMO;
  13. import com.gmail.nossr50.config.Config;
  14. import com.gmail.nossr50.datatypes.database.DatabaseUpdateType;
  15. import com.gmail.nossr50.datatypes.player.McMMOPlayer;
  16. import com.gmail.nossr50.datatypes.skills.SkillType;
  17. import com.gmail.nossr50.datatypes.spout.huds.McMMOHud;
  18. import com.gmail.nossr50.runnables.database.SQLReconnectTask;
  19. import com.gmail.nossr50.util.player.UserManager;
  20. import com.gmail.nossr50.util.spout.SpoutUtils;
  21. public final class DatabaseManager {
  22. private static String connectionString;
  23. private static String tablePrefix = Config.getInstance().getMySQLTablePrefix();
  24. private static Connection connection = null;
  25. // Scale waiting time by this much per failed attempt
  26. private static final double SCALING_FACTOR = 40;
  27. // Minimum wait in nanoseconds (default 500ms)
  28. private static final long MIN_WAIT = 500L * 1000000L;
  29. // Maximum time to wait between reconnects (default 5 minutes)
  30. private static final long MAX_WAIT = 5L * 60L * 1000L * 1000000L;
  31. // How long to wait when checking if connection is valid (default 3 seconds)
  32. private static final int VALID_TIMEOUT = 3;
  33. // When next to try connecting to Database in nanoseconds
  34. private static long nextReconnectTimestamp = 0L;
  35. // How many connection attempts have failed
  36. private static int reconnectAttempt = 0;
  37. private static final long ONE_MONTH = 2630000000L;
  38. private DatabaseManager() {}
  39. /**
  40. * Attempt to connect to the mySQL database.
  41. */
  42. public static void connect() {
  43. Config configInstance = Config.getInstance();
  44. connectionString = "jdbc:mysql://" + configInstance.getMySQLServerName() + ":" + configInstance.getMySQLServerPort() + "/" + configInstance.getMySQLDatabaseName();
  45. try {
  46. mcMMO.p.getLogger().info("Attempting connection to MySQL...");
  47. // Force driver to load if not yet loaded
  48. Class.forName("com.mysql.jdbc.Driver");
  49. Properties connectionProperties = new Properties();
  50. connectionProperties.put("user", configInstance.getMySQLUserName());
  51. connectionProperties.put("password", configInstance.getMySQLUserPassword());
  52. connectionProperties.put("autoReconnect", "false");
  53. connectionProperties.put("maxReconnects", "0");
  54. connection = DriverManager.getConnection(connectionString, connectionProperties);
  55. mcMMO.p.getLogger().info("Connection to MySQL was a success!");
  56. }
  57. catch (SQLException ex) {
  58. connection = null;
  59. if (reconnectAttempt == 0 || reconnectAttempt >= 11) {
  60. mcMMO.p.getLogger().info("Connection to MySQL failed!");
  61. }
  62. }
  63. catch (ClassNotFoundException ex) {
  64. connection = null;
  65. if (reconnectAttempt == 0 || reconnectAttempt >= 11) {
  66. mcMMO.p.getLogger().info("MySQL database driver not found!");
  67. }
  68. }
  69. }
  70. /**
  71. * Attempt to create the database structure.
  72. */
  73. public static void createStructure() {
  74. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "users` ("
  75. + "`id` int(10) unsigned NOT NULL AUTO_INCREMENT,"
  76. + "`user` varchar(40) NOT NULL,"
  77. + "`lastlogin` int(32) unsigned NOT NULL,"
  78. + "PRIMARY KEY (`id`),"
  79. + "UNIQUE KEY `user` (`user`)) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;");
  80. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "huds` ("
  81. + "`user_id` int(10) unsigned NOT NULL,"
  82. + "`hudtype` varchar(50) NOT NULL DEFAULT 'STANDARD',"
  83. + "PRIMARY KEY (`user_id`),"
  84. + "FOREIGN KEY (`user_id`) REFERENCES `" + tablePrefix + "users` (`id`) "
  85. + "ON DELETE CASCADE) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
  86. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "cooldowns` ("
  87. + "`user_id` int(10) unsigned NOT NULL,"
  88. + "`taming` int(32) unsigned NOT NULL DEFAULT '0',"
  89. + "`mining` int(32) unsigned NOT NULL DEFAULT '0',"
  90. + "`woodcutting` int(32) unsigned NOT NULL DEFAULT '0',"
  91. + "`repair` int(32) unsigned NOT NULL DEFAULT '0',"
  92. + "`unarmed` int(32) unsigned NOT NULL DEFAULT '0',"
  93. + "`herbalism` int(32) unsigned NOT NULL DEFAULT '0',"
  94. + "`excavation` int(32) unsigned NOT NULL DEFAULT '0',"
  95. + "`archery` int(32) unsigned NOT NULL DEFAULT '0',"
  96. + "`swords` int(32) unsigned NOT NULL DEFAULT '0',"
  97. + "`axes` int(32) unsigned NOT NULL DEFAULT '0',"
  98. + "`acrobatics` int(32) unsigned NOT NULL DEFAULT '0',"
  99. + "`blast_mining` int(32) unsigned NOT NULL DEFAULT '0',"
  100. + "PRIMARY KEY (`user_id`),"
  101. + "FOREIGN KEY (`user_id`) REFERENCES `" + tablePrefix + "users` (`id`) "
  102. + "ON DELETE CASCADE) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
  103. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "skills` ("
  104. + "`user_id` int(10) unsigned NOT NULL,"
  105. + "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
  106. + "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
  107. + "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
  108. + "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
  109. + "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
  110. + "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
  111. + "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
  112. + "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
  113. + "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
  114. + "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
  115. + "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
  116. + "PRIMARY KEY (`user_id`),"
  117. + "FOREIGN KEY (`user_id`) REFERENCES `" + tablePrefix + "users` (`id`) "
  118. + "ON DELETE CASCADE) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
  119. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "experience` ("
  120. + "`user_id` int(10) unsigned NOT NULL,"
  121. + "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
  122. + "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
  123. + "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
  124. + "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
  125. + "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
  126. + "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
  127. + "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
  128. + "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
  129. + "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
  130. + "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
  131. + "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
  132. + "PRIMARY KEY (`user_id`),"
  133. + "FOREIGN KEY (`user_id`) REFERENCES `" + tablePrefix + "users` (`id`) "
  134. + "ON DELETE CASCADE) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
  135. checkDatabaseStructure(DatabaseUpdateType.FISHING);
  136. checkDatabaseStructure(DatabaseUpdateType.BLAST_MINING);
  137. checkDatabaseStructure(DatabaseUpdateType.CASCADE_DELETE);
  138. checkDatabaseStructure(DatabaseUpdateType.INDEX);
  139. }
  140. /**
  141. * Attempt to write the SQL query.
  142. *
  143. * @param sql Query to write.
  144. * @return true if the query was successfully written, false otherwise.
  145. */
  146. public static boolean write(String sql) {
  147. if (!checkConnected()) {
  148. return false;
  149. }
  150. PreparedStatement statement = null;
  151. try {
  152. statement = connection.prepareStatement(sql);
  153. statement.executeUpdate();
  154. return true;
  155. }
  156. catch (SQLException ex) {
  157. printErrors(ex);
  158. return false;
  159. }
  160. finally {
  161. if (statement != null) {
  162. try {
  163. statement.close();
  164. }
  165. catch (SQLException e) {
  166. printErrors(e);
  167. return false;
  168. }
  169. }
  170. }
  171. }
  172. /**
  173. * Returns the number of rows affected by either a DELETE or UPDATE query
  174. *
  175. * @param sql SQL query to execute
  176. * @return the number of rows affected
  177. */
  178. public static int update(String sql) {
  179. int ret = 0;
  180. if (checkConnected()) {
  181. PreparedStatement statement = null;
  182. try {
  183. statement = connection.prepareStatement(sql);
  184. ret = statement.executeUpdate();
  185. }
  186. catch (SQLException ex) {
  187. printErrors(ex);
  188. }
  189. finally {
  190. if (statement != null) {
  191. try {
  192. statement.close();
  193. }
  194. catch (SQLException e) {
  195. printErrors(e);
  196. }
  197. }
  198. }
  199. }
  200. return ret;
  201. }
  202. /**
  203. * Get the Integer. Only return first row / first field.
  204. *
  205. * @param sql SQL query to execute
  206. * @return the value in the first row / first field
  207. */
  208. public static int getInt(String sql) {
  209. ResultSet resultSet = null;
  210. int result = 0;
  211. if (checkConnected()) {
  212. PreparedStatement statement = null;
  213. try {
  214. statement = connection.prepareStatement(sql);
  215. resultSet = statement.executeQuery();
  216. if (resultSet.next()) {
  217. result = resultSet.getInt(1);
  218. }
  219. else {
  220. result = 0;
  221. }
  222. }
  223. catch (SQLException ex) {
  224. printErrors(ex);
  225. }
  226. finally {
  227. if (statement != null) {
  228. try {
  229. statement.close();
  230. }
  231. catch (SQLException e) {
  232. printErrors(e);
  233. }
  234. }
  235. }
  236. }
  237. return result;
  238. }
  239. /**
  240. * Check connection status and re-establish if dead or stale.
  241. *
  242. * If the very first immediate attempt fails, further attempts
  243. * will be made in progressively larger intervals up to MAX_WAIT
  244. * intervals.
  245. *
  246. * This allows for MySQL to time out idle connections as needed by
  247. * server operator, without affecting McMMO, while still providing
  248. * protection against a database outage taking down Bukkit's tick
  249. * processing loop due to attemping a database connection each
  250. * time McMMO needs the database.
  251. *
  252. * @return the boolean value for whether or not we are connected
  253. */
  254. public static boolean checkConnected() {
  255. boolean isClosed = true;
  256. boolean isValid = false;
  257. boolean exists = (connection != null);
  258. // If we're waiting for server to recover then leave early
  259. if (nextReconnectTimestamp > 0 && nextReconnectTimestamp > System.nanoTime()) {
  260. return false;
  261. }
  262. if (exists) {
  263. try {
  264. isClosed = connection.isClosed();
  265. }
  266. catch (SQLException e) {
  267. isClosed = true;
  268. e.printStackTrace();
  269. printErrors(e);
  270. }
  271. if (!isClosed) {
  272. try {
  273. isValid = connection.isValid(VALID_TIMEOUT);
  274. }
  275. catch (SQLException e) {
  276. // Don't print stack trace because it's valid to lose idle connections to the server and have to restart them.
  277. isValid = false;
  278. }
  279. }
  280. }
  281. // Leave if all ok
  282. if (exists && !isClosed && isValid) {
  283. // Housekeeping
  284. nextReconnectTimestamp = 0;
  285. reconnectAttempt = 0;
  286. return true;
  287. }
  288. // Cleanup after ourselves for GC and MySQL's sake
  289. if (exists && !isClosed) {
  290. try {
  291. connection.close();
  292. }
  293. catch (SQLException ex) {
  294. // This is a housekeeping exercise, ignore errors
  295. }
  296. }
  297. // Try to connect again
  298. connect();
  299. // Leave if connection is good
  300. try {
  301. if (connection != null && !connection.isClosed()) {
  302. // Schedule a database save if we really had an outage
  303. if (reconnectAttempt > 1) {
  304. mcMMO.p.getServer().getScheduler().scheduleSyncDelayedTask(mcMMO.p, new SQLReconnectTask(), 5);
  305. }
  306. nextReconnectTimestamp = 0;
  307. reconnectAttempt = 0;
  308. return true;
  309. }
  310. }
  311. catch (SQLException e) {
  312. // Failed to check isClosed, so presume connection is bad and attempt later
  313. e.printStackTrace();
  314. printErrors(e);
  315. }
  316. reconnectAttempt++;
  317. nextReconnectTimestamp = (long)(System.nanoTime() + Math.min(MAX_WAIT, (reconnectAttempt * SCALING_FACTOR * MIN_WAIT)));
  318. return false;
  319. }
  320. /**
  321. * Read SQL query.
  322. *
  323. * @param sql SQL query to read
  324. * @return the rows in this SQL query
  325. */
  326. public static HashMap<Integer, ArrayList<String>> read(String sql) {
  327. ResultSet resultSet;
  328. HashMap<Integer, ArrayList<String>> rows = new HashMap<Integer, ArrayList<String>>();
  329. if (checkConnected()) {
  330. PreparedStatement statement = null;
  331. try {
  332. statement = connection.prepareStatement(sql);
  333. resultSet = statement.executeQuery();
  334. while (resultSet.next()) {
  335. ArrayList<String> column = new ArrayList<String>();
  336. for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
  337. column.add(resultSet.getString(i));
  338. }
  339. rows.put(resultSet.getRow(), column);
  340. }
  341. }
  342. catch (SQLException ex) {
  343. printErrors(ex);
  344. }
  345. finally {
  346. if (statement != null) {
  347. try {
  348. statement.close();
  349. }
  350. catch (SQLException e) {
  351. printErrors(e);
  352. }
  353. }
  354. }
  355. }
  356. return rows;
  357. }
  358. public static Map<String, Integer> readSQLRank(String playerName) {
  359. ResultSet resultSet;
  360. Map<String, Integer> skills = new HashMap<String, Integer>();
  361. if (checkConnected()) {
  362. try {
  363. for (SkillType skillType : SkillType.values()) {
  364. if (skillType.isChildSkill()) {
  365. continue;
  366. }
  367. String skillName = skillType.name().toLowerCase();
  368. String sql = "SELECT COUNT(*) AS rank FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " +
  369. "AND " + skillName + " > (SELECT " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
  370. "WHERE user = '" + playerName + "')";
  371. PreparedStatement statement = connection.prepareStatement(sql);
  372. resultSet = statement.executeQuery();
  373. resultSet.next();
  374. int rank = resultSet.getInt("rank");
  375. sql = "SELECT user, " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " +
  376. "AND " + skillName + " = (SELECT " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
  377. "WHERE user = '" + playerName + "') ORDER BY user";
  378. statement = connection.prepareStatement(sql);
  379. resultSet = statement.executeQuery();
  380. while (resultSet.next()) {
  381. if (resultSet.getString("user").equalsIgnoreCase(playerName)) {
  382. skills.put(skillType.name(), rank + resultSet.getRow());
  383. break;
  384. }
  385. }
  386. statement.close();
  387. }
  388. String sql = "SELECT COUNT(*) AS rank FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
  389. "WHERE taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing > 0 " +
  390. "AND taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing > " +
  391. "(SELECT taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing " +
  392. "FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE user = '" + playerName + "')";
  393. PreparedStatement statement = connection.prepareStatement(sql);
  394. resultSet = statement.executeQuery();
  395. resultSet.next();
  396. int rank = resultSet.getInt("rank");
  397. sql = "SELECT user, taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing " +
  398. "FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
  399. "WHERE taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing > 0 " +
  400. "AND taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing = " +
  401. "(SELECT taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing " +
  402. "FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE user = '" + playerName + "') ORDER BY user";
  403. statement = connection.prepareStatement(sql);
  404. resultSet = statement.executeQuery();
  405. while (resultSet.next()) {
  406. if (resultSet.getString("user").equalsIgnoreCase(playerName)) {
  407. skills.put("ALL", rank + resultSet.getRow());
  408. break;
  409. }
  410. }
  411. statement.close();
  412. }
  413. catch (SQLException ex) {
  414. printErrors(ex);
  415. }
  416. }
  417. return skills;
  418. }
  419. public static void purgePowerlessSQL() {
  420. mcMMO.p.getLogger().info("Purging powerless users...");
  421. HashMap<Integer, ArrayList<String>> usernames;
  422. usernames = read("SELECT u.user FROM " + tablePrefix + "skills AS s, " + tablePrefix + "users AS u " + "WHERE s.user_id = u.id AND " +
  423. "(s.taming+s.mining+s.woodcutting+s.repair+s.unarmed+s.herbalism+s.excavation+s.archery+s.swords+s.axes+s.acrobatics+s.fishing) = 0");
  424. write("DELETE FROM " + tablePrefix + "users WHERE " + tablePrefix + "users.id IN (SELECT * FROM " +
  425. "(SELECT u.id FROM " + tablePrefix + "skills AS s, " + tablePrefix + "users AS u " + "WHERE s.user_id = u.id " +
  426. "AND (s.taming+s.mining+s.woodcutting+s.repair+s.unarmed+s.herbalism+s.excavation+s.archery+s.swords+s.axes+s.acrobatics+s.fishing) = 0) AS p)");
  427. int purgedUsers = 0;
  428. for (int i = 1; i <= usernames.size(); i++) {
  429. String playerName = usernames.get(i).get(0);
  430. if (playerName == null || mcMMO.p.getServer().getOfflinePlayer(playerName).isOnline()) {
  431. continue;
  432. }
  433. profileCleanup(playerName);
  434. purgedUsers++;
  435. }
  436. mcMMO.p.getLogger().info("Purged " + purgedUsers + " users from the database.");
  437. }
  438. public static void purgeOldSQL() {
  439. mcMMO.p.getLogger().info("Purging old users...");
  440. long currentTime = System.currentTimeMillis();
  441. long purgeTime = ONE_MONTH * Config.getInstance().getOldUsersCutoff();
  442. HashMap<Integer, ArrayList<String>> usernames = read("SELECT user FROM " + tablePrefix + "users WHERE ((" + currentTime + " - lastlogin*1000) > " + purgeTime + ")");
  443. write("DELETE FROM " + tablePrefix + "users WHERE " + tablePrefix + "users.id IN (SELECT * FROM (SELECT id FROM " + tablePrefix + "users WHERE ((" + currentTime + " - lastlogin*1000) > " + purgeTime + ")) AS p)");
  444. int purgedUsers = 0;
  445. for (int i = 1; i <= usernames.size(); i++) {
  446. String playerName = usernames.get(i).get(0);
  447. if (playerName == null) {
  448. continue;
  449. }
  450. profileCleanup(playerName);
  451. purgedUsers++;
  452. }
  453. mcMMO.p.getLogger().info("Purged " + purgedUsers + " users from the database.");
  454. }
  455. public static void profileCleanup(String playerName) {
  456. McMMOPlayer mcMMOPlayer = UserManager.getPlayer(playerName);
  457. if (mcMMOPlayer != null) {
  458. Player player = mcMMOPlayer.getPlayer();
  459. McMMOHud spoutHud = mcMMOPlayer.getProfile().getSpoutHud();
  460. if (spoutHud != null) {
  461. spoutHud.removeWidgets();
  462. }
  463. UserManager.remove(playerName);
  464. if (player.isOnline()) {
  465. UserManager.addUser(player);
  466. if (mcMMO.spoutEnabled) {
  467. SpoutUtils.reloadSpoutPlayer(player);
  468. }
  469. }
  470. }
  471. }
  472. /**
  473. * Check database structure for missing values.
  474. *
  475. * @param update Type of data to check updates for
  476. */
  477. private static void checkDatabaseStructure(DatabaseUpdateType update) {
  478. String sql = null;
  479. ResultSet resultSet = null;
  480. HashMap<Integer, ArrayList<String>> rows = new HashMap<Integer, ArrayList<String>>();
  481. switch (update) {
  482. case BLAST_MINING:
  483. sql = "SELECT * FROM `" + tablePrefix + "cooldowns` ORDER BY `" + tablePrefix + "cooldowns`.`blast_mining` ASC LIMIT 0 , 30";
  484. break;
  485. case CASCADE_DELETE:
  486. write("ALTER TABLE `" + tablePrefix + "huds` ADD FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE;");
  487. write("ALTER TABLE `" + tablePrefix + "experience` ADD FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE;");
  488. write("ALTER TABLE `" + tablePrefix + "cooldowns` ADD FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE;");
  489. write("ALTER TABLE `" + tablePrefix + "skills` ADD FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE;");
  490. break;
  491. case FISHING:
  492. sql = "SELECT * FROM `" + tablePrefix + "experience` ORDER BY `" + tablePrefix + "experience`.`fishing` ASC LIMIT 0 , 30";
  493. break;
  494. case INDEX:
  495. if (read("SHOW INDEX FROM " + tablePrefix + "skills").size() != 13 && checkConnected()) {
  496. mcMMO.p.getLogger().info("Indexing tables, this may take a while on larger databases");
  497. write("ALTER TABLE `" + tablePrefix + "skills` ADD INDEX `idx_taming` (`taming`) USING BTREE, "
  498. + "ADD INDEX `idx_mining` (`mining`) USING BTREE, "
  499. + "ADD INDEX `idx_woodcutting` (`woodcutting`) USING BTREE, "
  500. + "ADD INDEX `idx_repair` (`repair`) USING BTREE, "
  501. + "ADD INDEX `idx_unarmed` (`unarmed`) USING BTREE, "
  502. + "ADD INDEX `idx_herbalism` (`herbalism`) USING BTREE, "
  503. + "ADD INDEX `idx_excavation` (`excavation`) USING BTREE, "
  504. + "ADD INDEX `idx_archery` (`archery`) USING BTREE, "
  505. + "ADD INDEX `idx_swords` (`swords`) USING BTREE, "
  506. + "ADD INDEX `idx_axes` (`axes`) USING BTREE, "
  507. + "ADD INDEX `idx_acrobatics` (`acrobatics`) USING BTREE, "
  508. + "ADD INDEX `idx_fishing` (`fishing`) USING BTREE;");
  509. }
  510. break;
  511. default:
  512. break;
  513. }
  514. PreparedStatement statement = null;
  515. try {
  516. if (!checkConnected()) {
  517. return;
  518. }
  519. statement = connection.prepareStatement(sql);
  520. resultSet = statement.executeQuery();
  521. while (resultSet.next()) {
  522. ArrayList<String> column = new ArrayList<String>();
  523. for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
  524. column.add(resultSet.getString(i));
  525. }
  526. rows.put(resultSet.getRow(), column);
  527. }
  528. }
  529. catch (SQLException ex) {
  530. switch (update) {
  531. case BLAST_MINING:
  532. mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Blast Mining...");
  533. write("ALTER TABLE `"+tablePrefix + "cooldowns` ADD `blast_mining` int(32) NOT NULL DEFAULT '0' ;");
  534. break;
  535. case FISHING:
  536. mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Fishing...");
  537. write("ALTER TABLE `"+tablePrefix + "skills` ADD `fishing` int(10) NOT NULL DEFAULT '0' ;");
  538. write("ALTER TABLE `"+tablePrefix + "experience` ADD `fishing` int(10) NOT NULL DEFAULT '0' ;");
  539. break;
  540. default:
  541. break;
  542. }
  543. }
  544. finally {
  545. if (resultSet != null) {
  546. try {
  547. resultSet.close();
  548. }
  549. catch (SQLException e) {
  550. // Ignore the error, we're leaving
  551. }
  552. }
  553. if (statement != null) {
  554. try {
  555. statement.close();
  556. }
  557. catch (SQLException e) {
  558. // Ignore the error, we're leaving
  559. }
  560. }
  561. }
  562. }
  563. private static void printErrors(SQLException ex) {
  564. mcMMO.p.getLogger().severe("SQLException: " + ex.getMessage());
  565. mcMMO.p.getLogger().severe("SQLState: " + ex.getSQLState());
  566. mcMMO.p.getLogger().severe("VendorError: " + ex.getErrorCode());
  567. }
  568. }