SQLDatabaseManager.java 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648
  1. package com.gmail.nossr50.database;
  2. import java.sql.Connection;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.ResultSetMetaData;
  6. import java.sql.SQLException;
  7. import java.sql.Statement;
  8. import java.util.ArrayList;
  9. import java.util.Collection;
  10. import java.util.EnumMap;
  11. import java.util.HashMap;
  12. import java.util.List;
  13. import java.util.Map;
  14. import java.util.Properties;
  15. import java.util.UUID;
  16. import com.gmail.nossr50.mcMMO;
  17. import com.gmail.nossr50.config.Config;
  18. import com.gmail.nossr50.datatypes.MobHealthbarType;
  19. import com.gmail.nossr50.datatypes.database.DatabaseType;
  20. import com.gmail.nossr50.datatypes.database.PlayerStat;
  21. import com.gmail.nossr50.datatypes.database.UpgradeType;
  22. import com.gmail.nossr50.datatypes.player.PlayerProfile;
  23. import com.gmail.nossr50.datatypes.skills.AbilityType;
  24. import com.gmail.nossr50.datatypes.skills.SkillType;
  25. import com.gmail.nossr50.runnables.database.UUIDUpdateAsyncTask;
  26. import com.gmail.nossr50.util.Misc;
  27. import snaq.db.ConnectionPool;
  28. public final class SQLDatabaseManager implements DatabaseManager {
  29. private static final String ALL_QUERY_VERSION = "taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing+alchemy";
  30. private String tablePrefix = Config.getInstance().getMySQLTablePrefix();
  31. private final int POOL_FETCH_TIMEOUT = 0; // How long a method will wait for a connection. Since none are on main thread, we can safely say wait for as long as you like.
  32. private final Map<UUID, Integer> cachedUserIDs = new HashMap<UUID, Integer>();
  33. private final Map<String, Integer> cachedUserIDsByName = new HashMap<String, Integer>();
  34. private ConnectionPool connectionPool;
  35. protected SQLDatabaseManager() {
  36. String connectionString = "jdbc:mysql://" + Config.getInstance().getMySQLServerName() + ":" + Config.getInstance().getMySQLServerPort() + "/" + Config.getInstance().getMySQLDatabaseName();
  37. try {
  38. // Force driver to load if not yet loaded
  39. Class.forName("com.mysql.jdbc.Driver");
  40. }
  41. catch (ClassNotFoundException e) {
  42. e.printStackTrace();
  43. return;
  44. //throw e; // aborts onEnable() Riking if you want to do this, fully implement it.
  45. }
  46. Properties connectionProperties = new Properties();
  47. connectionProperties.put("user", Config.getInstance().getMySQLUserName());
  48. connectionProperties.put("password", Config.getInstance().getMySQLUserPassword());
  49. connectionProperties.put("autoReconnect", "false");
  50. connectionProperties.put("cachePrepStmts", "true");
  51. connectionProperties.put("prepStmtCacheSize", "64");
  52. connectionProperties.put("prepStmtCacheSqlLimit", "2048");
  53. connectionProperties.put("useServerPrepStmts", "true");
  54. connectionPool = new ConnectionPool("mcMMO-Pool",
  55. 1 /*Minimum of one*/,
  56. Config.getInstance().getMySQLMaxPoolSize() /*max pool size */,
  57. Config.getInstance().getMySQLMaxConnections() /*max num connections*/,
  58. 0 /* idle timeout of connections */,
  59. connectionString,
  60. connectionProperties);
  61. connectionPool.init(); // Init first connection
  62. connectionPool.registerShutdownHook(); // Auto release on jvm exit just in case
  63. checkStructure();
  64. }
  65. public void purgePowerlessUsers() {
  66. mcMMO.p.getLogger().info("Purging powerless users...");
  67. Connection connection = null;
  68. Statement statement = null;
  69. ResultSet resultSet = null;
  70. List<String> usernames = new ArrayList<String>();
  71. try {
  72. connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
  73. statement = connection.createStatement();
  74. resultSet = statement.executeQuery("SELECT u.user FROM " + tablePrefix + "skills AS s, " + tablePrefix + "users AS u WHERE s.user_id = u.id 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");
  75. while (resultSet.next()) {
  76. usernames.add(resultSet.getString("user"));
  77. }
  78. resultSet.close();
  79. statement.executeUpdate("DELETE FROM u, e, h, s, c USING " + tablePrefix + "users u " +
  80. "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) " +
  81. "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " +
  82. "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " +
  83. "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " +
  84. "WHERE (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");
  85. }
  86. catch (SQLException ex) {
  87. printErrors(ex);
  88. }
  89. finally {
  90. if (resultSet != null) {
  91. try {
  92. resultSet.close();
  93. }
  94. catch (SQLException e) {
  95. // Ignore
  96. }
  97. }
  98. if (statement != null) {
  99. try {
  100. statement.close();
  101. }
  102. catch (SQLException e) {
  103. // Ignore
  104. }
  105. }
  106. if (connection != null) {
  107. try {
  108. connection.close();
  109. }
  110. catch (SQLException e) {
  111. // Ignore
  112. }
  113. }
  114. }
  115. if (!usernames.isEmpty()) {
  116. processPurge(usernames);
  117. }
  118. mcMMO.p.getLogger().info("Purged " + usernames.size() + " users from the database.");
  119. }
  120. public void purgeOldUsers() {
  121. mcMMO.p.getLogger().info("Purging old users...");
  122. Connection connection = null;
  123. Statement statement = null;
  124. ResultSet resultSet = null;
  125. List<String> usernames = new ArrayList<String>();
  126. try {
  127. connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
  128. statement = connection.createStatement();
  129. resultSet = statement.executeQuery("SELECT user FROM " + tablePrefix + "users WHERE ((NOW() - lastlogin * " + Misc.TIME_CONVERSION_FACTOR + ") > " + PURGE_TIME + ")");
  130. while (resultSet.next()) {
  131. usernames.add(resultSet.getString("user"));
  132. }
  133. resultSet.close();
  134. statement.executeUpdate("DELETE FROM u, e, h, s, c USING " + tablePrefix + "users u " +
  135. "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) " +
  136. "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " +
  137. "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " +
  138. "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " +
  139. "WHERE ((NOW() - lastlogin * " + Misc.TIME_CONVERSION_FACTOR + ") > " + PURGE_TIME + ")");
  140. }
  141. catch (SQLException ex) {
  142. printErrors(ex);
  143. }
  144. finally {
  145. if (resultSet != null) {
  146. try {
  147. resultSet.close();
  148. }
  149. catch (SQLException e) {
  150. // Ignore
  151. }
  152. }
  153. if (statement != null) {
  154. try {
  155. statement.close();
  156. }
  157. catch (SQLException e) {
  158. // Ignore
  159. }
  160. }
  161. if (connection != null) {
  162. try {
  163. connection.close();
  164. }
  165. catch (SQLException e) {
  166. // Ignore
  167. }
  168. }
  169. }
  170. if (!usernames.isEmpty()) {
  171. processPurge(usernames);
  172. }
  173. mcMMO.p.getLogger().info("Purged " + usernames.size() + " users from the database.");
  174. }
  175. public boolean removeUser(String playerName) {
  176. boolean success = false;
  177. Connection connection = null;
  178. PreparedStatement statement = null;
  179. try {
  180. connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
  181. statement = connection.prepareStatement("DELETE FROM u, e, h, s, c " +
  182. "USING " + tablePrefix + "users u " +
  183. "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) " +
  184. "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " +
  185. "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " +
  186. "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " +
  187. "WHERE u.user = ?");
  188. statement.setString(1, playerName);
  189. success = statement.executeUpdate() != 0;
  190. }
  191. catch (SQLException ex) {
  192. printErrors(ex);
  193. }
  194. finally {
  195. if (statement != null) {
  196. try {
  197. statement.close();
  198. }
  199. catch (SQLException e) {
  200. // Ignore
  201. }
  202. }
  203. if (connection != null) {
  204. try {
  205. connection.close();
  206. }
  207. catch (SQLException e) {
  208. // Ignore
  209. }
  210. }
  211. }
  212. if (success) {
  213. Misc.profileCleanup(playerName);
  214. }
  215. return success;
  216. }
  217. public boolean saveUser(PlayerProfile profile) {
  218. boolean success = true;
  219. PreparedStatement statement = null;
  220. Connection connection = null;
  221. try {
  222. connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
  223. int id = getUserID(connection, profile.getUniqueId());
  224. if (id == -1) {
  225. newUser(profile.getPlayerName(), profile.getUniqueId().toString());
  226. id = getUserID(connection, profile.getUniqueId());
  227. if (id == -1) {
  228. return false;
  229. }
  230. }
  231. statement = connection.prepareStatement("UPDATE " + tablePrefix + "users SET lastlogin = UNIX_TIMESTAMP() WHERE uuid = ?");
  232. statement.setString(1, profile.getUniqueId().toString());
  233. success &= (statement.executeUpdate() != 0);
  234. statement.close();
  235. statement = connection.prepareStatement("UPDATE " + tablePrefix + "skills SET "
  236. + " taming = ?, mining = ?, repair = ?, woodcutting = ?"
  237. + ", unarmed = ?, herbalism = ?, excavation = ?"
  238. + ", archery = ?, swords = ?, axes = ?, acrobatics = ?"
  239. + ", fishing = ?, alchemy = ? WHERE user_id = ?");
  240. statement.setInt(1, profile.getSkillLevel(SkillType.TAMING));
  241. statement.setInt(2, profile.getSkillLevel(SkillType.MINING));
  242. statement.setInt(3, profile.getSkillLevel(SkillType.REPAIR));
  243. statement.setInt(4, profile.getSkillLevel(SkillType.WOODCUTTING));
  244. statement.setInt(5, profile.getSkillLevel(SkillType.UNARMED));
  245. statement.setInt(6, profile.getSkillLevel(SkillType.HERBALISM));
  246. statement.setInt(7, profile.getSkillLevel(SkillType.EXCAVATION));
  247. statement.setInt(8, profile.getSkillLevel(SkillType.ARCHERY));
  248. statement.setInt(9, profile.getSkillLevel(SkillType.SWORDS));
  249. statement.setInt(10, profile.getSkillLevel(SkillType.AXES));
  250. statement.setInt(11, profile.getSkillLevel(SkillType.ACROBATICS));
  251. statement.setInt(12, profile.getSkillLevel(SkillType.FISHING));
  252. statement.setInt(13, profile.getSkillLevel(SkillType.ALCHEMY));
  253. statement.setInt(14, id);
  254. success &= (statement.executeUpdate() != 0);
  255. statement.close();
  256. statement = connection.prepareStatement("UPDATE " + tablePrefix + "experience SET "
  257. + " taming = ?, mining = ?, repair = ?, woodcutting = ?"
  258. + ", unarmed = ?, herbalism = ?, excavation = ?"
  259. + ", archery = ?, swords = ?, axes = ?, acrobatics = ?"
  260. + ", fishing = ?, alchemy = ? WHERE user_id = ?");
  261. statement.setInt(1, profile.getSkillXpLevel(SkillType.TAMING));
  262. statement.setInt(2, profile.getSkillXpLevel(SkillType.MINING));
  263. statement.setInt(3, profile.getSkillXpLevel(SkillType.REPAIR));
  264. statement.setInt(4, profile.getSkillXpLevel(SkillType.WOODCUTTING));
  265. statement.setInt(5, profile.getSkillXpLevel(SkillType.UNARMED));
  266. statement.setInt(6, profile.getSkillXpLevel(SkillType.HERBALISM));
  267. statement.setInt(7, profile.getSkillXpLevel(SkillType.EXCAVATION));
  268. statement.setInt(8, profile.getSkillXpLevel(SkillType.ARCHERY));
  269. statement.setInt(9, profile.getSkillXpLevel(SkillType.SWORDS));
  270. statement.setInt(10, profile.getSkillXpLevel(SkillType.AXES));
  271. statement.setInt(11, profile.getSkillXpLevel(SkillType.ACROBATICS));
  272. statement.setInt(12, profile.getSkillXpLevel(SkillType.FISHING));
  273. statement.setInt(13, profile.getSkillXpLevel(SkillType.ALCHEMY));
  274. statement.setInt(14, id);
  275. success &= (statement.executeUpdate() != 0);
  276. statement.close();
  277. statement = connection.prepareStatement("UPDATE " + tablePrefix + "cooldowns SET "
  278. + " mining = ?, woodcutting = ?, unarmed = ?"
  279. + ", herbalism = ?, excavation = ?, swords = ?"
  280. + ", axes = ?, blast_mining = ? WHERE user_id = ?");
  281. statement.setLong(1, profile.getAbilityDATS(AbilityType.SUPER_BREAKER));
  282. statement.setLong(2, profile.getAbilityDATS(AbilityType.TREE_FELLER));
  283. statement.setLong(3, profile.getAbilityDATS(AbilityType.BERSERK));
  284. statement.setLong(4, profile.getAbilityDATS(AbilityType.GREEN_TERRA));
  285. statement.setLong(5, profile.getAbilityDATS(AbilityType.GIGA_DRILL_BREAKER));
  286. statement.setLong(6, profile.getAbilityDATS(AbilityType.SERRATED_STRIKES));
  287. statement.setLong(7, profile.getAbilityDATS(AbilityType.SKULL_SPLITTER));
  288. statement.setLong(8, profile.getAbilityDATS(AbilityType.BLAST_MINING));
  289. statement.setInt(9, id);
  290. success = (statement.executeUpdate() != 0);
  291. statement.close();
  292. statement = connection.prepareStatement("UPDATE " + tablePrefix + "huds SET mobhealthbar = ? WHERE user_id = ?");
  293. statement.setString(1, profile.getMobHealthbarType() == null ? Config.getInstance().getMobHealthbarDefault().name() : profile.getMobHealthbarType().name());
  294. statement.setInt(2, id);
  295. success = (statement.executeUpdate() != 0);
  296. }
  297. catch (SQLException ex) {
  298. printErrors(ex);
  299. }
  300. finally {
  301. if (statement != null) {
  302. try {
  303. statement.close();
  304. }
  305. catch (SQLException e) {
  306. // Ignore
  307. }
  308. }
  309. if (connection != null) {
  310. try {
  311. connection.close();
  312. }
  313. catch (SQLException e) {
  314. // Ignore
  315. }
  316. }
  317. }
  318. return success;
  319. }
  320. public List<PlayerStat> readLeaderboard(SkillType skill, int pageNumber, int statsPerPage) {
  321. List<PlayerStat> stats = new ArrayList<PlayerStat>();
  322. String query = skill == null ? ALL_QUERY_VERSION : skill.name().toLowerCase();
  323. ResultSet resultSet = null;
  324. PreparedStatement statement = null;
  325. Connection connection = null;
  326. try {
  327. connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
  328. statement = connection.prepareStatement("SELECT " + query + ", user, NOW() FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON (user_id = id) WHERE " + query + " > 0 ORDER BY " + query + " DESC, user LIMIT ?, ?");
  329. statement.setInt(1, (pageNumber * statsPerPage) - statsPerPage);
  330. statement.setInt(2, statsPerPage);
  331. resultSet = statement.executeQuery();
  332. while (resultSet.next()) {
  333. ArrayList<String> column = new ArrayList<String>();
  334. for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
  335. column.add(resultSet.getString(i));
  336. }
  337. stats.add(new PlayerStat(column.get(1), Integer.valueOf(column.get(0))));
  338. }
  339. }
  340. catch (SQLException ex) {
  341. printErrors(ex);
  342. }
  343. finally {
  344. if (resultSet != null) {
  345. try {
  346. resultSet.close();
  347. }
  348. catch (SQLException e) {
  349. // Ignore
  350. }
  351. }
  352. if (statement != null) {
  353. try {
  354. statement.close();
  355. }
  356. catch (SQLException e) {
  357. // Ignore
  358. }
  359. }
  360. if (connection != null) {
  361. try {
  362. connection.close();
  363. }
  364. catch (SQLException e) {
  365. // Ignore
  366. }
  367. }
  368. }
  369. return stats;
  370. }
  371. public Map<SkillType, Integer> readRank(String playerName) {
  372. Map<SkillType, Integer> skills = new EnumMap<SkillType, Integer>(SkillType.class);
  373. ResultSet resultSet = null;
  374. PreparedStatement statement = null;
  375. Connection connection = null;
  376. try {
  377. connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
  378. for (SkillType skillType : SkillType.NON_CHILD_SKILLS) {
  379. String skillName = skillType.name().toLowerCase();
  380. String sql = "SELECT COUNT(*) AS rank FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " +
  381. "AND " + skillName + " > (SELECT " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
  382. "WHERE user = ?)";
  383. statement = connection.prepareStatement(sql);
  384. statement.setString(1, playerName);
  385. resultSet = statement.executeQuery();
  386. resultSet.next();
  387. int rank = resultSet.getInt("rank");
  388. sql = "SELECT user, " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " +
  389. "AND " + skillName + " = (SELECT " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
  390. "WHERE user = '" + playerName + "') ORDER BY user";
  391. resultSet.close();
  392. statement.close();
  393. statement = connection.prepareStatement(sql);
  394. resultSet = statement.executeQuery();
  395. while (resultSet.next()) {
  396. if (resultSet.getString("user").equalsIgnoreCase(playerName)) {
  397. skills.put(skillType, rank + resultSet.getRow());
  398. break;
  399. }
  400. }
  401. resultSet.close();
  402. statement.close();
  403. }
  404. String sql = "SELECT COUNT(*) AS rank FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
  405. "WHERE " + ALL_QUERY_VERSION + " > 0 " +
  406. "AND " + ALL_QUERY_VERSION + " > " +
  407. "(SELECT " + ALL_QUERY_VERSION + " " +
  408. "FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE user = ?)";
  409. statement = connection.prepareStatement(sql);
  410. statement.setString(1, playerName);
  411. resultSet = statement.executeQuery();
  412. resultSet.next();
  413. int rank = resultSet.getInt("rank");
  414. resultSet.close();
  415. statement.close();
  416. sql = "SELECT user, " + ALL_QUERY_VERSION + " " +
  417. "FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
  418. "WHERE " + ALL_QUERY_VERSION + " > 0 " +
  419. "AND " + ALL_QUERY_VERSION + " = " +
  420. "(SELECT " + ALL_QUERY_VERSION + " " +
  421. "FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE user = ?) ORDER BY user";
  422. statement = connection.prepareStatement(sql);
  423. statement.setString(1, playerName);
  424. resultSet = statement.executeQuery();
  425. while (resultSet.next()) {
  426. if (resultSet.getString("user").equalsIgnoreCase(playerName)) {
  427. skills.put(null, rank + resultSet.getRow());
  428. break;
  429. }
  430. }
  431. resultSet.close();
  432. statement.close();
  433. }
  434. catch (SQLException ex) {
  435. printErrors(ex);
  436. }
  437. finally {
  438. if (resultSet != null) {
  439. try {
  440. resultSet.close();
  441. }
  442. catch (SQLException e) {
  443. // Ignore
  444. }
  445. }
  446. if (statement != null) {
  447. try {
  448. statement.close();
  449. }
  450. catch (SQLException e) {
  451. // Ignore
  452. }
  453. }
  454. if (connection != null) {
  455. try {
  456. connection.close();
  457. }
  458. catch (SQLException e) {
  459. // Ignore
  460. }
  461. }
  462. }
  463. return skills;
  464. }
  465. public void newUser(String playerName, String uuid) {
  466. Connection connection = null;
  467. try {
  468. connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
  469. newUser(connection, playerName, uuid);
  470. }
  471. catch (SQLException ex) {
  472. printErrors(ex);
  473. }
  474. finally {
  475. if (connection != null) {
  476. try {
  477. connection.close();
  478. }
  479. catch (SQLException e) {
  480. // Ignore
  481. }
  482. }
  483. }
  484. }
  485. private void newUser(Connection connection, String playerName, String uuid) {
  486. ResultSet resultSet = null;
  487. PreparedStatement statement = null;
  488. try {
  489. statement = connection.prepareStatement("INSERT INTO " + tablePrefix + "users (user, uuid, lastlogin) VALUES (?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
  490. statement.setString(1, playerName);
  491. statement.setString(2, uuid);
  492. statement.setLong(3, System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR);
  493. statement.executeUpdate();
  494. resultSet = statement.getGeneratedKeys();
  495. if (!resultSet.next()) {
  496. return;
  497. }
  498. writeMissingRows(connection, resultSet.getInt(1));
  499. }
  500. catch (SQLException ex) {
  501. printErrors(ex);
  502. }
  503. finally {
  504. if (resultSet != null) {
  505. try {
  506. resultSet.close();
  507. }
  508. catch (SQLException e) {
  509. // Ignore
  510. }
  511. }
  512. if (statement != null) {
  513. try {
  514. statement.close();
  515. }
  516. catch (SQLException e) {
  517. // Ignore
  518. }
  519. }
  520. }
  521. }
  522. /**
  523. * This is a fallback method to provide the old way of getting a
  524. * PlayerProfile in case there is no UUID match found
  525. */
  526. private PlayerProfile loadPlayerNameProfile(String playerName, String uuid, boolean create, boolean retry) {
  527. PreparedStatement statement = null;
  528. Connection connection = null;
  529. ResultSet resultSet = null;
  530. try {
  531. connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
  532. int id = getUserID(connection, playerName);
  533. if (id == -1) {
  534. // There is no such user
  535. if (create) {
  536. newUser(playerName, uuid);
  537. return loadPlayerNameProfile(playerName, uuid, false, false);
  538. }
  539. // Return unloaded profile if can't create
  540. return new PlayerProfile(playerName, false);
  541. }
  542. // There is such a user
  543. writeMissingRows(connection, id);
  544. statement = connection.prepareStatement(
  545. "SELECT "
  546. + "s.taming, s.mining, s.repair, s.woodcutting, s.unarmed, s.herbalism, s.excavation, s.archery, s.swords, s.axes, s.acrobatics, s.fishing, s.alchemy, "
  547. + "e.taming, e.mining, e.repair, e.woodcutting, e.unarmed, e.herbalism, e.excavation, e.archery, e.swords, e.axes, e.acrobatics, e.fishing, e.alchemy, "
  548. + "c.taming, c.mining, c.repair, c.woodcutting, c.unarmed, c.herbalism, c.excavation, c.archery, c.swords, c.axes, c.acrobatics, c.blast_mining, "
  549. + "h.mobhealthbar, u.uuid "
  550. + "FROM " + tablePrefix + "users u "
  551. + "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) "
  552. + "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) "
  553. + "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) "
  554. + "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) "
  555. + "WHERE u.user = ?");
  556. statement.setString(1, playerName);
  557. resultSet = statement.executeQuery();
  558. if (resultSet.next()) {
  559. try {
  560. PlayerProfile ret = loadFromResult(playerName, resultSet);
  561. return ret;
  562. }
  563. catch (SQLException e) {
  564. }
  565. }
  566. }
  567. catch (SQLException ex) {
  568. printErrors(ex);
  569. }
  570. finally {
  571. if (resultSet != null) {
  572. try {
  573. resultSet.close();
  574. }
  575. catch (SQLException e) {
  576. // Ignore
  577. }
  578. }
  579. if (statement != null) {
  580. try {
  581. statement.close();
  582. }
  583. catch (SQLException e) {
  584. // Ignore
  585. }
  586. }
  587. if (connection != null) {
  588. try {
  589. connection.close();
  590. }
  591. catch (SQLException e) {
  592. // Ignore
  593. }
  594. }
  595. }
  596. // Problem, nothing was returned
  597. // Quit if this is second time around
  598. if (!retry) {
  599. return new PlayerProfile(playerName, false);
  600. }
  601. // Retry, and abort on re-failure
  602. return loadPlayerNameProfile(playerName, uuid, create, false);
  603. }
  604. @Deprecated
  605. public PlayerProfile loadPlayerProfile(String playerName, boolean create) {
  606. return loadPlayerProfile(playerName, "", false, true);
  607. }
  608. public PlayerProfile loadPlayerProfile(UUID uuid) {
  609. return loadPlayerProfile("", uuid.toString(), false, true);
  610. }
  611. public PlayerProfile loadPlayerProfile(String playerName, UUID uuid, boolean create) {
  612. return loadPlayerProfile(playerName, uuid.toString(), create, true);
  613. }
  614. private PlayerProfile loadPlayerProfile(String playerName, String uuid, boolean create, boolean retry) {
  615. PreparedStatement statement = null;
  616. Connection connection = null;
  617. ResultSet resultSet = null;
  618. try {
  619. connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
  620. int id = getUserID(connection, playerName);
  621. if (id == -1) {
  622. // There is no such user
  623. if (create) {
  624. newUser(playerName, uuid);
  625. return loadPlayerNameProfile(playerName, uuid, false, false);
  626. }
  627. // Return unloaded profile if can't create
  628. return new PlayerProfile(playerName, false);
  629. }
  630. // There is such a user
  631. writeMissingRows(connection, id);
  632. statement = connection.prepareStatement(
  633. "SELECT "
  634. + "s.taming, s.mining, s.repair, s.woodcutting, s.unarmed, s.herbalism, s.excavation, s.archery, s.swords, s.axes, s.acrobatics, s.fishing, s.alchemy, "
  635. + "e.taming, e.mining, e.repair, e.woodcutting, e.unarmed, e.herbalism, e.excavation, e.archery, e.swords, e.axes, e.acrobatics, e.fishing, e.alchemy, "
  636. + "c.taming, c.mining, c.repair, c.woodcutting, c.unarmed, c.herbalism, c.excavation, c.archery, c.swords, c.axes, c.acrobatics, c.blast_mining, "
  637. + "h.mobhealthbar, u.uuid "
  638. + "FROM " + tablePrefix + "users u "
  639. + "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) "
  640. + "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) "
  641. + "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) "
  642. + "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) "
  643. + "WHERE u.UUID = ?");
  644. statement.setString(1, uuid);
  645. resultSet = statement.executeQuery();
  646. if (resultSet.next()) {
  647. try {
  648. PlayerProfile profile = loadFromResult(playerName, resultSet);
  649. resultSet.close();
  650. statement.close();
  651. if (!playerName.isEmpty() && !profile.getPlayerName().isEmpty()) {
  652. statement = connection.prepareStatement(
  653. "UPDATE `" + tablePrefix + "users` "
  654. + "SET user = ? "
  655. + "WHERE UUID = ?");
  656. statement.setString(1, playerName);
  657. statement.setString(2, uuid);
  658. statement.executeUpdate();
  659. statement.close();
  660. }
  661. return profile;
  662. }
  663. catch (SQLException e) {
  664. }
  665. }
  666. resultSet.close();
  667. }
  668. catch (SQLException ex) {
  669. printErrors(ex);
  670. }
  671. finally {
  672. if (resultSet != null) {
  673. try {
  674. resultSet.close();
  675. }
  676. catch (SQLException e) {
  677. // Ignore
  678. }
  679. }
  680. if (statement != null) {
  681. try {
  682. statement.close();
  683. }
  684. catch (SQLException e) {
  685. // Ignore
  686. }
  687. }
  688. if (connection != null) {
  689. try {
  690. connection.close();
  691. }
  692. catch (SQLException e) {
  693. // Ignore
  694. }
  695. }
  696. }
  697. // Problem, nothing was returned
  698. // Retry the old fashioned way if this is second time around
  699. if (!retry) {
  700. return loadPlayerNameProfile(playerName, uuid, create, true);
  701. }
  702. // Retry, and abort on re-failure
  703. return loadPlayerProfile(playerName, uuid, create, false);
  704. }
  705. public void convertUsers(DatabaseManager destination) {
  706. PreparedStatement statement = null;
  707. Connection connection = null;
  708. ResultSet resultSet = null;
  709. try {
  710. connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
  711. statement = connection.prepareStatement(
  712. "SELECT "
  713. + "s.taming, s.mining, s.repair, s.woodcutting, s.unarmed, s.herbalism, s.excavation, s.archery, s.swords, s.axes, s.acrobatics, s.fishing, s.alchemy, "
  714. + "e.taming, e.mining, e.repair, e.woodcutting, e.unarmed, e.herbalism, e.excavation, e.archery, e.swords, e.axes, e.acrobatics, e.fishing, e.alchemy, "
  715. + "c.taming, c.mining, c.repair, c.woodcutting, c.unarmed, c.herbalism, c.excavation, c.archery, c.swords, c.axes, c.acrobatics, c.blast_mining, "
  716. + "h.mobhealthbar, u.uuid "
  717. + "FROM " + tablePrefix + "users u "
  718. + "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) "
  719. + "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) "
  720. + "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) "
  721. + "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) "
  722. + "WHERE u.user = ?");
  723. List<String> usernames = getStoredUsers();
  724. int convertedUsers = 0;
  725. long startMillis = System.currentTimeMillis();
  726. for (String playerName : usernames) {
  727. statement.setString(1, playerName);
  728. try {
  729. resultSet = statement.executeQuery();
  730. resultSet.next();
  731. destination.saveUser(loadFromResult(playerName, resultSet));
  732. resultSet.close();
  733. }
  734. catch (SQLException e) {
  735. // Ignore
  736. }
  737. convertedUsers++;
  738. Misc.printProgress(convertedUsers, progressInterval, startMillis);
  739. }
  740. }
  741. catch (SQLException e) {
  742. printErrors(e);
  743. }
  744. finally {
  745. if (resultSet != null) {
  746. try {
  747. resultSet.close();
  748. }
  749. catch (SQLException e) {
  750. // Ignore
  751. }
  752. }
  753. if (statement != null) {
  754. try {
  755. statement.close();
  756. }
  757. catch (SQLException e) {
  758. // Ignore
  759. }
  760. }
  761. if (connection != null) {
  762. try {
  763. connection.close();
  764. }
  765. catch (SQLException e) {
  766. // Ignore
  767. }
  768. }
  769. }
  770. }
  771. public boolean saveUserUUID(String userName, UUID uuid) {
  772. PreparedStatement statement = null;
  773. Connection connection = null;
  774. try {
  775. connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
  776. statement = connection.prepareStatement(
  777. "UPDATE `" + tablePrefix + "users` SET "
  778. + " uuid = ? WHERE user = ?");
  779. statement.setString(1, uuid.toString());
  780. statement.setString(2, userName);
  781. statement.execute();
  782. return true;
  783. }
  784. catch (SQLException ex) {
  785. printErrors(ex);
  786. return false;
  787. }
  788. finally {
  789. if (statement != null) {
  790. try {
  791. statement.close();
  792. }
  793. catch (SQLException e) {
  794. // Ignore
  795. }
  796. }
  797. if (connection != null) {
  798. try {
  799. connection.close();
  800. }
  801. catch (SQLException e) {
  802. // Ignore
  803. }
  804. }
  805. }
  806. }
  807. public boolean saveUserUUIDs(Map<String, UUID> fetchedUUIDs) {
  808. PreparedStatement statement = null;
  809. int count = 0;
  810. Connection connection = null;
  811. try {
  812. connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
  813. statement = connection.prepareStatement("UPDATE " + tablePrefix + "users SET uuid = ? WHERE user = ?");
  814. for (Map.Entry<String, UUID> entry : fetchedUUIDs.entrySet()) {
  815. statement.setString(1, entry.getValue().toString());
  816. statement.setString(2, entry.getKey());
  817. statement.addBatch();
  818. count++;
  819. if ((count % 500) == 0) {
  820. statement.executeBatch();
  821. count = 0;
  822. }
  823. }
  824. if (count != 0) {
  825. statement.executeBatch();
  826. }
  827. return true;
  828. }
  829. catch (SQLException ex) {
  830. printErrors(ex);
  831. return false;
  832. }
  833. finally {
  834. if (statement != null) {
  835. try {
  836. statement.close();
  837. }
  838. catch (SQLException e) {
  839. // Ignore
  840. }
  841. }
  842. if (connection != null) {
  843. try {
  844. connection.close();
  845. }
  846. catch (SQLException e) {
  847. // Ignore
  848. }
  849. }
  850. }
  851. }
  852. public List<String> getStoredUsers() {
  853. ArrayList<String> users = new ArrayList<String>();
  854. Statement statement = null;
  855. Connection connection = null;
  856. ResultSet resultSet = null;
  857. try {
  858. connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
  859. statement = connection.createStatement();
  860. resultSet = statement.executeQuery("SELECT user FROM " + tablePrefix + "users");
  861. while (resultSet.next()) {
  862. users.add(resultSet.getString("user"));
  863. }
  864. }
  865. catch (SQLException e) {
  866. printErrors(e);
  867. }
  868. finally {
  869. if (resultSet != null) {
  870. try {
  871. resultSet.close();
  872. }
  873. catch (SQLException e) {
  874. // Ignore
  875. }
  876. }
  877. if (statement != null) {
  878. try {
  879. statement.close();
  880. }
  881. catch (SQLException e) {
  882. // Ignore
  883. }
  884. }
  885. if (connection != null) {
  886. try {
  887. connection.close();
  888. }
  889. catch (SQLException e) {
  890. // Ignore
  891. }
  892. }
  893. }
  894. return users;
  895. }
  896. /**
  897. * Checks that the database structure is present and correct
  898. */
  899. private void checkStructure() {
  900. Statement statement = null;
  901. Connection connection = null;
  902. try {
  903. connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
  904. statement = connection.createStatement();
  905. statement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "users` ("
  906. + "`id` int(10) unsigned NOT NULL AUTO_INCREMENT,"
  907. + "`user` varchar(40) NOT NULL,"
  908. + "`uuid` varchar(36) NULL DEFAULT NULL,"
  909. + "`lastlogin` int(32) unsigned NOT NULL,"
  910. + "PRIMARY KEY (`id`),"
  911. + "UNIQUE KEY `user` (`user`),"
  912. + "UNIQUE KEY `uuid` (`uuid`)) DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;");
  913. statement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "huds` ("
  914. + "`user_id` int(10) unsigned NOT NULL,"
  915. + "`mobhealthbar` varchar(50) NOT NULL DEFAULT '" + Config.getInstance().getMobHealthbarDefault() + "',"
  916. + "PRIMARY KEY (`user_id`)) "
  917. + "DEFAULT CHARSET=latin1;");
  918. statement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "cooldowns` ("
  919. + "`user_id` int(10) unsigned NOT NULL,"
  920. + "`taming` int(32) unsigned NOT NULL DEFAULT '0',"
  921. + "`mining` int(32) unsigned NOT NULL DEFAULT '0',"
  922. + "`woodcutting` int(32) unsigned NOT NULL DEFAULT '0',"
  923. + "`repair` int(32) unsigned NOT NULL DEFAULT '0',"
  924. + "`unarmed` int(32) unsigned NOT NULL DEFAULT '0',"
  925. + "`herbalism` int(32) unsigned NOT NULL DEFAULT '0',"
  926. + "`excavation` int(32) unsigned NOT NULL DEFAULT '0',"
  927. + "`archery` int(32) unsigned NOT NULL DEFAULT '0',"
  928. + "`swords` int(32) unsigned NOT NULL DEFAULT '0',"
  929. + "`axes` int(32) unsigned NOT NULL DEFAULT '0',"
  930. + "`acrobatics` int(32) unsigned NOT NULL DEFAULT '0',"
  931. + "`blast_mining` int(32) unsigned NOT NULL DEFAULT '0',"
  932. + "PRIMARY KEY (`user_id`)) "
  933. + "DEFAULT CHARSET=latin1;");
  934. statement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "skills` ("
  935. + "`user_id` int(10) unsigned NOT NULL,"
  936. + "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
  937. + "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
  938. + "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
  939. + "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
  940. + "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
  941. + "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
  942. + "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
  943. + "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
  944. + "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
  945. + "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
  946. + "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
  947. + "`fishing` int(10) unsigned NOT NULL DEFAULT '0',"
  948. + "`alchemy` int(10) unsigned NOT NULL DEFAULT '0',"
  949. + "PRIMARY KEY (`user_id`)) "
  950. + "DEFAULT CHARSET=latin1;");
  951. statement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "experience` ("
  952. + "`user_id` int(10) unsigned NOT NULL,"
  953. + "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
  954. + "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
  955. + "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
  956. + "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
  957. + "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
  958. + "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
  959. + "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
  960. + "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
  961. + "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
  962. + "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
  963. + "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
  964. + "`fishing` int(10) unsigned NOT NULL DEFAULT '0',"
  965. + "`alchemy` int(10) unsigned NOT NULL DEFAULT '0',"
  966. + "PRIMARY KEY (`user_id`)) "
  967. + "DEFAULT CHARSET=latin1;");
  968. for (UpgradeType updateType : UpgradeType.values()) {
  969. checkDatabaseStructure(connection, updateType);
  970. }
  971. mcMMO.p.getLogger().info("Killing orphans");
  972. statement.executeUpdate("DELETE FROM `" + tablePrefix + "experience` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "users` `u` WHERE `" + tablePrefix + "experience`.`user_id` = `u`.`id`)");
  973. statement.executeUpdate("DELETE FROM `" + tablePrefix + "huds` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "users` `u` WHERE `" + tablePrefix + "huds`.`user_id` = `u`.`id`)");
  974. statement.executeUpdate("DELETE FROM `" + tablePrefix + "cooldowns` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "users` `u` WHERE `" + tablePrefix + "cooldowns`.`user_id` = `u`.`id`)");
  975. statement.executeUpdate("DELETE FROM `" + tablePrefix + "skills` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "users` `u` WHERE `" + tablePrefix + "skills`.`user_id` = `u`.`id`)");
  976. }
  977. catch (SQLException ex) {
  978. printErrors(ex);
  979. }
  980. finally {
  981. if (statement != null) {
  982. try {
  983. statement.close();
  984. }
  985. catch (SQLException e) {
  986. // Ignore
  987. }
  988. }
  989. if (connection != null) {
  990. try {
  991. connection.close();
  992. }
  993. catch (SQLException e) {
  994. // Ignore
  995. }
  996. }
  997. }
  998. }
  999. /**
  1000. * Check database structure for necessary upgrades.
  1001. *
  1002. * @param upgrade Upgrade to attempt to apply
  1003. */
  1004. private void checkDatabaseStructure(Connection connection, UpgradeType upgrade) {
  1005. if (!mcMMO.getUpgradeManager().shouldUpgrade(upgrade)) {
  1006. mcMMO.p.debug("Skipping " + upgrade.name() + " upgrade (unneeded)");
  1007. return;
  1008. }
  1009. Statement statement = null;
  1010. try {
  1011. statement = connection.createStatement();
  1012. switch (upgrade) {
  1013. case ADD_FISHING:
  1014. checkUpgradeAddFishing(statement);
  1015. break;
  1016. case ADD_BLAST_MINING_COOLDOWN:
  1017. checkUpgradeAddBlastMiningCooldown(statement);
  1018. break;
  1019. case ADD_SQL_INDEXES:
  1020. checkUpgradeAddSQLIndexes(statement);
  1021. break;
  1022. case ADD_MOB_HEALTHBARS:
  1023. checkUpgradeAddMobHealthbars(statement);
  1024. break;
  1025. case DROP_SQL_PARTY_NAMES:
  1026. checkUpgradeDropPartyNames(statement);
  1027. break;
  1028. case DROP_SPOUT:
  1029. checkUpgradeDropSpout(statement);
  1030. break;
  1031. case ADD_ALCHEMY:
  1032. checkUpgradeAddAlchemy(statement);
  1033. break;
  1034. case ADD_UUIDS:
  1035. checkUpgradeAddUUIDs(statement);
  1036. return;
  1037. default:
  1038. break;
  1039. }
  1040. mcMMO.getUpgradeManager().setUpgradeCompleted(upgrade);
  1041. }
  1042. catch (SQLException ex) {
  1043. printErrors(ex);
  1044. }
  1045. finally {
  1046. if (statement != null) {
  1047. try {
  1048. statement.close();
  1049. }
  1050. catch (SQLException e) {
  1051. // Ignore
  1052. }
  1053. }
  1054. }
  1055. }
  1056. private void writeMissingRows(Connection connection, int id) {
  1057. PreparedStatement statement = null;
  1058. try {
  1059. statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "experience (user_id) VALUES (?)");
  1060. statement.setInt(1, id);
  1061. statement.execute();
  1062. statement.close();
  1063. statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "skills (user_id) VALUES (?)");
  1064. statement.setInt(1, id);
  1065. statement.execute();
  1066. statement.close();
  1067. statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "cooldowns (user_id) VALUES (?)");
  1068. statement.setInt(1, id);
  1069. statement.execute();
  1070. statement.close();
  1071. statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "huds (user_id, mobhealthbar) VALUES (?, ?)");
  1072. statement.setInt(1, id);
  1073. statement.setString(2, Config.getInstance().getMobHealthbarDefault().name());
  1074. statement.execute();
  1075. statement.close();
  1076. }
  1077. catch (SQLException ex) {
  1078. printErrors(ex);
  1079. }
  1080. finally {
  1081. if (statement != null) {
  1082. try {
  1083. statement.close();
  1084. }
  1085. catch (SQLException e) {
  1086. // Ignore
  1087. }
  1088. }
  1089. }
  1090. }
  1091. private void processPurge(Collection<String> usernames) {
  1092. for (String user : usernames) {
  1093. Misc.profileCleanup(user);
  1094. }
  1095. }
  1096. private PlayerProfile loadFromResult(String playerName, ResultSet result) throws SQLException {
  1097. Map<SkillType, Integer> skills = new EnumMap<SkillType, Integer>(SkillType.class); // Skill & Level
  1098. Map<SkillType, Float> skillsXp = new EnumMap<SkillType, Float>(SkillType.class); // Skill & XP
  1099. Map<AbilityType, Integer> skillsDATS = new EnumMap<AbilityType, Integer>(AbilityType.class); // Ability & Cooldown
  1100. MobHealthbarType mobHealthbarType;
  1101. UUID uuid;
  1102. final int OFFSET_SKILLS = 0; // TODO update these numbers when the query
  1103. // changes (a new skill is added)
  1104. final int OFFSET_XP = 13;
  1105. final int OFFSET_DATS = 26;
  1106. final int OFFSET_OTHER = 38;
  1107. skills.put(SkillType.TAMING, result.getInt(OFFSET_SKILLS + 1));
  1108. skills.put(SkillType.MINING, result.getInt(OFFSET_SKILLS + 2));
  1109. skills.put(SkillType.REPAIR, result.getInt(OFFSET_SKILLS + 3));
  1110. skills.put(SkillType.WOODCUTTING, result.getInt(OFFSET_SKILLS + 4));
  1111. skills.put(SkillType.UNARMED, result.getInt(OFFSET_SKILLS + 5));
  1112. skills.put(SkillType.HERBALISM, result.getInt(OFFSET_SKILLS + 6));
  1113. skills.put(SkillType.EXCAVATION, result.getInt(OFFSET_SKILLS + 7));
  1114. skills.put(SkillType.ARCHERY, result.getInt(OFFSET_SKILLS + 8));
  1115. skills.put(SkillType.SWORDS, result.getInt(OFFSET_SKILLS + 9));
  1116. skills.put(SkillType.AXES, result.getInt(OFFSET_SKILLS + 10));
  1117. skills.put(SkillType.ACROBATICS, result.getInt(OFFSET_SKILLS + 11));
  1118. skills.put(SkillType.FISHING, result.getInt(OFFSET_SKILLS + 12));
  1119. skills.put(SkillType.ALCHEMY, result.getInt(OFFSET_SKILLS + 13));
  1120. skillsXp.put(SkillType.TAMING, result.getFloat(OFFSET_XP + 1));
  1121. skillsXp.put(SkillType.MINING, result.getFloat(OFFSET_XP + 2));
  1122. skillsXp.put(SkillType.REPAIR, result.getFloat(OFFSET_XP + 3));
  1123. skillsXp.put(SkillType.WOODCUTTING, result.getFloat(OFFSET_XP + 4));
  1124. skillsXp.put(SkillType.UNARMED, result.getFloat(OFFSET_XP + 5));
  1125. skillsXp.put(SkillType.HERBALISM, result.getFloat(OFFSET_XP + 6));
  1126. skillsXp.put(SkillType.EXCAVATION, result.getFloat(OFFSET_XP + 7));
  1127. skillsXp.put(SkillType.ARCHERY, result.getFloat(OFFSET_XP + 8));
  1128. skillsXp.put(SkillType.SWORDS, result.getFloat(OFFSET_XP + 9));
  1129. skillsXp.put(SkillType.AXES, result.getFloat(OFFSET_XP + 10));
  1130. skillsXp.put(SkillType.ACROBATICS, result.getFloat(OFFSET_XP + 11));
  1131. skillsXp.put(SkillType.FISHING, result.getFloat(OFFSET_XP + 12));
  1132. skillsXp.put(SkillType.ALCHEMY, result.getFloat(OFFSET_XP + 13));
  1133. // Taming - Unused - result.getInt(OFFSET_DATS + 1)
  1134. skillsDATS.put(AbilityType.SUPER_BREAKER, result.getInt(OFFSET_DATS + 2));
  1135. // Repair - Unused - result.getInt(OFFSET_DATS + 3)
  1136. skillsDATS.put(AbilityType.TREE_FELLER, result.getInt(OFFSET_DATS + 4));
  1137. skillsDATS.put(AbilityType.BERSERK, result.getInt(OFFSET_DATS + 5));
  1138. skillsDATS.put(AbilityType.GREEN_TERRA, result.getInt(OFFSET_DATS + 6));
  1139. skillsDATS.put(AbilityType.GIGA_DRILL_BREAKER, result.getInt(OFFSET_DATS + 7));
  1140. // Archery - Unused - result.getInt(OFFSET_DATS + 8)
  1141. skillsDATS.put(AbilityType.SERRATED_STRIKES, result.getInt(OFFSET_DATS + 9));
  1142. skillsDATS.put(AbilityType.SKULL_SPLITTER, result.getInt(OFFSET_DATS + 10));
  1143. // Acrobatics - Unused - result.getInt(OFFSET_DATS + 11)
  1144. skillsDATS.put(AbilityType.BLAST_MINING, result.getInt(OFFSET_DATS + 12));
  1145. try {
  1146. mobHealthbarType = MobHealthbarType.valueOf(result.getString(OFFSET_OTHER + 2));
  1147. }
  1148. catch (Exception e) {
  1149. mobHealthbarType = Config.getInstance().getMobHealthbarDefault();
  1150. }
  1151. try {
  1152. uuid = UUID.fromString(result.getString(OFFSET_OTHER + 3));
  1153. }
  1154. catch (Exception e) {
  1155. uuid = null;
  1156. }
  1157. return new PlayerProfile(playerName, uuid, skills, skillsXp, skillsDATS, mobHealthbarType);
  1158. }
  1159. private void printErrors(SQLException ex) {
  1160. StackTraceElement element = ex.getStackTrace()[0];
  1161. mcMMO.p.getLogger().severe("Location: " + element.getMethodName() + " " + element.getLineNumber());
  1162. mcMMO.p.getLogger().severe("SQLException: " + ex.getMessage());
  1163. mcMMO.p.getLogger().severe("SQLState: " + ex.getSQLState());
  1164. mcMMO.p.getLogger().severe("VendorError: " + ex.getErrorCode());
  1165. }
  1166. public DatabaseType getDatabaseType() {
  1167. return DatabaseType.SQL;
  1168. }
  1169. private void checkUpgradeAddAlchemy(final Statement statement) throws SQLException {
  1170. try {
  1171. statement.executeQuery("SELECT `alchemy` FROM `" + tablePrefix + "skills` LIMIT 1");
  1172. }
  1173. catch (SQLException ex) {
  1174. mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Alchemy...");
  1175. statement.executeUpdate("ALTER TABLE `" + tablePrefix + "skills` ADD `alchemy` int(10) NOT NULL DEFAULT '0'");
  1176. statement.executeUpdate("ALTER TABLE `" + tablePrefix + "experience` ADD `alchemy` int(10) NOT NULL DEFAULT '0'");
  1177. }
  1178. }
  1179. private void checkUpgradeAddBlastMiningCooldown(final Statement statement) throws SQLException {
  1180. try {
  1181. statement.executeQuery("SELECT `blast_mining` FROM `" + tablePrefix + "cooldowns` LIMIT 1");
  1182. }
  1183. catch (SQLException ex) {
  1184. mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Blast Mining...");
  1185. statement.executeUpdate("ALTER TABLE `" + tablePrefix + "cooldowns` ADD `blast_mining` int(32) NOT NULL DEFAULT '0'");
  1186. }
  1187. }
  1188. private void checkUpgradeAddFishing(final Statement statement) throws SQLException {
  1189. try {
  1190. statement.executeQuery("SELECT `fishing` FROM `" + tablePrefix + "skills` LIMIT 1");
  1191. }
  1192. catch (SQLException ex) {
  1193. mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Fishing...");
  1194. statement.executeUpdate("ALTER TABLE `" + tablePrefix + "skills` ADD `fishing` int(10) NOT NULL DEFAULT '0'");
  1195. statement.executeUpdate("ALTER TABLE `" + tablePrefix + "experience` ADD `fishing` int(10) NOT NULL DEFAULT '0'");
  1196. }
  1197. }
  1198. private void checkUpgradeAddMobHealthbars(final Statement statement) throws SQLException {
  1199. try {
  1200. statement.executeQuery("SELECT `mobhealthbar` FROM `" + tablePrefix + "huds` LIMIT 1");
  1201. }
  1202. catch (SQLException ex) {
  1203. mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for mob healthbars...");
  1204. statement.executeUpdate("ALTER TABLE `" + tablePrefix + "huds` ADD `mobhealthbar` varchar(50) NOT NULL DEFAULT '" + Config.getInstance().getMobHealthbarDefault() + "'");
  1205. }
  1206. }
  1207. private void checkUpgradeAddSQLIndexes(final Statement statement) throws SQLException {
  1208. ResultSet resultSet = null;
  1209. try {
  1210. resultSet = statement.executeQuery("SHOW INDEX FROM `" + tablePrefix + "skills` WHERE `Key_name` LIKE 'idx\\_%'");
  1211. resultSet.last();
  1212. if (resultSet.getRow() != SkillType.NON_CHILD_SKILLS.size()) {
  1213. mcMMO.p.getLogger().info("Indexing tables, this may take a while on larger databases");
  1214. for (SkillType skill : SkillType.NON_CHILD_SKILLS) {
  1215. String skill_name = skill.name().toLowerCase();
  1216. try {
  1217. statement.executeUpdate("ALTER TABLE `" + tablePrefix + "skills` ADD INDEX `idx_" + skill_name + "` (`" + skill_name + "`) USING BTREE");
  1218. }
  1219. catch (SQLException ex) {
  1220. // Ignore
  1221. }
  1222. }
  1223. }
  1224. }
  1225. catch (SQLException ex) {
  1226. printErrors(ex);
  1227. }
  1228. finally {
  1229. if (resultSet != null) {
  1230. try {
  1231. resultSet.close();
  1232. }
  1233. catch (SQLException e) {
  1234. // Ignore
  1235. }
  1236. }
  1237. }
  1238. }
  1239. private void checkUpgradeAddUUIDs(final Statement statement) {
  1240. List<String> names = new ArrayList<String>();
  1241. ResultSet resultSet = null;
  1242. try {
  1243. resultSet = statement.executeQuery("SELECT * FROM `" + tablePrefix + "users` LIMIT 1");
  1244. ResultSetMetaData rsmeta = resultSet.getMetaData();
  1245. boolean column_exists = false;
  1246. for (int i = 1; i <= rsmeta.getColumnCount(); i++) {
  1247. if (rsmeta.getColumnName(i).equalsIgnoreCase("uuid")) {
  1248. column_exists = true;
  1249. break;
  1250. }
  1251. }
  1252. if (!column_exists) {
  1253. mcMMO.p.getLogger().info("Adding UUIDs to mcMMO MySQL user table...");
  1254. statement.executeUpdate("ALTER TABLE `" + tablePrefix + "users` ADD `uuid` varchar(36) NULL DEFAULT NULL");
  1255. statement.executeUpdate("ALTER TABLE `" + tablePrefix + "users` ADD UNIQUE INDEX `uuid` (`uuid`) USING BTREE");
  1256. }
  1257. }
  1258. catch (SQLException ex) {
  1259. printErrors(ex);
  1260. }
  1261. finally {
  1262. if (resultSet != null) {
  1263. try {
  1264. resultSet.close();
  1265. }
  1266. catch (SQLException e) {
  1267. // Ignore
  1268. }
  1269. }
  1270. }
  1271. try {
  1272. resultSet = statement.executeQuery("SELECT `user` FROM `" + tablePrefix + "users` WHERE `uuid` IS NULL");
  1273. while (resultSet.next()) {
  1274. names.add(resultSet.getString("user"));
  1275. }
  1276. }
  1277. catch (SQLException ex) {
  1278. printErrors(ex);
  1279. }
  1280. finally {
  1281. if (resultSet != null) {
  1282. try {
  1283. resultSet.close();
  1284. }
  1285. catch (SQLException e) {
  1286. // Ignore
  1287. }
  1288. }
  1289. }
  1290. if (!names.isEmpty()) {
  1291. new UUIDUpdateAsyncTask(mcMMO.p, names).runTaskAsynchronously(mcMMO.p);
  1292. }
  1293. }
  1294. private void checkUpgradeDropPartyNames(final Statement statement) {
  1295. ResultSet resultSet = null;
  1296. try {
  1297. resultSet = statement.executeQuery("SELECT * FROM `" + tablePrefix + "users` LIMIT 1");
  1298. ResultSetMetaData rsmeta = resultSet.getMetaData();
  1299. boolean column_exists = false;
  1300. for (int i = 1; i <= rsmeta.getColumnCount(); i++) {
  1301. if (rsmeta.getColumnName(i).equalsIgnoreCase("party")) {
  1302. column_exists = true;
  1303. break;
  1304. }
  1305. }
  1306. if (column_exists) {
  1307. mcMMO.p.getLogger().info("Removing party name from users table...");
  1308. statement.executeUpdate("ALTER TABLE `" + tablePrefix + "users` DROP COLUMN `party`");
  1309. }
  1310. }
  1311. catch (SQLException ex) {
  1312. printErrors(ex);
  1313. }
  1314. finally {
  1315. if (resultSet != null) {
  1316. try {
  1317. resultSet.close();
  1318. }
  1319. catch (SQLException e) {
  1320. // Ignore
  1321. }
  1322. }
  1323. }
  1324. }
  1325. private void checkUpgradeDropSpout(final Statement statement) {
  1326. ResultSet resultSet = null;
  1327. try {
  1328. resultSet = statement.executeQuery("SELECT * FROM `" + tablePrefix + "huds` LIMIT 1");
  1329. ResultSetMetaData rsmeta = resultSet.getMetaData();
  1330. boolean column_exists = false;
  1331. for (int i = 1; i <= rsmeta.getColumnCount(); i++) {
  1332. if (rsmeta.getColumnName(i).equalsIgnoreCase("hudtype")) {
  1333. column_exists = true;
  1334. break;
  1335. }
  1336. }
  1337. if (column_exists) {
  1338. mcMMO.p.getLogger().info("Removing Spout HUD type from huds table...");
  1339. statement.executeUpdate("ALTER TABLE `" + tablePrefix + "huds` DROP COLUMN `hudtype`");
  1340. }
  1341. }
  1342. catch (SQLException ex) {
  1343. printErrors(ex);
  1344. }
  1345. finally {
  1346. if (resultSet != null) {
  1347. try {
  1348. resultSet.close();
  1349. }
  1350. catch (SQLException e) {
  1351. // Ignore
  1352. }
  1353. }
  1354. }
  1355. }
  1356. private int getUserID(final Connection connection, final String playerName) {
  1357. Integer id = cachedUserIDsByName.get(playerName.toLowerCase());
  1358. if (id != null) {
  1359. return id;
  1360. }
  1361. ResultSet resultSet = null;
  1362. PreparedStatement statement = null;
  1363. try {
  1364. statement = connection.prepareStatement("SELECT id, uuid FROM " + tablePrefix + "users WHERE user = ?");
  1365. statement.setString(1, playerName);
  1366. resultSet = statement.executeQuery();
  1367. if (resultSet.next()) {
  1368. id = resultSet.getInt("id");
  1369. cachedUserIDsByName.put(playerName.toLowerCase(), id);
  1370. try {
  1371. cachedUserIDs.put(UUID.fromString(resultSet.getString("uuid")), id);
  1372. }
  1373. catch (Exception e) {
  1374. }
  1375. return id;
  1376. }
  1377. }
  1378. catch (SQLException ex) {
  1379. printErrors(ex);
  1380. }
  1381. finally {
  1382. if (resultSet != null) {
  1383. try {
  1384. resultSet.close();
  1385. }
  1386. catch (SQLException e) {
  1387. // Ignore
  1388. }
  1389. }
  1390. if (statement != null) {
  1391. try {
  1392. statement.close();
  1393. }
  1394. catch (SQLException e) {
  1395. // Ignore
  1396. }
  1397. }
  1398. }
  1399. return -1;
  1400. }
  1401. private int getUserID(final Connection connection, final UUID uuid) {
  1402. if (cachedUserIDs.containsKey(uuid)) {
  1403. return cachedUserIDs.get(uuid);
  1404. }
  1405. ResultSet resultSet = null;
  1406. PreparedStatement statement = null;
  1407. try {
  1408. statement = connection.prepareStatement("SELECT id, user FROM " + tablePrefix + "users WHERE uuid = ?");
  1409. statement.setString(1, uuid.toString());
  1410. resultSet = statement.executeQuery();
  1411. if (resultSet.next()) {
  1412. int id = resultSet.getInt("id");
  1413. cachedUserIDs.put(uuid, id);
  1414. cachedUserIDsByName.put(resultSet.getString("user").toLowerCase(), id);
  1415. return id;
  1416. }
  1417. }
  1418. catch (SQLException ex) {
  1419. printErrors(ex);
  1420. }
  1421. finally {
  1422. if (resultSet != null) {
  1423. try {
  1424. resultSet.close();
  1425. }
  1426. catch (SQLException e) {
  1427. // Ignore
  1428. }
  1429. }
  1430. if (statement != null) {
  1431. try {
  1432. statement.close();
  1433. }
  1434. catch (SQLException e) {
  1435. // Ignore
  1436. }
  1437. }
  1438. }
  1439. return -1;
  1440. }
  1441. @Override
  1442. public void onDisable() {
  1443. connectionPool.release();
  1444. }
  1445. }