SQLDatabaseManager.java 61 KB

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