SQLDatabaseManager.java 61 KB

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