diff --git a/src/main/java/org/maxgamer/quickshop/QuickShop.java b/src/main/java/org/maxgamer/quickshop/QuickShop.java index 048ce7e18..2c1fb268b 100644 --- a/src/main/java/org/maxgamer/quickshop/QuickShop.java +++ b/src/main/java/org/maxgamer/quickshop/QuickShop.java @@ -107,6 +107,11 @@ public class QuickShop extends JavaPlugin { private BootError bootError; @Getter private CommandManager commandManager; + /** + * The database for storing all our data for persistence + */ + @Getter + private Database database; /** * Contains all SQL tasks */ @@ -559,23 +564,6 @@ public class QuickShop extends JavaPlugin { // ignore, we didn't care that } - Util.debugLog("Cleaning up resources and unloading all shops..."); - /* Remove all display items, and any dupes we can find */ - if (shopManager != null) { - shopManager.clear(); - } - - Util.debugLog("Cleaning up database queues..."); - if (this.getDatabaseManager() != null) { - this.getDatabaseManager().unInit(); - } - - // this.reloadConfig(); - Util.debugLog("Calling integrations..."); - this.integrationHelper.callIntegrationsUnload(IntegrateStage.onUnloadAfter); - this.compatibilityTool.clear(); - new HashSet<>(this.integrationHelper.getIntegrations()).forEach(integratedPlugin -> this.integrationHelper.unregister(integratedPlugin)); - Util.debugLog("Unregistering tasks..."); // if (itemWatcherTask != null) // itemWatcherTask.cancel(); @@ -586,6 +574,25 @@ public class QuickShop extends JavaPlugin { if (this.updateWatcher != null) { this.updateWatcher.uninit(); } + Util.debugLog("Cleaning up resources and unloading all shops..."); + /* Remove all display items, and any dupes we can find */ + if (shopManager != null) { + shopManager.clear(); + } + + Util.debugLog("Cleaning up database queues..."); + if (this.getDatabaseManager() != null) { + this.getDatabaseManager().unInit(); + } + /* Close Database */ + if (database != null) { + this.database.close(); + } + // this.reloadConfig(); + Util.debugLog("Calling integrations..."); + this.integrationHelper.callIntegrationsUnload(IntegrateStage.onUnloadAfter); + this.compatibilityTool.clear(); + new HashSet<>(this.integrationHelper.getIntegrations()).forEach(integratedPlugin -> this.integrationHelper.unregister(integratedPlugin)); Util.debugLog("Cleanup tasks..."); try { @@ -852,7 +859,7 @@ public class QuickShop extends JavaPlugin { private boolean setupDatabase() { try { ConfigurationSection dbCfg = getConfig().getConfigurationSection("database"); - AbstractDatabaseCore dbCore; + DatabaseCore dbCore; if (Objects.requireNonNull(dbCfg).getBoolean("mysql")) { // MySQL database - Required database be created first. dbPrefix = dbCfg.getString("prefix"); @@ -870,10 +877,11 @@ public class QuickShop extends JavaPlugin { // SQLite database - Doing this handles file creation dbCore = new SQLiteCore(this, new File(this.getDataFolder(), "shops.db")); } - this.databaseManager = new DatabaseManager(this, ServiceInjector.getDatabaseCore(dbCore)); + this.database = new Database(ServiceInjector.getDatabaseCore(dbCore)); + this.databaseManager = new DatabaseManager(this, this.database); // Make the database up to date - this.databaseHelper = new DatabaseHelper(this, this.databaseManager); - } catch (DatabaseManager.ConnectionException e) { + this.databaseHelper = new DatabaseHelper(this, this.database, this.databaseManager); + } catch (Database.ConnectionException e) { e.printStackTrace(); if (setupDBonEnableding) { bootError = BuiltInSolution.databaseError(); @@ -937,7 +945,7 @@ public class QuickShop extends JavaPlugin { String useEnhanceShopProtect = String.valueOf(getConfig().getBoolean("shop.enchance-shop-protect")); String useOngoingFee = String.valueOf(getConfig().getBoolean("shop.ongoing-fee.enable")); String disableDebugLogger = String.valueOf(getConfig().getBoolean("disable-debuglogger")); - String databaseType = this.getDatabaseManager().getDatabase().getName(); + String databaseType = this.getDatabase().getCore().getName(); String displayType = DisplayItem.getNowUsing().name(); String itemMatcherType = this.getItemMatcher().getName(); String useStackItem = String.valueOf(this.isAllowStack()); diff --git a/src/main/java/org/maxgamer/quickshop/ServiceInjector.java b/src/main/java/org/maxgamer/quickshop/ServiceInjector.java index 8e934cdf8..1c4326f7a 100644 --- a/src/main/java/org/maxgamer/quickshop/ServiceInjector.java +++ b/src/main/java/org/maxgamer/quickshop/ServiceInjector.java @@ -1,6 +1,5 @@ /* * This file is a part of project QuickShop, the name is ServiceInjector.java - * Copyright (C) Ghost_chu * Copyright (C) PotatoCraft Studio and contributors * * This program is free software: you can redistribute it and/or modify it @@ -24,7 +23,7 @@ import org.bukkit.Bukkit; import org.bukkit.plugin.RegisteredServiceProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.maxgamer.quickshop.database.AbstractDatabaseCore; +import org.maxgamer.quickshop.database.DatabaseCore; import org.maxgamer.quickshop.economy.EconomyCore; import org.maxgamer.quickshop.util.language.game.GameLanguage; import org.maxgamer.quickshop.util.matcher.item.ItemMatcher; @@ -60,9 +59,9 @@ public class ServiceInjector { } } - public static @NotNull AbstractDatabaseCore getDatabaseCore(@NotNull AbstractDatabaseCore def) { - @Nullable RegisteredServiceProvider registeredServiceProvider = - Bukkit.getServicesManager().getRegistration(AbstractDatabaseCore.class); + public static @NotNull DatabaseCore getDatabaseCore(@NotNull DatabaseCore def) { + @Nullable RegisteredServiceProvider registeredServiceProvider = + Bukkit.getServicesManager().getRegistration(DatabaseCore.class); if (registeredServiceProvider == null) { return def; } else { diff --git a/src/main/java/org/maxgamer/quickshop/command/subcommand/SubCommand_Convert.java b/src/main/java/org/maxgamer/quickshop/command/subcommand/SubCommand_Convert.java index f3c4de1a0..06fbe16f2 100644 --- a/src/main/java/org/maxgamer/quickshop/command/subcommand/SubCommand_Convert.java +++ b/src/main/java/org/maxgamer/quickshop/command/subcommand/SubCommand_Convert.java @@ -1,6 +1,5 @@ /* * This file is a part of project QuickShop, the name is SubCommand_Convert.java - * Copyright (C) Ghost_chu * Copyright (C) PotatoCraft Studio and contributors * * This program is free software: you can redistribute it and/or modify it @@ -65,7 +64,7 @@ public class SubCommand_Convert implements CommandProcesser { return; } if (cmdArg[0].equalsIgnoreCase("mysql")) { - if (plugin.getDatabaseManager().getDatabase() instanceof MySQLCore) { + if (plugin.getDatabase().getCore() instanceof MySQLCore) { sender.sendMessage(ChatColor.RED + "Please switch to SQLite before converting to MySQL."); return; } @@ -76,22 +75,24 @@ public class SubCommand_Convert implements CommandProcesser { String port = dbCfg.getString("port"); String databaseStr = dbCfg.getString("database"); boolean useSSL = dbCfg.getBoolean("usessl"); - AbstractDatabaseCore dbCore = new MySQLCore(plugin, Objects.requireNonNull(host, "MySQL host can't be null"), Objects.requireNonNull(user, "MySQL username can't be null"), Objects.requireNonNull(pass, "MySQL password can't be null"), Objects.requireNonNull(databaseStr, "MySQL database name can't be null"), Objects.requireNonNull(port, "MySQL port can't be null"), useSSL); - DatabaseManager databaseManager = new DatabaseManager(QuickShop.getInstance(), dbCore); + DatabaseCore dbCore = new MySQLCore(plugin, Objects.requireNonNull(host, "MySQL host can't be null"), Objects.requireNonNull(user, "MySQL username can't be null"), Objects.requireNonNull(pass, "MySQL password can't be null"), Objects.requireNonNull(databaseStr, "MySQL database name can't be null"), Objects.requireNonNull(port, "MySQL port can't be null"), useSSL); + Database database = new Database(dbCore); + DatabaseManager databaseManager = new DatabaseManager(QuickShop.getInstance(), database); sender.sendMessage(ChatColor.GREEN + "Converting..."); - this.transferShops(new DatabaseHelper(plugin, databaseManager), sender); + this.transferShops(new DatabaseHelper(plugin, database, databaseManager), sender); databaseManager.unInit(); sender.sendMessage(ChatColor.GREEN + "All done, please edit config.yml to mysql to apply changes."); } else if (cmdArg[0].equalsIgnoreCase("sqlite")) { - if (plugin.getDatabaseManager().getDatabase() instanceof SQLiteCore) { + if (plugin.getDatabase().getCore() instanceof SQLiteCore) { sender.sendMessage(ChatColor.GREEN + "Please switch to MySQL before converting to SQLite."); return; } - AbstractDatabaseCore core = new SQLiteCore(plugin, new File(plugin.getDataFolder(), "shops.db")); - DatabaseManager databaseManager = new DatabaseManager(QuickShop.getInstance(), core); + DatabaseCore core = new SQLiteCore(plugin, new File(plugin.getDataFolder(), "shops.db")); + Database database = new Database(core); + DatabaseManager databaseManager = new DatabaseManager(QuickShop.getInstance(), database); sender.sendMessage(ChatColor.GREEN + "Converting..."); - this.transferShops(new DatabaseHelper(plugin, databaseManager), sender); + this.transferShops(new DatabaseHelper(plugin, database, databaseManager), sender); databaseManager.unInit(); sender.sendMessage(ChatColor.GREEN + "All done, please edit config.yml to sqlite to apply changes."); diff --git a/src/main/java/org/maxgamer/quickshop/database/BufferStatement.java b/src/main/java/org/maxgamer/quickshop/database/BufferStatement.java new file mode 100644 index 000000000..0a1118b91 --- /dev/null +++ b/src/main/java/org/maxgamer/quickshop/database/BufferStatement.java @@ -0,0 +1,76 @@ +/* + * This file is a part of project QuickShop, the name is BufferStatement.java + * Copyright (C) PotatoCraft Studio and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + * + */ + +package org.maxgamer.quickshop.database; + +import org.jetbrains.annotations.NotNull; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Arrays; + +public class BufferStatement { + + @NotNull + private final String query; + + @NotNull + private final Object[] values; + + /** + * Represents a PreparedStatement in a state before preparing it (E.g. No file I/O Required) + * + * @param query The query to execute. E.g. INSERT INTO accounts (user, passwd) VALUES (?, ?) + * @param values The values to replace ? with in query. These are in order. + */ + public BufferStatement(@NotNull String query, @NotNull Object... values) { + this.query = query; + this.values = values; + } + + /** + * @return A string representation of this statement. Returns "Query: " + query + ", values: " + + * Arrays.toString(values). + */ + @Override + public String toString() { + return "Query: " + query + ", values: " + Arrays.toString(values); + } + + /** + * Returns a prepared statement using the given connection. Will try to return an empty statement + * if something went wrong. If that fails, returns null. + * + *

This method escapes everything automatically. + * + * @param con The connection to prepare this on using con.prepareStatement(..) + * @return The prepared statement, ready for execution. + * @throws SQLException Throw exception when failed to execute something in SQL + */ + PreparedStatement prepareStatement(@NotNull Connection con) throws SQLException { + PreparedStatement ps; + ps = con.prepareStatement(query); + for (int i = 1; i <= values.length; i++) { + ps.setObject(i, values[i - 1]); + } + return ps; + } + +} diff --git a/src/main/java/org/maxgamer/quickshop/database/Database.java b/src/main/java/org/maxgamer/quickshop/database/Database.java new file mode 100644 index 000000000..cc93096df --- /dev/null +++ b/src/main/java/org/maxgamer/quickshop/database/Database.java @@ -0,0 +1,153 @@ +/* + * This file is a part of project QuickShop, the name is Database.java + * Copyright (C) PotatoCraft Studio and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + * + */ + +package org.maxgamer.quickshop.database; + +import org.jetbrains.annotations.NotNull; + +import java.sql.*; + +public class Database { + + @NotNull + private final DatabaseCore core; + + /** + * Creates a new database and validates its connection. + * + *

If the connection is invalid, this will throw a ConnectionException. + * + * @param core The core for the database, either MySQL or SQLite. + * @throws ConnectionException If the connection was invalid + */ + public Database(@NotNull DatabaseCore core) throws ConnectionException { + try { + try { + if (!core.getConnection().isValid(30)) { + throw new ConnectionException("The database does not appear to be valid!"); + } + } catch (AbstractMethodError ignored) { + // You don't need to validate this core. + } + } catch (SQLException e) { + throw new ConnectionException(e.getMessage()); + } + this.core = core; + } + + /** + * Closes the database + */ + public void close() { + this.core.close(); + } + + /** + * Executes the given statement either immediately, or soon. + * + * @param query The query + * @param objs The string values for each ? in the given query. + */ + public void execute(@NotNull String query, @NotNull Object... objs) { + BufferStatement bs = new BufferStatement(query, objs); + core.queue(bs); + } + + /** + * Returns true if the given table has the given column + * + * @param table The table + * @param column The column + * @return True if the given table has the given column + * @throws SQLException If the database isn't connected + */ + public boolean hasColumn(@NotNull String table, @NotNull String column) throws SQLException { + if (!hasTable(table)) { + return false; + } + String query = "SELECT * FROM " + table + " LIMIT 1"; + try { + PreparedStatement ps = this.getConnection().prepareStatement(query); + ResultSet rs = ps.executeQuery(); + ResultSetMetaData metaData = rs.getMetaData(); + for (int i = 1; i <= metaData.getColumnCount(); i++) { + if (metaData.getColumnLabel(i).equals(column)) { + return true; + } + } + rs.close(); + } catch (SQLException e) { + return false; + } + return false; // Uh, wtf. + } + + /** + * Returns true if the table exists + * + * @param table The table to check for + * @return True if the table is found + * @throws SQLException Throw exception when failed execute somethins on SQL + */ + @SuppressWarnings("BooleanMethodIsAlwaysInverted") + boolean hasTable(@NotNull String table) throws SQLException { + ResultSet rs = getConnection().getMetaData().getTables(null, null, "%", null); + while (rs.next()) { + if (table.equalsIgnoreCase(rs.getString("TABLE_NAME"))) { + rs.close(); + return true; + } + } + rs.close(); + return false; + } + + /** + * Fetches the connection to this database for querying. Try to avoid doing this in the main + * thread. + * + * @return Fetches the connection to this database for querying. + */ + public Connection getConnection() { + return core.getConnection(); + } + + /** + * Returns the database core object, that this database runs on. + * + * @return the database core object, that this database runs on. + */ + @NotNull + public DatabaseCore getCore() { + return core; + } + + /** + * Represents a connection error, generally when the server can't connect to MySQL or something. + */ + public static final class ConnectionException extends Exception { + private static final long serialVersionUID = 8348749992936357317L; + + private ConnectionException(String msg) { + super(msg); + } + + } + +} diff --git a/src/main/java/org/maxgamer/quickshop/database/DatabaseConnection.java b/src/main/java/org/maxgamer/quickshop/database/DatabaseConnection.java deleted file mode 100644 index eae08883f..000000000 --- a/src/main/java/org/maxgamer/quickshop/database/DatabaseConnection.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.maxgamer.quickshop.database; - -import org.maxgamer.quickshop.QuickShop; - -import java.sql.Connection; -import java.sql.SQLException; - -public class DatabaseConnection implements AutoCloseable { - - private final Connection connection; - private volatile boolean using; - - public DatabaseConnection(Connection connection) { - this.connection = connection; - } - - public boolean isValid() { - try { - return connection.isValid(30000); - } catch (SQLException ignored) { - return false; - } catch (AbstractMethodError ignored) { - //driver not supported - return true; - } - } - - public void close() { - try { - Connection connection = get(); - if (!connection.isClosed()) { - if (!connection.getAutoCommit()) { - connection.commit(); - } - connection.close(); - } - } catch (SQLException ignored) { - } finally { - release(); - } - } - - public Connection get() { - if (!using) { - using = true; - return connection; - } else { - throw new ConnectionIsUsingException(); - } - } - - public void release() { - if (using) { - using = false; - QuickShop.getInstance().getDatabaseManager().getDatabase().signalForNewConnection(); - } - } - - public boolean isUsing() { - return using; - } - - public static class ConnectionIsUsingException extends IllegalStateException { - } -} diff --git a/src/main/java/org/maxgamer/quickshop/database/AbstractDatabaseCore.java b/src/main/java/org/maxgamer/quickshop/database/DatabaseCore.java similarity index 53% rename from src/main/java/org/maxgamer/quickshop/database/AbstractDatabaseCore.java rename to src/main/java/org/maxgamer/quickshop/database/DatabaseCore.java index 7b046e51d..75f949751 100644 --- a/src/main/java/org/maxgamer/quickshop/database/AbstractDatabaseCore.java +++ b/src/main/java/org/maxgamer/quickshop/database/DatabaseCore.java @@ -1,6 +1,5 @@ /* * This file is a part of project QuickShop, the name is DatabaseCore.java - * Copyright (C) Ghost_chu * Copyright (C) PotatoCraft Studio and contributors * * This program is free software: you can redistribute it and/or modify it @@ -23,34 +22,20 @@ package org.maxgamer.quickshop.database; import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.ReentrantLock; +import java.sql.Connection; -public abstract class AbstractDatabaseCore { - private final ReentrantLock lock = new ReentrantLock(true); - private final Condition conditionLock = lock.newCondition(); +public interface DatabaseCore { - void waitForConnection() { - try { - lock.lock(); - conditionLock.await(); - lock.unlock(); - } catch (InterruptedException ignored) { - } - } + void close(); - void signalForNewConnection() { - lock.lock(); - conditionLock.signal(); - lock.unlock(); - } + void flush(); - abstract void close(); + void queue(BufferStatement bs); - abstract DatabaseConnection getConnection(); + Connection getConnection(); - abstract public @NotNull String getName(); + @NotNull String getName(); - abstract public @NotNull Plugin getPlugin(); + @NotNull Plugin getPlugin(); } diff --git a/src/main/java/org/maxgamer/quickshop/database/DatabaseHelper.java b/src/main/java/org/maxgamer/quickshop/database/DatabaseHelper.java index a082e6430..46a962ae4 100644 --- a/src/main/java/org/maxgamer/quickshop/database/DatabaseHelper.java +++ b/src/main/java/org/maxgamer/quickshop/database/DatabaseHelper.java @@ -1,6 +1,5 @@ /* * This file is a part of project QuickShop, the name is DatabaseHelper.java - * Copyright (C) Ghost_chu * Copyright (C) PotatoCraft Studio and contributors * * This program is free software: you can redistribute it and/or modify it @@ -41,6 +40,8 @@ import java.util.function.Consumer; */ public class DatabaseHelper { + @NotNull + private final Database db; @NotNull private final DatabaseManager manager; @@ -48,13 +49,14 @@ public class DatabaseHelper { @NotNull private final QuickShop plugin; - public DatabaseHelper(@NotNull QuickShop plugin, @NotNull DatabaseManager manager) throws SQLException { + public DatabaseHelper(@NotNull QuickShop plugin, @NotNull Database db, @NotNull DatabaseManager manager) throws SQLException { + this.db = db; this.plugin = plugin; this.manager = manager; - if (!manager.hasTable(plugin.getDbPrefix() + "shops")) { + if (!db.hasTable(plugin.getDbPrefix() + "shops")) { createShopsTable(); } - if (!manager.hasTable(plugin.getDbPrefix() + "messages")) { + if (!db.hasTable(plugin.getDbPrefix() + "messages")) { createMessagesTable(); } checkColumns(); @@ -62,78 +64,93 @@ public class DatabaseHelper { /** * Creates the database table 'shops'. + * + * @throws SQLException If the connection is invalid. */ - private void createShopsTable() { - String sqlString = "CREATE TABLE " + plugin.getDbPrefix() + "shops (owner VARCHAR(255) NOT NULL, price double(32, 2) NOT NULL, itemConfig TEXT CHARSET utf8 NOT NULL, x INTEGER(32) NOT NULL, y INTEGER(32) NOT NULL, z INTEGER(32) NOT NULL, world VARCHAR(32) NOT NULL, unlimited boolean, type boolean, PRIMARY KEY (x, y, z, world) );"; - manager.runInstantTask(new DatabaseTask(sqlString)); + private void createShopsTable() throws SQLException { + Statement st = db.getConnection().createStatement(); + String createTable = "CREATE TABLE " + plugin + .getDbPrefix() + "shops (owner VARCHAR(255) NOT NULL, price double(32, 2) NOT NULL, itemConfig TEXT CHARSET utf8 NOT NULL, x INTEGER(32) NOT NULL, y INTEGER(32) NOT NULL, z INTEGER(32) NOT NULL, world VARCHAR(32) NOT NULL, unlimited boolean, type boolean, PRIMARY KEY (x, y, z, world) );"; + st.execute(createTable); } /** * Creates the database table 'messages' + * + * @return Create failed or successed. + * @throws SQLException If the connection is invalid */ - private void createMessagesTable() { + private boolean createMessagesTable() throws SQLException { + Statement st = db.getConnection().createStatement(); String createTable = "CREATE TABLE " + plugin.getDbPrefix() + "messages (owner VARCHAR(255) NOT NULL, message TEXT(25) NOT NULL, time BIGINT(32) NOT NULL );"; - if (manager.getDatabase() instanceof MySQLCore) { + if (plugin.getDatabase().getCore() instanceof MySQLCore) { createTable = "CREATE TABLE " + plugin.getDbPrefix() + "messages (owner VARCHAR(255) NOT NULL, message TEXT(25) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL , time BIGINT(32) NOT NULL );"; } - manager.runInstantTask(new DatabaseTask(createTable)); + return st.execute(createTable); } /** * Verifies that all required columns exist. */ private void checkColumns() { - DatabaseTask.Task checkTask = new DatabaseTask.Task() { - @Override - public void edit(PreparedStatement ps) { - - } - - @Override - public void onFailed(SQLException e) { - - } - }; - // V3.4.2 - manager.runInstantTask(new DatabaseTask("ALTER TABLE " + plugin - .getDbPrefix() + "shops MODIFY COLUMN price double(32,2) NOT NULL AFTER owner", checkTask)); - // V3.4.3 - manager.runInstantTask(new DatabaseTask("ALTER TABLE " + plugin - .getDbPrefix() + "messages MODIFY COLUMN time BIGINT(32) NOT NULL AFTER message", checkTask)); - //Extra column + PreparedStatement ps = null; try { - if (!manager.hasColumn(plugin.getDbPrefix() + "shops", "extra")) { - String sqlString; - // Reremake - DataStorage @TODO needs testing - if (manager.getDatabase() instanceof MySQLCore) { - sqlString = "ALTER TABLE " + plugin - .getDbPrefix() + "shops ADD extra LONGTEXT"; - } else { - sqlString = "ALTER TABLE " + plugin - .getDbPrefix() + "shops ADD COLUMN extra TEXT"; - } - manager.runInstantTask(new DatabaseTask(sqlString, new DatabaseTask.Task() { - @Override - public void edit(PreparedStatement ps) throws SQLException { - } + // V3.4.2 - @Override - public void onFailed(SQLException e) { - Util.debugLog("Error to create EXTRA column: " + e.getMessage()); - } - })); - Util.debugLog("Setting up the column EXTRA..."); - } + ps = db.getConnection().prepareStatement("ALTER TABLE " + plugin + .getDbPrefix() + "shops MODIFY COLUMN price double(32,2) NOT NULL AFTER owner"); + ps.execute(); + ps.close(); } catch (SQLException e) { - Util.debugLog("Error to create EXTRA column: " + e.getMessage()); //ignore } - if (manager.getDatabase() instanceof MySQLCore) { - manager.runInstantTask(new DatabaseTask("ALTER TABLE " + plugin - .getDbPrefix() + "messages MODIFY COLUMN message text CHARACTER SET utf8mb4 NOT NULL AFTER owner", checkTask)); + try { + // V3.4.3 + ps = db.getConnection().prepareStatement("ALTER TABLE " + plugin + .getDbPrefix() + "messages MODIFY COLUMN time BIGINT(32) NOT NULL AFTER message"); + ps.execute(); + ps.close(); + } catch (SQLException e) { + //ignore + } + try { + if (!db.hasColumn(plugin + .getDbPrefix() + "shops", "extra")) { + // Reremake - DataStorage @TODO needs testing + if (db.getCore() instanceof MySQLCore) { + ps = db.getConnection().prepareStatement("ALTER TABLE " + plugin + .getDbPrefix() + "shops ADD extra LONGTEXT"); + } else { + ps = db.getConnection().prepareStatement("ALTER TABLE " + plugin + .getDbPrefix() + "shops ADD COLUMN extra TEXT"); + } + Util.debugLog("Setting up the column EXTRA..."); + ps.execute(); + ps.close(); + } + } catch (SQLException e) { + //ignore + Util.debugLog("Error to create EXTRA column: " + e.getMessage()); + } + if (db.getCore() instanceof MySQLCore) { + try { + ps = db.getConnection().prepareStatement("ALTER TABLE " + plugin + .getDbPrefix() + "messages MODIFY COLUMN message text CHARACTER SET utf8mb4 NOT NULL AFTER owner"); + ps.execute(); + ps.close(); + } catch (SQLException e) { + //ignore + } + } + + if (ps != null) { + try { + ps.close(); + } catch (SQLException ignored) { + } } } @@ -143,18 +160,18 @@ public class DatabaseHelper { // .getDbPrefix() + "messages WHERE time < ?", weekAgo); String sqlString = "DELETE FROM " + plugin .getDbPrefix() + "messages WHERE time < ?"; - manager.addDelayTask(new DatabaseTask(sqlString, ps -> ps.setLong(1, weekAgo))); + manager.add(new DatabaseTask(sqlString, ps -> ps.setLong(1, weekAgo))); } public void cleanMessageForPlayer(@NotNull UUID player) { String sqlString = "DELETE FROM " + plugin.getDbPrefix() + "messages WHERE owner = ?"; - manager.addDelayTask(new DatabaseTask(sqlString, (ps) -> ps.setString(1, player.toString()))); + manager.add(new DatabaseTask(sqlString, (ps) -> ps.setString(1, player.toString()))); } public void createShop(@NotNull Shop shop, @Nullable Runnable onSuccess, @Nullable Consumer onFailed) { removeShop(shop); //First purge old exist shop before create new shop. String sqlString = "INSERT INTO " + plugin.getDbPrefix() + "shops (owner, price, itemConfig, x, y, z, world, unlimited, type, extra) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - manager.addDelayTask(new DatabaseTask(sqlString, new DatabaseTask.Task() { + manager.add(new DatabaseTask(sqlString, new DatabaseTask.Task() { @Override public void edit(PreparedStatement ps) throws SQLException { Location location = shop.getLocation(); @@ -211,8 +228,8 @@ public class DatabaseHelper { String sqlString = "DELETE FROM " + plugin.getDbPrefix() + "shops WHERE x = ? AND y = ? AND z = ? AND world = ?" - + (manager.getDatabase() instanceof MySQLCore ? " LIMIT 1" : ""); - manager.addDelayTask(new DatabaseTask(sqlString, (ps) -> { + + (db.getCore() instanceof MySQLCore ? " LIMIT 1" : ""); + manager.add(new DatabaseTask(sqlString, (ps) -> { Location location = shop.getLocation(); ps.setInt(1, location.getBlockX()); ps.setInt(2, location.getBlockY()); @@ -222,26 +239,22 @@ public class DatabaseHelper { } - public WarpedResultSet selectAllMessages() throws SQLException { - return selectTable("messages"); + public ResultSet selectAllMessages() throws SQLException { + Statement st = db.getConnection().createStatement(); + String selectAllShops = "SELECT * FROM " + plugin.getDbPrefix() + "messages"; + return st.executeQuery(selectAllShops); } - private WarpedResultSet selectTable(String table) throws SQLException { - DatabaseConnection databaseConnection = manager.getDatabase().getConnection(); - Statement st = databaseConnection.get().createStatement(); - String selectAllShops = "SELECT * FROM " + plugin.getDbPrefix() + table; - ResultSet resultSet = st.executeQuery(selectAllShops); - return new WarpedResultSet(resultSet, databaseConnection); - } - - public WarpedResultSet selectAllShops() throws SQLException { - return selectTable("shops"); + public ResultSet selectAllShops() throws SQLException { + Statement st = db.getConnection().createStatement(); + String selectAllShops = "SELECT * FROM " + plugin.getDbPrefix() + "shops"; + return st.executeQuery(selectAllShops); } public void sendMessage(@NotNull UUID player, @NotNull String message, long time) { String sqlString = "INSERT INTO " + plugin.getDbPrefix() + "messages (owner, message, time) VALUES (?, ?, ?)"; - manager.addDelayTask( + manager.add( new DatabaseTask( sqlString, (ps) -> { @@ -253,9 +266,9 @@ public class DatabaseHelper { public void updateOwner2UUID(@NotNull String ownerUUID, int x, int y, int z, @NotNull String worldName) { String sqlString = "UPDATE " + plugin - .getDbPrefix() + "shops SET owner = ? WHERE x = ? AND y = ? AND z = ? AND world = ?" + ( - manager.getDatabase() instanceof MySQLCore ? " LIMIT 1" : ""); - manager.addDelayTask( + .getDbPrefix() + "shops SET owner = ? WHERE x = ? AND y = ? AND z = ? AND world = ?" + (db + .getCore() instanceof MySQLCore ? " LIMIT 1" : ""); + manager.add( //plugin.getDB().getConnection().createStatement() // .executeUpdate("UPDATE " + plugin.getDbPrefix() + "shops SET owner = \"" + ownerUUID.toString() // + "\" WHERE x = " + x + " AND y = " + y + " AND z = " + z @@ -273,7 +286,7 @@ public class DatabaseHelper { double price, int x, int y, int z, String world, String extra) { String sqlString = "UPDATE " + plugin .getDbPrefix() + "shops SET owner = ?, itemConfig = ?, unlimited = ?, type = ?, price = ?, extra = ? WHERE x = ? AND y = ? and z = ? and world = ?"; - manager.addDelayTask(new DatabaseTask(sqlString, ps -> { + manager.add(new DatabaseTask(sqlString, ps -> { ps.setString(1, owner); ps.setString(2, Util.serialize(item)); ps.setInt(3, unlimited); diff --git a/src/main/java/org/maxgamer/quickshop/database/DatabaseManager.java b/src/main/java/org/maxgamer/quickshop/database/DatabaseManager.java index f572d10c3..f094794fb 100644 --- a/src/main/java/org/maxgamer/quickshop/database/DatabaseManager.java +++ b/src/main/java/org/maxgamer/quickshop/database/DatabaseManager.java @@ -1,6 +1,5 @@ /* * This file is a part of project QuickShop, the name is DatabaseManager.java - * Copyright (C) Ghost_chu * Copyright (C) PotatoCraft Studio and contributors * * This program is free software: you can redistribute it and/or modify it @@ -20,7 +19,6 @@ package org.maxgamer.quickshop.database; -import lombok.Getter; import org.bukkit.plugin.IllegalPluginAccessException; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; @@ -31,7 +29,8 @@ import org.maxgamer.quickshop.util.Timer; import org.maxgamer.quickshop.util.Util; import org.maxgamer.quickshop.util.WarningSender; -import java.sql.*; +import java.sql.Connection; +import java.sql.SQLException; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; import java.util.logging.Level; @@ -44,8 +43,7 @@ public class DatabaseManager { private final Queue sqlQueue = new LinkedBlockingQueue<>(); @NotNull - @Getter - private final AbstractDatabaseCore database; + private final Database database; @NotNull private final QuickShop plugin; @@ -60,150 +58,84 @@ public class DatabaseManager { * Queued database manager. Use queue to solve run SQL make server lagg issue. * * @param plugin plugin main class - * @param dbCore database core + * @param db database */ - public DatabaseManager(@NotNull QuickShop plugin, @NotNull AbstractDatabaseCore dbCore) throws ConnectionException { + public DatabaseManager(@NotNull QuickShop plugin, @NotNull Database db) { this.plugin = plugin; this.warningSender = new WarningSender(plugin, 600000); - if (!dbCore.getConnection().isValid()) { - throw new DatabaseManager.ConnectionException("The database does not appear to be valid!"); - } - this.database = dbCore; + this.database = db; this.useQueue = plugin.getConfig().getBoolean("database.queue"); - if (useQueue) { - try { - task = - new BukkitRunnable() { - @Override - public void run() { - plugin.getDatabaseManager().runTask(); - } - }.runTaskTimerAsynchronously(plugin, 1, plugin.getConfig().getLong("database.queue-commit-interval") * 20); - } catch (IllegalPluginAccessException e) { - Util.debugLog("Plugin is disabled but trying create database task, move to Main Thread..."); - plugin.getDatabaseManager().runTask(); - } + if (!useQueue) { + return; } - } - - /** - * Returns true if the table exists - * - * @param table The table to check for - * @return True if the table is found - * @throws SQLException Throw exception when failed execute somethins on SQL - */ - boolean hasTable(@NotNull String table) throws SQLException { - DatabaseConnection connection = database.getConnection(); - ResultSet rs = connection.get().getMetaData().getTables(null, null, "%", null); - boolean match = false; - while (rs.next()) { - if (table.equalsIgnoreCase(rs.getString("TABLE_NAME"))) { - match = true; - break; - } - } - rs.close(); - connection.release(); - return match; - } - - /** - * Returns true if the given table has the given column - * - * @param table The table - * @param column The column - * @return True if the given table has the given column - * @throws SQLException If the database isn't connected - */ - public boolean hasColumn(@NotNull String table, @NotNull String column) throws SQLException { - if (!hasTable(table)) { - return false; - } - - DatabaseConnection connection = database.getConnection(); - String query = "SELECT * FROM " + table + " LIMIT 1"; - boolean match = false; try { - PreparedStatement ps = connection.get().prepareStatement(query); - ResultSet rs = ps.executeQuery(); - ResultSetMetaData metaData = rs.getMetaData(); - for (int i = 1; i <= metaData.getColumnCount(); i++) { - if (metaData.getColumnLabel(i).equals(column)) { - match = true; - break; - } - } - rs.close(); - - } catch (SQLException e) { - return match; - } finally { - connection.release(); + task = + new BukkitRunnable() { + @Override + public void run() { + plugin.getDatabaseManager().runTask(); + } + }.runTaskTimerAsynchronously(plugin, 1, plugin.getConfig().getLong("database.queue-commit-interval") * 20); + } catch (IllegalPluginAccessException e) { + Util.debugLog("Plugin is disabled but trying create database task, move to Main Thread..."); + plugin.getDatabaseManager().runTask(); } - return match; // Uh, wtf. } /** * Internal method, runTasks in queue. */ - private void runTask() { // synchronized for QUICKSHOP-WX - synchronized (sqlQueue) { - if (sqlQueue.isEmpty()) { - return; - } - DatabaseConnection dbconnection = this.database.getConnection(); - Connection connection = dbconnection.get(); - try { - //start our commit - connection.setAutoCommit(false); - Timer ctimer = new Timer(true); - while (true) { - if (!dbconnection.isValid()) { - warningSender.sendWarn("Database connection may lost, we are trying reconnecting, if this message appear too many times, you should check your database file(sqlite) and internet connection(mysql)."); - //connection isn't stable, let autocommit on - dbconnection.release(); - dbconnection.close(); - return; // Waiting next crycle and hope it success reconnected. - } - - Timer timer = new Timer(true); - DatabaseTask task = sqlQueue.poll(); - if (task == null) { - break; - } - Util.debugLog("Executing the SQL task: " + task); - - task.run(connection); - long tookTime = timer.endTimer(); - if (tookTime > 300) { - warningSender.sendWarn( - "Database performance warning: It took too long time (" - + tookTime - + "ms) to execute the task, it may cause the network connection with MySQL server or just MySQL server too slow, change to a better MySQL server or switch to a local SQLite database!"); - } + private synchronized void runTask() { // synchronized for QUICKSHOP-WX + if (sqlQueue.isEmpty()) { + return; + } + try { + Connection connection = this.database.getConnection(); + //start our commit + connection.setAutoCommit(false); + Timer ctimer = new Timer(true); + while (true) { + if (!connection.isValid(3000)) { + warningSender.sendWarn("Database connection may lost, we are trying reconnecting, if this message appear too many times, you should check your database file(sqlite) and internet connection(mysql)."); + //connection isn't stable, let autocommit on + connection = database.getConnection(); + continue; // Waiting next crycle and hope it success reconnected. } - if (!connection.getAutoCommit()) { - connection.commit(); - connection.setAutoCommit(true); + + Timer timer = new Timer(true); + DatabaseTask task = sqlQueue.poll(); + if (task == null) { + break; } - long tookTime = ctimer.endTimer(); - if (tookTime > 5500) { + Util.debugLog("Executing the SQL task: " + task); + + task.run(connection); + long tookTime = timer.endTimer(); + if (tookTime > 300) { warningSender.sendWarn( "Database performance warning: It took too long time (" + tookTime + "ms) to execute the task, it may cause the network connection with MySQL server or just MySQL server too slow, change to a better MySQL server or switch to a local SQLite database!"); } - - } catch (SQLException sqle) { - plugin.getSentryErrorReporter().ignoreThrow(); - this.plugin - .getLogger() - .log(Level.WARNING, "Database connection may lost, we are trying reconnecting, if this message appear too many times, you should check your database file(sqlite) and internet connection(mysql).", sqle); - } finally { - dbconnection.release(); } + if (!connection.getAutoCommit()) { + connection.commit(); + connection.setAutoCommit(true); + } + long tookTime = ctimer.endTimer(); + if (tookTime > 5500) { + warningSender.sendWarn( + "Database performance warning: It took too long time (" + + tookTime + + "ms) to execute the task, it may cause the network connection with MySQL server or just MySQL server too slow, change to a better MySQL server or switch to a local SQLite database!"); + } + connection.close(); + } catch (SQLException sqle) { + plugin.getSentryErrorReporter().ignoreThrow(); + this.plugin + .getLogger() + .log(Level.WARNING, "Database connection may lost, we are trying reconnecting, if this message appear too many times, you should check your database file(sqlite) and internet connection(mysql).", sqle); } // try { @@ -221,49 +153,23 @@ public class DatabaseManager { * * @param task The DatabaseTask you want add in queue. */ - public void runInstantTask(DatabaseTask task) { - DatabaseConnection connection = database.getConnection(); - task.run(connection.get()); - connection.release(); - } - - /** - * Add DatabaseTask to queue waiting flush to database, - * - * @param task The DatabaseTask you want add in queue. - */ - public void addDelayTask(DatabaseTask task) { + public void add(DatabaseTask task) { if (useQueue) { - synchronized (sqlQueue) { - sqlQueue.offer(task); - } + sqlQueue.offer(task); } else { - runInstantTask(task); + task.run(database.getConnection()); } } /** * Unload the DatabaseManager, run at onDisable() */ - public synchronized void unInit() { + public void unInit() { if (task != null && !task.isCancelled()) { task.cancel(); } plugin.getLogger().info("Please wait for the data to flush its data..."); runTask(); - database.close(); } - - /** - * Represents a connection error, generally when the server can't connect to MySQL or something. - */ - public static final class ConnectionException extends Exception { - private static final long serialVersionUID = 8348749992936357317L; - - private ConnectionException(String msg) { - super(msg); - } - - } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/quickshop/database/DatabaseTask.java b/src/main/java/org/maxgamer/quickshop/database/DatabaseTask.java index 674e84644..18dcf1076 100644 --- a/src/main/java/org/maxgamer/quickshop/database/DatabaseTask.java +++ b/src/main/java/org/maxgamer/quickshop/database/DatabaseTask.java @@ -1,6 +1,5 @@ /* * This file is a part of project QuickShop, the name is DatabaseTask.java - * Copyright (C) Ghost_chu * Copyright (C) PotatoCraft Studio and contributors * * This program is free software: you can redistribute it and/or modify it @@ -31,9 +30,6 @@ import java.sql.SQLException; @ToString() public class DatabaseTask { - private final static Task emptyTask = ps -> { - - }; private final String statement; private final Task task; @@ -42,11 +38,6 @@ public class DatabaseTask { this.task = task; } - public DatabaseTask(String statement) { - this.statement = statement; - this.task = emptyTask; - } - public void run(@NonNull Connection connection) { try (PreparedStatement ps = connection.prepareStatement(statement)) { diff --git a/src/main/java/org/maxgamer/quickshop/database/MySQLCore.java b/src/main/java/org/maxgamer/quickshop/database/MySQLCore.java index c106d7fc2..19b4af37c 100644 --- a/src/main/java/org/maxgamer/quickshop/database/MySQLCore.java +++ b/src/main/java/org/maxgamer/quickshop/database/MySQLCore.java @@ -1,6 +1,5 @@ /* * This file is a part of project QuickShop, the name is MySQLCore.java - * Copyright (C) Ghost_chu * Copyright (C) PotatoCraft Studio and contributors * * This program is free software: you can redistribute it and/or modify it @@ -25,16 +24,18 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.maxgamer.quickshop.QuickShop; +import java.sql.Connection; import java.sql.DriverManager; +import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Properties; -public class MySQLCore extends AbstractDatabaseCore { +public class MySQLCore implements DatabaseCore { private static final int MAX_CONNECTIONS = 8; - private final List POOL = new ArrayList<>(); + private final List POOL = new ArrayList<>(); /** * The connection properties... user, pass, autoReconnect.. */ @@ -65,35 +66,55 @@ public class MySQLCore extends AbstractDatabaseCore { info.setProperty("useSSL", String.valueOf(useSSL)); this.url = "jdbc:mysql://" + host + ":" + port + "/" + database; for (int i = 0; i < MAX_CONNECTIONS; i++) { - try { - POOL.add(new DatabaseConnection(DriverManager.getConnection(this.url, info))); - } catch (SQLException throwables) { - throw new IllegalStateException("Unable to create a new connection", throwables); - } + POOL.add(null); } } @Override - void close() { - for (DatabaseConnection databaseConnection : POOL) { - if (databaseConnection == null || !databaseConnection.isValid()) { - continue; - } - if (!databaseConnection.isUsing()) { - databaseConnection.close(); - } else { - //Wait until the connection is finished - try { - Thread.sleep(2000); - } catch (InterruptedException ignored) { - } finally { - close(); + public void close() { + try { + for (Connection connection : POOL) { + if (connection == null || connection.isClosed()) { + continue; } + if (!connection.getAutoCommit()) { + connection.commit(); + } + connection.close(); } + } catch (SQLException ignored) { } // Nothing, because queries are executed immediately for MySQL } + @Override + public void flush() { + // Nothing, because queries are executed immediately for MySQL + } + + @Override + public void queue(@NotNull BufferStatement bs) { + try { + + Connection con = this.getConnection(); + while (con == null) { + try { + Thread.sleep(15); + } catch (InterruptedException e) { + // ignore + } + // Try again + con = this.getConnection(); + } + + PreparedStatement ps = bs.prepareStatement(con); + ps.execute(); + ps.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + /** * Gets the database connection for executing queries on. * @@ -101,31 +122,24 @@ public class MySQLCore extends AbstractDatabaseCore { */ @Nullable @Override - DatabaseConnection getConnection() { + public Connection getConnection() { for (int i = 0; i < MAX_CONNECTIONS; i++) { - DatabaseConnection connection = POOL.get(i); - // If we have a current connection, fetch it - if (connection != null && !connection.isUsing()) { - if (connection.isValid()) { + Connection connection = POOL.get(i); + try { + // If we have a current connection, fetch it + if (connection != null && !connection.isClosed() && connection.isValid(10)) { return connection; - } else { // Else, it is invalid, so we return another connection. - connection.close(); - try { - connection = new DatabaseConnection(DriverManager.getConnection(this.url, info)); - POOL.set(i, connection); - return connection; - } catch (SQLException e) { - throw new RuntimeException("Unable to create a new connection", e); - } } + connection = DriverManager.getConnection(this.url, info); + POOL.set(i, connection); + return connection; + } catch (SQLException e) { + e.printStackTrace(); } - } - //If all connection is unusable, wait a moment - waitForConnection(); - return getConnection(); + return null; } @Override diff --git a/src/main/java/org/maxgamer/quickshop/database/SQLiteCore.java b/src/main/java/org/maxgamer/quickshop/database/SQLiteCore.java index da7475493..2d4755114 100644 --- a/src/main/java/org/maxgamer/quickshop/database/SQLiteCore.java +++ b/src/main/java/org/maxgamer/quickshop/database/SQLiteCore.java @@ -1,6 +1,5 @@ /* * This file is a part of project QuickShop, the name is SQLiteCore.java - * Copyright (C) Ghost_chu * Copyright (C) PotatoCraft Studio and contributors * * This program is free software: you can redistribute it and/or modify it @@ -27,15 +26,21 @@ import org.maxgamer.quickshop.QuickShop; import java.io.File; import java.io.IOException; +import java.sql.Connection; import java.sql.DriverManager; +import java.sql.PreparedStatement; import java.sql.SQLException; +import java.util.LinkedList; +import java.util.Objects; -public class SQLiteCore extends AbstractDatabaseCore { +public class SQLiteCore implements DatabaseCore { private final File dbFile; + private final LinkedList queue = new LinkedList<>(); @NotNull private final QuickShop plugin; - private DatabaseConnection connection; + private Connection connection; + private volatile Thread watcher; public SQLiteCore(@NotNull QuickShop plugin, @NotNull File dbFile) { this.plugin = plugin; @@ -43,22 +48,45 @@ public class SQLiteCore extends AbstractDatabaseCore { } @Override - void close() { - if (!connection.isUsing()) { - if (connection != null && !connection.isValid()) { + public void close() { + flush(); + try { + if (connection != null) { connection.close(); } - } else { - //Wait until the connection is finished - try { - Thread.sleep(2000); - } catch (InterruptedException ignored) { - } finally { - close(); + } catch (SQLException ignored) { + } + } + + @Override + public void flush() { + while (!queue.isEmpty()) { + BufferStatement bs; + synchronized (queue) { + bs = queue.removeFirst(); + } + synchronized (dbFile) { + try { + + PreparedStatement ps = bs.prepareStatement(Objects.requireNonNull(getConnection())); + ps.execute(); + ps.close(); + } catch (SQLException e) { + e.printStackTrace(); + } } } } + @Override + public void queue(@NotNull BufferStatement bs) { + synchronized (queue) { + queue.add(bs); + } + if (watcher == null || !watcher.isAlive()) { + startWatcher(); + } + } /** * Gets the database connection for executing queries on. @@ -67,48 +95,37 @@ public class SQLiteCore extends AbstractDatabaseCore { */ @Nullable @Override - DatabaseConnection getConnection() { - if (this.connection == null) { - return connection = genConnection(); - } - // If we have a current connection, fetch it - if (!this.connection.isUsing()) { - if (connection.isValid()) { + public Connection getConnection() { + try { + // If we have a current connection, fetch it + if (this.connection != null && !this.connection.isClosed()) { return this.connection; - } else { - connection.close(); - return connection = genConnection(); } + } catch (SQLException e) { + e.printStackTrace(); } - //If all connection is unusable, wait a moment - waitForConnection(); - return getConnection(); - } - - @Nullable - private DatabaseConnection genConnection() { if (this.dbFile.exists()) { + // So we need a new connection try { Class.forName("org.sqlite.JDBC"); - this.connection = new DatabaseConnection(DriverManager.getConnection("jdbc:sqlite:" + this.dbFile)); + this.connection = DriverManager.getConnection("jdbc:sqlite:" + this.dbFile); return this.connection; - } catch (ClassNotFoundException e) { - throw new IllegalStateException("Sqlite driver is not found", e); - } catch (SQLException e) { - throw new IllegalStateException("Start sqlite database connection failed", e); + } catch (ClassNotFoundException | SQLException e) { + e.printStackTrace(); + return null; } } else { - // So we need a new file. + // So we need a new file too. try { // Create the file - //noinspection ResultOfMethodCallIgnored this.dbFile.createNewFile(); + // Now we won't need a new file, just a connection. + // This will return that new connection. + return this.getConnection(); } catch (IOException e) { - throw new IllegalStateException("Sqlite database file create failed", e); + e.printStackTrace(); + return null; } - // Now we won't need a new file, just a connection. - // This will return that new connection. - return this.genConnection(); } } @@ -122,4 +139,18 @@ public class SQLiteCore extends AbstractDatabaseCore { return plugin; } + private void startWatcher() { + watcher = + new Thread( + () -> { + try { + Thread.sleep(30000); + } catch (InterruptedException e) { + // ignore + } + flush(); + }); + watcher.start(); + } + } diff --git a/src/main/java/org/maxgamer/quickshop/database/WarpedResultSet.java b/src/main/java/org/maxgamer/quickshop/database/WarpedResultSet.java deleted file mode 100644 index f9d674d5c..000000000 --- a/src/main/java/org/maxgamer/quickshop/database/WarpedResultSet.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.maxgamer.quickshop.database; - -import lombok.Getter; - -import java.sql.ResultSet; -import java.sql.SQLException; - -public class WarpedResultSet implements AutoCloseable { - @Getter - private final ResultSet resultSet; - private final DatabaseConnection databaseConnection; - - public WarpedResultSet(ResultSet resultSet, DatabaseConnection databaseConnection) { - this.resultSet = resultSet; - this.databaseConnection = databaseConnection; - } - - @Override - public void close() throws SQLException { - resultSet.close(); - databaseConnection.release(); - } -} diff --git a/src/main/java/org/maxgamer/quickshop/shop/ShopLoader.java b/src/main/java/org/maxgamer/quickshop/shop/ShopLoader.java index 5a39118b1..b3e0ceae8 100644 --- a/src/main/java/org/maxgamer/quickshop/shop/ShopLoader.java +++ b/src/main/java/org/maxgamer/quickshop/shop/ShopLoader.java @@ -1,6 +1,5 @@ /* * This file is a part of project QuickShop, the name is ShopLoader.java - * Copyright (C) Ghost_chu * Copyright (C) PotatoCraft Studio and contributors * * This program is free software: you can redistribute it and/or modify it @@ -33,7 +32,6 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.maxgamer.quickshop.QuickShop; -import org.maxgamer.quickshop.database.WarpedResultSet; import org.maxgamer.quickshop.util.JsonUtil; import org.maxgamer.quickshop.util.Timer; import org.maxgamer.quickshop.util.Util; @@ -85,10 +83,11 @@ public class ShopLoader { public void loadShops(@Nullable String worldName) { boolean backupedDatabaseInDeleteProcess = false; Timer totalLoadTimer = new Timer(true); - this.plugin.getLogger().info("Loading shops from the database..."); - Timer fetchTimer = new Timer(true); - try (WarpedResultSet warpRS = plugin.getDatabaseHelper().selectAllShops()) { - ResultSet rs = warpRS.getResultSet(); + try { + this.plugin.getLogger().info("Loading shops from the database..."); + Timer fetchTimer = new Timer(true); + + ResultSet rs = plugin.getDatabaseHelper().selectAllShops(); this.plugin .getLogger() .info("Used " + fetchTimer.endTimer() + "ms to fetch all shops from the database."); @@ -151,6 +150,7 @@ public class ShopLoader { } singleShopLoaded(singleShopLoadTimer); } + rs.close(); long totalUsedTime = totalLoadTimer.endTimer(); long avgPerShop = mean(loadTimes.toArray(new Long[0])); this.plugin @@ -249,6 +249,25 @@ public class ShopLoader { logger.warning("Location: " + ((shopLocation == null) ? "NULL" : shopLocation.toString())); logger.warning( "Block: " + ((shopLocation == null) ? "NULL" : shopLocation.getBlock().getType().name())); + logger.warning(" >> Database Info"); + try { + logger.warning("Connected: " + plugin.getDatabase().getConnection().isClosed()); + } catch (SQLException | NullPointerException e) { + logger.warning("Connected: " + "FALSE - Failed to load status."); + } + + try { + logger.warning("Readonly: " + plugin.getDatabase().getConnection().isReadOnly()); + } catch (SQLException | NullPointerException e) { + logger.warning("Readonly: " + "FALSE - Failed to load status."); + } + + try { + logger.warning("ClientInfo: " + plugin.getDatabase().getConnection().getClientInfo()); + } catch (SQLException | NullPointerException e) { + logger.warning("ClientInfo: " + "FALSE - Failed to load status."); + } + logger.warning("#######################################"); if (errors > 10) { logger.severe( @@ -336,13 +355,13 @@ public class ShopLoader { this.x = origin.getX(); this.y = origin.getY(); this.z = origin.getZ(); - this.world = Bukkit.getWorld(origin.getWorld()); - this.location = new Location(world, x, y, z); this.price = origin.getPrice(); this.unlimited = origin.isUnlimited(); - this.moderators = deserializeModerator(origin.getModerators()); this.type = ShopType.fromID(origin.getType()); + this.world = Bukkit.getWorld(origin.getWorld()); this.item = deserializeItem(origin.getItem()); + this.moderators = deserializeModerator(origin.getModerators()); + this.location = new Location(world, x, y, z); //noinspection unchecked this.extra = JsonUtil.getGson().fromJson(origin.getExtra(), Map.class); if (this.extra == null) { diff --git a/src/main/java/org/maxgamer/quickshop/util/MsgUtil.java b/src/main/java/org/maxgamer/quickshop/util/MsgUtil.java index d617c880f..ecebe5241 100644 --- a/src/main/java/org/maxgamer/quickshop/util/MsgUtil.java +++ b/src/main/java/org/maxgamer/quickshop/util/MsgUtil.java @@ -1,6 +1,5 @@ /* * This file is a part of project QuickShop, the name is MsgUtil.java - * Copyright (C) Ghost_chu * Copyright (C) PotatoCraft Studio and contributors * * This program is free software: you can redistribute it and/or modify it @@ -49,7 +48,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.maxgamer.quickshop.QuickShop; import org.maxgamer.quickshop.ServiceInjector; -import org.maxgamer.quickshop.database.WarpedResultSet; import org.maxgamer.quickshop.event.ShopControlPanelOpenEvent; import org.maxgamer.quickshop.fileportlek.old.IFile; import org.maxgamer.quickshop.fileportlek.old.JSONFile; @@ -452,8 +450,8 @@ public class MsgUtil { */ public static void loadTransactionMessages() { outGoingPlayerMessages.clear(); // Delete old messages - try (WarpedResultSet warpRS = plugin.getDatabaseHelper().selectAllMessages()) { - ResultSet rs = warpRS.getResultSet(); + try { + ResultSet rs = plugin.getDatabaseHelper().selectAllMessages(); while (rs.next()) { String owner = rs.getString("owner"); UUID ownerUUID; diff --git a/src/main/java/org/maxgamer/quickshop/util/Util.java b/src/main/java/org/maxgamer/quickshop/util/Util.java index 406eb2966..2a4533d5b 100644 --- a/src/main/java/org/maxgamer/quickshop/util/Util.java +++ b/src/main/java/org/maxgamer/quickshop/util/Util.java @@ -1,6 +1,5 @@ /* * This file is a part of project QuickShop, the name is Util.java - * Copyright (C) Ghost_chu * Copyright (C) PotatoCraft Studio and contributors * * This program is free software: you can redistribute it and/or modify it @@ -20,6 +19,7 @@ package org.maxgamer.quickshop.util; +import com.google.common.io.Files; import lombok.NonNull; import org.bukkit.*; import org.bukkit.block.*; @@ -55,7 +55,6 @@ import java.io.*; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.nio.charset.StandardCharsets; -import java.nio.file.Files; import java.text.DecimalFormat; import java.util.AbstractMap.SimpleEntry; import java.util.*; @@ -110,7 +109,7 @@ public class Util { * @return The result for backup */ public static boolean backupDatabase() { - if (plugin.getDatabaseManager().getDatabase() instanceof MySQLCore) { + if (plugin.getDatabase().getCore() instanceof MySQLCore) { return true; // Backup and logs by MySQL } File dataFolder = plugin.getDataFolder(); @@ -122,7 +121,7 @@ public class Util { String uuid = UUID.randomUUID().toString().replaceAll("_", ""); File bksqlfile = new File(dataFolder, "/shops_backup_" + uuid + ".db"); try { - Files.copy(sqlfile.toPath(), bksqlfile.toPath()); + Files.copy(sqlfile, bksqlfile); } catch (Exception e1) { e1.printStackTrace(); plugin.getLogger().warning("Failed to backup the database."); diff --git a/src/main/java/org/maxgamer/quickshop/util/paste/Paste.java b/src/main/java/org/maxgamer/quickshop/util/paste/Paste.java index bbdf1feaf..426348029 100644 --- a/src/main/java/org/maxgamer/quickshop/util/paste/Paste.java +++ b/src/main/java/org/maxgamer/quickshop/util/paste/Paste.java @@ -1,6 +1,5 @@ /* * This file is a part of project QuickShop, the name is Paste.java - * Copyright (C) Ghost_chu * Copyright (C) PotatoCraft Studio and contributors * * This program is free software: you can redistribute it and/or modify it @@ -29,7 +28,6 @@ import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.maxgamer.quickshop.QuickShop; -import org.maxgamer.quickshop.database.WarpedResultSet; import org.maxgamer.quickshop.economy.Economy; import org.maxgamer.quickshop.economy.EconomyCore; import org.maxgamer.quickshop.economy.Economy_Vault; @@ -146,7 +144,7 @@ public class Paste { } else { finalReport.append("\tEconomyCore: ").append(plugin.getEconomy().getCore().getName()).append("@").append(plugin.getEconomy().getCore().getPlugin().getName()).append("\n"); } - finalReport.append("\tDatabaseCore: ").append(plugin.getDatabaseManager().getDatabase().getName()).append("@").append(plugin.getDatabaseManager().getDatabase().getPlugin().getName()).append("\n"); + finalReport.append("\tDatabaseCore: ").append(plugin.getDatabase().getCore().getName()).append("@").append(plugin.getDatabase().getCore().getPlugin().getName()).append("\n"); finalReport.append("\tGameLanguage Processor: ").append(MsgUtil.gameLanguage.getName()).append("@").append(MsgUtil.gameLanguage.getPlugin().getName()).append("\n"); finalReport.append("================================================\n"); finalReport.append("Worlds:\n"); @@ -395,12 +393,11 @@ public class Paste { finalReport.append("================================================\n"); int totalDB = 0; - try (WarpedResultSet warpRS = plugin.getDatabaseHelper().selectAllShops()) { - while (warpRS.getResultSet().next()) { - totalDB++; - } + ResultSet resultSet = plugin.getDatabaseHelper().selectAllShops(); + while (resultSet.next()) { + totalDB++; } - + resultSet.close(); finalReport.append("Shops in DB(RealTime): ").append(totalDB).append("\n"); finalReport.append("================================================\n"); finalReport.append("Shops in Mem:\n");