From 37b56103e1dacd2ab4bb958b2299fc9d1f308f2e Mon Sep 17 00:00:00 2001 From: Jon Huang Date: Mon, 29 Jan 2024 19:53:48 -0800 Subject: [PATCH 01/15] Add PostgreSQL support. --- lang/en.yml | 2 + pom.xml | 5 + .../java/net/coreprotect/CoreProtect.java | 18 ++- .../java/net/coreprotect/api/BlockAPI.java | 4 +- .../net/coreprotect/api/SessionLookup.java | 3 +- .../net/coreprotect/command/PurgeCommand.java | 59 ++++--- .../coreprotect/command/StatusCommand.java | 18 ++- .../java/net/coreprotect/config/Config.java | 42 ++--- .../net/coreprotect/config/ConfigHandler.java | 49 ++++-- .../net/coreprotect/config/DatabaseType.java | 7 + .../consumer/process/ArtInsertProcess.java | 3 +- .../process/BlockDataInsertProcess.java | 3 +- .../consumer/process/EntityInsertProcess.java | 3 +- .../consumer/process/EntitySpawnProcess.java | 4 +- .../process/MaterialInsertProcess.java | 3 +- .../consumer/process/SignUpdateProcess.java | 10 +- .../consumer/process/SkullUpdateProcess.java | 2 +- .../consumer/process/WorldInsertProcess.java | 2 +- .../net/coreprotect/database/Database.java | 150 ++++++++++++++---- .../java/net/coreprotect/database/Lookup.java | 9 +- .../coreprotect/database/StatementUtils.java | 27 ++++ .../database/logger/UsernameLogger.java | 39 +++-- .../database/lookup/BlockLookup.java | 4 +- .../lookup/ChestTransactionLookup.java | 8 +- .../database/lookup/InteractionLookup.java | 4 +- .../database/lookup/PlayerLookup.java | 5 +- .../database/lookup/SignMessageLookup.java | 4 +- .../database/statement/UserStatement.java | 23 ++- .../net/coreprotect/language/Language.java | 2 + .../java/net/coreprotect/language/Phrase.java | 2 + .../net/coreprotect/model/BlockGroup.java | 2 +- .../java/net/coreprotect/patch/Patch.java | 2 +- .../coreprotect/patch/script/__2_10_0.java | 3 +- .../coreprotect/patch/script/__2_11_0.java | 5 +- .../coreprotect/patch/script/__2_15_0.java | 5 +- .../coreprotect/patch/script/__2_16_0.java | 3 +- .../coreprotect/patch/script/__2_17_0.java | 3 +- .../coreprotect/patch/script/__2_18_0.java | 7 +- .../coreprotect/patch/script/__2_19_0.java | 5 +- .../coreprotect/patch/script/__2_20_0.java | 3 +- .../coreprotect/patch/script/__2_21_0.java | 3 +- .../coreprotect/patch/script/__2_22_0.java | 3 +- .../net/coreprotect/patch/script/__2_5_0.java | 3 +- .../net/coreprotect/patch/script/__2_6_0.java | 3 +- .../java/net/coreprotect/utility/Util.java | 5 +- 45 files changed, 401 insertions(+), 168 deletions(-) create mode 100644 src/main/java/net/coreprotect/config/DatabaseType.java create mode 100644 src/main/java/net/coreprotect/database/StatementUtils.java diff --git a/lang/en.yml b/lang/en.yml index d2fcd5dfc..1d31f816d 100644 --- a/lang/en.yml +++ b/lang/en.yml @@ -125,6 +125,7 @@ MISSING_PARAMETERS: "Please use \"{0}\"." MISSING_ROLLBACK_RADIUS: "You did not specify a {rollback|restore} radius." MISSING_ROLLBACK_USER: "You did not specify a {rollback|restore} user." MYSQL_UNAVAILABLE: "Unable to connect to MySQL server." +PGSQL_UNAVAILABLE: "Unable to connect to PostgreSQL server." NETWORK_CONNECTION: "Connection by {0} {successful|failed}. Using {1} {2}." NETWORK_TEST: "Network test data has been successful sent." NO_DATA: "No data found at {0}." @@ -196,6 +197,7 @@ UPGRADE_IN_PROGRESS: "Upgrade in progress. Please try again later." USER_NOT_FOUND: "User \"{0}\" not found." USER_OFFLINE: "The user \"{0}\" is not online." USING_MYSQL: "Using MySQL for data storage." +USING_PGSQL: "Using PostgreSQL for data storage." USING_SQLITE: "Using SQLite for data storage." VALID_DONATION_KEY: "Valid donation key." VERSION_NOTICE: "Version {0} is now available." diff --git a/pom.xml b/pom.xml index 0c035ad77..a60a4d823 100755 --- a/pom.xml +++ b/pom.xml @@ -129,5 +129,10 @@ HikariCP 5.0.1 + + org.postgresql + postgresql + 42.7.1 + \ No newline at end of file diff --git a/src/main/java/net/coreprotect/CoreProtect.java b/src/main/java/net/coreprotect/CoreProtect.java index 7530af160..21e28afba 100755 --- a/src/main/java/net/coreprotect/CoreProtect.java +++ b/src/main/java/net/coreprotect/CoreProtect.java @@ -88,11 +88,19 @@ public void onEnable() { if (start) { PluginDescriptionFile pluginDescription = this.getDescription(); Util.sendConsoleComponentStartup(Bukkit.getServer().getConsoleSender(), Phrase.build(Phrase.ENABLE_SUCCESS, ConfigHandler.EDITION_NAME)); - if (Config.getGlobal().MYSQL) { - Chat.console(Phrase.build(Phrase.USING_MYSQL)); - } - else { - Chat.console(Phrase.build(Phrase.USING_SQLITE)); + switch (Config.getGlobal().DB_TYPE) { + case MYSQL: { + Chat.console(Phrase.build(Phrase.USING_MYSQL)); + break; + } + case PGSQL: { + Chat.console(Phrase.build(Phrase.USING_PGSQL)); + break; + } + case SQLITE: { + Chat.console(Phrase.build(Phrase.USING_SQLITE)); + break; + } } Chat.console("--------------------"); diff --git a/src/main/java/net/coreprotect/api/BlockAPI.java b/src/main/java/net/coreprotect/api/BlockAPI.java index 203363bb5..a9fceb673 100644 --- a/src/main/java/net/coreprotect/api/BlockAPI.java +++ b/src/main/java/net/coreprotect/api/BlockAPI.java @@ -10,6 +10,7 @@ import net.coreprotect.config.ConfigHandler; import net.coreprotect.database.Database; +import net.coreprotect.database.StatementUtils; import net.coreprotect.database.statement.UserStatement; import net.coreprotect.utility.Util; @@ -38,7 +39,8 @@ public static List performLookup(Block block, int offset) { } Statement statement = connection.createStatement(); - String query = "SELECT time,user,action,type,data,blockdata,rolled_back FROM " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND time > '" + checkTime + "' ORDER BY rowid DESC"; + + String query = "SELECT time,\"user\",action,type,data,blockdata,rolled_back FROM " + StatementUtils.getTableName("block") + " " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND time > '" + checkTime + "' ORDER BY rowid DESC"; ResultSet results = statement.executeQuery(query); while (results.next()) { diff --git a/src/main/java/net/coreprotect/api/SessionLookup.java b/src/main/java/net/coreprotect/api/SessionLookup.java index 60500697a..c633e4654 100644 --- a/src/main/java/net/coreprotect/api/SessionLookup.java +++ b/src/main/java/net/coreprotect/api/SessionLookup.java @@ -10,6 +10,7 @@ import net.coreprotect.config.Config; import net.coreprotect.config.ConfigHandler; import net.coreprotect.database.Database; +import net.coreprotect.database.StatementUtils; import net.coreprotect.database.statement.UserStatement; public class SessionLookup { @@ -44,7 +45,7 @@ public static List performLookup(String user, int offset) { int userId = ConfigHandler.playerIdCache.get(user.toLowerCase(Locale.ROOT)); try (Statement statement = connection.createStatement()) { - String query = "SELECT time,user,wid,x,y,z,action FROM " + ConfigHandler.prefix + "session WHERE user = '" + userId + "' AND time > '" + checkTime + "' ORDER BY rowid DESC"; + String query = "SELECT time,\"user\",wid,x,y,z,action FROM " + StatementUtils.getTableName("session") + " WHERE user = '" + userId + "' AND time > '" + checkTime + "' ORDER BY rowid DESC"; ResultSet results = statement.executeQuery(query); while (results.next()) { String resultTime = results.getString("time"); diff --git a/src/main/java/net/coreprotect/command/PurgeCommand.java b/src/main/java/net/coreprotect/command/PurgeCommand.java index 59850c193..f5f2a15ed 100755 --- a/src/main/java/net/coreprotect/command/PurgeCommand.java +++ b/src/main/java/net/coreprotect/command/PurgeCommand.java @@ -15,8 +15,10 @@ import net.coreprotect.config.Config; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.config.DatabaseType; import net.coreprotect.consumer.Consumer; import net.coreprotect.database.Database; +import net.coreprotect.database.StatementUtils; import net.coreprotect.language.Phrase; import net.coreprotect.language.Selector; import net.coreprotect.patch.Patch; @@ -137,7 +139,7 @@ public void run() { boolean abort = false; String purgePrefix = "tmp_" + ConfigHandler.prefix; - if (!Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE == DatabaseType.SQLITE) { query = "ATTACH DATABASE '" + ConfigHandler.path + ConfigHandler.sqlite + ".tmp' AS tmp_db"; preparedStmt = connection.prepareStatement(query); preparedStmt.execute(); @@ -154,7 +156,7 @@ public void run() { return; } - if (!Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE == DatabaseType.SQLITE) { for (String table : ConfigHandler.databaseTables) { try { query = "DROP TABLE IF EXISTS " + purgePrefix + table + ""; @@ -177,7 +179,7 @@ public void run() { String tableName = table.replaceAll("_", " "); Chat.sendGlobalMessage(player, Phrase.build(Phrase.PURGE_PROCESSING, tableName)); - if (!Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE == DatabaseType.SQLITE) { String columns = ""; ResultSet rs = connection.createStatement().executeQuery("SELECT * FROM " + purgePrefix + table); ResultSetMetaData resultSetMetaData = rs.getMetaData(); @@ -205,7 +207,7 @@ else if (argWid == 0) { timeLimit = " WHERE (time >= '" + timeEnd + "' OR time < '" + timeStart + "')"; } } - query = "INSERT INTO " + purgePrefix + table + " SELECT " + columns + " FROM " + ConfigHandler.prefix + table + timeLimit; + query = "INSERT INTO " + purgePrefix + table + " SELECT " + columns + " FROM " + StatementUtils.getTableName(table) + timeLimit; preparedStmt = connection.prepareStatement(query); preparedStmt.execute(); preparedStmt.close(); @@ -231,7 +233,7 @@ else if (argWid == 0) { } try { - query = "REINDEX " + ConfigHandler.prefix + table; + query = "REINDEX " + StatementUtils.getTableName(table); preparedStmt = connection.prepareStatement(query); preparedStmt.execute(); preparedStmt.close(); @@ -242,7 +244,7 @@ else if (argWid == 0) { try { String index = " NOT INDEXED"; - query = "INSERT INTO " + purgePrefix + table + " SELECT " + columns + " FROM " + ConfigHandler.prefix + table + index; + query = "INSERT INTO " + purgePrefix + table + " SELECT " + columns + " FROM " + StatementUtils.getTableName(table) + index; preparedStmt = connection.prepareStatement(query); preparedStmt.execute(); preparedStmt.close(); @@ -279,7 +281,7 @@ else if (argWid > 0) { if (purgeTables.contains(table)) { int oldCount = 0; try { - query = "SELECT COUNT(*) as count FROM " + ConfigHandler.prefix + table + " LIMIT 0, 1"; + query = "SELECT COUNT(*) as count FROM " + StatementUtils.getTableName(table) + " LIMIT 1"; preparedStmt = connection.prepareStatement(query); ResultSet resultSet = preparedStmt.executeQuery(); while (resultSet.next()) { @@ -294,7 +296,7 @@ else if (argWid > 0) { int new_count = 0; try { - query = "SELECT COUNT(*) as count FROM " + purgePrefix + table + " LIMIT 0, 1"; + query = "SELECT COUNT(*) as count FROM " + purgePrefix + table + " LIMIT 1"; preparedStmt = connection.prepareStatement(query); ResultSet resultSet = preparedStmt.executeQuery(); while (resultSet.next()) { @@ -311,7 +313,7 @@ else if (argWid > 0) { } } - if (Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE != DatabaseType.SQLITE) { try { boolean purge = purgeTables.contains(table); @@ -324,7 +326,7 @@ else if (argWid > 0) { } if (purge) { - query = "DELETE FROM " + ConfigHandler.prefix + table + " WHERE time < '" + timeEnd + "' AND time >= '" + timeStart + "'" + worldRestriction; + query = "DELETE FROM " + StatementUtils.getTableName(table) + " WHERE time < '" + timeEnd + "' AND time >= '" + timeStart + "'" + worldRestriction; preparedStmt = connection.prepareStatement(query); preparedStmt.execute(); removed = removed + preparedStmt.getUpdateCount(); @@ -342,20 +344,39 @@ else if (argWid > 0) { } } - if (Config.getGlobal().MYSQL && optimize) { - Chat.sendGlobalMessage(player, Phrase.build(Phrase.PURGE_OPTIMIZING)); - for (String table : ConfigHandler.databaseTables) { - query = "OPTIMIZE LOCAL TABLE " + ConfigHandler.prefix + table + ""; - preparedStmt = connection.prepareStatement(query); - preparedStmt.execute(); - preparedStmt.close(); + if (optimize) { + switch (Config.getGlobal().DB_TYPE) { + case MYSQL: { + Chat.sendGlobalMessage(player, Phrase.build(Phrase.PURGE_OPTIMIZING)); + for (String table : ConfigHandler.databaseTables) { + query = "OPTIMIZE LOCAL TABLE " + StatementUtils.getTableName(table) + ""; + preparedStmt = connection.prepareStatement(query); + preparedStmt.execute(); + preparedStmt.close(); + } + break; + } + case PGSQL: { + Chat.sendGlobalMessage(player, Phrase.build(Phrase.PURGE_OPTIMIZING)); + for (String table : ConfigHandler.databaseTables) { + query = "VACUUM ANALYZE " + StatementUtils.getTableName(table); + preparedStmt = connection.prepareStatement(query); + preparedStmt.execute(); + preparedStmt.close(); + } + break; + } + default: { + // no optimization options for SQLite + break; + } } } connection.close(); if (abort) { - if (!Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE == DatabaseType.SQLITE) { (new File(ConfigHandler.path + ConfigHandler.sqlite + ".tmp")).delete(); } ConfigHandler.loadDatabase(); @@ -365,7 +386,7 @@ else if (argWid > 0) { return; } - if (!Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE == DatabaseType.SQLITE) { (new File(ConfigHandler.path + ConfigHandler.sqlite)).delete(); (new File(ConfigHandler.path + ConfigHandler.sqlite + ".tmp")).renameTo(new File(ConfigHandler.path + ConfigHandler.sqlite)); } diff --git a/src/main/java/net/coreprotect/command/StatusCommand.java b/src/main/java/net/coreprotect/command/StatusCommand.java index 2d806fc2f..bfc7544b8 100755 --- a/src/main/java/net/coreprotect/command/StatusCommand.java +++ b/src/main/java/net/coreprotect/command/StatusCommand.java @@ -65,11 +65,19 @@ Items processed (last 60 minutes) if (firstVersion.length() > 0) { firstVersion = " (" + Phrase.build(Phrase.FIRST_VERSION, firstVersion) + ")"; } - if (Config.getGlobal().MYSQL) { - Chat.sendMessage(player, Color.DARK_AQUA + Phrase.build(Phrase.STATUS_DATABASE, Color.WHITE, "MySQL") + firstVersion); - } - else { - Chat.sendMessage(player, Color.DARK_AQUA + Phrase.build(Phrase.STATUS_DATABASE, Color.WHITE, "SQLite") + firstVersion); + switch (Config.getGlobal().DB_TYPE) { + case MYSQL: { + Chat.sendMessage(player, Color.DARK_AQUA + Phrase.build(Phrase.STATUS_DATABASE, Color.WHITE, "MySQL") + firstVersion); + break; + } + case PGSQL: { + Chat.sendMessage(player, Color.DARK_AQUA + Phrase.build(Phrase.STATUS_DATABASE, Color.WHITE, "PostgreSQL") + firstVersion); + break; + } + case SQLITE: { + Chat.sendMessage(player, Color.DARK_AQUA + Phrase.build(Phrase.STATUS_DATABASE, Color.WHITE, "SQLite") + firstVersion); + break; + } } if (ConfigHandler.worldeditEnabled) { diff --git a/src/main/java/net/coreprotect/config/Config.java b/src/main/java/net/coreprotect/config/Config.java index bae4f1617..13a05b739 100644 --- a/src/main/java/net/coreprotect/config/Config.java +++ b/src/main/java/net/coreprotect/config/Config.java @@ -11,6 +11,7 @@ import java.nio.file.Files; import java.util.HashMap; import java.util.LinkedHashMap; +import java.util.Locale; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.CompletableFuture; @@ -36,11 +37,13 @@ public class Config extends Language { private Config defaults; public String DONATION_KEY; - public String PREFIX; - public String MYSQL_HOST; - public String MYSQL_DATABASE; - public String MYSQL_USERNAME; - public String MYSQL_PASSWORD; + public DatabaseType DB_TYPE; + public String DB_PREFIX; + public String DB_HOST; + public int DB_PORT; + public String DB_DATABASE; + public String DB_USERNAME; + public String DB_PASSWORD; public String LANGUAGE; public boolean ENABLE_AWE; public boolean ENABLE_SSL; @@ -51,7 +54,6 @@ public class Config extends Language { public boolean HOPPER_FILTER_META; public boolean EXCLUDE_TNT; public boolean NETWORK_DEBUG; - public boolean MYSQL; public boolean CHECK_UPDATES; public boolean API_ENABLED; public boolean VERBOSE; @@ -91,19 +93,18 @@ public class Config extends Language { public boolean USERNAME_CHANGES; public boolean WORLDEDIT; public int MAXIMUM_POOL_SIZE; - public int MYSQL_PORT; public int DEFAULT_RADIUS; public int MAX_RADIUS; static { DEFAULT_VALUES.put("donation-key", ""); - DEFAULT_VALUES.put("use-mysql", "false"); + DEFAULT_VALUES.put("db-type", "sqlite"); DEFAULT_VALUES.put("table-prefix", "co_"); - DEFAULT_VALUES.put("mysql-host", "127.0.0.1"); - DEFAULT_VALUES.put("mysql-port", "3306"); - DEFAULT_VALUES.put("mysql-database", "database"); - DEFAULT_VALUES.put("mysql-username", "root"); - DEFAULT_VALUES.put("mysql-password", ""); + DEFAULT_VALUES.put("db-host", "127.0.0.1"); + DEFAULT_VALUES.put("db-port", "3306"); + DEFAULT_VALUES.put("db-database", "database"); + DEFAULT_VALUES.put("db-username", "root"); + DEFAULT_VALUES.put("db-password", ""); DEFAULT_VALUES.put("language", "en"); DEFAULT_VALUES.put("check-updates", "true"); DEFAULT_VALUES.put("api-enabled", "true"); @@ -146,7 +147,6 @@ public class Config extends Language { DEFAULT_VALUES.put("worldedit", "true"); HEADERS.put("donation-key", new String[] { "# CoreProtect is donationware. Obtain a donation key from coreprotect.net/donate/" }); - HEADERS.put("use-mysql", new String[] { "# MySQL is optional and not required.", "# If you prefer to use MySQL, enable the following and fill out the fields." }); HEADERS.put("language", new String[] { "# If modified, will automatically attempt to translate languages phrases.", "# List of language codes: https://coreprotect.net/languages/" }); HEADERS.put("check-updates", new String[] { "# If enabled, CoreProtect will check for updates when your server starts up.", "# If an update is available, you'll be notified via your server console.", }); HEADERS.put("api-enabled", new String[] { "# If enabled, other plugins will be able to utilize the CoreProtect API.", }); @@ -202,13 +202,13 @@ private void readValues() { this.UNKNOWN_LOGGING = this.getBoolean("unknown-logging", false); this.MAXIMUM_POOL_SIZE = this.getInt("maximum-pool-size", 10); this.DONATION_KEY = this.getString("donation-key"); - this.MYSQL = this.getBoolean("use-mysql"); - this.PREFIX = this.getString("table-prefix"); - this.MYSQL_HOST = this.getString("mysql-host"); - this.MYSQL_PORT = this.getInt("mysql-port"); - this.MYSQL_DATABASE = this.getString("mysql-database"); - this.MYSQL_USERNAME = this.getString("mysql-username"); - this.MYSQL_PASSWORD = this.getString("mysql-password"); + this.DB_TYPE = DatabaseType.valueOf(DatabaseType.class, this.getString("db-type").toUpperCase(Locale.US)); + this.DB_PREFIX = this.getString("table-prefix"); + this.DB_HOST = this.getString("db-host"); + this.DB_PORT = this.getInt("db-port"); + this.DB_DATABASE = this.getString("db-database"); + this.DB_USERNAME = this.getString("db-username"); + this.DB_PASSWORD = this.getString("db-password"); this.LANGUAGE = this.getString("language"); this.CHECK_UPDATES = this.getBoolean("check-updates"); this.API_ENABLED = this.getBoolean("api-enabled"); diff --git a/src/main/java/net/coreprotect/config/ConfigHandler.java b/src/main/java/net/coreprotect/config/ConfigHandler.java index a1cd7f7ad..c1f5ece54 100644 --- a/src/main/java/net/coreprotect/config/ConfigHandler.java +++ b/src/main/java/net/coreprotect/config/ConfigHandler.java @@ -26,6 +26,7 @@ import net.coreprotect.bukkit.BukkitAdapter; import net.coreprotect.consumer.Queue; import net.coreprotect.database.Database; +import net.coreprotect.database.StatementUtils; import net.coreprotect.database.statement.UserStatement; import net.coreprotect.language.Phrase; import net.coreprotect.listener.ListenerHandler; @@ -167,17 +168,17 @@ private static void loadConfig() { ConfigFile.init(ConfigFile.LANGUAGE_CACHE); // load translation cache // Enforce "co_" table prefix if using SQLite. - if (!Config.getGlobal().MYSQL) { - Config.getGlobal().PREFIX = "co_"; + if (Config.getGlobal().DB_TYPE == DatabaseType.SQLITE) { + Config.getGlobal().DB_PREFIX = "co_"; } - ConfigHandler.host = Config.getGlobal().MYSQL_HOST; - ConfigHandler.port = Config.getGlobal().MYSQL_PORT; - ConfigHandler.database = Config.getGlobal().MYSQL_DATABASE; - ConfigHandler.username = Config.getGlobal().MYSQL_USERNAME; - ConfigHandler.password = Config.getGlobal().MYSQL_PASSWORD; + ConfigHandler.host = Config.getGlobal().DB_HOST; + ConfigHandler.port = Config.getGlobal().DB_PORT; + ConfigHandler.database = Config.getGlobal().DB_DATABASE; + ConfigHandler.username = Config.getGlobal().DB_USERNAME; + ConfigHandler.password = Config.getGlobal().DB_PASSWORD; ConfigHandler.maximumPoolSize = Config.getGlobal().MAXIMUM_POOL_SIZE; - ConfigHandler.prefix = Config.getGlobal().PREFIX; + ConfigHandler.prefix = Config.getGlobal().DB_PREFIX; ConfigHandler.loadBlacklist(); // Load the blacklist file if it exists. } @@ -190,7 +191,7 @@ public static void loadDatabase() { // close old pool when we reload the database, e.g. in purge command Database.closeConnection(); - if (!Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE == DatabaseType.SQLITE) { try { File tempFile = File.createTempFile("CoreProtect_" + System.currentTimeMillis(), ".tmp"); tempFile.setExecutable(true); @@ -219,8 +220,7 @@ public static void loadDatabase() { catch (Exception e) { e.printStackTrace(); } - } - else { + } else if (Config.getGlobal().DB_TYPE == DatabaseType.MYSQL){ HikariConfig config = new HikariConfig(); try { Class.forName("com.mysql.cj.jdbc.Driver"); @@ -251,6 +251,21 @@ public static void loadDatabase() { config.addDataSourceProperty("allowPublicKeyRetrieval", "true"); config.addDataSourceProperty("useSSL", Config.getGlobal().ENABLE_SSL); + ConfigHandler.hikariDataSource = new HikariDataSource(config); + } else if (Config.getGlobal().DB_TYPE == DatabaseType.PGSQL) { + HikariConfig config = new HikariConfig(); + try { + Class.forName("org.postgresql.Driver"); + config.setDriverClassName("org.postgresql.Driver"); + } catch (Exception e) { + throw new RuntimeException(e); + } + config.setJdbcUrl("jdbc:postgresql://" + ConfigHandler.host + ":" + ConfigHandler.port + "/" + ConfigHandler.database); + config.setUsername(ConfigHandler.username); + config.setPassword(ConfigHandler.password); + config.setMaxLifetime(300000); + config.setKeepaliveTime(60000); + ConfigHandler.hikariDataSource = new HikariDataSource(config); } @@ -259,7 +274,7 @@ public static void loadDatabase() { public static void loadTypes(Statement statement) { try { - String query = "SELECT id,material FROM " + ConfigHandler.prefix + "material_map"; + String query = "SELECT id,material FROM " + StatementUtils.getTableName("material_map"); ResultSet rs = statement.executeQuery(query); ConfigHandler.materials.clear(); ConfigHandler.materialsReversed.clear(); @@ -276,7 +291,7 @@ public static void loadTypes(Statement statement) { } rs.close(); - query = "SELECT id,data FROM " + ConfigHandler.prefix + "blockdata_map"; + query = "SELECT id,data FROM " + StatementUtils.getTableName("blockdata_map"); rs = statement.executeQuery(query); ConfigHandler.blockdata.clear(); ConfigHandler.blockdataReversed.clear(); @@ -293,7 +308,7 @@ public static void loadTypes(Statement statement) { } rs.close(); - query = "SELECT id,art FROM " + ConfigHandler.prefix + "art_map"; + query = "SELECT id,art FROM " + StatementUtils.getTableName("art_map"); rs = statement.executeQuery(query); ConfigHandler.art.clear(); ConfigHandler.artReversed.clear(); @@ -310,7 +325,7 @@ public static void loadTypes(Statement statement) { } rs.close(); - query = "SELECT id,entity FROM " + ConfigHandler.prefix + "entity_map"; + query = "SELECT id,entity FROM " + StatementUtils.getTableName("entity_map"); rs = statement.executeQuery(query); ConfigHandler.entities.clear(); ConfigHandler.entitiesReversed.clear(); @@ -334,7 +349,7 @@ public static void loadTypes(Statement statement) { public static void loadWorlds(Statement statement) { try { - String query = "SELECT id,world FROM " + ConfigHandler.prefix + "world"; + String query = "SELECT id,world FROM " + StatementUtils.getTableName("world"); ResultSet rs = statement.executeQuery(query); ConfigHandler.worlds.clear(); ConfigHandler.worldsReversed.clear(); @@ -379,7 +394,7 @@ private static boolean checkDatabaseLock(Statement statement) { locked = false; unixtimestamp = (int) (System.currentTimeMillis() / 1000L); int checkTime = unixtimestamp - 15; - String query = "SELECT * FROM " + ConfigHandler.prefix + "database_lock WHERE rowid='1' AND status='1' AND time >= '" + checkTime + "' LIMIT 1"; + String query = "SELECT * FROM " + StatementUtils.getTableName("database_lock") + " WHERE rowid='1' AND status='1' AND time >= '" + checkTime + "' LIMIT 1"; ResultSet rs = statement.executeQuery(query); while (rs.next()) { if (unixtimestamp < waitTime) { diff --git a/src/main/java/net/coreprotect/config/DatabaseType.java b/src/main/java/net/coreprotect/config/DatabaseType.java new file mode 100644 index 000000000..0b4963003 --- /dev/null +++ b/src/main/java/net/coreprotect/config/DatabaseType.java @@ -0,0 +1,7 @@ +package net.coreprotect.config; + +public enum DatabaseType { + SQLITE, + MYSQL, + PGSQL; // PostgreSQL +} \ No newline at end of file diff --git a/src/main/java/net/coreprotect/consumer/process/ArtInsertProcess.java b/src/main/java/net/coreprotect/consumer/process/ArtInsertProcess.java index 1479f7f8f..9a0ac7e02 100644 --- a/src/main/java/net/coreprotect/consumer/process/ArtInsertProcess.java +++ b/src/main/java/net/coreprotect/consumer/process/ArtInsertProcess.java @@ -4,6 +4,7 @@ import java.sql.Statement; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.database.StatementUtils; import net.coreprotect.database.statement.MaterialStatement; import net.coreprotect.language.Phrase; import net.coreprotect.language.Selector; @@ -13,7 +14,7 @@ class ArtInsertProcess { static void process(PreparedStatement preparedStmt, Statement statement, int batchCount, Object name, int materialId) { if (name instanceof String) { - String query = "SELECT id FROM " + ConfigHandler.prefix + "art_map WHERE id = '" + materialId + "' LIMIT 0, 1"; + String query = "SELECT id FROM " + StatementUtils.getTableName("art_map") + " WHERE id = '" + materialId + "' LIMIT 1"; boolean hasMaterial = MaterialStatement.hasMaterial(statement, query); if (!hasMaterial) { MaterialStatement.insert(preparedStmt, batchCount, materialId, (String) name); diff --git a/src/main/java/net/coreprotect/consumer/process/BlockDataInsertProcess.java b/src/main/java/net/coreprotect/consumer/process/BlockDataInsertProcess.java index 2e53366ac..2487674a9 100644 --- a/src/main/java/net/coreprotect/consumer/process/BlockDataInsertProcess.java +++ b/src/main/java/net/coreprotect/consumer/process/BlockDataInsertProcess.java @@ -4,6 +4,7 @@ import java.sql.Statement; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.database.StatementUtils; import net.coreprotect.database.statement.MaterialStatement; import net.coreprotect.language.Phrase; import net.coreprotect.language.Selector; @@ -13,7 +14,7 @@ class BlockDataInsertProcess { static void process(PreparedStatement preparedStmt, Statement statement, int batchCount, Object name, int materialId) { if (name instanceof String) { - String query = "SELECT id FROM " + ConfigHandler.prefix + "blockdata_map WHERE id = '" + materialId + "' LIMIT 0, 1"; + String query = "SELECT id FROM " + StatementUtils.getTableName("blockdata_map") + " WHERE id = '" + materialId + "' LIMIT 1"; boolean hasMaterial = MaterialStatement.hasMaterial(statement, query); if (!hasMaterial) { MaterialStatement.insert(preparedStmt, batchCount, materialId, (String) name); diff --git a/src/main/java/net/coreprotect/consumer/process/EntityInsertProcess.java b/src/main/java/net/coreprotect/consumer/process/EntityInsertProcess.java index f6bae6783..84e5f2d2e 100644 --- a/src/main/java/net/coreprotect/consumer/process/EntityInsertProcess.java +++ b/src/main/java/net/coreprotect/consumer/process/EntityInsertProcess.java @@ -4,6 +4,7 @@ import java.sql.Statement; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.database.StatementUtils; import net.coreprotect.database.statement.MaterialStatement; import net.coreprotect.language.Phrase; import net.coreprotect.language.Selector; @@ -13,7 +14,7 @@ class EntityInsertProcess { static void process(PreparedStatement preparedStmt, Statement statement, int batchCount, Object name, int materialId) { if (name instanceof String) { - String query = "SELECT id FROM " + ConfigHandler.prefix + "entity_map WHERE id = '" + materialId + "' LIMIT 0, 1"; + String query = "SELECT id FROM " + StatementUtils.getTableName("entity_map") + " WHERE id = '" + materialId + "' LIMIT 1"; boolean hasMaterial = MaterialStatement.hasMaterial(statement, query); if (!hasMaterial) { MaterialStatement.insert(preparedStmt, batchCount, materialId, (String) name); diff --git a/src/main/java/net/coreprotect/consumer/process/EntitySpawnProcess.java b/src/main/java/net/coreprotect/consumer/process/EntitySpawnProcess.java index f9dbbe43d..25611f595 100644 --- a/src/main/java/net/coreprotect/consumer/process/EntitySpawnProcess.java +++ b/src/main/java/net/coreprotect/consumer/process/EntitySpawnProcess.java @@ -6,7 +6,7 @@ import org.bukkit.block.BlockState; import org.bukkit.entity.EntityType; -import net.coreprotect.config.ConfigHandler; +import net.coreprotect.database.StatementUtils; import net.coreprotect.database.statement.EntityStatement; import net.coreprotect.utility.entity.EntityUtil; @@ -16,7 +16,7 @@ static void process(Statement statement, Object object, int rowId) { if (object instanceof Object[]) { BlockState block = (BlockState) ((Object[]) object)[0]; EntityType type = (EntityType) ((Object[]) object)[1]; - String query = "SELECT data FROM " + ConfigHandler.prefix + "entity WHERE rowid='" + rowId + "' LIMIT 0, 1"; + String query = "SELECT data FROM " + StatementUtils.getTableName("entity") + " WHERE rowid='" + rowId + "' LIMIT 1"; List data = EntityStatement.getData(statement, block, query); EntityUtil.spawnEntity(block, type, data); } diff --git a/src/main/java/net/coreprotect/consumer/process/MaterialInsertProcess.java b/src/main/java/net/coreprotect/consumer/process/MaterialInsertProcess.java index 26dcf7210..c12c99689 100644 --- a/src/main/java/net/coreprotect/consumer/process/MaterialInsertProcess.java +++ b/src/main/java/net/coreprotect/consumer/process/MaterialInsertProcess.java @@ -4,6 +4,7 @@ import java.sql.Statement; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.database.StatementUtils; import net.coreprotect.database.statement.MaterialStatement; import net.coreprotect.language.Phrase; import net.coreprotect.language.Selector; @@ -13,7 +14,7 @@ class MaterialInsertProcess { static void process(PreparedStatement preparedStmt, Statement statement, int batchCount, Object name, int materialId) { if (name instanceof String) { - String query = "SELECT id FROM " + ConfigHandler.prefix + "material_map WHERE id = '" + materialId + "' LIMIT 0, 1"; + String query = "SELECT id FROM " + StatementUtils.getTableName("material_map") + " WHERE id = '" + materialId + "' LIMIT 1"; boolean hasMaterial = MaterialStatement.hasMaterial(statement, query); if (!hasMaterial) { MaterialStatement.insert(preparedStmt, batchCount, materialId, (String) name); diff --git a/src/main/java/net/coreprotect/consumer/process/SignUpdateProcess.java b/src/main/java/net/coreprotect/consumer/process/SignUpdateProcess.java index c410d98c1..3e464c593 100644 --- a/src/main/java/net/coreprotect/consumer/process/SignUpdateProcess.java +++ b/src/main/java/net/coreprotect/consumer/process/SignUpdateProcess.java @@ -6,6 +6,7 @@ import org.bukkit.block.BlockState; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.database.StatementUtils; import net.coreprotect.database.statement.SignStatement; import net.coreprotect.utility.Util; @@ -24,12 +25,11 @@ static void process(Statement statement, Object object, String user, int action, int z = block.getZ(); int wid = Util.getWorldId(block.getWorld().getName()); int userid = ConfigHandler.playerIdCache.get(user.toLowerCase(Locale.ROOT)); - String query = ""; + String query; if (action == 0) { - query = "SELECT color, color_secondary, data, waxed, face, line_1, line_2, line_3, line_4, line_5, line_6, line_7, line_8 FROM " + ConfigHandler.prefix + "sign WHERE user='" + userid + "' AND wid='" + wid + "' AND x='" + x + "' AND z='" + z + "' AND y='" + y + "' AND time < '" + time + "' ORDER BY rowid DESC LIMIT 0, 1"; - } - else { - query = "SELECT color, color_secondary, data, waxed, face, line_1, line_2, line_3, line_4, line_5, line_6, line_7, line_8 FROM " + ConfigHandler.prefix + "sign WHERE user='" + userid + "' AND wid='" + wid + "' AND x='" + x + "' AND z='" + z + "' AND y='" + y + "' AND time >= '" + time + "' ORDER BY rowid ASC LIMIT 0, 1"; + query = "SELECT color, color_secondary, data, waxed, face, line_1, line_2, line_3, line_4, line_5, line_6, line_7, line_8 FROM " + StatementUtils.getTableName("sign") + " WHERE user='" + userid + "' AND wid='" + wid + "' AND x='" + x + "' AND z='" + z + "' AND y='" + y + "' AND time < '" + time + "' ORDER BY rowid DESC LIMIT 1"; + } else { + query = "SELECT color, color_secondary, data, waxed, face, line_1, line_2, line_3, line_4, line_5, line_6, line_7, line_8 FROM " + StatementUtils.getTableName("sign") + " WHERE user='" + userid + "' AND wid='" + wid + "' AND x='" + x + "' AND z='" + z + "' AND y='" + y + "' AND time >= '" + time + "' ORDER BY rowid ASC LIMIT 1"; } SignStatement.getData(statement, block, query); Util.updateBlock(block); diff --git a/src/main/java/net/coreprotect/consumer/process/SkullUpdateProcess.java b/src/main/java/net/coreprotect/consumer/process/SkullUpdateProcess.java index d9a5277ea..a54be38e1 100644 --- a/src/main/java/net/coreprotect/consumer/process/SkullUpdateProcess.java +++ b/src/main/java/net/coreprotect/consumer/process/SkullUpdateProcess.java @@ -18,7 +18,7 @@ static void process(Statement statement, Object object, int rowId) { */ if (object instanceof BlockState) { BlockState block = (BlockState) object; - String query = "SELECT owner FROM " + ConfigHandler.prefix + "skull WHERE rowid='" + rowId + "' LIMIT 0, 1"; + String query = "SELECT owner FROM " + ConfigHandler.prefix + "skull WHERE rowid='" + rowId + "' LIMIT 1"; SkullStatement.getData(statement, block, query); Util.updateBlock(block); } diff --git a/src/main/java/net/coreprotect/consumer/process/WorldInsertProcess.java b/src/main/java/net/coreprotect/consumer/process/WorldInsertProcess.java index 7da30f9e4..395b14ac8 100644 --- a/src/main/java/net/coreprotect/consumer/process/WorldInsertProcess.java +++ b/src/main/java/net/coreprotect/consumer/process/WorldInsertProcess.java @@ -14,7 +14,7 @@ class WorldInsertProcess { static void process(PreparedStatement preparedStmt, int batchCount, Statement statement, Object world, int worldId) { if (world instanceof String) { - String query = "SELECT id FROM " + ConfigHandler.prefix + "world WHERE id = '" + worldId + "' LIMIT 0, 1"; + String query = "SELECT id FROM " + ConfigHandler.prefix + "world WHERE id = '" + worldId + "' LIMIT 1"; boolean hasMaterial = MaterialStatement.hasMaterial(statement, query); if (!hasMaterial) { WorldStatement.insert(preparedStmt, batchCount, worldId, (String) world); diff --git a/src/main/java/net/coreprotect/database/Database.java b/src/main/java/net/coreprotect/database/Database.java index 844c8f05d..5d9b0c410 100755 --- a/src/main/java/net/coreprotect/database/Database.java +++ b/src/main/java/net/coreprotect/database/Database.java @@ -17,6 +17,7 @@ import net.coreprotect.config.Config; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.config.DatabaseType; import net.coreprotect.consumer.Consumer; import net.coreprotect.consumer.Queue; import net.coreprotect.consumer.process.Process; @@ -47,11 +48,10 @@ public static void beginTransaction(Statement statement) { Consumer.transacting = true; try { - if (Config.getGlobal().MYSQL) { - statement.executeUpdate("START TRANSACTION"); - } - else { + if (Config.getGlobal().DB_TYPE == DatabaseType.SQLITE) { statement.executeUpdate("BEGIN TRANSACTION"); + } else { + statement.executeUpdate("START TRANSACTION"); } } catch (Exception e) { @@ -64,11 +64,10 @@ public static void commitTransaction(Statement statement) throws Exception { while (true) { try { - if (Config.getGlobal().MYSQL) { - statement.executeUpdate("COMMIT"); - } - else { + if (Config.getGlobal().DB_TYPE == DatabaseType.SQLITE) { statement.executeUpdate("COMMIT TRANSACTION"); + } else { + statement.executeUpdate("COMMIT"); } } catch (Exception e) { @@ -90,7 +89,7 @@ public static void commitTransaction(Statement statement) throws Exception { } public static void performCheckpoint(Statement statement) throws SQLException { - if (!Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE == DatabaseType.SQLITE) { statement.executeUpdate("PRAGMA wal_checkpoint(TRUNCATE)"); } } @@ -107,7 +106,7 @@ public static void setMultiInt(PreparedStatement statement, int value, int count } public static boolean hasReturningKeys() { - return (!Config.getGlobal().MYSQL && ConfigHandler.SERVER_VERSION >= 20); + return (Config.getGlobal().DB_TYPE == DatabaseType.SQLITE && ConfigHandler.SERVER_VERSION >= 20); } public static void containerBreakCheck(String user, Material type, Object container, ItemStack[] contents, Location location) { @@ -147,18 +146,22 @@ public static Connection getConnection(boolean force, boolean startup, boolean o if (!force && (ConfigHandler.converterRunning || ConfigHandler.purgeRunning)) { return connection; } - if (Config.getGlobal().MYSQL) { + DatabaseType dbType = Config.getGlobal().DB_TYPE; + if (dbType != DatabaseType.SQLITE) { try { connection = ConfigHandler.hikariDataSource.getConnection(); ConfigHandler.databaseReachable = true; } catch (Exception e) { ConfigHandler.databaseReachable = false; - Chat.sendConsoleMessage(Color.RED + "[CoreProtect] " + Phrase.build(Phrase.MYSQL_UNAVAILABLE)); + if (dbType == DatabaseType.MYSQL) { + Chat.sendConsoleMessage(Color.RED + "[CoreProtect] " + Phrase.build(Phrase.MYSQL_UNAVAILABLE)); + } else if (dbType == DatabaseType.PGSQL){ + Chat.sendConsoleMessage(Color.RED + "[CoreProtect] " + Phrase.build(Phrase.PGSQL_UNAVAILABLE)); + } e.printStackTrace(); } - } - else { + } else { if (Consumer.transacting && onlyCheckTransacting) { Consumer.interrupt = true; } @@ -219,20 +222,20 @@ else if (table == 2) { public static PreparedStatement prepareStatement(Connection connection, int type, boolean keys) { PreparedStatement preparedStatement = null; try { - String signInsert = "INSERT INTO " + ConfigHandler.prefix + "sign (time, user, wid, x, y, z, action, color, color_secondary, data, waxed, face, line_1, line_2, line_3, line_4, line_5, line_6, line_7, line_8) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - String blockInsert = "INSERT INTO " + ConfigHandler.prefix + "block (time, user, wid, x, y, z, type, data, meta, blockdata, action, rolled_back) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - String skullInsert = "INSERT INTO " + ConfigHandler.prefix + "skull (time, owner) VALUES (?, ?)"; - String containerInsert = "INSERT INTO " + ConfigHandler.prefix + "container (time, user, wid, x, y, z, type, data, amount, metadata, action, rolled_back) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - String itemInsert = "INSERT INTO " + ConfigHandler.prefix + "item (time, user, wid, x, y, z, type, data, amount, action, rolled_back) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - String worldInsert = "INSERT INTO " + ConfigHandler.prefix + "world (id, world) VALUES (?, ?)"; - String chatInsert = "INSERT INTO " + ConfigHandler.prefix + "chat (time, user, wid, x, y, z, message) VALUES (?, ?, ?, ?, ?, ?, ?)"; - String commandInsert = "INSERT INTO " + ConfigHandler.prefix + "command (time, user, wid, x, y, z, message) VALUES (?, ?, ?, ?, ?, ?, ?)"; - String sessionInsert = "INSERT INTO " + ConfigHandler.prefix + "session (time, user, wid, x, y, z, action) VALUES (?, ?, ?, ?, ?, ?, ?)"; - String entityInsert = "INSERT INTO " + ConfigHandler.prefix + "entity (time, data) VALUES (?, ?)"; - String materialInsert = "INSERT INTO " + ConfigHandler.prefix + "material_map (id, material) VALUES (?, ?)"; - String artInsert = "INSERT INTO " + ConfigHandler.prefix + "art_map (id, art) VALUES (?, ?)"; - String entityMapInsert = "INSERT INTO " + ConfigHandler.prefix + "entity_map (id, entity) VALUES (?, ?)"; - String blockdataInsert = "INSERT INTO " + ConfigHandler.prefix + "blockdata_map (id, data) VALUES (?, ?)"; + String signInsert = "INSERT INTO " + StatementUtils.getTableName("sign") + " (time, \"user\", wid, x, y, z, action, color, color_secondary, data, waxed, face, line_1, line_2, line_3, line_4, line_5, line_6, line_7, line_8) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + String blockInsert = "INSERT INTO " + StatementUtils.getTableName("block") + " (time, \"user\", wid, x, y, z, type, data, meta, blockdata, action, rolled_back) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + String skullInsert = "INSERT INTO " + StatementUtils.getTableName("skull") + " (time, owner) VALUES (?, ?)"; + String containerInsert = "INSERT INTO " + StatementUtils.getTableName("container") + " (time, \"user\", wid, x, y, z, type, data, amount, metadata, action, rolled_back) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + String itemInsert = "INSERT INTO " + StatementUtils.getTableName("item") + " (time, \"user\", wid, x, y, z, type, data, amount, action, rolled_back) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + String worldInsert = "INSERT INTO " + StatementUtils.getTableName("world") + " (id, world) VALUES (?, ?)"; + String chatInsert = "INSERT INTO " + StatementUtils.getTableName("chat") + " (time, \"user\", wid, x, y, z, message) VALUES (?, ?, ?, ?, ?, ?, ?)"; + String commandInsert = "INSERT INTO " + StatementUtils.getTableName("command") + " (time, \"user\", wid, x, y, z, message) VALUES (?, ?, ?, ?, ?, ?, ?)"; + String sessionInsert = "INSERT INTO " + StatementUtils.getTableName("session") + " (time, \"user\", wid, x, y, z, action) VALUES (?, ?, ?, ?, ?, ?, ?)"; + String entityInsert = "INSERT INTO " + StatementUtils.getTableName("entity") + " (time, data) VALUES (?, ?)"; + String materialInsert = "INSERT INTO " + StatementUtils.getTableName("material_map") + " (id, material) VALUES (?, ?)"; + String artInsert = "INSERT INTO " + StatementUtils.getTableName("art_map") + " (id, art) VALUES (?, ?)"; + String entityMapInsert = "INSERT INTO " + StatementUtils.getTableName("entity_map") + " (id, entity) VALUES (?, ?)"; + String blockdataInsert = "INSERT INTO " + StatementUtils.getTableName("blockdata_map") + " (id, data) VALUES (?, ?)"; switch (type) { case SIGN: @@ -310,7 +313,7 @@ private static PreparedStatement prepareStatement(Connection connection, String private static void initializeTables(String prefix, Statement statement) { try { - if (!Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE == DatabaseType.SQLITE) { if (!Config.getGlobal().DISABLE_WAL) { statement.executeUpdate("PRAGMA journal_mode=WAL;"); } @@ -341,8 +344,90 @@ private static void initializeTables(String prefix, Statement statement) { public static void createDatabaseTables(String prefix, boolean purge) { ConfigHandler.databaseTables.clear(); ConfigHandler.databaseTables.addAll(Arrays.asList("art_map", "block", "chat", "command", "container", "item", "database_lock", "entity", "entity_map", "material_map", "blockdata_map", "session", "sign", "skull", "user", "username_log", "version", "world")); + DatabaseType dbType = Config.getGlobal().DB_TYPE; + if (dbType == DatabaseType.PGSQL) { + boolean success = false; + try (Connection connection = Database.getConnection(true, true, true, 0)) { + if (connection != null) { + Statement statement = connection.createStatement(); + statement.executeUpdate("create table if not exists \"" + prefix + "art_map\" (\"rowid\" bigserial primary key not null, \"id\" integer not null, \"art\" varchar(255) not null)"); + statement.executeUpdate("create index if not exists \"" + prefix + "art_map_id_index\" on \"" + prefix + "art_map\" (\"id\")"); + + statement.executeUpdate("create table if not exists \"" + prefix + "block\" (\"rowid\" bigserial primary key not null, \"time\" integer not null, \"user\" integer not null, \"wid\" integer not null, \"x\" integer not null, \"y\" smallint not null, \"z\" integer not null, \"type\" integer not null, \"data\" integer not null, \"meta\" bytea null, \"blockdata\" bytea null, \"action\" smallint not null, \"rolled_back\" smallint not null)"); + statement.executeUpdate("create index if not exists \"" + prefix + "block_wid_x_z_time_index\" on \"" + prefix + "block\" (\"wid\", \"x\", \"z\", \"time\")"); + statement.executeUpdate("create index if not exists \"" + prefix + "block_user_time_index\" on \"" + prefix + "block\" (\"user\", \"time\")"); + statement.executeUpdate("create index if not exists \"" + prefix + "block_type_time_index\" on \"" + prefix + "block\" (\"type\", \"time\")"); + + statement.executeUpdate("create table if not exists \"" + prefix + "chat\" (\"rowid\" bigserial primary key not null, \"time\" integer not null, \"user\" integer not null, \"wid\" integer not null, \"x\" integer not null, \"y\" smallint not null, \"z\" integer not null, \"message\" text not null)"); + statement.executeUpdate("create index if not exists \"" + prefix + "chat_time_index\" on \"" + prefix + "chat\" (\"time\")"); + statement.executeUpdate("create index if not exists \"" + prefix + "chat_user_time_index\" on \"" + prefix + "chat\" (\"user\", \"time\")"); + statement.executeUpdate("create index if not exists \"" + prefix + "chat_wid_x_z_time_index\" on \"" + prefix + "chat\" (\"wid\", \"x\", \"z\", \"time\")"); + + statement.executeUpdate("create table if not exists \"" + prefix + "command\" (\"rowid\" bigserial primary key not null, \"time\" integer not null, \"user\" integer not null, \"wid\" integer not null, \"x\" integer not null, \"y\" smallint not null, \"z\" integer not null, \"message\" text not null)"); + statement.executeUpdate("create index if not exists \"" + prefix + "command_time_index\" on \"" + prefix + "command\" (\"time\")"); + statement.executeUpdate("create index if not exists \"" + prefix + "command_user_time_index\" on \"" + prefix + "command\" (\"user\", \"time\")"); + statement.executeUpdate("create index if not exists \"" + prefix + "command_wid_x_z_time_index\" on \"" + prefix + "command\" (\"wid\", \"x\", \"z\", \"time\")"); + + statement.executeUpdate("create table if not exists \"" + prefix + "container\" (\"rowid\" bigserial primary key not null, \"time\" integer not null, \"user\" integer not null, \"wid\" integer not null, \"x\" integer not null, \"y\" smallint not null, \"z\" integer not null, \"type\" integer not null, \"data\" integer not null, \"amount\" integer not null, \"metadata\" bytea null, \"action\" smallint not null, \"rolled_back\" smallint not null)"); + statement.executeUpdate("create index if not exists \"" + prefix + "container_wid_x_z_time_index\" on \"" + prefix + "container\" (\"wid\", \"x\", \"z\", \"time\")"); + statement.executeUpdate("create index if not exists \"" + prefix + "container_user_time_index\" on \"" + prefix + "container\" (\"user\", \"time\")"); + statement.executeUpdate("create index if not exists \"" + prefix + "container_type_time_index\" on \"" + prefix + "container\" (\"type\", \"time\")"); + + statement.executeUpdate("create table if not exists \"" + prefix + "item\" (\"rowid\" bigserial primary key not null, \"time\" integer not null, \"user\" integer not null, \"wid\" integer not null, \"x\" integer not null, \"y\" smallint not null, \"z\" integer not null, \"type\" integer not null, \"data\" bytea not null, \"amount\" integer not null, \"action\" smallint not null, \"rolled_back\" smallint not null)"); + statement.executeUpdate("create index if not exists \"" + prefix + "item_wid_x_z_time_index\" on \"" + prefix + "item\" (\"wid\", \"x\", \"z\", \"time\")"); + statement.executeUpdate("create index if not exists \"" + prefix + "item_user_time_index\" on \"" + prefix + "item\" (\"user\", \"time\")"); + statement.executeUpdate("create index if not exists \"" + prefix + "item_type_time_index\" on \"" + prefix + "item\" (\"type\", \"time\")"); + + statement.executeUpdate("create table if not exists \"" + prefix + "database_lock\" (\"rowid\" bigserial primary key not null, \"status\" smallint not null, \"time\" integer not null)"); + statement.executeUpdate("create table if not exists \"" + prefix + "entity\" (\"rowid\" bigserial primary key not null, \"time\" integer not null, \"data\" bytea not null)"); - if (Config.getGlobal().MYSQL) { + statement.executeUpdate("create table if not exists \"" + prefix + "entity_map\" (\"rowid\" bigserial primary key not null, \"id\" integer not null, \"entity\" varchar(255) not null)"); + + statement.executeUpdate("create index if not exists \"" + prefix + "entity_map_id_index\" on \"" + prefix + "entity_map\" (\"id\")"); + + statement.executeUpdate("create table if not exists \"" + prefix + "material_map\" (\"rowid\" bigserial primary key not null, \"id\" integer not null, \"material\" varchar(255) not null)"); + statement.executeUpdate("create index if not exists \"" + prefix + "material_map_id_index\" on \"" + prefix + "material_map\" (\"id\")"); + + statement.executeUpdate("create table if not exists \"" + prefix + "blockdata_map\" (\"rowid\" bigserial primary key not null, \"id\" integer not null, \"data\" varchar(255) not null)"); + statement.executeUpdate("create index if not exists \"" + prefix + "blockdata_map_id_index\" on \"" + prefix + "blockdata_map\" (\"id\")"); + + statement.executeUpdate("create table if not exists \"" + prefix + "session\" (\"rowid\" bigserial primary key not null, \"time\" integer not null, \"user\" integer not null, \"wid\" integer not null, \"x\" integer not null, \"y\" smallint not null, \"z\" integer not null, \"action\" smallint not null)"); + statement.executeUpdate("create index if not exists \"" + prefix + "session_wid_x_y_time_index\" on \"" + prefix + "session\" (\"wid\", \"x\", \"y\", \"time\")"); + statement.executeUpdate("create index if not exists \"" + prefix + "session_action_time_index\" on \"" + prefix + "session\" (\"action\", \"time\")"); + statement.executeUpdate("create index if not exists \"" + prefix + "session_user_time_index\" on \"" + prefix + "session\" (\"user\", \"time\")"); + statement.executeUpdate("create index if not exists \"" + prefix + "session_time_index\" on \"" + prefix + "session\" (\"time\")"); + + statement.executeUpdate("create table if not exists \"" + prefix + "sign\" (\"rowid\" bigserial primary key not null, \"time\" integer not null, \"user\" integer not null, \"wid\" integer not null, \"x\" integer not null, \"y\" smallint not null, \"z\" integer not null, \"action\" smallint not null, \"color\" integer not null, \"color_secondary\" integer not null, \"data\" smallint not null, \"waxed\" smallint not null, \"face\" smallint not null, \"line_1\" varchar(100) not null, \"line_2\" varchar(100) not null, \"line_3\" varchar(100) not null, \"line_4\" varchar(100) not null, \"line_5\" varchar(100) not null, \"line_6\" varchar(100) not null, \"line_7\" varchar(100) not null, \"line_8\" varchar(100) not null)"); + statement.executeUpdate("create index if not exists \"" + prefix + "sign_wid_x_z_time_index\" on \"" + prefix + "sign\" (\"wid\", \"x\", \"z\", \"time\")"); + statement.executeUpdate("create index if not exists \"" + prefix + "sign_user_time_index\" on \"" + prefix + "sign\" (\"user\", \"time\")"); + statement.executeUpdate("create index if not exists \"" + prefix + "sign_time_index\" on \"" + prefix + "sign\" (\"time\")"); + + statement.executeUpdate("create table if not exists \"" + prefix + "skull\" (\"rowid\" bigserial primary key not null, \"time\" integer not null, \"owner\" varchar(64) not null)"); + + statement.executeUpdate("create table if not exists \"" + prefix + "user\" (\"rowid\" bigserial primary key not null, \"time\" integer not null, \"user\" varchar(255) not null, \"uuid\" uuid null)"); + statement.executeUpdate("create index if not exists \"" + prefix + "user_user_index\" on \"" + prefix + "user\" (\"user\")"); + statement.executeUpdate("create index if not exists \"" + prefix + "user_uuid_index\" on \"" + prefix + "user\" (\"uuid\")"); + + statement.executeUpdate("create table if not exists \"" + prefix + "username_log\" (\"rowid\" bigserial primary key not null, \"time\" integer not null, \"uuid\" uuid not null, \"user\" varchar(100) not null)"); + statement.executeUpdate("create index if not exists \"" + prefix + "username_log_uuid_user_index\" on \"username_log\" (\"uuid\", \"user\")"); + + statement.executeUpdate("create table if not exists \"" + prefix + "version\" (\"rowid\" bigserial primary key not null, \"time\" integer not null, \"version\" varchar(16) not null)"); + + statement.executeUpdate("create table if not exists \"" + prefix + "world\" (\"rowid\" bigserial primary key not null, \"id\" integer not null, \"world\" varchar(255) not null)"); + statement.executeUpdate("create index if not exists \"" + prefix + "world_id_index\" on \"" + prefix + "world\" (\"id\")"); + if (!purge) { + initializeTables(prefix, statement); + } + statement.close(); + success = true; + } + } catch (Exception e) { + e.printStackTrace(); + } + if (!success) { + Config.getGlobal().DB_TYPE = DatabaseType.SQLITE; + } + } else if (dbType == DatabaseType.MYSQL) { boolean success = false; try (Connection connection = Database.getConnection(true, true, true, 0)) { if (connection != null) { @@ -391,10 +476,9 @@ public static void createDatabaseTables(String prefix, boolean purge) { e.printStackTrace(); } if (!success) { - Config.getGlobal().MYSQL = false; + Config.getGlobal().DB_TYPE = DatabaseType.SQLITE; } - } - if (!Config.getGlobal().MYSQL) { + } else { try (Connection connection = Database.getConnection(true, 0)) { Statement statement = connection.createStatement(); List tableData = new ArrayList<>(); diff --git a/src/main/java/net/coreprotect/database/Lookup.java b/src/main/java/net/coreprotect/database/Lookup.java index 93b9b2b9f..bfc21538b 100755 --- a/src/main/java/net/coreprotect/database/Lookup.java +++ b/src/main/java/net/coreprotect/database/Lookup.java @@ -19,6 +19,7 @@ import net.coreprotect.bukkit.BukkitAdapter; import net.coreprotect.config.Config; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.config.DatabaseType; import net.coreprotect.consumer.Consumer; import net.coreprotect.consumer.Queue; import net.coreprotect.database.logger.ItemLogger; @@ -646,7 +647,7 @@ else if (inventoryQuery || actionExclude.length() > 0 || includeBlock.length() > String baseQuery = ((!includeEntity.isEmpty() || !excludeEntity.isEmpty()) ? queryEntity : queryBlock); if (limitOffset > -1 && limitCount > -1) { - queryLimit = " LIMIT " + limitOffset + ", " + limitCount + ""; + queryLimit = " LIMIT " + limitCount + " OFFSET " + limitOffset; unionLimit = " ORDER BY time DESC, id DESC LIMIT " + (limitOffset + limitCount) + ""; } @@ -687,13 +688,13 @@ else if (actionList.contains(11)) { if (count) { rows = "COUNT(*) as count"; - queryLimit = " LIMIT 0, 3"; + queryLimit = " LIMIT 3"; queryOrder = ""; unionLimit = ""; } String unionSelect = "SELECT * FROM ("; - if (Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE != DatabaseType.SQLITE) { if (queryTable.equals("block")) { if (includeBlock.length() > 0 || includeEntity.length() > 0) { index = "USE INDEX(type) IGNORE INDEX(user,wid) "; @@ -819,7 +820,7 @@ public static String whoPlaced(Statement statement, BlockState block) { int z = block.getZ(); int time = (int) (System.currentTimeMillis() / 1000L); int worldId = Util.getWorldId(block.getWorld().getName()); - String query = "SELECT user,type FROM " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND rolled_back IN(0,2) AND action='1' ORDER BY rowid DESC LIMIT 0, 1"; + String query = "SELECT user,type FROM " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND rolled_back IN(0,2) AND action='1' ORDER BY rowid DESC LIMIT 1"; ResultSet results = statement.executeQuery(query); while (results.next()) { diff --git a/src/main/java/net/coreprotect/database/StatementUtils.java b/src/main/java/net/coreprotect/database/StatementUtils.java new file mode 100644 index 000000000..dadba20e6 --- /dev/null +++ b/src/main/java/net/coreprotect/database/StatementUtils.java @@ -0,0 +1,27 @@ +package net.coreprotect.database; + +import java.util.Objects; + +import org.jetbrains.annotations.NotNull; + +import net.coreprotect.config.ConfigHandler; + +public final class StatementUtils { + private StatementUtils() { + } + + public static String getTableName(@NotNull String table) { + Objects.requireNonNull(table, "table cannot be null"); + return "\"" + ConfigHandler.prefix + table + "\""; + } + + public static String getLimit(int limit, int offset) { + if (limit <= 0) { + throw new IllegalArgumentException("limit must be greater than 0"); + } + if (offset < 0) { + throw new IllegalArgumentException("offset cannot be negative"); + } + return "LIMIT " + limit + " OFFSET " + offset; + } +} \ No newline at end of file diff --git a/src/main/java/net/coreprotect/database/logger/UsernameLogger.java b/src/main/java/net/coreprotect/database/logger/UsernameLogger.java index a639c1465..3119223f9 100644 --- a/src/main/java/net/coreprotect/database/logger/UsernameLogger.java +++ b/src/main/java/net/coreprotect/database/logger/UsernameLogger.java @@ -3,9 +3,14 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; +import java.sql.Types; import java.util.Locale; +import java.util.UUID; +import net.coreprotect.config.Config; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.config.DatabaseType; +import net.coreprotect.database.StatementUtils; public class UsernameLogger { @@ -18,12 +23,16 @@ public static void log(Connection connection, String user, String uuid, int conf if (ConfigHandler.blacklist.get(user.toLowerCase(Locale.ROOT)) != null) { return; } - + DatabaseType dbType = Config.getGlobal().DB_TYPE; int idRow = -1; String userRow = null; - String query = "SELECT rowid as id, user FROM " + ConfigHandler.prefix + "user WHERE uuid = ? LIMIT 0, 1"; + String query = "SELECT rowid as id, user FROM " + StatementUtils.getTableName("user") + " WHERE uuid = ? LIMIT 1"; PreparedStatement preparedStmt = connection.prepareStatement(query); - preparedStmt.setString(1, uuid); + if (dbType == DatabaseType.PGSQL) { + preparedStmt.setObject(1, UUID.fromString(uuid), Types.OTHER); + } else { + preparedStmt.setString(1, uuid); + } ResultSet rs = preparedStmt.executeQuery(); while (rs.next()) { idRow = rs.getInt("id"); @@ -42,9 +51,13 @@ else if (!user.equalsIgnoreCase(userRow)) { } if (update) { - preparedStmt = connection.prepareStatement("UPDATE " + ConfigHandler.prefix + "user SET user = ?, uuid = ? WHERE rowid = ?"); + preparedStmt = connection.prepareStatement("UPDATE " + StatementUtils.getTableName("user") + " SET \"user\" = ?, uuid = ? WHERE rowid = ?"); preparedStmt.setString(1, user); - preparedStmt.setString(2, uuid); + if (dbType == DatabaseType.PGSQL) { + preparedStmt.setObject(2, UUID.fromString(uuid), Types.OTHER); + } else { + preparedStmt.setString(2, uuid); + } preparedStmt.setInt(3, idRow); preparedStmt.executeUpdate(); preparedStmt.close(); @@ -61,9 +74,13 @@ else if (!user.equalsIgnoreCase(userRow)) { } else { boolean foundUUID = false; - query = "SELECT rowid as id FROM " + ConfigHandler.prefix + "username_log WHERE uuid = ? AND user = ? LIMIT 0, 1"; + query = "SELECT rowid as id FROM " + StatementUtils.getTableName("username_log") + " WHERE uuid = ? AND \"user\" = ? LIMIT 1"; PreparedStatement preparedStatement = connection.prepareStatement(query); - preparedStatement.setString(1, uuid); + if (dbType == DatabaseType.PGSQL) { + preparedStmt.setObject(1, UUID.fromString(uuid), Types.OTHER); + } else { + preparedStmt.setString(1, uuid); + } preparedStatement.setString(2, user); rs = preparedStatement.executeQuery(); while (rs.next()) { @@ -78,9 +95,13 @@ else if (!user.equalsIgnoreCase(userRow)) { } if (update && configUsernames == 1) { - preparedStmt = connection.prepareStatement("INSERT INTO " + ConfigHandler.prefix + "username_log (time, uuid, user) VALUES (?, ?, ?)"); + preparedStmt = connection.prepareStatement("INSERT INTO " + StatementUtils.getTableName("username_log") + " (time, uuid, \"user\") VALUES (?, ?, ?)"); preparedStmt.setInt(1, time); - preparedStmt.setString(2, uuid); + if (dbType == DatabaseType.PGSQL) { + preparedStmt.setObject(2, UUID.fromString(uuid), Types.OTHER); + } else { + preparedStmt.setString(2, uuid); + } preparedStmt.setString(3, user); preparedStmt.executeUpdate(); preparedStmt.close(); diff --git a/src/main/java/net/coreprotect/database/lookup/BlockLookup.java b/src/main/java/net/coreprotect/database/lookup/BlockLookup.java index 26147aa2a..904c9c676 100644 --- a/src/main/java/net/coreprotect/database/lookup/BlockLookup.java +++ b/src/main/java/net/coreprotect/database/lookup/BlockLookup.java @@ -57,7 +57,7 @@ else if (commandSender.hasPermission("coreprotect.coreprotect")) { String blockName = block.getType().name().toLowerCase(Locale.ROOT); - String query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action IN(0,1) AND time >= '" + checkTime + "' LIMIT 0, 1"; + String query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action IN(0,1) AND time >= '" + checkTime + "' LIMIT 1"; ResultSet results = statement.executeQuery(query); while (results.next()) { count = results.getInt("count"); @@ -65,7 +65,7 @@ else if (commandSender.hasPermission("coreprotect.coreprotect")) { results.close(); int totalPages = (int) Math.ceil(count / (limit + 0.0)); - query = "SELECT time,user,action,type,data,rolled_back FROM " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action IN(0,1) AND time >= '" + checkTime + "' ORDER BY rowid DESC LIMIT " + page_start + ", " + limit + ""; + query = "SELECT time,user,action,type,data,rolled_back FROM " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action IN(0,1) AND time >= '" + checkTime + "' ORDER BY rowid DESC LIMIT " + limit + " OFFSET " + page_start; results = statement.executeQuery(query); StringBuilder resultTextBuilder = new StringBuilder(); diff --git a/src/main/java/net/coreprotect/database/lookup/ChestTransactionLookup.java b/src/main/java/net/coreprotect/database/lookup/ChestTransactionLookup.java index 4137a0c3c..33779ea2a 100644 --- a/src/main/java/net/coreprotect/database/lookup/ChestTransactionLookup.java +++ b/src/main/java/net/coreprotect/database/lookup/ChestTransactionLookup.java @@ -56,9 +56,9 @@ else if (commandSender.hasPermission("coreprotect.coreprotect")) { int rowMax = page * limit; int pageStart = rowMax - limit; - String query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "container " + Util.getWidIndex("container") + "WHERE wid = '" + worldId + "' AND (x = '" + x + "' OR x = '" + x2 + "') AND (z = '" + z + "' OR z = '" + z2 + "') AND y = '" + y + "' LIMIT 0, 1"; + String query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "container " + Util.getWidIndex("container") + "WHERE wid = '" + worldId + "' AND (x = '" + x + "' OR x = '" + x2 + "') AND (z = '" + z + "' OR z = '" + z2 + "') AND y = '" + y + "' LIMIT 1"; if (exact) { - query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "container " + Util.getWidIndex("container") + "WHERE wid = '" + worldId + "' AND (x = '" + l.getBlockX() + "') AND (z = '" + l.getBlockZ() + "') AND y = '" + y + "' LIMIT 0, 1"; + query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "container " + Util.getWidIndex("container") + "WHERE wid = '" + worldId + "' AND (x = '" + l.getBlockX() + "') AND (z = '" + l.getBlockZ() + "') AND y = '" + y + "' LIMIT 1"; } ResultSet results = statement.executeQuery(query); @@ -69,9 +69,9 @@ else if (commandSender.hasPermission("coreprotect.coreprotect")) { int totalPages = (int) Math.ceil(count / (limit + 0.0)); - query = "SELECT time,user,action,type,data,amount,metadata,rolled_back FROM " + ConfigHandler.prefix + "container " + Util.getWidIndex("container") + "WHERE wid = '" + worldId + "' AND (x = '" + x + "' OR x = '" + x2 + "') AND (z = '" + z + "' OR z = '" + z2 + "') AND y = '" + y + "' ORDER BY rowid DESC LIMIT " + pageStart + ", " + limit + ""; + query = "SELECT time,user,action,type,data,amount,metadata,rolled_back FROM " + ConfigHandler.prefix + "container " + Util.getWidIndex("container") + "WHERE wid = '" + worldId + "' AND (x = '" + x + "' OR x = '" + x2 + "') AND (z = '" + z + "' OR z = '" + z2 + "') AND y = '" + y + "' ORDER BY rowid DESC LIMIT " + limit + " OFFSET " + pageStart; if (exact) { - query = "SELECT time,user,action,type,data,amount,metadata,rolled_back FROM " + ConfigHandler.prefix + "container " + Util.getWidIndex("container") + "WHERE wid = '" + worldId + "' AND (x = '" + l.getBlockX() + "') AND (z = '" + l.getBlockZ() + "') AND y = '" + y + "' ORDER BY rowid DESC LIMIT " + pageStart + ", " + limit + ""; + query = "SELECT time,user,action,type,data,amount,metadata,rolled_back FROM " + ConfigHandler.prefix + "container " + Util.getWidIndex("container") + "WHERE wid = '" + worldId + "' AND (x = '" + l.getBlockX() + "') AND (z = '" + l.getBlockZ() + "') AND y = '" + y + "' ORDER BY rowid DESC LIMIT " + limit + " OFFSET " + pageStart; } results = statement.executeQuery(query); while (results.next()) { diff --git a/src/main/java/net/coreprotect/database/lookup/InteractionLookup.java b/src/main/java/net/coreprotect/database/lookup/InteractionLookup.java index bcf2ba4b0..1b51f45ab 100644 --- a/src/main/java/net/coreprotect/database/lookup/InteractionLookup.java +++ b/src/main/java/net/coreprotect/database/lookup/InteractionLookup.java @@ -55,7 +55,7 @@ else if (commandSender.hasPermission("coreprotect.coreprotect")) { checkTime = time - offset; } - String query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action='2' AND time >= '" + checkTime + "' LIMIT 0, 1"; + String query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action='2' AND time >= '" + checkTime + "' LIMIT 1"; ResultSet results = statement.executeQuery(query); while (results.next()) { @@ -64,7 +64,7 @@ else if (commandSender.hasPermission("coreprotect.coreprotect")) { results.close(); int totalPages = (int) Math.ceil(count / (limit + 0.0)); - query = "SELECT time,user,action,type,data,rolled_back FROM " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action='2' AND time >= '" + checkTime + "' ORDER BY rowid DESC LIMIT " + pageStart + ", " + limit + ""; + query = "SELECT time,user,action,type,data,rolled_back FROM " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action='2' AND time >= '" + checkTime + "' ORDER BY rowid DESC LIMIT " + limit + " OFFSET " + pageStart; results = statement.executeQuery(query); StringBuilder resultBuilder = new StringBuilder(); diff --git a/src/main/java/net/coreprotect/database/lookup/PlayerLookup.java b/src/main/java/net/coreprotect/database/lookup/PlayerLookup.java index c65c6f26a..d363db1d7 100644 --- a/src/main/java/net/coreprotect/database/lookup/PlayerLookup.java +++ b/src/main/java/net/coreprotect/database/lookup/PlayerLookup.java @@ -7,6 +7,7 @@ import net.coreprotect.config.Config; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.config.DatabaseType; public class PlayerLookup { @@ -20,11 +21,11 @@ public static boolean playerExists(Connection connection, String user) { } String collate = ""; - if (!Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE == DatabaseType.SQLITE) { collate = " COLLATE NOCASE"; } - String query = "SELECT rowid as id, uuid FROM " + ConfigHandler.prefix + "user WHERE user = ?" + collate + " LIMIT 0, 1"; + String query = "SELECT rowid as id, uuid FROM " + ConfigHandler.prefix + "user WHERE user = ?" + collate + " LIMIT 1"; PreparedStatement preparedStmt = connection.prepareStatement(query); preparedStmt.setString(1, user); diff --git a/src/main/java/net/coreprotect/database/lookup/SignMessageLookup.java b/src/main/java/net/coreprotect/database/lookup/SignMessageLookup.java index 1d19a505d..873302039 100644 --- a/src/main/java/net/coreprotect/database/lookup/SignMessageLookup.java +++ b/src/main/java/net/coreprotect/database/lookup/SignMessageLookup.java @@ -55,7 +55,7 @@ else if (commandSender.hasPermission("coreprotect.coreprotect")) { int rowMax = page * limit; int pageStart = rowMax - limit; - String query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "sign " + Util.getWidIndex("sign") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action = '1' AND (LENGTH(line_1) > 0 OR LENGTH(line_2) > 0 OR LENGTH(line_3) > 0 OR LENGTH(line_4) > 0 OR LENGTH(line_5) > 0 OR LENGTH(line_6) > 0 OR LENGTH(line_7) > 0 OR LENGTH(line_8) > 0) LIMIT 0, 1"; + String query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "sign " + Util.getWidIndex("sign") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action = '1' AND (LENGTH(line_1) > 0 OR LENGTH(line_2) > 0 OR LENGTH(line_3) > 0 OR LENGTH(line_4) > 0 OR LENGTH(line_5) > 0 OR LENGTH(line_6) > 0 OR LENGTH(line_7) > 0 OR LENGTH(line_8) > 0) LIMIT 1"; ResultSet results = statement.executeQuery(query); while (results.next()) { @@ -65,7 +65,7 @@ else if (commandSender.hasPermission("coreprotect.coreprotect")) { int totalPages = (int) Math.ceil(count / (limit + 0.0)); - query = "SELECT time,user,face,line_1,line_2,line_3,line_4,line_5,line_6,line_7,line_8 FROM " + ConfigHandler.prefix + "sign " + Util.getWidIndex("sign") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action = '1' AND (LENGTH(line_1) > 0 OR LENGTH(line_2) > 0 OR LENGTH(line_3) > 0 OR LENGTH(line_4) > 0 OR LENGTH(line_5) > 0 OR LENGTH(line_6) > 0 OR LENGTH(line_7) > 0 OR LENGTH(line_8) > 0) ORDER BY rowid DESC LIMIT " + pageStart + ", " + limit + ""; + query = "SELECT time,user,face,line_1,line_2,line_3,line_4,line_5,line_6,line_7,line_8 FROM " + ConfigHandler.prefix + "sign " + Util.getWidIndex("sign") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action = '1' AND (LENGTH(line_1) > 0 OR LENGTH(line_2) > 0 OR LENGTH(line_3) > 0 OR LENGTH(line_4) > 0 OR LENGTH(line_5) > 0 OR LENGTH(line_6) > 0 OR LENGTH(line_7) > 0 OR LENGTH(line_8) > 0) ORDER BY rowid DESC LIMIT " + limit + " OFFSET " + pageStart; results = statement.executeQuery(query); while (results.next()) { diff --git a/src/main/java/net/coreprotect/database/statement/UserStatement.java b/src/main/java/net/coreprotect/database/statement/UserStatement.java index 00df51a4e..ddf9a77d0 100644 --- a/src/main/java/net/coreprotect/database/statement/UserStatement.java +++ b/src/main/java/net/coreprotect/database/statement/UserStatement.java @@ -5,11 +5,15 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import java.sql.Types; import java.util.Locale; +import java.util.UUID; import net.coreprotect.config.Config; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.config.DatabaseType; import net.coreprotect.database.Database; +import net.coreprotect.database.StatementUtils; public class UserStatement { @@ -25,10 +29,10 @@ public static int insert(Connection connection, String user) { PreparedStatement preparedStmt = null; if (Database.hasReturningKeys()) { - preparedStmt = connection.prepareStatement("INSERT INTO " + ConfigHandler.prefix + "user (time, user) VALUES (?, ?) RETURNING rowid"); + preparedStmt = connection.prepareStatement("INSERT INTO " + StatementUtils.getTableName("user") + " (time, \"user\") VALUES (?, ?) RETURNING rowid"); } else { - preparedStmt = connection.prepareStatement("INSERT INTO " + ConfigHandler.prefix + "user (time, user) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS); + preparedStmt = connection.prepareStatement("INSERT INTO " + StatementUtils.getTableName("user") + " (time, \"user\") VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS); } preparedStmt.setInt(1, unixtimestamp); @@ -67,24 +71,29 @@ public static int getId(PreparedStatement preparedStatement, String user, boolea public static int loadId(Connection connection, String user, String uuid) { // generate if doesn't exist int id = -1; + DatabaseType dbType = Config.getGlobal().DB_TYPE; try { String collate = ""; - if (!Config.getGlobal().MYSQL) { + if (dbType == DatabaseType.SQLITE) { collate = " COLLATE NOCASE"; } String where = "user = ?" + collate; if (uuid != null) { - where = where + " OR uuid = ?"; + where += " OR uuid = ?"; } - String query = "SELECT rowid as id, uuid FROM " + ConfigHandler.prefix + "user WHERE " + where + " ORDER BY rowid ASC LIMIT 0, 1"; + String query = "SELECT rowid as id, uuid FROM " + StatementUtils.getTableName("user") + " WHERE " + where + " ORDER BY rowid ASC LIMIT 1"; PreparedStatement preparedStmt = connection.prepareStatement(query); preparedStmt.setString(1, user); if (uuid != null) { - preparedStmt.setString(2, uuid); + if (dbType == DatabaseType.PGSQL) { + preparedStmt.setObject(2, UUID.fromString(uuid), Types.OTHER); + } else { + preparedStmt.setString(2, uuid); + } } ResultSet resultSet = preparedStmt.executeQuery(); @@ -120,7 +129,7 @@ public static String loadName(Connection connection, int id) { try { Statement statement = connection.createStatement(); - String query = "SELECT user, uuid FROM " + ConfigHandler.prefix + "user WHERE rowid='" + id + "' LIMIT 0, 1"; + String query = "SELECT user, uuid FROM " + StatementUtils.getTableName("user") + " WHERE rowid='" + id + "' LIMIT 1"; ResultSet resultSet = statement.executeQuery(query); while (resultSet.next()) { diff --git a/src/main/java/net/coreprotect/language/Language.java b/src/main/java/net/coreprotect/language/Language.java index d390701ee..47d9370a8 100644 --- a/src/main/java/net/coreprotect/language/Language.java +++ b/src/main/java/net/coreprotect/language/Language.java @@ -154,6 +154,7 @@ public static void loadPhrases() { phrases.put(Phrase.MISSING_ROLLBACK_RADIUS, "You did not specify a {rollback|restore} radius."); phrases.put(Phrase.MISSING_ROLLBACK_USER, "You did not specify a {rollback|restore} user."); phrases.put(Phrase.MYSQL_UNAVAILABLE, "Unable to connect to MySQL server."); + phrases.put(Phrase.PGSQL_UNAVAILABLE, "Unable to connect to PostgreSQL server."); phrases.put(Phrase.NETWORK_CONNECTION, "Connection by {0} {successful|failed}. Using {1} {2}."); phrases.put(Phrase.NETWORK_TEST, "Network test data has been successful sent."); phrases.put(Phrase.NO_DATA, "No data found at {0}."); @@ -225,6 +226,7 @@ public static void loadPhrases() { phrases.put(Phrase.USER_NOT_FOUND, "User \"{0}\" not found."); phrases.put(Phrase.USER_OFFLINE, "The user \"{0}\" is not online."); phrases.put(Phrase.USING_MYSQL, "Using MySQL for data storage."); + phrases.put(Phrase.USING_PGSQL, "Using PostgreSQL for data storage."); phrases.put(Phrase.USING_SQLITE, "Using SQLite for data storage."); phrases.put(Phrase.VALID_DONATION_KEY, "Valid donation key."); phrases.put(Phrase.VERSION_NOTICE, "Version {0} is now available."); diff --git a/src/main/java/net/coreprotect/language/Phrase.java b/src/main/java/net/coreprotect/language/Phrase.java index b976e238e..5baf45ac4 100644 --- a/src/main/java/net/coreprotect/language/Phrase.java +++ b/src/main/java/net/coreprotect/language/Phrase.java @@ -137,6 +137,7 @@ public enum Phrase { MISSING_ROLLBACK_RADIUS, MISSING_ROLLBACK_USER, MYSQL_UNAVAILABLE, + PGSQL_UNAVAILABLE, NETWORK_CONNECTION, NETWORK_TEST, NO_DATA, @@ -208,6 +209,7 @@ public enum Phrase { USER_NOT_FOUND, USER_OFFLINE, USING_MYSQL, + USING_PGSQL, USING_SQLITE, VALID_DONATION_KEY, VERSION_NOTICE, diff --git a/src/main/java/net/coreprotect/model/BlockGroup.java b/src/main/java/net/coreprotect/model/BlockGroup.java index e53635b60..07f2e20d2 100644 --- a/src/main/java/net/coreprotect/model/BlockGroup.java +++ b/src/main/java/net/coreprotect/model/BlockGroup.java @@ -56,7 +56,7 @@ public static void initialize() { TRACK_ANY.addAll(BUTTONS); TRACK_TOP.addAll(DOORS); TRACK_TOP.addAll(PRESSURE_PLATES); - TRACK_TOP.addAll(Tag.CARPETS.getValues()); + TRACK_TOP.addAll(Tag.WOOL_CARPETS.getValues()); TRACK_TOP_BOTTOM.addAll(LANTERNS); LIGHTABLES.addAll(CANDLES); INTERACT_BLOCKS.addAll(DOORS); diff --git a/src/main/java/net/coreprotect/patch/Patch.java b/src/main/java/net/coreprotect/patch/Patch.java index ea32dfcaa..22bbf58ac 100755 --- a/src/main/java/net/coreprotect/patch/Patch.java +++ b/src/main/java/net/coreprotect/patch/Patch.java @@ -52,7 +52,7 @@ protected static String getClassVersion(String version) { public static Integer[] getDatabaseVersion(Connection connection, boolean lastVersion) { Integer[] last_version = new Integer[] { 0, 0, 0 }; try { - String query = "SELECT version FROM " + ConfigHandler.prefix + "version ORDER BY rowid " + (lastVersion ? "DESC" : "ASC") + " LIMIT 0, 1"; + String query = "SELECT version FROM " + ConfigHandler.prefix + "version ORDER BY rowid " + (lastVersion ? "DESC" : "ASC") + " LIMIT 1"; Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(query); while (rs.next()) { diff --git a/src/main/java/net/coreprotect/patch/script/__2_10_0.java b/src/main/java/net/coreprotect/patch/script/__2_10_0.java index 10375e062..b293027de 100755 --- a/src/main/java/net/coreprotect/patch/script/__2_10_0.java +++ b/src/main/java/net/coreprotect/patch/script/__2_10_0.java @@ -4,12 +4,13 @@ import net.coreprotect.config.Config; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.config.DatabaseType; public class __2_10_0 { protected static boolean patch(Statement statement) { try { - if (Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE != DatabaseType.SQLITE) { statement.executeUpdate("ALTER TABLE " + ConfigHandler.prefix + "user ADD COLUMN uuid varchar(64), ADD INDEX(uuid)"); } else { diff --git a/src/main/java/net/coreprotect/patch/script/__2_11_0.java b/src/main/java/net/coreprotect/patch/script/__2_11_0.java index f55a6b984..2bef8dd99 100755 --- a/src/main/java/net/coreprotect/patch/script/__2_11_0.java +++ b/src/main/java/net/coreprotect/patch/script/__2_11_0.java @@ -9,12 +9,13 @@ import net.coreprotect.config.Config; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.config.DatabaseType; public class __2_11_0 { protected static boolean patch(Statement statement) { try { - if (Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE != DatabaseType.SQLITE) { statement.executeUpdate("START TRANSACTION"); } else { @@ -54,7 +55,7 @@ protected static boolean patch(Statement statement) { } } - if (Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE != DatabaseType.SQLITE) { statement.executeUpdate("COMMIT"); } else { diff --git a/src/main/java/net/coreprotect/patch/script/__2_15_0.java b/src/main/java/net/coreprotect/patch/script/__2_15_0.java index 03cdfdab7..2ea7a4c0e 100755 --- a/src/main/java/net/coreprotect/patch/script/__2_15_0.java +++ b/src/main/java/net/coreprotect/patch/script/__2_15_0.java @@ -6,13 +6,14 @@ import net.coreprotect.config.Config; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.config.DatabaseType; import net.coreprotect.database.Database; public class __2_15_0 { protected static boolean patch(Statement statement) { try { - if (Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE != DatabaseType.SQLITE) { statement.executeUpdate("ALTER TABLE " + ConfigHandler.prefix + "chat MODIFY message VARCHAR(1000)"); statement.executeUpdate("ALTER TABLE " + ConfigHandler.prefix + "command MODIFY message VARCHAR(1000)"); statement.executeUpdate("ALTER TABLE " + ConfigHandler.prefix + "user MODIFY user VARCHAR(100)"); @@ -39,7 +40,7 @@ protected static boolean patch(Statement statement) { Database.commitTransaction(statement); try { - if (Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE != DatabaseType.SQLITE) { statement.executeUpdate("ALTER TABLE " + ConfigHandler.prefix + "block MODIFY COLUMN rowid bigint NOT NULL AUTO_INCREMENT, ADD COLUMN blockdata BLOB"); } else { diff --git a/src/main/java/net/coreprotect/patch/script/__2_16_0.java b/src/main/java/net/coreprotect/patch/script/__2_16_0.java index 9943b55bd..86bbdcd75 100755 --- a/src/main/java/net/coreprotect/patch/script/__2_16_0.java +++ b/src/main/java/net/coreprotect/patch/script/__2_16_0.java @@ -6,6 +6,7 @@ import net.coreprotect.config.Config; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.config.DatabaseType; import net.coreprotect.database.Database; import net.coreprotect.patch.Patch; @@ -13,7 +14,7 @@ public class __2_16_0 { protected static boolean patch(Statement statement) { try { - if (Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE != DatabaseType.SQLITE) { try { statement.executeUpdate("ALTER TABLE " + ConfigHandler.prefix + "skull MODIFY owner VARCHAR(64), DROP COLUMN type, DROP COLUMN data, DROP COLUMN rotation"); } diff --git a/src/main/java/net/coreprotect/patch/script/__2_17_0.java b/src/main/java/net/coreprotect/patch/script/__2_17_0.java index 64c3ee495..4afc4f03c 100755 --- a/src/main/java/net/coreprotect/patch/script/__2_17_0.java +++ b/src/main/java/net/coreprotect/patch/script/__2_17_0.java @@ -4,12 +4,13 @@ import net.coreprotect.config.Config; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.config.DatabaseType; public class __2_17_0 { protected static boolean patch(Statement statement) { try { - if (Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE != DatabaseType.SQLITE) { statement.executeUpdate("ALTER TABLE " + ConfigHandler.prefix + "sign ADD COLUMN color int"); } else { diff --git a/src/main/java/net/coreprotect/patch/script/__2_18_0.java b/src/main/java/net/coreprotect/patch/script/__2_18_0.java index 5ceb267f8..b1cbdcca9 100644 --- a/src/main/java/net/coreprotect/patch/script/__2_18_0.java +++ b/src/main/java/net/coreprotect/patch/script/__2_18_0.java @@ -13,6 +13,7 @@ import net.coreprotect.config.Config; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.config.DatabaseType; import net.coreprotect.database.Database; import net.coreprotect.patch.Patch; import net.coreprotect.utility.Util; @@ -25,7 +26,7 @@ protected static boolean patch(Statement statement) { try { try { - if (Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE != DatabaseType.SQLITE) { statement.executeUpdate("ALTER TABLE " + ConfigHandler.prefix + "block ADD COLUMN blockdata BLOB"); } } @@ -41,7 +42,7 @@ protected static boolean patch(Statement statement) { return false; } - String query = "SELECT rowid, id, material FROM " + ConfigHandler.prefix + "material_map WHERE material LIKE 'minecraft:legacy_%' LIMIT 0, 1"; + String query = "SELECT rowid, id, material FROM " + ConfigHandler.prefix + "material_map WHERE material LIKE 'minecraft:legacy_%' LIMIT 1"; String preparedBlockQuery = "SELECT rowid as id, data, blockdata FROM " + ConfigHandler.prefix + "block WHERE type = ? AND action < '3'"; String preparedContainerQuery = "SELECT rowid as id FROM " + ConfigHandler.prefix + "container WHERE type = ?"; String preparedBlockUpdateQuery = "UPDATE " + ConfigHandler.prefix + "block SET type = ?, blockdata = ? WHERE rowid = ?"; @@ -178,7 +179,7 @@ protected static boolean patch(Statement statement) { if (createIndexes) { try { - if (Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE != DatabaseType.SQLITE) { statement.executeUpdate("ALTER TABLE " + ConfigHandler.prefix + "art_map ADD INDEX(id)"); statement.executeUpdate("ALTER TABLE " + ConfigHandler.prefix + "entity_map ADD INDEX(id)"); statement.executeUpdate("ALTER TABLE " + ConfigHandler.prefix + "material_map ADD INDEX(id)"); diff --git a/src/main/java/net/coreprotect/patch/script/__2_19_0.java b/src/main/java/net/coreprotect/patch/script/__2_19_0.java index 75300d588..999941c97 100644 --- a/src/main/java/net/coreprotect/patch/script/__2_19_0.java +++ b/src/main/java/net/coreprotect/patch/script/__2_19_0.java @@ -11,6 +11,7 @@ import net.coreprotect.config.Config; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.config.DatabaseType; import net.coreprotect.database.Database; import net.coreprotect.language.Phrase; import net.coreprotect.language.Selector; @@ -22,7 +23,7 @@ public class __2_19_0 { protected static boolean patch(Statement statement) { try { - if (Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE != DatabaseType.SQLITE) { try { statement.executeUpdate("ALTER TABLE " + ConfigHandler.prefix + "sign ADD COLUMN action int"); statement.executeUpdate("ALTER TABLE " + ConfigHandler.prefix + "sign DROP INDEX wid"); @@ -139,7 +140,7 @@ protected static boolean patch(Statement statement) { } String blockQuery = "SELECT time, user, wid, x, y, z FROM " + ConfigHandler.prefix + "block WHERE type IN(" + signData.toString() + ") AND action='1' ORDER BY rowid ASC"; - String preparedSignQuery = "SELECT rowid as id FROM " + ConfigHandler.prefix + "sign WHERE user = ? AND wid = ? AND x = ? AND y = ? AND z = ? AND time >= ? ORDER BY rowid ASC LIMIT 0, 1"; + String preparedSignQuery = "SELECT rowid as id FROM " + ConfigHandler.prefix + "sign WHERE user = ? AND wid = ? AND x = ? AND y = ? AND z = ? AND time >= ? ORDER BY rowid ASC LIMIT 1"; String preparedQueryUpdate = "UPDATE " + ConfigHandler.prefix + "sign SET action = 1 WHERE rowid = ?"; PreparedStatement preparedSignStatement = statement.getConnection().prepareStatement(preparedSignQuery); PreparedStatement preparedStatementUpdate = statement.getConnection().prepareStatement(preparedQueryUpdate); diff --git a/src/main/java/net/coreprotect/patch/script/__2_20_0.java b/src/main/java/net/coreprotect/patch/script/__2_20_0.java index 49e88cb39..7587c5584 100644 --- a/src/main/java/net/coreprotect/patch/script/__2_20_0.java +++ b/src/main/java/net/coreprotect/patch/script/__2_20_0.java @@ -8,6 +8,7 @@ import net.coreprotect.config.Config; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.config.DatabaseType; import net.coreprotect.database.Database; import net.coreprotect.language.Phrase; import net.coreprotect.language.Selector; @@ -19,7 +20,7 @@ public class __2_20_0 { protected static boolean patch(Statement statement) { try { - if (Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE != DatabaseType.SQLITE) { try { statement.executeUpdate("ALTER TABLE " + ConfigHandler.prefix + "command MODIFY message VARCHAR(16000), CONVERT TO CHARACTER SET utf8mb4"); } diff --git a/src/main/java/net/coreprotect/patch/script/__2_21_0.java b/src/main/java/net/coreprotect/patch/script/__2_21_0.java index 8ac664b63..72b5fce3f 100644 --- a/src/main/java/net/coreprotect/patch/script/__2_21_0.java +++ b/src/main/java/net/coreprotect/patch/script/__2_21_0.java @@ -5,6 +5,7 @@ import net.coreprotect.config.Config; import net.coreprotect.config.ConfigFile; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.config.DatabaseType; import net.coreprotect.language.Phrase; import net.coreprotect.language.Selector; import net.coreprotect.patch.Patch; @@ -14,7 +15,7 @@ public class __2_21_0 { protected static boolean patch(Statement statement) { try { - if (Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE != DatabaseType.SQLITE) { try { statement.executeUpdate("ALTER TABLE " + ConfigHandler.prefix + "item ADD COLUMN rolled_back TINYINT DEFAULT 0;"); } diff --git a/src/main/java/net/coreprotect/patch/script/__2_22_0.java b/src/main/java/net/coreprotect/patch/script/__2_22_0.java index ad8fbd57a..fb2ba8149 100644 --- a/src/main/java/net/coreprotect/patch/script/__2_22_0.java +++ b/src/main/java/net/coreprotect/patch/script/__2_22_0.java @@ -4,6 +4,7 @@ import net.coreprotect.config.Config; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.config.DatabaseType; import net.coreprotect.language.Phrase; import net.coreprotect.language.Selector; import net.coreprotect.patch.Patch; @@ -13,7 +14,7 @@ public class __2_22_0 { protected static boolean patch(Statement statement) { try { - if (Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE != DatabaseType.SQLITE) { try { statement.executeUpdate("ALTER TABLE " + ConfigHandler.prefix + "sign ADD COLUMN line_5 VARCHAR(100);"); } diff --git a/src/main/java/net/coreprotect/patch/script/__2_5_0.java b/src/main/java/net/coreprotect/patch/script/__2_5_0.java index 61bf5b832..07b1f68b7 100755 --- a/src/main/java/net/coreprotect/patch/script/__2_5_0.java +++ b/src/main/java/net/coreprotect/patch/script/__2_5_0.java @@ -4,13 +4,14 @@ import net.coreprotect.config.Config; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.config.DatabaseType; import net.coreprotect.patch.Patch; public class __2_5_0 { protected static boolean patch(Statement statement) { try { - if (Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE != DatabaseType.SQLITE) { try { statement.executeUpdate("ALTER TABLE " + ConfigHandler.prefix + "sign MODIFY line_1 VARCHAR(100)"); statement.executeUpdate("ALTER TABLE " + ConfigHandler.prefix + "sign MODIFY line_2 VARCHAR(100)"); diff --git a/src/main/java/net/coreprotect/patch/script/__2_6_0.java b/src/main/java/net/coreprotect/patch/script/__2_6_0.java index bb1bb8e7d..ca113f16e 100755 --- a/src/main/java/net/coreprotect/patch/script/__2_6_0.java +++ b/src/main/java/net/coreprotect/patch/script/__2_6_0.java @@ -4,12 +4,13 @@ import net.coreprotect.config.Config; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.config.DatabaseType; public class __2_6_0 { protected static boolean patch(Statement statement) { try { - if (Config.getGlobal().MYSQL) { + if (Config.getGlobal().DB_TYPE != DatabaseType.SQLITE) { statement.executeUpdate("START TRANSACTION"); statement.executeUpdate("CREATE TEMPORARY TABLE " + ConfigHandler.prefix + "version_tmp(rowid int, time int, version varchar(16)) ENGINE=InnoDB"); statement.executeUpdate("INSERT INTO " + ConfigHandler.prefix + "version_tmp SELECT rowid,time,version FROM " + ConfigHandler.prefix + "version;"); diff --git a/src/main/java/net/coreprotect/utility/Util.java b/src/main/java/net/coreprotect/utility/Util.java index b0e3f853c..5188885f4 100755 --- a/src/main/java/net/coreprotect/utility/Util.java +++ b/src/main/java/net/coreprotect/utility/Util.java @@ -54,6 +54,7 @@ import net.coreprotect.bukkit.BukkitAdapter; import net.coreprotect.config.Config; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.config.DatabaseType; import net.coreprotect.consumer.Queue; import net.coreprotect.database.Rollback; import net.coreprotect.language.Phrase; @@ -1589,8 +1590,8 @@ public static boolean checkWorldEdit() { public static String getWidIndex(String queryTable) { String index = ""; - boolean isMySQL = Config.getGlobal().MYSQL; - if (isMySQL) { + boolean isRDB = Config.getGlobal().DB_TYPE != DatabaseType.SQLITE; + if (isRDB) { index = "USE INDEX(wid) "; } else { From 0a235c0f5d142d8c2b60bae365c3812c09d25486 Mon Sep 17 00:00:00 2001 From: Jon Huang Date: Mon, 29 Jan 2024 23:45:53 -0800 Subject: [PATCH 02/15] Update. --- src/main/java/net/coreprotect/api/BlockAPI.java | 15 +++++++++------ .../java/net/coreprotect/api/SessionLookup.java | 8 +++++--- .../net/coreprotect/consumer/process/Process.java | 3 ++- .../consumer/process/SkullUpdateProcess.java | 4 ++-- .../consumer/process/WorldInsertProcess.java | 3 ++- .../java/net/coreprotect/database/Database.java | 6 +++--- .../java/net/coreprotect/database/Lookup.java | 14 +++++++------- .../coreprotect/database/lookup/BlockLookup.java | 5 +++-- .../database/lookup/ChestTransactionLookup.java | 9 +++++---- .../database/lookup/InteractionLookup.java | 5 +++-- .../coreprotect/database/lookup/PlayerLookup.java | 3 ++- .../database/lookup/SignMessageLookup.java | 5 +++-- src/main/java/net/coreprotect/patch/Patch.java | 9 +++++---- 13 files changed, 51 insertions(+), 38 deletions(-) diff --git a/src/main/java/net/coreprotect/api/BlockAPI.java b/src/main/java/net/coreprotect/api/BlockAPI.java index a9fceb673..f535609a1 100644 --- a/src/main/java/net/coreprotect/api/BlockAPI.java +++ b/src/main/java/net/coreprotect/api/BlockAPI.java @@ -1,8 +1,8 @@ package net.coreprotect.api; import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; -import java.sql.Statement; import java.util.ArrayList; import java.util.List; @@ -38,10 +38,13 @@ public static List performLookup(Block block, int offset) { return result; } - Statement statement = connection.createStatement(); - - String query = "SELECT time,\"user\",action,type,data,blockdata,rolled_back FROM " + StatementUtils.getTableName("block") + " " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND time > '" + checkTime + "' ORDER BY rowid DESC"; - ResultSet results = statement.executeQuery(query); + PreparedStatement ps = connection.prepareStatement("SELECT time, \"user\", action, type, data, blockdata, rolled_back FROM " + StatementUtils.getTableName("block") + " " + Util.getWidIndex("block") + "WHERE wid = ? AND x = ? AND z = ? AND y = ? AND time > ? ORDER BY rowid DESC"); + ps.setInt(1, worldId); + ps.setInt(2, x); + ps.setInt(3, z); + ps.setInt(4, y); + ps.setInt(5, checkTime); + ResultSet results = ps.executeQuery(); while (results.next()) { String resultTime = results.getString("time"); @@ -62,7 +65,7 @@ public static List performLookup(Block block, int offset) { result.add(lineData); } results.close(); - statement.close(); + ps.close(); } catch (Exception e) { e.printStackTrace(); diff --git a/src/main/java/net/coreprotect/api/SessionLookup.java b/src/main/java/net/coreprotect/api/SessionLookup.java index c633e4654..64e956052 100644 --- a/src/main/java/net/coreprotect/api/SessionLookup.java +++ b/src/main/java/net/coreprotect/api/SessionLookup.java @@ -1,6 +1,7 @@ package net.coreprotect.api; import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; @@ -44,9 +45,10 @@ public static List performLookup(String user, int offset) { } int userId = ConfigHandler.playerIdCache.get(user.toLowerCase(Locale.ROOT)); - try (Statement statement = connection.createStatement()) { - String query = "SELECT time,\"user\",wid,x,y,z,action FROM " + StatementUtils.getTableName("session") + " WHERE user = '" + userId + "' AND time > '" + checkTime + "' ORDER BY rowid DESC"; - ResultSet results = statement.executeQuery(query); + try (PreparedStatement statement = connection.prepareStatement("SELECT time, \"user\", wid, x, y, z, action FROM " + StatementUtils.getTableName("session") + " WHERE user = ? AND time > ? ORDER BY rowid DESC")) { + statement.setInt(1, userId); + statement.setInt(2, checkTime); + ResultSet results = statement.executeQuery(); while (results.next()) { String resultTime = results.getString("time"); int resultUserId = results.getInt("user"); diff --git a/src/main/java/net/coreprotect/consumer/process/Process.java b/src/main/java/net/coreprotect/consumer/process/Process.java index 563549d99..543e59015 100755 --- a/src/main/java/net/coreprotect/consumer/process/Process.java +++ b/src/main/java/net/coreprotect/consumer/process/Process.java @@ -13,6 +13,7 @@ import net.coreprotect.config.ConfigHandler; import net.coreprotect.consumer.Consumer; import net.coreprotect.database.Database; +import net.coreprotect.database.StatementUtils; import net.coreprotect.database.statement.UserStatement; public class Process { @@ -58,7 +59,7 @@ protected static void updateLockTable(Statement statement, int locked) { int unixTimestamp = (int) (System.currentTimeMillis() / 1000L); int timeSinceLastUpdate = unixTimestamp - lastLockUpdate; if (timeSinceLastUpdate >= 15 || locked == 0) { - statement.executeUpdate("UPDATE " + ConfigHandler.prefix + "database_lock SET status = '" + locked + "', time = '" + unixTimestamp + "' WHERE rowid = '1'"); + statement.executeUpdate("UPDATE " + StatementUtils.getTableName("database_lock") + " SET status = '" + locked + "', time = '" + unixTimestamp + "' WHERE rowid = '1'"); lastLockUpdate = unixTimestamp; } } diff --git a/src/main/java/net/coreprotect/consumer/process/SkullUpdateProcess.java b/src/main/java/net/coreprotect/consumer/process/SkullUpdateProcess.java index a54be38e1..20084c682 100644 --- a/src/main/java/net/coreprotect/consumer/process/SkullUpdateProcess.java +++ b/src/main/java/net/coreprotect/consumer/process/SkullUpdateProcess.java @@ -4,9 +4,9 @@ import org.bukkit.block.BlockState; +import net.coreprotect.database.StatementUtils; import net.coreprotect.database.statement.SkullStatement; import net.coreprotect.utility.Util; -import net.coreprotect.config.ConfigHandler; class SkullUpdateProcess { @@ -18,7 +18,7 @@ static void process(Statement statement, Object object, int rowId) { */ if (object instanceof BlockState) { BlockState block = (BlockState) object; - String query = "SELECT owner FROM " + ConfigHandler.prefix + "skull WHERE rowid='" + rowId + "' LIMIT 1"; + String query = "SELECT owner FROM " + StatementUtils.getTableName("skull") + " WHERE rowid='" + rowId + "' LIMIT 1"; SkullStatement.getData(statement, block, query); Util.updateBlock(block); } diff --git a/src/main/java/net/coreprotect/consumer/process/WorldInsertProcess.java b/src/main/java/net/coreprotect/consumer/process/WorldInsertProcess.java index 395b14ac8..77e31839a 100644 --- a/src/main/java/net/coreprotect/consumer/process/WorldInsertProcess.java +++ b/src/main/java/net/coreprotect/consumer/process/WorldInsertProcess.java @@ -4,6 +4,7 @@ import java.sql.Statement; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.database.StatementUtils; import net.coreprotect.database.statement.MaterialStatement; import net.coreprotect.database.statement.WorldStatement; import net.coreprotect.language.Phrase; @@ -14,7 +15,7 @@ class WorldInsertProcess { static void process(PreparedStatement preparedStmt, int batchCount, Statement statement, Object world, int worldId) { if (world instanceof String) { - String query = "SELECT id FROM " + ConfigHandler.prefix + "world WHERE id = '" + worldId + "' LIMIT 1"; + String query = "SELECT id FROM " + StatementUtils.getTableName("world") + " WHERE id = '" + worldId + "' LIMIT 1"; boolean hasMaterial = MaterialStatement.hasMaterial(statement, query); if (!hasMaterial) { WorldStatement.insert(preparedStmt, batchCount, worldId, (String) world); diff --git a/src/main/java/net/coreprotect/database/Database.java b/src/main/java/net/coreprotect/database/Database.java index 5d9b0c410..cbbcb4f3e 100755 --- a/src/main/java/net/coreprotect/database/Database.java +++ b/src/main/java/net/coreprotect/database/Database.java @@ -205,13 +205,13 @@ public static void performUpdate(Statement statement, long id, int rb, int table try { int rolledBack = Util.toggleRolledBack(rb, (table == 2 || table == 3 || table == 4)); // co_item, co_container, co_block if (table == 1 || table == 3) { - statement.executeUpdate("UPDATE " + ConfigHandler.prefix + "container SET rolled_back='" + rolledBack + "' WHERE rowid='" + id + "'"); + statement.executeUpdate("UPDATE " + StatementUtils.getTableName("container") + " SET rolled_back='" + rolledBack + "' WHERE rowid='" + id + "'"); } else if (table == 2) { - statement.executeUpdate("UPDATE " + ConfigHandler.prefix + "item SET rolled_back='" + rolledBack + "' WHERE rowid='" + id + "'"); + statement.executeUpdate("UPDATE " + StatementUtils.getTableName("item") + " SET rolled_back='" + rolledBack + "' WHERE rowid='" + id + "'"); } else { - statement.executeUpdate("UPDATE " + ConfigHandler.prefix + "block SET rolled_back='" + rolledBack + "' WHERE rowid='" + id + "'"); + statement.executeUpdate("UPDATE " + StatementUtils.getTableName("block") + " SET rolled_back='" + rolledBack + "' WHERE rowid='" + id + "'"); } } catch (Exception e) { diff --git a/src/main/java/net/coreprotect/database/Lookup.java b/src/main/java/net/coreprotect/database/Lookup.java index bfc21538b..7afa4f648 100755 --- a/src/main/java/net/coreprotect/database/Lookup.java +++ b/src/main/java/net/coreprotect/database/Lookup.java @@ -752,18 +752,18 @@ else if (actionList.contains(11)) { baseQuery = baseQuery.replace("action NOT IN(-1)", "action NOT IN(3)"); // if block specified for include/exclude, filter out entity data } - query = unionSelect + "SELECT " + "'0' as tbl," + rows + " FROM " + ConfigHandler.prefix + "block " + index + "WHERE" + baseQuery + unionLimit + ") UNION ALL "; + query = unionSelect + "SELECT " + "'0' as tbl," + rows + " FROM " + StatementUtils.getTableName("block") + " " + index + "WHERE" + baseQuery + unionLimit + ") UNION ALL "; itemLookup = true; } if (itemLookup) { if (!count) { - rows = "rowid as id,time,user,wid,x,y,z,type,metadata,data,amount,action,rolled_back"; + rows = "rowid as id,time,\"user\",wid,x,y,z,type,metadata,data,amount,action,rolled_back"; } - query = query + unionSelect + "SELECT " + "'1' as tbl," + rows + " FROM " + ConfigHandler.prefix + "container WHERE" + queryBlock + unionLimit + ") UNION ALL "; + query = query + unionSelect + "SELECT " + "'1' as tbl," + rows + " FROM " + StatementUtils.getTableName("container") + " WHERE" + queryBlock + unionLimit + ") UNION ALL "; if (!count) { - rows = "rowid as id,time,user,wid,x,y,z,type,data as metadata,0 as data,amount,action,rolled_back"; + rows = "rowid as id,time,\"user\",wid,x,y,z,type,data as metadata,0 as data,amount,action,rolled_back"; queryOrder = " ORDER BY time DESC, tbl DESC, id DESC"; } @@ -771,7 +771,7 @@ else if (actionList.contains(11)) { queryBlock = queryBlock.replace("action NOT IN(-1)", "action NOT IN(" + actionExclude + ")"); } - query = query + unionSelect + "SELECT " + "'2' as tbl," + rows + " FROM " + ConfigHandler.prefix + "item WHERE" + queryBlock + unionLimit + ")"; + query = query + unionSelect + "SELECT " + "'2' as tbl," + rows + " FROM " + StatementUtils.getTableName("item") + " WHERE" + queryBlock + unionLimit + ")"; } if (query.length() == 0) { @@ -779,7 +779,7 @@ else if (actionList.contains(11)) { baseQuery = baseQuery.replace("action NOT IN(-1)", "action NOT IN(" + actionExclude + ")"); } - query = "SELECT " + "'0' as tbl," + rows + " FROM " + ConfigHandler.prefix + queryTable + " " + index + "WHERE" + baseQuery; + query = "SELECT " + "'0' as tbl," + rows + " FROM " + StatementUtils.getTableName(queryTable) + " " + index + "WHERE" + baseQuery; } query = query + queryOrder + queryLimit + ""; @@ -820,7 +820,7 @@ public static String whoPlaced(Statement statement, BlockState block) { int z = block.getZ(); int time = (int) (System.currentTimeMillis() / 1000L); int worldId = Util.getWorldId(block.getWorld().getName()); - String query = "SELECT user,type FROM " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND rolled_back IN(0,2) AND action='1' ORDER BY rowid DESC LIMIT 1"; + String query = "SELECT \"user\", type FROM " + StatementUtils.getTableName("block") + " " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND rolled_back IN(0,2) AND action='1' ORDER BY rowid DESC LIMIT 1"; ResultSet results = statement.executeQuery(query); while (results.next()) { diff --git a/src/main/java/net/coreprotect/database/lookup/BlockLookup.java b/src/main/java/net/coreprotect/database/lookup/BlockLookup.java index 904c9c676..c9a901c43 100644 --- a/src/main/java/net/coreprotect/database/lookup/BlockLookup.java +++ b/src/main/java/net/coreprotect/database/lookup/BlockLookup.java @@ -9,6 +9,7 @@ import org.bukkit.command.CommandSender; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.database.StatementUtils; import net.coreprotect.database.statement.UserStatement; import net.coreprotect.language.Phrase; import net.coreprotect.language.Selector; @@ -57,7 +58,7 @@ else if (commandSender.hasPermission("coreprotect.coreprotect")) { String blockName = block.getType().name().toLowerCase(Locale.ROOT); - String query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action IN(0,1) AND time >= '" + checkTime + "' LIMIT 1"; + String query = "SELECT COUNT(*) as count from " + StatementUtils.getTableName("block") + " " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action IN(0,1) AND time >= '" + checkTime + "' LIMIT 1"; ResultSet results = statement.executeQuery(query); while (results.next()) { count = results.getInt("count"); @@ -65,7 +66,7 @@ else if (commandSender.hasPermission("coreprotect.coreprotect")) { results.close(); int totalPages = (int) Math.ceil(count / (limit + 0.0)); - query = "SELECT time,user,action,type,data,rolled_back FROM " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action IN(0,1) AND time >= '" + checkTime + "' ORDER BY rowid DESC LIMIT " + limit + " OFFSET " + page_start; + query = "SELECT time,user,action,type,data,rolled_back FROM " + StatementUtils.getTableName("block") + " " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action IN(0,1) AND time >= '" + checkTime + "' ORDER BY rowid DESC LIMIT " + limit + " OFFSET " + page_start; results = statement.executeQuery(query); StringBuilder resultTextBuilder = new StringBuilder(); diff --git a/src/main/java/net/coreprotect/database/lookup/ChestTransactionLookup.java b/src/main/java/net/coreprotect/database/lookup/ChestTransactionLookup.java index 33779ea2a..a3687887c 100644 --- a/src/main/java/net/coreprotect/database/lookup/ChestTransactionLookup.java +++ b/src/main/java/net/coreprotect/database/lookup/ChestTransactionLookup.java @@ -11,6 +11,7 @@ import org.bukkit.command.CommandSender; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.database.StatementUtils; import net.coreprotect.database.statement.UserStatement; import net.coreprotect.language.Phrase; import net.coreprotect.language.Selector; @@ -56,9 +57,9 @@ else if (commandSender.hasPermission("coreprotect.coreprotect")) { int rowMax = page * limit; int pageStart = rowMax - limit; - String query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "container " + Util.getWidIndex("container") + "WHERE wid = '" + worldId + "' AND (x = '" + x + "' OR x = '" + x2 + "') AND (z = '" + z + "' OR z = '" + z2 + "') AND y = '" + y + "' LIMIT 1"; + String query = "SELECT COUNT(*) as count from " + StatementUtils.getTableName("container") + " " + Util.getWidIndex("container") + "WHERE wid = '" + worldId + "' AND (x = '" + x + "' OR x = '" + x2 + "') AND (z = '" + z + "' OR z = '" + z2 + "') AND y = '" + y + "' LIMIT 1"; if (exact) { - query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "container " + Util.getWidIndex("container") + "WHERE wid = '" + worldId + "' AND (x = '" + l.getBlockX() + "') AND (z = '" + l.getBlockZ() + "') AND y = '" + y + "' LIMIT 1"; + query = "SELECT COUNT(*) as count from " + StatementUtils.getTableName("container") + " " + Util.getWidIndex("container") + "WHERE wid = '" + worldId + "' AND (x = '" + l.getBlockX() + "') AND (z = '" + l.getBlockZ() + "') AND y = '" + y + "' LIMIT 1"; } ResultSet results = statement.executeQuery(query); @@ -69,9 +70,9 @@ else if (commandSender.hasPermission("coreprotect.coreprotect")) { int totalPages = (int) Math.ceil(count / (limit + 0.0)); - query = "SELECT time,user,action,type,data,amount,metadata,rolled_back FROM " + ConfigHandler.prefix + "container " + Util.getWidIndex("container") + "WHERE wid = '" + worldId + "' AND (x = '" + x + "' OR x = '" + x2 + "') AND (z = '" + z + "' OR z = '" + z2 + "') AND y = '" + y + "' ORDER BY rowid DESC LIMIT " + limit + " OFFSET " + pageStart; + query = "SELECT time, \"user\", action, type, data, amount, metadata, rolled_back FROM " + StatementUtils.getTableName("container") + " " + Util.getWidIndex("container") + "WHERE wid = '" + worldId + "' AND (x = '" + x + "' OR x = '" + x2 + "') AND (z = '" + z + "' OR z = '" + z2 + "') AND y = '" + y + "' ORDER BY rowid DESC LIMIT " + limit + " OFFSET " + pageStart; if (exact) { - query = "SELECT time,user,action,type,data,amount,metadata,rolled_back FROM " + ConfigHandler.prefix + "container " + Util.getWidIndex("container") + "WHERE wid = '" + worldId + "' AND (x = '" + l.getBlockX() + "') AND (z = '" + l.getBlockZ() + "') AND y = '" + y + "' ORDER BY rowid DESC LIMIT " + limit + " OFFSET " + pageStart; + query = "SELECT time, \"user\", action, type, data, amount, metadata, rolled_back FROM " + StatementUtils.getTableName("container") + " " + Util.getWidIndex("container") + "WHERE wid = '" + worldId + "' AND (x = '" + l.getBlockX() + "') AND (z = '" + l.getBlockZ() + "') AND y = '" + y + "' ORDER BY rowid DESC LIMIT " + limit + " OFFSET " + pageStart; } results = statement.executeQuery(query); while (results.next()) { diff --git a/src/main/java/net/coreprotect/database/lookup/InteractionLookup.java b/src/main/java/net/coreprotect/database/lookup/InteractionLookup.java index 1b51f45ab..1ef98512c 100644 --- a/src/main/java/net/coreprotect/database/lookup/InteractionLookup.java +++ b/src/main/java/net/coreprotect/database/lookup/InteractionLookup.java @@ -9,6 +9,7 @@ import org.bukkit.command.CommandSender; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.database.StatementUtils; import net.coreprotect.database.statement.UserStatement; import net.coreprotect.language.Phrase; import net.coreprotect.language.Selector; @@ -55,7 +56,7 @@ else if (commandSender.hasPermission("coreprotect.coreprotect")) { checkTime = time - offset; } - String query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action='2' AND time >= '" + checkTime + "' LIMIT 1"; + String query = "SELECT COUNT(*) as count from " + StatementUtils.getTableName("block") + " " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action='2' AND time >= '" + checkTime + "' LIMIT 1"; ResultSet results = statement.executeQuery(query); while (results.next()) { @@ -64,7 +65,7 @@ else if (commandSender.hasPermission("coreprotect.coreprotect")) { results.close(); int totalPages = (int) Math.ceil(count / (limit + 0.0)); - query = "SELECT time,user,action,type,data,rolled_back FROM " + ConfigHandler.prefix + "block " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action='2' AND time >= '" + checkTime + "' ORDER BY rowid DESC LIMIT " + limit + " OFFSET " + pageStart; + query = "SELECT time, \"user\", action, type, data, rolled_back FROM " + StatementUtils.getTableName("block") + " " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action='2' AND time >= '" + checkTime + "' ORDER BY rowid DESC LIMIT " + limit + " OFFSET " + pageStart; results = statement.executeQuery(query); StringBuilder resultBuilder = new StringBuilder(); diff --git a/src/main/java/net/coreprotect/database/lookup/PlayerLookup.java b/src/main/java/net/coreprotect/database/lookup/PlayerLookup.java index d363db1d7..31c5f35cf 100644 --- a/src/main/java/net/coreprotect/database/lookup/PlayerLookup.java +++ b/src/main/java/net/coreprotect/database/lookup/PlayerLookup.java @@ -8,6 +8,7 @@ import net.coreprotect.config.Config; import net.coreprotect.config.ConfigHandler; import net.coreprotect.config.DatabaseType; +import net.coreprotect.database.StatementUtils; public class PlayerLookup { @@ -25,7 +26,7 @@ public static boolean playerExists(Connection connection, String user) { collate = " COLLATE NOCASE"; } - String query = "SELECT rowid as id, uuid FROM " + ConfigHandler.prefix + "user WHERE user = ?" + collate + " LIMIT 1"; + String query = "SELECT rowid as id, uuid FROM " + StatementUtils.getTableName("user") + " WHERE user = ?" + collate + " LIMIT 1"; PreparedStatement preparedStmt = connection.prepareStatement(query); preparedStmt.setString(1, user); diff --git a/src/main/java/net/coreprotect/database/lookup/SignMessageLookup.java b/src/main/java/net/coreprotect/database/lookup/SignMessageLookup.java index 873302039..5cf5d5917 100644 --- a/src/main/java/net/coreprotect/database/lookup/SignMessageLookup.java +++ b/src/main/java/net/coreprotect/database/lookup/SignMessageLookup.java @@ -11,6 +11,7 @@ import org.bukkit.command.CommandSender; import net.coreprotect.config.ConfigHandler; +import net.coreprotect.database.StatementUtils; import net.coreprotect.database.statement.UserStatement; import net.coreprotect.language.Phrase; import net.coreprotect.language.Selector; @@ -55,7 +56,7 @@ else if (commandSender.hasPermission("coreprotect.coreprotect")) { int rowMax = page * limit; int pageStart = rowMax - limit; - String query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "sign " + Util.getWidIndex("sign") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action = '1' AND (LENGTH(line_1) > 0 OR LENGTH(line_2) > 0 OR LENGTH(line_3) > 0 OR LENGTH(line_4) > 0 OR LENGTH(line_5) > 0 OR LENGTH(line_6) > 0 OR LENGTH(line_7) > 0 OR LENGTH(line_8) > 0) LIMIT 1"; + String query = "SELECT COUNT(*) as count from " + StatementUtils.getTableName("sign") + " " + Util.getWidIndex("sign") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action = '1' AND (LENGTH(line_1) > 0 OR LENGTH(line_2) > 0 OR LENGTH(line_3) > 0 OR LENGTH(line_4) > 0 OR LENGTH(line_5) > 0 OR LENGTH(line_6) > 0 OR LENGTH(line_7) > 0 OR LENGTH(line_8) > 0) LIMIT 1"; ResultSet results = statement.executeQuery(query); while (results.next()) { @@ -65,7 +66,7 @@ else if (commandSender.hasPermission("coreprotect.coreprotect")) { int totalPages = (int) Math.ceil(count / (limit + 0.0)); - query = "SELECT time,user,face,line_1,line_2,line_3,line_4,line_5,line_6,line_7,line_8 FROM " + ConfigHandler.prefix + "sign " + Util.getWidIndex("sign") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action = '1' AND (LENGTH(line_1) > 0 OR LENGTH(line_2) > 0 OR LENGTH(line_3) > 0 OR LENGTH(line_4) > 0 OR LENGTH(line_5) > 0 OR LENGTH(line_6) > 0 OR LENGTH(line_7) > 0 OR LENGTH(line_8) > 0) ORDER BY rowid DESC LIMIT " + limit + " OFFSET " + pageStart; + query = "SELECT time,user,face,line_1,line_2,line_3,line_4,line_5,line_6,line_7,line_8 FROM " + StatementUtils.getTableName("sign") + " " + Util.getWidIndex("sign") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action = '1' AND (LENGTH(line_1) > 0 OR LENGTH(line_2) > 0 OR LENGTH(line_3) > 0 OR LENGTH(line_4) > 0 OR LENGTH(line_5) > 0 OR LENGTH(line_6) > 0 OR LENGTH(line_7) > 0 OR LENGTH(line_8) > 0) ORDER BY rowid DESC LIMIT " + limit + " OFFSET " + pageStart; results = statement.executeQuery(query); while (results.next()) { diff --git a/src/main/java/net/coreprotect/patch/Patch.java b/src/main/java/net/coreprotect/patch/Patch.java index 22bbf58ac..a853d7d92 100755 --- a/src/main/java/net/coreprotect/patch/Patch.java +++ b/src/main/java/net/coreprotect/patch/Patch.java @@ -17,6 +17,7 @@ import net.coreprotect.config.ConfigHandler; import net.coreprotect.consumer.Consumer; import net.coreprotect.database.Database; +import net.coreprotect.database.StatementUtils; import net.coreprotect.language.Phrase; import net.coreprotect.utility.Chat; import net.coreprotect.utility.Color; @@ -52,7 +53,7 @@ protected static String getClassVersion(String version) { public static Integer[] getDatabaseVersion(Connection connection, boolean lastVersion) { Integer[] last_version = new Integer[] { 0, 0, 0 }; try { - String query = "SELECT version FROM " + ConfigHandler.prefix + "version ORDER BY rowid " + (lastVersion ? "DESC" : "ASC") + " LIMIT 1"; + String query = "SELECT version FROM " + StatementUtils.getTableName("version") + " ORDER BY rowid " + (lastVersion ? "DESC" : "ASC") + " LIMIT 1"; Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(query); while (rs.next()) { @@ -213,10 +214,10 @@ private static int runPatcher(Integer[] lastVersion, Integer[] version) { // mark as being up to date int unixtimestamp = (int) (System.currentTimeMillis() / 1000L); if (result >= 0) { - statement.executeUpdate("INSERT INTO " + ConfigHandler.prefix + "version (time,version) VALUES ('" + unixtimestamp + "', '" + version[0] + "." + version[1] + "." + version[2] + "')"); + statement.executeUpdate("INSERT INTO " + StatementUtils.getTableName("version") + " (time,version) VALUES ('" + unixtimestamp + "', '" + version[0] + "." + version[1] + "." + version[2] + "')"); } else if (patched) { - statement.executeUpdate("INSERT INTO " + ConfigHandler.prefix + "version (time,version) VALUES ('" + unixtimestamp + "', '" + newVersion[0] + "." + newVersion[1] + "." + newVersion[2] + "')"); + statement.executeUpdate("INSERT INTO " + StatementUtils.getTableName("version") + " (time,version) VALUES ('" + unixtimestamp + "', '" + newVersion[0] + "." + newVersion[1] + "." + newVersion[2] + "')"); } statement.close(); @@ -307,7 +308,7 @@ else if (finished == -1) { } else if (lastVersion[0] == 0) { int unixtimestamp = (int) (System.currentTimeMillis() / 1000L); - statement.executeUpdate("INSERT INTO " + ConfigHandler.prefix + "version (time,version) VALUES ('" + unixtimestamp + "', '" + currentVersion[0] + "." + (ConfigHandler.EDITION_BRANCH.contains("-dev") ? (currentVersion[1] - 1) : currentVersion[1]) + "." + currentVersion[2] + "')"); + statement.executeUpdate("INSERT INTO " + StatementUtils.getTableName("version") + " (time,version) VALUES ('" + unixtimestamp + "', '" + currentVersion[0] + "." + (ConfigHandler.EDITION_BRANCH.contains("-dev") ? (currentVersion[1] - 1) : currentVersion[1]) + "." + currentVersion[2] + "')"); } else { currentVersion[2] = 0; From 0695bb751bbdd1af7493bed656b7fbdf492b38dd Mon Sep 17 00:00:00 2001 From: Jon Huang Date: Tue, 30 Jan 2024 09:23:55 -0700 Subject: [PATCH 03/15] Update. --- .../java/net/coreprotect/api/BlockAPI.java | 52 ++++++------ .../net/coreprotect/api/SessionLookup.java | 35 ++++---- .../java/net/coreprotect/config/Config.java | 2 +- .../database/logger/UsernameLogger.java | 84 +++++++++---------- 4 files changed, 85 insertions(+), 88 deletions(-) diff --git a/src/main/java/net/coreprotect/api/BlockAPI.java b/src/main/java/net/coreprotect/api/BlockAPI.java index f535609a1..e9e1bcf6a 100644 --- a/src/main/java/net/coreprotect/api/BlockAPI.java +++ b/src/main/java/net/coreprotect/api/BlockAPI.java @@ -38,36 +38,34 @@ public static List performLookup(Block block, int offset) { return result; } - PreparedStatement ps = connection.prepareStatement("SELECT time, \"user\", action, type, data, blockdata, rolled_back FROM " + StatementUtils.getTableName("block") + " " + Util.getWidIndex("block") + "WHERE wid = ? AND x = ? AND z = ? AND y = ? AND time > ? ORDER BY rowid DESC"); - ps.setInt(1, worldId); - ps.setInt(2, x); - ps.setInt(3, z); - ps.setInt(4, y); - ps.setInt(5, checkTime); - ResultSet results = ps.executeQuery(); + try (PreparedStatement ps = connection.prepareStatement("SELECT time, \"user\", action, type, data, blockdata, rolled_back FROM " + StatementUtils.getTableName("block") + " " + Util.getWidIndex("block") + "WHERE wid = ? AND x = ? AND z = ? AND y = ? AND time > ? ORDER BY rowid DESC")) { + ps.setInt(1, worldId); + ps.setInt(2, x); + ps.setInt(3, z); + ps.setInt(4, y); + ps.setInt(5, checkTime); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + String resultTime = rs.getString("time"); + int resultUserId = rs.getInt("user"); + String resultAction = rs.getString("action"); + int resultType = rs.getInt("type"); + String resultData = rs.getString("data"); + byte[] resultBlockData = rs.getBytes("blockdata"); + String resultRolledBack = rs.getString("rolled_back"); + if (ConfigHandler.playerIdCacheReversed.get(resultUserId) == null) { + UserStatement.loadName(connection, resultUserId); + } + String resultUser = ConfigHandler.playerIdCacheReversed.get(resultUserId); + String blockData = Util.byteDataToString(resultBlockData, resultType); - while (results.next()) { - String resultTime = results.getString("time"); - int resultUserId = results.getInt("user"); - String resultAction = results.getString("action"); - int resultType = results.getInt("type"); - String resultData = results.getString("data"); - byte[] resultBlockData = results.getBytes("blockdata"); - String resultRolledBack = results.getString("rolled_back"); - if (ConfigHandler.playerIdCacheReversed.get(resultUserId) == null) { - UserStatement.loadName(connection, resultUserId); + String[] lookupData = new String[] { resultTime, resultUser, String.valueOf(x), String.valueOf(y), String.valueOf(z), String.valueOf(resultType), resultData, resultAction, resultRolledBack, String.valueOf(worldId), blockData }; + String[] lineData = Util.toStringArray(lookupData); + result.add(lineData); + } } - String resultUser = ConfigHandler.playerIdCacheReversed.get(resultUserId); - String blockData = Util.byteDataToString(resultBlockData, resultType); - - String[] lookupData = new String[] { resultTime, resultUser, String.valueOf(x), String.valueOf(y), String.valueOf(z), String.valueOf(resultType), resultData, resultAction, resultRolledBack, String.valueOf(worldId), blockData }; - String[] lineData = Util.toStringArray(lookupData); - result.add(lineData); } - results.close(); - ps.close(); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/net/coreprotect/api/SessionLookup.java b/src/main/java/net/coreprotect/api/SessionLookup.java index 64e956052..4f24af9b2 100644 --- a/src/main/java/net/coreprotect/api/SessionLookup.java +++ b/src/main/java/net/coreprotect/api/SessionLookup.java @@ -3,7 +3,6 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; -import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Locale; @@ -45,28 +44,28 @@ public static List performLookup(String user, int offset) { } int userId = ConfigHandler.playerIdCache.get(user.toLowerCase(Locale.ROOT)); - try (PreparedStatement statement = connection.prepareStatement("SELECT time, \"user\", wid, x, y, z, action FROM " + StatementUtils.getTableName("session") + " WHERE user = ? AND time > ? ORDER BY rowid DESC")) { + try (PreparedStatement statement = connection.prepareStatement("SELECT time, \"user\", wid, x, y, z, action FROM " + StatementUtils.getTableName("session") + " WHERE \"user\" = ? AND time > ? ORDER BY rowid DESC")) { statement.setInt(1, userId); statement.setInt(2, checkTime); - ResultSet results = statement.executeQuery(); - while (results.next()) { - String resultTime = results.getString("time"); - int resultUserId = results.getInt("user"); - String resultWorldId = results.getString("wid"); - String resultX = results.getString("x"); - String resultY = results.getString("y"); - String resultZ = results.getString("z"); - String resultAction = results.getString("action"); + try (ResultSet results = statement.executeQuery()) { + while (results.next()) { + String resultTime = results.getString("time"); + int resultUserId = results.getInt("user"); + String resultWorldId = results.getString("wid"); + String resultX = results.getString("x"); + String resultY = results.getString("y"); + String resultZ = results.getString("z"); + String resultAction = results.getString("action"); - if (ConfigHandler.playerIdCacheReversed.get(resultUserId) == null) { - UserStatement.loadName(connection, resultUserId); - } - String resultUser = ConfigHandler.playerIdCacheReversed.get(resultUserId); + if (ConfigHandler.playerIdCacheReversed.get(resultUserId) == null) { + UserStatement.loadName(connection, resultUserId); + } + String resultUser = ConfigHandler.playerIdCacheReversed.get(resultUserId); - String[] lookupData = new String[] { resultTime, resultUser, resultX, resultY, resultZ, resultWorldId, type, resultAction }; - result.add(lookupData); + String[] lookupData = new String[] { resultTime, resultUser, resultX, resultY, resultZ, resultWorldId, type, resultAction }; + result.add(lookupData); + } } - results.close(); } } catch (Exception e) { diff --git a/src/main/java/net/coreprotect/config/Config.java b/src/main/java/net/coreprotect/config/Config.java index 13a05b739..ad5f1c998 100644 --- a/src/main/java/net/coreprotect/config/Config.java +++ b/src/main/java/net/coreprotect/config/Config.java @@ -202,7 +202,7 @@ private void readValues() { this.UNKNOWN_LOGGING = this.getBoolean("unknown-logging", false); this.MAXIMUM_POOL_SIZE = this.getInt("maximum-pool-size", 10); this.DONATION_KEY = this.getString("donation-key"); - this.DB_TYPE = DatabaseType.valueOf(DatabaseType.class, this.getString("db-type").toUpperCase(Locale.US)); + this.DB_TYPE = DatabaseType.valueOf(DatabaseType.class, this.getString("db-type").toUpperCase(Locale.ROOT)); this.DB_PREFIX = this.getString("table-prefix"); this.DB_HOST = this.getString("db-host"); this.DB_PORT = this.getInt("db-port"); diff --git a/src/main/java/net/coreprotect/database/logger/UsernameLogger.java b/src/main/java/net/coreprotect/database/logger/UsernameLogger.java index 3119223f9..050764070 100644 --- a/src/main/java/net/coreprotect/database/logger/UsernameLogger.java +++ b/src/main/java/net/coreprotect/database/logger/UsernameLogger.java @@ -27,19 +27,19 @@ public static void log(Connection connection, String user, String uuid, int conf int idRow = -1; String userRow = null; String query = "SELECT rowid as id, user FROM " + StatementUtils.getTableName("user") + " WHERE uuid = ? LIMIT 1"; - PreparedStatement preparedStmt = connection.prepareStatement(query); - if (dbType == DatabaseType.PGSQL) { - preparedStmt.setObject(1, UUID.fromString(uuid), Types.OTHER); - } else { - preparedStmt.setString(1, uuid); - } - ResultSet rs = preparedStmt.executeQuery(); - while (rs.next()) { - idRow = rs.getInt("id"); - userRow = rs.getString("user").toLowerCase(Locale.ROOT); + try (PreparedStatement preparedStmt = connection.prepareStatement(query)) { + if (dbType == DatabaseType.PGSQL) { + preparedStmt.setObject(1, UUID.fromString(uuid), Types.OTHER); + } else { + preparedStmt.setString(1, uuid); + } + try (ResultSet rs = preparedStmt.executeQuery()) { + while (rs.next()) { + idRow = rs.getInt("id"); + userRow = rs.getString("user").toLowerCase(Locale.ROOT); + } + } } - rs.close(); - preparedStmt.close(); boolean update = false; if (userRow == null) { @@ -51,16 +51,16 @@ else if (!user.equalsIgnoreCase(userRow)) { } if (update) { - preparedStmt = connection.prepareStatement("UPDATE " + StatementUtils.getTableName("user") + " SET \"user\" = ?, uuid = ? WHERE rowid = ?"); - preparedStmt.setString(1, user); - if (dbType == DatabaseType.PGSQL) { - preparedStmt.setObject(2, UUID.fromString(uuid), Types.OTHER); - } else { - preparedStmt.setString(2, uuid); + try (PreparedStatement preparedStmt = connection.prepareStatement("UPDATE " + StatementUtils.getTableName("user") + " SET \"user\" = ?, uuid = ? WHERE rowid = ?")) { + preparedStmt.setString(1, user); + if (dbType == DatabaseType.PGSQL) { + preparedStmt.setObject(2, UUID.fromString(uuid), Types.OTHER); + } else { + preparedStmt.setString(2, uuid); + } + preparedStmt.setInt(3, idRow); + preparedStmt.executeUpdate(); } - preparedStmt.setInt(3, idRow); - preparedStmt.executeUpdate(); - preparedStmt.close(); /* //Commented out to prevent potential issues if player manages to stay logged in with old username @@ -75,19 +75,19 @@ else if (!user.equalsIgnoreCase(userRow)) { else { boolean foundUUID = false; query = "SELECT rowid as id FROM " + StatementUtils.getTableName("username_log") + " WHERE uuid = ? AND \"user\" = ? LIMIT 1"; - PreparedStatement preparedStatement = connection.prepareStatement(query); - if (dbType == DatabaseType.PGSQL) { - preparedStmt.setObject(1, UUID.fromString(uuid), Types.OTHER); - } else { - preparedStmt.setString(1, uuid); - } - preparedStatement.setString(2, user); - rs = preparedStatement.executeQuery(); - while (rs.next()) { - foundUUID = true; + try (PreparedStatement preparedStmt = connection.prepareStatement(query)) { + if (dbType == DatabaseType.PGSQL) { + preparedStmt.setObject(1, UUID.fromString(uuid), Types.OTHER); + } else { + preparedStmt.setString(1, uuid); + } + preparedStmt.setString(2, user); + try (ResultSet rs = preparedStmt.executeQuery()) { + while (rs.next()) { + foundUUID = true; + } + } } - rs.close(); - preparedStatement.close(); if (!foundUUID) { update = true; @@ -95,16 +95,16 @@ else if (!user.equalsIgnoreCase(userRow)) { } if (update && configUsernames == 1) { - preparedStmt = connection.prepareStatement("INSERT INTO " + StatementUtils.getTableName("username_log") + " (time, uuid, \"user\") VALUES (?, ?, ?)"); - preparedStmt.setInt(1, time); - if (dbType == DatabaseType.PGSQL) { - preparedStmt.setObject(2, UUID.fromString(uuid), Types.OTHER); - } else { - preparedStmt.setString(2, uuid); + try (PreparedStatement preparedStmt = connection.prepareStatement("INSERT INTO " + StatementUtils.getTableName("username_log") + " (time, uuid, \"user\") VALUES (?, ?, ?)")) { + preparedStmt.setInt(1, time); + if (dbType == DatabaseType.PGSQL) { + preparedStmt.setObject(2, UUID.fromString(uuid), Types.OTHER); + } else { + preparedStmt.setString(2, uuid); + } + preparedStmt.setString(3, user); + preparedStmt.executeUpdate(); } - preparedStmt.setString(3, user); - preparedStmt.executeUpdate(); - preparedStmt.close(); } ConfigHandler.playerIdCache.put(user.toLowerCase(Locale.ROOT), idRow); From c77ee07727868c73c874a3f86540862239278b20 Mon Sep 17 00:00:00 2001 From: Jon Huang Date: Tue, 30 Jan 2024 09:34:49 -0700 Subject: [PATCH 04/15] Update. --- .../database/statement/UserStatement.java | 42 ++++++++----------- 1 file changed, 18 insertions(+), 24 deletions(-) diff --git a/src/main/java/net/coreprotect/database/statement/UserStatement.java b/src/main/java/net/coreprotect/database/statement/UserStatement.java index ddf9a77d0..94aadcc7a 100644 --- a/src/main/java/net/coreprotect/database/statement/UserStatement.java +++ b/src/main/java/net/coreprotect/database/statement/UserStatement.java @@ -27,32 +27,26 @@ public static int insert(Connection connection, String user) { try { int unixtimestamp = (int) (System.currentTimeMillis() / 1000L); - PreparedStatement preparedStmt = null; if (Database.hasReturningKeys()) { - preparedStmt = connection.prepareStatement("INSERT INTO " + StatementUtils.getTableName("user") + " (time, \"user\") VALUES (?, ?) RETURNING rowid"); - } - else { - preparedStmt = connection.prepareStatement("INSERT INTO " + StatementUtils.getTableName("user") + " (time, \"user\") VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS); - } - - preparedStmt.setInt(1, unixtimestamp); - preparedStmt.setString(2, user); - - if (Database.hasReturningKeys()) { - ResultSet resultSet = preparedStmt.executeQuery(); - resultSet.next(); - id = resultSet.getInt(1); - resultSet.close(); - } - else { - preparedStmt.executeUpdate(); - ResultSet keys = preparedStmt.getGeneratedKeys(); - keys.next(); - id = keys.getInt(1); - keys.close(); + try (PreparedStatement preparedStmt = connection.prepareStatement("INSERT INTO " + StatementUtils.getTableName("user") + " (time, \"user\") VALUES (?, ?) RETURNING rowid")) { + preparedStmt.setInt(1, unixtimestamp); + preparedStmt.setString(2, user); + try (ResultSet resultSet = preparedStmt.executeQuery()) { + resultSet.next(); + id = resultSet.getInt(1); + } + } + } else { + try (PreparedStatement preparedStmt = connection.prepareStatement("INSERT INTO " + StatementUtils.getTableName("user") + " (time, \"user\") VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS)) { + preparedStmt.setInt(1, unixtimestamp); + preparedStmt.setString(2, user); + preparedStmt.executeUpdate(); + try (ResultSet keys = preparedStmt.getGeneratedKeys()) { + keys.next(); + id = keys.getInt(1); + } + } } - - preparedStmt.close(); } catch (Exception e) { e.printStackTrace(); From f07c0a7df8249f7014c529fab96da0ac0cbeb4e2 Mon Sep 17 00:00:00 2001 From: Jon Huang Date: Tue, 30 Jan 2024 09:02:47 -0800 Subject: [PATCH 05/15] Refactor. --- .../net/coreprotect/command/PurgeCommand.java | 129 +++++++----------- .../database/lookup/SignMessageLookup.java | 2 +- .../java/net/coreprotect/utility/Util.java | 13 +- 3 files changed, 62 insertions(+), 82 deletions(-) diff --git a/src/main/java/net/coreprotect/command/PurgeCommand.java b/src/main/java/net/coreprotect/command/PurgeCommand.java index f5f2a15ed..71b267765 100755 --- a/src/main/java/net/coreprotect/command/PurgeCommand.java +++ b/src/main/java/net/coreprotect/command/PurgeCommand.java @@ -134,16 +134,13 @@ public void run() { } Consumer.isPaused = true; - String query = ""; - PreparedStatement preparedStmt = null; boolean abort = false; String purgePrefix = "tmp_" + ConfigHandler.prefix; if (Config.getGlobal().DB_TYPE == DatabaseType.SQLITE) { - query = "ATTACH DATABASE '" + ConfigHandler.path + ConfigHandler.sqlite + ".tmp' AS tmp_db"; - preparedStmt = connection.prepareStatement(query); - preparedStmt.execute(); - preparedStmt.close(); + try (PreparedStatement ps = connection.prepareStatement("ATTACH DATABASE '" + ConfigHandler.path + ConfigHandler.sqlite + ".tmp' AS tmp_db")) { + ps.execute(); + } purgePrefix = "tmp_db." + ConfigHandler.prefix; } @@ -158,13 +155,9 @@ public void run() { if (Config.getGlobal().DB_TYPE == DatabaseType.SQLITE) { for (String table : ConfigHandler.databaseTables) { - try { - query = "DROP TABLE IF EXISTS " + purgePrefix + table + ""; - preparedStmt = connection.prepareStatement(query); - preparedStmt.execute(); - preparedStmt.close(); - } - catch (Exception e) { + try (PreparedStatement ps = connection.prepareStatement("DROP TABLE IF EXISTS " + purgePrefix + table)) { + ps.execute(); + } catch (Exception e) { e.printStackTrace(); } } @@ -181,19 +174,20 @@ public void run() { if (Config.getGlobal().DB_TYPE == DatabaseType.SQLITE) { String columns = ""; - ResultSet rs = connection.createStatement().executeQuery("SELECT * FROM " + purgePrefix + table); - ResultSetMetaData resultSetMetaData = rs.getMetaData(); - int columnCount = resultSetMetaData.getColumnCount(); - for (int i = 1; i <= columnCount; i++) { - String name = resultSetMetaData.getColumnName(i); - if (columns.length() == 0) { - columns = name; - } - else { - columns = columns + "," + name; + try (PreparedStatement ps = connection.prepareStatement("SELECT * FROM " + purgePrefix + table); + ResultSet rs = ps.executeQuery();) { + ResultSetMetaData resultSetMetaData = rs.getMetaData(); + int columnCount = resultSetMetaData.getColumnCount(); + for (int i = 1; i <= columnCount; i++) { + String name = resultSetMetaData.getColumnName(i); + if (columns.length() == 0) { + columns = name; + } + else { + columns = columns + "," + name; + } } } - rs.close(); boolean error = false; if (!excludeTables.contains(table)) { @@ -207,10 +201,9 @@ else if (argWid == 0) { timeLimit = " WHERE (time >= '" + timeEnd + "' OR time < '" + timeStart + "')"; } } - query = "INSERT INTO " + purgePrefix + table + " SELECT " + columns + " FROM " + StatementUtils.getTableName(table) + timeLimit; - preparedStmt = connection.prepareStatement(query); - preparedStmt.execute(); - preparedStmt.close(); + try (PreparedStatement ps = connection.prepareStatement("INSERT INTO " + purgePrefix + table + " SELECT " + columns + " FROM " + StatementUtils.getTableName(table) + timeLimit)) { + ps.execute(); + } } catch (Exception e) { error = true; @@ -222,21 +215,15 @@ else if (argWid == 0) { Chat.sendGlobalMessage(player, Phrase.build(Phrase.PURGE_ERROR, tableName)); Chat.sendGlobalMessage(player, Phrase.build(Phrase.PURGE_REPAIRING)); - try { - query = "DELETE FROM " + purgePrefix + table; - preparedStmt = connection.prepareStatement(query); - preparedStmt.execute(); - preparedStmt.close(); + try (PreparedStatement ps = connection.prepareStatement("DELETE FROM " + purgePrefix + table)) { + ps.execute(); } catch (Exception e) { e.printStackTrace(); } - try { - query = "REINDEX " + StatementUtils.getTableName(table); - preparedStmt = connection.prepareStatement(query); - preparedStmt.execute(); - preparedStmt.close(); + try (PreparedStatement ps = connection.prepareStatement("REINDEX " + StatementUtils.getTableName(table))) { + ps.execute(); } catch (Exception e) { e.printStackTrace(); @@ -244,10 +231,9 @@ else if (argWid == 0) { try { String index = " NOT INDEXED"; - query = "INSERT INTO " + purgePrefix + table + " SELECT " + columns + " FROM " + StatementUtils.getTableName(table) + index; - preparedStmt = connection.prepareStatement(query); - preparedStmt.execute(); - preparedStmt.close(); + try (PreparedStatement ps = connection.prepareStatement("INSERT INTO " + purgePrefix + table + " SELECT " + columns + " FROM " + StatementUtils.getTableName(table) + index)) { + ps.execute(); + } } catch (Exception e) { e.printStackTrace(); @@ -267,10 +253,9 @@ else if (argWid > 0) { } if (purge) { - query = "DELETE FROM " + purgePrefix + table + " WHERE time < '" + timeEnd + "' AND time >= '" + timeStart + "'" + worldRestriction; - preparedStmt = connection.prepareStatement(query); - preparedStmt.execute(); - preparedStmt.close(); + try (PreparedStatement ps = connection.prepareStatement("DELETE FROM " + purgePrefix + table + " WHERE time < '" + timeEnd + "' AND time >= '" + timeStart + "'" + worldRestriction)) { + ps.execute(); + } } } catch (Exception e) { @@ -280,32 +265,22 @@ else if (argWid > 0) { if (purgeTables.contains(table)) { int oldCount = 0; - try { - query = "SELECT COUNT(*) as count FROM " + StatementUtils.getTableName(table) + " LIMIT 1"; - preparedStmt = connection.prepareStatement(query); - ResultSet resultSet = preparedStmt.executeQuery(); + try (PreparedStatement ps = connection.prepareStatement("SELECT COUNT(*) as count FROM " + StatementUtils.getTableName(table) + " LIMIT 1"); + ResultSet resultSet = ps.executeQuery();) { while (resultSet.next()) { oldCount = resultSet.getInt("count"); } - resultSet.close(); - preparedStmt.close(); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } int new_count = 0; - try { - query = "SELECT COUNT(*) as count FROM " + purgePrefix + table + " LIMIT 1"; - preparedStmt = connection.prepareStatement(query); - ResultSet resultSet = preparedStmt.executeQuery(); + try (PreparedStatement ps = connection.prepareStatement("SELECT COUNT(*) as count FROM " + purgePrefix + table + " LIMIT 1"); + ResultSet resultSet = ps.executeQuery();) { while (resultSet.next()) { new_count = resultSet.getInt("count"); } - resultSet.close(); - preparedStmt.close(); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } @@ -319,18 +294,22 @@ else if (argWid > 0) { String worldRestriction = ""; if (argWid > 0 && worldTables.contains(table)) { - worldRestriction = " AND wid = '" + argWid + "'"; + worldRestriction = " AND wid = ?"; } else if (argWid > 0) { purge = false; } if (purge) { - query = "DELETE FROM " + StatementUtils.getTableName(table) + " WHERE time < '" + timeEnd + "' AND time >= '" + timeStart + "'" + worldRestriction; - preparedStmt = connection.prepareStatement(query); - preparedStmt.execute(); - removed = removed + preparedStmt.getUpdateCount(); - preparedStmt.close(); + try (PreparedStatement preparedStmt = connection.prepareStatement("DELETE FROM " + StatementUtils.getTableName(table) + " WHERE time < ? AND time >= ?" + worldRestriction)) { + preparedStmt.setLong(1, timeEnd); + preparedStmt.setLong(2, timeStart); + if (!worldRestriction.isEmpty()) { + preparedStmt.setInt(3, argWid); + } + preparedStmt.execute(); + removed = removed + preparedStmt.getUpdateCount(); + } } } catch (Exception e) { @@ -349,20 +328,18 @@ else if (argWid > 0) { case MYSQL: { Chat.sendGlobalMessage(player, Phrase.build(Phrase.PURGE_OPTIMIZING)); for (String table : ConfigHandler.databaseTables) { - query = "OPTIMIZE LOCAL TABLE " + StatementUtils.getTableName(table) + ""; - preparedStmt = connection.prepareStatement(query); - preparedStmt.execute(); - preparedStmt.close(); + try (PreparedStatement preparedStmt = connection.prepareStatement("OPTIMIZE LOCAL TABLE " + StatementUtils.getTableName(table))) { + preparedStmt.execute(); + } } break; } case PGSQL: { Chat.sendGlobalMessage(player, Phrase.build(Phrase.PURGE_OPTIMIZING)); for (String table : ConfigHandler.databaseTables) { - query = "VACUUM ANALYZE " + StatementUtils.getTableName(table); - preparedStmt = connection.prepareStatement(query); - preparedStmt.execute(); - preparedStmt.close(); + try (PreparedStatement preparedStmt = connection.prepareStatement("VACUUM ANALYZE " + StatementUtils.getTableName(table))) { + preparedStmt.execute(); + } } break; } diff --git a/src/main/java/net/coreprotect/database/lookup/SignMessageLookup.java b/src/main/java/net/coreprotect/database/lookup/SignMessageLookup.java index 5cf5d5917..7125eb55d 100644 --- a/src/main/java/net/coreprotect/database/lookup/SignMessageLookup.java +++ b/src/main/java/net/coreprotect/database/lookup/SignMessageLookup.java @@ -66,7 +66,7 @@ else if (commandSender.hasPermission("coreprotect.coreprotect")) { int totalPages = (int) Math.ceil(count / (limit + 0.0)); - query = "SELECT time,user,face,line_1,line_2,line_3,line_4,line_5,line_6,line_7,line_8 FROM " + StatementUtils.getTableName("sign") + " " + Util.getWidIndex("sign") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action = '1' AND (LENGTH(line_1) > 0 OR LENGTH(line_2) > 0 OR LENGTH(line_3) > 0 OR LENGTH(line_4) > 0 OR LENGTH(line_5) > 0 OR LENGTH(line_6) > 0 OR LENGTH(line_7) > 0 OR LENGTH(line_8) > 0) ORDER BY rowid DESC LIMIT " + limit + " OFFSET " + pageStart; + query = "SELECT time, \"user\", face, line_1, line_2, line_3, line_4, line_5, line_6, line_7, line_8 FROM " + StatementUtils.getTableName("sign") + " " + Util.getWidIndex("sign") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action = '1' AND (LENGTH(line_1) > 0 OR LENGTH(line_2) > 0 OR LENGTH(line_3) > 0 OR LENGTH(line_4) > 0 OR LENGTH(line_5) > 0 OR LENGTH(line_6) > 0 OR LENGTH(line_7) > 0 OR LENGTH(line_8) > 0) ORDER BY rowid DESC LIMIT " + limit + " OFFSET " + pageStart; results = statement.executeQuery(query); while (results.next()) { diff --git a/src/main/java/net/coreprotect/utility/Util.java b/src/main/java/net/coreprotect/utility/Util.java index 5188885f4..2f030362d 100755 --- a/src/main/java/net/coreprotect/utility/Util.java +++ b/src/main/java/net/coreprotect/utility/Util.java @@ -1589,12 +1589,12 @@ public static boolean checkWorldEdit() { } public static String getWidIndex(String queryTable) { - String index = ""; - boolean isRDB = Config.getGlobal().DB_TYPE != DatabaseType.SQLITE; - if (isRDB) { + DatabaseType dbType = Config.getGlobal().DB_TYPE; + String index; + if (dbType == DatabaseType.MYSQL) { + // mysql has the use index hint index = "USE INDEX(wid) "; - } - else { + } else if (dbType == DatabaseType.SQLITE) { switch (queryTable) { case "block": index = "INDEXED BY block_index "; @@ -1618,8 +1618,11 @@ public static String getWidIndex(String queryTable) { index = "INDEXED BY session_index "; break; default: + index = ""; break; } + } else { + index = ""; } return index; From 53176ab0c9b22e03006a4b9feadc4f1c28188ad9 Mon Sep 17 00:00:00 2001 From: Jon Huang Date: Tue, 30 Jan 2024 13:01:11 -0800 Subject: [PATCH 06/15] Update. --- src/main/java/net/coreprotect/config/ConfigHandler.java | 2 +- src/main/java/net/coreprotect/database/Database.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/net/coreprotect/config/ConfigHandler.java b/src/main/java/net/coreprotect/config/ConfigHandler.java index c1f5ece54..141759e43 100644 --- a/src/main/java/net/coreprotect/config/ConfigHandler.java +++ b/src/main/java/net/coreprotect/config/ConfigHandler.java @@ -308,7 +308,7 @@ public static void loadTypes(Statement statement) { } rs.close(); - query = "SELECT id,art FROM " + StatementUtils.getTableName("art_map"); + query = "SELECT id, art FROM " + StatementUtils.getTableName("art_map"); rs = statement.executeQuery(query); ConfigHandler.art.clear(); ConfigHandler.artReversed.clear(); diff --git a/src/main/java/net/coreprotect/database/Database.java b/src/main/java/net/coreprotect/database/Database.java index cbbcb4f3e..2db26ed70 100755 --- a/src/main/java/net/coreprotect/database/Database.java +++ b/src/main/java/net/coreprotect/database/Database.java @@ -373,7 +373,7 @@ public static void createDatabaseTables(String prefix, boolean purge) { statement.executeUpdate("create index if not exists \"" + prefix + "container_user_time_index\" on \"" + prefix + "container\" (\"user\", \"time\")"); statement.executeUpdate("create index if not exists \"" + prefix + "container_type_time_index\" on \"" + prefix + "container\" (\"type\", \"time\")"); - statement.executeUpdate("create table if not exists \"" + prefix + "item\" (\"rowid\" bigserial primary key not null, \"time\" integer not null, \"user\" integer not null, \"wid\" integer not null, \"x\" integer not null, \"y\" smallint not null, \"z\" integer not null, \"type\" integer not null, \"data\" bytea not null, \"amount\" integer not null, \"action\" smallint not null, \"rolled_back\" smallint not null)"); + statement.executeUpdate("create table if not exists \"" + prefix + "item\" (\"rowid\" bigserial primary key not null, \"time\" integer not null, \"user\" integer not null, \"wid\" integer not null, \"x\" integer not null, \"y\" smallint not null, \"z\" integer not null, \"type\" integer not null, \"data\" bytea null, \"amount\" integer not null, \"action\" smallint not null, \"rolled_back\" smallint not null)"); statement.executeUpdate("create index if not exists \"" + prefix + "item_wid_x_z_time_index\" on \"" + prefix + "item\" (\"wid\", \"x\", \"z\", \"time\")"); statement.executeUpdate("create index if not exists \"" + prefix + "item_user_time_index\" on \"" + prefix + "item\" (\"user\", \"time\")"); statement.executeUpdate("create index if not exists \"" + prefix + "item_type_time_index\" on \"" + prefix + "item\" (\"type\", \"time\")"); From 19382da77849eb66939f71c70bcf6dcb640c1264 Mon Sep 17 00:00:00 2001 From: Jon Huang Date: Tue, 30 Jan 2024 13:30:57 -0800 Subject: [PATCH 07/15] Fix. --- .../consumer/process/SignUpdateProcess.java | 4 ++-- .../java/net/coreprotect/database/Lookup.java | 18 +++++++++--------- .../database/logger/UsernameLogger.java | 2 +- .../database/lookup/BlockLookup.java | 2 +- .../database/lookup/PlayerLookup.java | 2 +- .../database/statement/UserStatement.java | 2 +- 6 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/main/java/net/coreprotect/consumer/process/SignUpdateProcess.java b/src/main/java/net/coreprotect/consumer/process/SignUpdateProcess.java index 3e464c593..6b6ad4a92 100644 --- a/src/main/java/net/coreprotect/consumer/process/SignUpdateProcess.java +++ b/src/main/java/net/coreprotect/consumer/process/SignUpdateProcess.java @@ -27,9 +27,9 @@ static void process(Statement statement, Object object, String user, int action, int userid = ConfigHandler.playerIdCache.get(user.toLowerCase(Locale.ROOT)); String query; if (action == 0) { - query = "SELECT color, color_secondary, data, waxed, face, line_1, line_2, line_3, line_4, line_5, line_6, line_7, line_8 FROM " + StatementUtils.getTableName("sign") + " WHERE user='" + userid + "' AND wid='" + wid + "' AND x='" + x + "' AND z='" + z + "' AND y='" + y + "' AND time < '" + time + "' ORDER BY rowid DESC LIMIT 1"; + query = "SELECT color, color_secondary, data, waxed, face, line_1, line_2, line_3, line_4, line_5, line_6, line_7, line_8 FROM " + StatementUtils.getTableName("sign") + " WHERE \"user\"='" + userid + "' AND wid='" + wid + "' AND x='" + x + "' AND z='" + z + "' AND y='" + y + "' AND time < '" + time + "' ORDER BY rowid DESC LIMIT 1"; } else { - query = "SELECT color, color_secondary, data, waxed, face, line_1, line_2, line_3, line_4, line_5, line_6, line_7, line_8 FROM " + StatementUtils.getTableName("sign") + " WHERE user='" + userid + "' AND wid='" + wid + "' AND x='" + x + "' AND z='" + z + "' AND y='" + y + "' AND time >= '" + time + "' ORDER BY rowid ASC LIMIT 1"; + query = "SELECT color, color_secondary, data, waxed, face, line_1, line_2, line_3, line_4, line_5, line_6, line_7, line_8 FROM " + StatementUtils.getTableName("sign") + " WHERE \"user\"='" + userid + "' AND wid='" + wid + "' AND x='" + x + "' AND z='" + z + "' AND y='" + y + "' AND time >= '" + time + "' ORDER BY rowid ASC LIMIT 1"; } SignStatement.getData(statement, block, query); Util.updateBlock(block); diff --git a/src/main/java/net/coreprotect/database/Lookup.java b/src/main/java/net/coreprotect/database/Lookup.java index 7afa4f648..60706567f 100755 --- a/src/main/java/net/coreprotect/database/Lookup.java +++ b/src/main/java/net/coreprotect/database/Lookup.java @@ -651,16 +651,16 @@ else if (inventoryQuery || actionExclude.length() > 0 || includeBlock.length() > unionLimit = " ORDER BY time DESC, id DESC LIMIT " + (limitOffset + limitCount) + ""; } - String rows = "rowid as id,time,user,wid,x,y,z,action,type,data,meta,blockdata,rolled_back"; + String rows = "rowid as id,time,\"user\",wid,x,y,z,action,type,data,meta,blockdata,rolled_back"; String queryOrder = " ORDER BY rowid DESC"; if (actionList.contains(4) || actionList.contains(5)) { queryTable = "container"; - rows = "rowid as id,time,user,wid,x,y,z,action,type,data,rolled_back,amount,metadata"; + rows = "rowid as id,time,\"user\",wid,x,y,z,action,type,data,rolled_back,amount,metadata"; } else if (actionList.contains(6) || actionList.contains(7)) { queryTable = "chat"; - rows = "rowid as id,time,user,message"; + rows = "rowid as id,time,\"user\",message"; if (PluginChannelHandshakeListener.getInstance().isPluginChannelPlayer(user)) { rows += ",wid,x,y,z"; } @@ -671,19 +671,19 @@ else if (actionList.contains(6) || actionList.contains(7)) { } else if (actionList.contains(8)) { queryTable = "session"; - rows = "rowid as id,time,user,wid,x,y,z,action"; + rows = "rowid as id,time,\"user\",wid,x,y,z,action"; } else if (actionList.contains(9)) { queryTable = "username_log"; - rows = "rowid as id,time,uuid,user"; + rows = "rowid as id,time,uuid,\"user\""; } else if (actionList.contains(10)) { queryTable = "sign"; - rows = "rowid as id,time,user,wid,x,y,z,face,line_1,line_2,line_3,line_4,line_5,line_6,line_7,line_8"; + rows = "rowid as id,time,\"user\",wid,x,y,z,face,line_1,line_2,line_3,line_4,line_5,line_6,line_7,line_8"; } else if (actionList.contains(11)) { queryTable = "item"; - rows = "rowid as id,time,user,wid,x,y,z,type,data as metadata,0 as data,amount,action,0 as rolled_back"; + rows = "rowid as id,time,\"user\",wid,x,y,z,type,data as metadata,0 as data,amount,action,0 as rolled_back"; } if (count) { @@ -732,7 +732,7 @@ else if (actionList.contains(11)) { boolean itemLookup = inventoryQuery; if ((lookup && actionList.size() == 0) || (itemLookup && !actionList.contains(0))) { if (!count) { - rows = "rowid as id,time,user,wid,x,y,z,type,meta as metadata,data,-1 as amount,action,rolled_back"; + rows = "rowid as id,time,\"user\",wid,x,y,z,type,meta as metadata,data,-1 as amount,action,rolled_back"; } if (inventoryQuery) { @@ -744,7 +744,7 @@ else if (actionList.contains(11)) { } if (!count) { - rows = "rowid as id,time,user,wid,x,y,z,type,meta as metadata,data,1 as amount,action,rolled_back"; + rows = "rowid as id,time,\"user\",wid,x,y,z,type,meta as metadata,data,1 as amount,action,rolled_back"; } } diff --git a/src/main/java/net/coreprotect/database/logger/UsernameLogger.java b/src/main/java/net/coreprotect/database/logger/UsernameLogger.java index 050764070..fd0878ce9 100644 --- a/src/main/java/net/coreprotect/database/logger/UsernameLogger.java +++ b/src/main/java/net/coreprotect/database/logger/UsernameLogger.java @@ -26,7 +26,7 @@ public static void log(Connection connection, String user, String uuid, int conf DatabaseType dbType = Config.getGlobal().DB_TYPE; int idRow = -1; String userRow = null; - String query = "SELECT rowid as id, user FROM " + StatementUtils.getTableName("user") + " WHERE uuid = ? LIMIT 1"; + String query = "SELECT rowid as id, \"user\" FROM " + StatementUtils.getTableName("user") + " WHERE uuid = ? LIMIT 1"; try (PreparedStatement preparedStmt = connection.prepareStatement(query)) { if (dbType == DatabaseType.PGSQL) { preparedStmt.setObject(1, UUID.fromString(uuid), Types.OTHER); diff --git a/src/main/java/net/coreprotect/database/lookup/BlockLookup.java b/src/main/java/net/coreprotect/database/lookup/BlockLookup.java index c9a901c43..ee37fd5d2 100644 --- a/src/main/java/net/coreprotect/database/lookup/BlockLookup.java +++ b/src/main/java/net/coreprotect/database/lookup/BlockLookup.java @@ -66,7 +66,7 @@ else if (commandSender.hasPermission("coreprotect.coreprotect")) { results.close(); int totalPages = (int) Math.ceil(count / (limit + 0.0)); - query = "SELECT time,user,action,type,data,rolled_back FROM " + StatementUtils.getTableName("block") + " " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action IN(0,1) AND time >= '" + checkTime + "' ORDER BY rowid DESC LIMIT " + limit + " OFFSET " + page_start; + query = "SELECT time, \"user\", action, type, data, rolled_back FROM " + StatementUtils.getTableName("block") + " " + Util.getWidIndex("block") + "WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action IN(0,1) AND time >= '" + checkTime + "' ORDER BY rowid DESC LIMIT " + limit + " OFFSET " + page_start; results = statement.executeQuery(query); StringBuilder resultTextBuilder = new StringBuilder(); diff --git a/src/main/java/net/coreprotect/database/lookup/PlayerLookup.java b/src/main/java/net/coreprotect/database/lookup/PlayerLookup.java index 31c5f35cf..494794f72 100644 --- a/src/main/java/net/coreprotect/database/lookup/PlayerLookup.java +++ b/src/main/java/net/coreprotect/database/lookup/PlayerLookup.java @@ -26,7 +26,7 @@ public static boolean playerExists(Connection connection, String user) { collate = " COLLATE NOCASE"; } - String query = "SELECT rowid as id, uuid FROM " + StatementUtils.getTableName("user") + " WHERE user = ?" + collate + " LIMIT 1"; + String query = "SELECT rowid as id, uuid FROM " + StatementUtils.getTableName("user") + " WHERE \"user\" = ?" + collate + " LIMIT 1"; PreparedStatement preparedStmt = connection.prepareStatement(query); preparedStmt.setString(1, user); diff --git a/src/main/java/net/coreprotect/database/statement/UserStatement.java b/src/main/java/net/coreprotect/database/statement/UserStatement.java index 94aadcc7a..f8edda88d 100644 --- a/src/main/java/net/coreprotect/database/statement/UserStatement.java +++ b/src/main/java/net/coreprotect/database/statement/UserStatement.java @@ -73,7 +73,7 @@ public static int loadId(Connection connection, String user, String uuid) { collate = " COLLATE NOCASE"; } - String where = "user = ?" + collate; + String where = "\"user\" = ?" + collate; if (uuid != null) { where += " OR uuid = ?"; } From 0494c3177594a13eb9b9c6ea62d7d80719f3f616 Mon Sep 17 00:00:00 2001 From: Jon Huang Date: Tue, 30 Jan 2024 14:13:46 -0800 Subject: [PATCH 08/15] Fix. --- .../java/net/coreprotect/database/statement/UserStatement.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/net/coreprotect/database/statement/UserStatement.java b/src/main/java/net/coreprotect/database/statement/UserStatement.java index f8edda88d..0db23f7f9 100644 --- a/src/main/java/net/coreprotect/database/statement/UserStatement.java +++ b/src/main/java/net/coreprotect/database/statement/UserStatement.java @@ -123,7 +123,7 @@ public static String loadName(Connection connection, int id) { try { Statement statement = connection.createStatement(); - String query = "SELECT user, uuid FROM " + StatementUtils.getTableName("user") + " WHERE rowid='" + id + "' LIMIT 1"; + String query = "SELECT \"user\", uuid FROM " + StatementUtils.getTableName("user") + " WHERE rowid='" + id + "' LIMIT 1"; ResultSet resultSet = statement.executeQuery(query); while (resultSet.next()) { From 3d317fb0e5be360089262e90476e2e0f9bd4e568 Mon Sep 17 00:00:00 2001 From: Jon Huang Date: Tue, 30 Jan 2024 19:14:26 -0800 Subject: [PATCH 09/15] Update. --- .../java/net/coreprotect/config/Config.java | 1 + .../coreprotect/database/StatementUtils.java | 18 +++++++++++++++--- .../java/net/coreprotect/model/BlockGroup.java | 2 +- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/main/java/net/coreprotect/config/Config.java b/src/main/java/net/coreprotect/config/Config.java index ad5f1c998..63b2e930e 100644 --- a/src/main/java/net/coreprotect/config/Config.java +++ b/src/main/java/net/coreprotect/config/Config.java @@ -147,6 +147,7 @@ public class Config extends Language { DEFAULT_VALUES.put("worldedit", "true"); HEADERS.put("donation-key", new String[] { "# CoreProtect is donationware. Obtain a donation key from coreprotect.net/donate/" }); + HEADERS.put("db-type", new String[] { "# The database type to use. By default this is \"sqlite\"", "# Available options: sqlite, mysql, pgsql" }); HEADERS.put("language", new String[] { "# If modified, will automatically attempt to translate languages phrases.", "# List of language codes: https://coreprotect.net/languages/" }); HEADERS.put("check-updates", new String[] { "# If enabled, CoreProtect will check for updates when your server starts up.", "# If an update is available, you'll be notified via your server console.", }); HEADERS.put("api-enabled", new String[] { "# If enabled, other plugins will be able to utilize the CoreProtect API.", }); diff --git a/src/main/java/net/coreprotect/database/StatementUtils.java b/src/main/java/net/coreprotect/database/StatementUtils.java index dadba20e6..f07c1b223 100644 --- a/src/main/java/net/coreprotect/database/StatementUtils.java +++ b/src/main/java/net/coreprotect/database/StatementUtils.java @@ -2,19 +2,31 @@ import java.util.Objects; -import org.jetbrains.annotations.NotNull; - import net.coreprotect.config.ConfigHandler; public final class StatementUtils { private StatementUtils() { } - public static String getTableName(@NotNull String table) { + /** + * Creates a table name with the configured prefix and provided table name. + * + * @param table The SQL table name. + * @return The prepended table name with the table prefix. + */ + public static String getTableName(String table) { Objects.requireNonNull(table, "table cannot be null"); return "\"" + ConfigHandler.prefix + table + "\""; } + /** + * Creates a SQL "LIMIT ... OFFSET ..." query fragment compatible with multiple + * databases. + * + * @param limit The number of results to limit. + * @param offset The offset for the results. + * @return The SQL limit statement as a {@link String}. + */ public static String getLimit(int limit, int offset) { if (limit <= 0) { throw new IllegalArgumentException("limit must be greater than 0"); diff --git a/src/main/java/net/coreprotect/model/BlockGroup.java b/src/main/java/net/coreprotect/model/BlockGroup.java index 07f2e20d2..e53635b60 100644 --- a/src/main/java/net/coreprotect/model/BlockGroup.java +++ b/src/main/java/net/coreprotect/model/BlockGroup.java @@ -56,7 +56,7 @@ public static void initialize() { TRACK_ANY.addAll(BUTTONS); TRACK_TOP.addAll(DOORS); TRACK_TOP.addAll(PRESSURE_PLATES); - TRACK_TOP.addAll(Tag.WOOL_CARPETS.getValues()); + TRACK_TOP.addAll(Tag.CARPETS.getValues()); TRACK_TOP_BOTTOM.addAll(LANTERNS); LIGHTABLES.addAll(CANDLES); INTERACT_BLOCKS.addAll(DOORS); From 4471ee208d9ea29794b17211d5948e2453afd6f2 Mon Sep 17 00:00:00 2001 From: Jon Huang Date: Tue, 30 Jan 2024 20:09:57 -0800 Subject: [PATCH 10/15] Migrate database options. --- .../java/net/coreprotect/config/Config.java | 30 ++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/src/main/java/net/coreprotect/config/Config.java b/src/main/java/net/coreprotect/config/Config.java index 63b2e930e..664331e19 100644 --- a/src/main/java/net/coreprotect/config/Config.java +++ b/src/main/java/net/coreprotect/config/Config.java @@ -203,13 +203,32 @@ private void readValues() { this.UNKNOWN_LOGGING = this.getBoolean("unknown-logging", false); this.MAXIMUM_POOL_SIZE = this.getInt("maximum-pool-size", 10); this.DONATION_KEY = this.getString("donation-key"); - this.DB_TYPE = DatabaseType.valueOf(DatabaseType.class, this.getString("db-type").toUpperCase(Locale.ROOT)); + this.DB_TYPE = DatabaseType.valueOf(DatabaseType.class, this.getString("db-type", "sqlite").toUpperCase(Locale.ROOT)); + if (this.has("use-mysql") && this.getBoolean("use-mysql")) { + // legacy configuration has mysql enabled + this.DB_TYPE = DatabaseType.MYSQL; + } this.DB_PREFIX = this.getString("table-prefix"); this.DB_HOST = this.getString("db-host"); + if (this.DB_HOST == null && this.has("mysql-host")) { + this.DB_HOST = this.getString("mysql-host"); + } this.DB_PORT = this.getInt("db-port"); + if (this.DB_PORT == 0 && this.has("mysql-port")) { + this.DB_PORT = this.getInt("mysql-port"); + } this.DB_DATABASE = this.getString("db-database"); + if (this.DB_DATABASE == null && this.has("mysql-database")) { + this.DB_DATABASE = this.getString("mysql-database"); + } this.DB_USERNAME = this.getString("db-username"); + if (this.DB_USERNAME == null && this.has("mysql-username")) { + this.DB_USERNAME = this.getString("mysql-username"); + } this.DB_PASSWORD = this.getString("db-password"); + if (this.DB_PASSWORD == null && this.has("mysql-password")) { + this.DB_PASSWORD = this.getString("mysql-password"); + } this.LANGUAGE = this.getString("language"); this.CHECK_UPDATES = this.getBoolean("check-updates"); this.API_ENABLED = this.getBoolean("api-enabled"); @@ -279,6 +298,10 @@ public void setDefaults(final Config defaults) { this.defaults = defaults; } + private boolean has(final String key) { + return this.config.containsKey(key); + } + private String get(final String key, final String dfl) { String configured = this.config.get(key); if (configured == null) { @@ -326,6 +349,11 @@ private String getString(final String key) { return configured == null ? "" : configured; } + private String getString(final String key, final String dfl) { + final String configured = this.get(key, dfl); + return configured == null ? "" : configured; + } + public void clearConfig() { this.config.clear(); } From 8e4e2368af198c961367b33a2e83bdcc6fc14dde Mon Sep 17 00:00:00 2001 From: Jon Huang Date: Tue, 30 Jan 2024 20:37:35 -0800 Subject: [PATCH 11/15] Set db type to mysql if mysql is enabled. --- src/main/java/net/coreprotect/config/Config.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/net/coreprotect/config/Config.java b/src/main/java/net/coreprotect/config/Config.java index 664331e19..cf9694124 100644 --- a/src/main/java/net/coreprotect/config/Config.java +++ b/src/main/java/net/coreprotect/config/Config.java @@ -207,6 +207,7 @@ private void readValues() { if (this.has("use-mysql") && this.getBoolean("use-mysql")) { // legacy configuration has mysql enabled this.DB_TYPE = DatabaseType.MYSQL; + DEFAULT_VALUES.put("db-type", DatabaseType.MYSQL.toString().toLowerCase(Locale.ROOT)); } this.DB_PREFIX = this.getString("table-prefix"); this.DB_HOST = this.getString("db-host"); From 2b4c101ed766810cff27cc3b5717da502186eac7 Mon Sep 17 00:00:00 2001 From: Jon Huang Date: Sun, 11 Feb 2024 20:15:33 -0800 Subject: [PATCH 12/15] Fix. --- src/main/java/net/coreprotect/database/Database.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/net/coreprotect/database/Database.java b/src/main/java/net/coreprotect/database/Database.java index 2db26ed70..16b51d2f0 100755 --- a/src/main/java/net/coreprotect/database/Database.java +++ b/src/main/java/net/coreprotect/database/Database.java @@ -397,7 +397,7 @@ public static void createDatabaseTables(String prefix, boolean purge) { statement.executeUpdate("create index if not exists \"" + prefix + "session_user_time_index\" on \"" + prefix + "session\" (\"user\", \"time\")"); statement.executeUpdate("create index if not exists \"" + prefix + "session_time_index\" on \"" + prefix + "session\" (\"time\")"); - statement.executeUpdate("create table if not exists \"" + prefix + "sign\" (\"rowid\" bigserial primary key not null, \"time\" integer not null, \"user\" integer not null, \"wid\" integer not null, \"x\" integer not null, \"y\" smallint not null, \"z\" integer not null, \"action\" smallint not null, \"color\" integer not null, \"color_secondary\" integer not null, \"data\" smallint not null, \"waxed\" smallint not null, \"face\" smallint not null, \"line_1\" varchar(100) not null, \"line_2\" varchar(100) not null, \"line_3\" varchar(100) not null, \"line_4\" varchar(100) not null, \"line_5\" varchar(100) not null, \"line_6\" varchar(100) not null, \"line_7\" varchar(100) not null, \"line_8\" varchar(100) not null)"); + statement.executeUpdate("create table if not exists \"" + prefix + "sign\" (\"rowid\" bigserial primary key not null, \"time\" integer not null, \"user\" integer not null, \"wid\" integer not null, \"x\" integer not null, \"y\" smallint not null, \"z\" integer not null, \"action\" smallint not null, \"color\" integer not null, \"color_secondary\" integer not null, \"data\" smallint not null, \"waxed\" smallint not null, \"face\" smallint not null, \"line_1\" varchar(100) null, \"line_2\" varchar(100) null, \"line_3\" varchar(100) null, \"line_4\" varchar(100) null, \"line_5\" varchar(100) null, \"line_6\" varchar(100) null, \"line_7\" varchar(100) null, \"line_8\" varchar(100) null)"); statement.executeUpdate("create index if not exists \"" + prefix + "sign_wid_x_z_time_index\" on \"" + prefix + "sign\" (\"wid\", \"x\", \"z\", \"time\")"); statement.executeUpdate("create index if not exists \"" + prefix + "sign_user_time_index\" on \"" + prefix + "sign\" (\"user\", \"time\")"); statement.executeUpdate("create index if not exists \"" + prefix + "sign_time_index\" on \"" + prefix + "sign\" (\"time\")"); From 5922523326142105854e7014de9c2097dd7133ad Mon Sep 17 00:00:00 2001 From: PseudoResonance Date: Tue, 16 Apr 2024 07:28:57 -0700 Subject: [PATCH 13/15] Add extra JDBC parameter config option Config option to supply extra parameters to the JDBC string for advanced cases. Example: Useful for connecting to Postgres behind pgbouncer when set to ?prepareThreshold=0 Signed-off-by: PseudoResonance --- src/main/java/net/coreprotect/config/Config.java | 4 ++++ src/main/java/net/coreprotect/config/ConfigHandler.java | 6 ++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main/java/net/coreprotect/config/Config.java b/src/main/java/net/coreprotect/config/Config.java index cf9694124..6feecb111 100644 --- a/src/main/java/net/coreprotect/config/Config.java +++ b/src/main/java/net/coreprotect/config/Config.java @@ -44,6 +44,7 @@ public class Config extends Language { public String DB_DATABASE; public String DB_USERNAME; public String DB_PASSWORD; + public String DB_JDBC_PARAMETERS; public String LANGUAGE; public boolean ENABLE_AWE; public boolean ENABLE_SSL; @@ -105,6 +106,7 @@ public class Config extends Language { DEFAULT_VALUES.put("db-database", "database"); DEFAULT_VALUES.put("db-username", "root"); DEFAULT_VALUES.put("db-password", ""); + DEFAULT_VALUES.put("db-jdbc-parameters", ""); DEFAULT_VALUES.put("language", "en"); DEFAULT_VALUES.put("check-updates", "true"); DEFAULT_VALUES.put("api-enabled", "true"); @@ -148,6 +150,7 @@ public class Config extends Language { HEADERS.put("donation-key", new String[] { "# CoreProtect is donationware. Obtain a donation key from coreprotect.net/donate/" }); HEADERS.put("db-type", new String[] { "# The database type to use. By default this is \"sqlite\"", "# Available options: sqlite, mysql, pgsql" }); + HEADERS.put("db-jdbc-parameters", new String[] { "# Extra parameters to append to the JDBC connection string. Only needed for advanced cases." }); HEADERS.put("language", new String[] { "# If modified, will automatically attempt to translate languages phrases.", "# List of language codes: https://coreprotect.net/languages/" }); HEADERS.put("check-updates", new String[] { "# If enabled, CoreProtect will check for updates when your server starts up.", "# If an update is available, you'll be notified via your server console.", }); HEADERS.put("api-enabled", new String[] { "# If enabled, other plugins will be able to utilize the CoreProtect API.", }); @@ -230,6 +233,7 @@ private void readValues() { if (this.DB_PASSWORD == null && this.has("mysql-password")) { this.DB_PASSWORD = this.getString("mysql-password"); } + this.DB_JDBC_PARAMETERS = this.getString("db-jdbc-parameters"); this.LANGUAGE = this.getString("language"); this.CHECK_UPDATES = this.getBoolean("check-updates"); this.API_ENABLED = this.getBoolean("api-enabled"); diff --git a/src/main/java/net/coreprotect/config/ConfigHandler.java b/src/main/java/net/coreprotect/config/ConfigHandler.java index 141759e43..b2ca24755 100644 --- a/src/main/java/net/coreprotect/config/ConfigHandler.java +++ b/src/main/java/net/coreprotect/config/ConfigHandler.java @@ -52,6 +52,7 @@ public class ConfigHandler extends Queue { public static String database = "database"; public static String username = "root"; public static String password = ""; + public static String jdbcParameters = ""; public static String prefix = "co_"; public static int maximumPoolSize = 10; @@ -177,6 +178,7 @@ private static void loadConfig() { ConfigHandler.database = Config.getGlobal().DB_DATABASE; ConfigHandler.username = Config.getGlobal().DB_USERNAME; ConfigHandler.password = Config.getGlobal().DB_PASSWORD; + ConfigHandler.jdbcParameters = Config.getGlobal().DB_JDBC_PARAMETERS; ConfigHandler.maximumPoolSize = Config.getGlobal().MAXIMUM_POOL_SIZE; ConfigHandler.prefix = Config.getGlobal().DB_PREFIX; @@ -230,7 +232,7 @@ public static void loadDatabase() { config.setDriverClassName("com.mysql.jdbc.Driver"); } - config.setJdbcUrl("jdbc:mysql://" + ConfigHandler.host + ":" + ConfigHandler.port + "/" + ConfigHandler.database); + config.setJdbcUrl("jdbc:mysql://" + ConfigHandler.host + ":" + ConfigHandler.port + "/" + ConfigHandler.database + ConfigHandler.jdbcParameters); config.setUsername(ConfigHandler.username); config.setPassword(ConfigHandler.password); config.setMaximumPoolSize(ConfigHandler.maximumPoolSize); @@ -260,7 +262,7 @@ public static void loadDatabase() { } catch (Exception e) { throw new RuntimeException(e); } - config.setJdbcUrl("jdbc:postgresql://" + ConfigHandler.host + ":" + ConfigHandler.port + "/" + ConfigHandler.database); + config.setJdbcUrl("jdbc:postgresql://" + ConfigHandler.host + ":" + ConfigHandler.port + "/" + ConfigHandler.database + ConfigHandler.jdbcParameters); config.setUsername(ConfigHandler.username); config.setPassword(ConfigHandler.password); config.setMaxLifetime(300000); From c7931d83c12b693ef632729f33813e4793a3946d Mon Sep 17 00:00:00 2001 From: PseudoResonance Date: Tue, 16 Apr 2024 07:30:23 -0700 Subject: [PATCH 14/15] Fix Postgres lookup Disables index hinting for Postgres Adds subquery aliases when creating unions Signed-off-by: PseudoResonance --- .../net/coreprotect/database/Database.java | 2 +- .../java/net/coreprotect/database/Lookup.java | 22 ++++++++++++++----- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/main/java/net/coreprotect/database/Database.java b/src/main/java/net/coreprotect/database/Database.java index 16b51d2f0..cea27ad0e 100755 --- a/src/main/java/net/coreprotect/database/Database.java +++ b/src/main/java/net/coreprotect/database/Database.java @@ -409,7 +409,7 @@ public static void createDatabaseTables(String prefix, boolean purge) { statement.executeUpdate("create index if not exists \"" + prefix + "user_uuid_index\" on \"" + prefix + "user\" (\"uuid\")"); statement.executeUpdate("create table if not exists \"" + prefix + "username_log\" (\"rowid\" bigserial primary key not null, \"time\" integer not null, \"uuid\" uuid not null, \"user\" varchar(100) not null)"); - statement.executeUpdate("create index if not exists \"" + prefix + "username_log_uuid_user_index\" on \"username_log\" (\"uuid\", \"user\")"); + statement.executeUpdate("create index if not exists \"" + prefix + "username_log_uuid_user_index\" on \"" + prefix + "username_log\" (\"uuid\", \"user\")"); statement.executeUpdate("create table if not exists \"" + prefix + "version\" (\"rowid\" bigserial primary key not null, \"time\" integer not null, \"version\" varchar(16) not null)"); diff --git a/src/main/java/net/coreprotect/database/Lookup.java b/src/main/java/net/coreprotect/database/Lookup.java index 60706567f..ac6056b65 100755 --- a/src/main/java/net/coreprotect/database/Lookup.java +++ b/src/main/java/net/coreprotect/database/Lookup.java @@ -356,6 +356,7 @@ private static ResultSet rawLookupResultSet(Statement statement, CommandSender u String unionLimit = ""; String index = ""; String query = ""; + String alias = ""; if (checkUuids.size() > 0) { String list = ""; @@ -694,7 +695,7 @@ else if (actionList.contains(11)) { } String unionSelect = "SELECT * FROM ("; - if (Config.getGlobal().DB_TYPE != DatabaseType.SQLITE) { + if (Config.getGlobal().DB_TYPE == DatabaseType.MYSQL) { if (queryTable.equals("block")) { if (includeBlock.length() > 0 || includeEntity.length() > 0) { index = "USE INDEX(type) IGNORE INDEX(user,wid) "; @@ -712,7 +713,7 @@ else if (actionList.contains(11)) { unionSelect = "("; } - else { + else if (Config.getGlobal().DB_TYPE == DatabaseType.SQLITE) { if (queryTable.equals("block")) { if (includeBlock.length() > 0 || includeEntity.length() > 0) { index = "INDEXED BY block_type_index "; @@ -752,7 +753,11 @@ else if (actionList.contains(11)) { baseQuery = baseQuery.replace("action NOT IN(-1)", "action NOT IN(3)"); // if block specified for include/exclude, filter out entity data } - query = unionSelect + "SELECT " + "'0' as tbl," + rows + " FROM " + StatementUtils.getTableName("block") + " " + index + "WHERE" + baseQuery + unionLimit + ") UNION ALL "; + if (Config.getGlobal().DB_TYPE == DatabaseType.PGSQL) { + alias = " AS union1"; + } + + query = unionSelect + "SELECT " + "'0' as tbl," + rows + " FROM " + StatementUtils.getTableName("block") + " " + index + "WHERE" + baseQuery + unionLimit + ")" + alias + " UNION ALL "; itemLookup = true; } @@ -760,7 +765,11 @@ else if (actionList.contains(11)) { if (!count) { rows = "rowid as id,time,\"user\",wid,x,y,z,type,metadata,data,amount,action,rolled_back"; } - query = query + unionSelect + "SELECT " + "'1' as tbl," + rows + " FROM " + StatementUtils.getTableName("container") + " WHERE" + queryBlock + unionLimit + ") UNION ALL "; + + if (Config.getGlobal().DB_TYPE == DatabaseType.PGSQL) { + alias = " AS union2"; + } + query = query + unionSelect + "SELECT " + "'1' as tbl," + rows + " FROM " + StatementUtils.getTableName("container") + " WHERE" + queryBlock + unionLimit + ")" + alias + " UNION ALL "; if (!count) { rows = "rowid as id,time,\"user\",wid,x,y,z,type,data as metadata,0 as data,amount,action,rolled_back"; @@ -771,7 +780,10 @@ else if (actionList.contains(11)) { queryBlock = queryBlock.replace("action NOT IN(-1)", "action NOT IN(" + actionExclude + ")"); } - query = query + unionSelect + "SELECT " + "'2' as tbl," + rows + " FROM " + StatementUtils.getTableName("item") + " WHERE" + queryBlock + unionLimit + ")"; + if (Config.getGlobal().DB_TYPE == DatabaseType.PGSQL) { + alias = " AS union3"; + } + query = query + unionSelect + "SELECT " + "'2' as tbl," + rows + " FROM " + StatementUtils.getTableName("item") + " WHERE" + queryBlock + unionLimit + ")" + alias; } if (query.length() == 0) { From 6744c42c42d18c1c20370b8b42bd62162fcfbd2e Mon Sep 17 00:00:00 2001 From: PseudoResonance Date: Tue, 16 Apr 2024 07:35:16 -0700 Subject: [PATCH 15/15] Fix formatting Signed-off-by: PseudoResonance --- src/main/java/net/coreprotect/config/Config.java | 4 ++-- src/main/java/net/coreprotect/config/ConfigHandler.java | 2 +- src/main/java/net/coreprotect/database/Lookup.java | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/net/coreprotect/config/Config.java b/src/main/java/net/coreprotect/config/Config.java index 6feecb111..cd75cb5ce 100644 --- a/src/main/java/net/coreprotect/config/Config.java +++ b/src/main/java/net/coreprotect/config/Config.java @@ -44,7 +44,7 @@ public class Config extends Language { public String DB_DATABASE; public String DB_USERNAME; public String DB_PASSWORD; - public String DB_JDBC_PARAMETERS; + public String DB_JDBC_PARAMETERS; public String LANGUAGE; public boolean ENABLE_AWE; public boolean ENABLE_SSL; @@ -233,7 +233,7 @@ private void readValues() { if (this.DB_PASSWORD == null && this.has("mysql-password")) { this.DB_PASSWORD = this.getString("mysql-password"); } - this.DB_JDBC_PARAMETERS = this.getString("db-jdbc-parameters"); + this.DB_JDBC_PARAMETERS = this.getString("db-jdbc-parameters"); this.LANGUAGE = this.getString("language"); this.CHECK_UPDATES = this.getBoolean("check-updates"); this.API_ENABLED = this.getBoolean("api-enabled"); diff --git a/src/main/java/net/coreprotect/config/ConfigHandler.java b/src/main/java/net/coreprotect/config/ConfigHandler.java index b2ca24755..85618e88e 100644 --- a/src/main/java/net/coreprotect/config/ConfigHandler.java +++ b/src/main/java/net/coreprotect/config/ConfigHandler.java @@ -52,7 +52,7 @@ public class ConfigHandler extends Queue { public static String database = "database"; public static String username = "root"; public static String password = ""; - public static String jdbcParameters = ""; + public static String jdbcParameters = ""; public static String prefix = "co_"; public static int maximumPoolSize = 10; diff --git a/src/main/java/net/coreprotect/database/Lookup.java b/src/main/java/net/coreprotect/database/Lookup.java index ac6056b65..dd1031123 100755 --- a/src/main/java/net/coreprotect/database/Lookup.java +++ b/src/main/java/net/coreprotect/database/Lookup.java @@ -356,7 +356,7 @@ private static ResultSet rawLookupResultSet(Statement statement, CommandSender u String unionLimit = ""; String index = ""; String query = ""; - String alias = ""; + String alias = ""; if (checkUuids.size() > 0) { String list = "";