diff --git a/README.md b/README.md index bb997fbc..6642223e 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ HuskHomes can be used on your Spigot, Sponge or Fabric server, and with a MySQL Database even works cross-server, letting players teleport across your proxy (Bungee or Velocity) network! ## Features -**⭐ Works cross-server** — Let players seamlessly teleport and set homes across your proxies network of servers using MySQL. +**⭐ Works cross-server** — Let players seamlessly teleport and set homes across your proxies network of servers using MySQL/MariaDB. **⭐ Zero learning curve** — Your players already know how to use it! /sethome, /home, /tpa, /rtp—among others—are all built-in and easy-to-use. diff --git a/build.gradle b/build.gradle index 7a08dffb..023eaf28 100644 --- a/build.gradle +++ b/build.gradle @@ -21,6 +21,7 @@ ext { set 'jedis_version', jedis_version.toString() set 'sqlite_driver_version', sqlite_driver_version.toString() set 'mysql_driver_version', mysql_driver_version.toString() + set 'mariadb_driver_version', mariadb_driver_version.toString() } allprojects { @@ -41,6 +42,7 @@ allprojects { url 'https://s01.oss.sonatype.org/content/repositories/snapshots/' mavenContent { snapshotsOnly() } } + maven { url 'https://repo.william278.net/releases/' } maven { url 'https://maven.fabricmc.net/' } maven { url 'https://libraries.minecraft.net/' } maven { url 'https://api.modrinth.com/maven' } diff --git a/bukkit/build.gradle b/bukkit/build.gradle index 632a7026..a2060c07 100644 --- a/bukkit/build.gradle +++ b/bukkit/build.gradle @@ -10,7 +10,7 @@ dependencies { compileOnly 'org.spigotmc:spigot-api:1.16.5-R0.1-SNAPSHOT' compileOnly 'org.jetbrains:annotations:24.0.1' compileOnly 'de.themoep:minedown-adventure:1.7.2-SNAPSHOT' - compileOnly 'net.william278:Annotaml:2.0.1' + compileOnly 'net.william278:annotaml:2.0.4' compileOnly 'net.william278:DesertWell:2.0.4' compileOnly 'com.github.MilkBowl:VaultAPI:1.7.1' compileOnly 'me.clip:placeholderapi:2.11.3' diff --git a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java index cbe2723b..9c4c299c 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java +++ b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java @@ -30,6 +30,7 @@ import net.william278.huskhomes.config.Server; import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.config.Spawn; import net.william278.huskhomes.database.Database; +import net.william278.huskhomes.database.H2Database; import net.william278.huskhomes.database.MySqlDatabase; import net.william278.huskhomes.database.SqLiteDatabase; import net.william278.huskhomes.event.BukkitEventDispatcher; @@ -135,6 +136,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, BukkitTask this.database = switch (getSettings().getDatabaseType()) { case MYSQL, MARIADB -> new MySqlDatabase(this); case SQLITE -> new SqLiteDatabase(this); + case H2 -> new H2Database(this); }; database.initialize(); diff --git a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitTask.java b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitTask.java index 854c8baa..b44d26fa 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitTask.java +++ b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitTask.java @@ -48,6 +48,11 @@ public interface BukkitTask extends Task { @Override public void run() { + if (isPluginDisabled()) { + runnable.run(); + return; + } + if (delayTicks > 0) { this.task = getScheduler().globalRegionalScheduler().runDelayed(runnable, delayTicks); } else { @@ -74,6 +79,11 @@ public interface BukkitTask extends Task { @Override public void run() { + if (isPluginDisabled()) { + runnable.run(); + return; + } + if (!cancelled) { this.task = getScheduler().asyncScheduler().run(runnable); } @@ -98,6 +108,10 @@ public interface BukkitTask extends Task { @Override public void run() { + if (isPluginDisabled()) { + return; + } + if (!cancelled) { this.task = getScheduler().asyncScheduler().runAtFixedRate(runnable, Duration.ZERO, Duration .of(repeatingTicks * 50L, ChronoUnit.MILLIS) @@ -106,6 +120,11 @@ public interface BukkitTask extends Task { } } + // Returns if the Bukkit HuskHomes plugin is disabled + default boolean isPluginDisabled() { + return !((BukkitHuskHomes) getPlugin()).isEnabled(); + } + interface Supplier extends Task.Supplier { @NotNull diff --git a/bukkit/src/main/resources/plugin.yml b/bukkit/src/main/resources/plugin.yml index 4fc5e7fb..1e41c82d 100644 --- a/bukkit/src/main/resources/plugin.yml +++ b/bukkit/src/main/resources/plugin.yml @@ -15,7 +15,9 @@ softdepend: libraries: - 'redis.clients:jedis:${jedis_version}' - 'com.mysql:mysql-connector-j:${mysql_driver_version}' + - 'org.mariadb.jdbc:mariadb-java-client:${mariadb_driver_version}' - 'org.xerial:sqlite-jdbc:${sqlite_driver_version}' + - 'com.h2database:h2:${h2_driver_version}' commands: home: diff --git a/common/build.gradle b/common/build.gradle index e955ae21..0ea164be 100644 --- a/common/build.gradle +++ b/common/build.gradle @@ -11,7 +11,7 @@ dependencies { api 'org.apache.commons:commons-text:1.10.0' api 'de.themoep:minedown-adventure:1.7.2-SNAPSHOT' api 'com.google.code.gson:gson:2.10.1' - api 'net.william278:Annotaml:2.0.1' + api 'net.william278:annotaml:2.0.4' api 'net.william278:PagineDown:1.1' api 'net.william278:DesertWell:2.0.4' api 'dev.dejvokep:boosted-yaml:1.3.1' @@ -20,9 +20,11 @@ dependencies { exclude module: 'slf4j-api' } - compileOnly 'redis.clients:jedis:' + jedis_version - compileOnly 'org.xerial:sqlite-jdbc:' + sqlite_driver_version - compileOnly 'com.mysql:mysql-connector-j:' + mysql_driver_version + compileOnly "redis.clients:jedis:$jedis_version" + compileOnly "org.xerial:sqlite-jdbc:$sqlite_driver_version" + compileOnly "com.mysql:mysql-connector-j:$mysql_driver_version" + compileOnly "org.mariadb.jdbc:mariadb-java-client:$mariadb_driver_version" + compileOnly "com.h2database:h2:$h2_driver_version" compileOnly 'org.jetbrains:annotations:24.0.1' compileOnly 'com.google.guava:guava:32.1.1-jre' diff --git a/common/src/main/java/net/william278/huskhomes/config/Settings.java b/common/src/main/java/net/william278/huskhomes/config/Settings.java index a23452d2..6be3e8c0 100644 --- a/common/src/main/java/net/william278/huskhomes/config/Settings.java +++ b/common/src/main/java/net/william278/huskhomes/config/Settings.java @@ -55,11 +55,11 @@ public class Settings { private boolean checkForUpdates = true; // Database settings - @YamlComment("Type of database to use (SQLITE, MYSQL or MARIADB)") + @YamlComment("Type of database to use (SQLITE, H2, MYSQL or MARIADB)") @YamlKey("database.type") private Database.Type databaseType = Database.Type.SQLITE; - @YamlComment("Specify credentials here if you are using MYSQL as your database type") + @YamlComment("Specify credentials here if you are using MYSQL or MARIADB as your database type") @YamlKey("database.mysql.credentials.host") private String mySqlHost = "localhost"; @@ -81,7 +81,7 @@ public class Settings { + "&useUnicode=true" + "&characterEncoding=UTF-8"; - @YamlComment("MYSQL database Hikari connection pool properties. " + @YamlComment("MYSQL / MARIADB database Hikari connection pool properties. " + "Don't modify this unless you know what you're doing!") @YamlKey("database.mysql.connection_pool.size") private int mySqlConnectionPoolSize = 12; diff --git a/common/src/main/java/net/william278/huskhomes/database/Database.java b/common/src/main/java/net/william278/huskhomes/database/Database.java index f30f0738..98d4225f 100644 --- a/common/src/main/java/net/william278/huskhomes/database/Database.java +++ b/common/src/main/java/net/william278/huskhomes/database/Database.java @@ -440,7 +440,8 @@ public abstract class Database { public enum Type { MYSQL("MySQL"), MARIADB("MariaDB"), - SQLITE("SQLite"); + SQLITE("SQLite"), + H2("H2"); private final String displayName; diff --git a/common/src/main/java/net/william278/huskhomes/database/H2Database.java b/common/src/main/java/net/william278/huskhomes/database/H2Database.java new file mode 100644 index 00000000..4f1124fe --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/database/H2Database.java @@ -0,0 +1,1096 @@ +/* + * This file is part of HuskHomes, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.huskhomes.database; + +import net.william278.huskhomes.HuskHomes; +import net.william278.huskhomes.position.*; +import net.william278.huskhomes.teleport.Teleport; +import net.william278.huskhomes.teleport.TeleportationException; +import net.william278.huskhomes.user.OnlineUser; +import net.william278.huskhomes.user.SavedUser; +import net.william278.huskhomes.user.User; +import net.william278.huskhomes.util.TransactionResolver; +import org.h2.jdbcx.JdbcConnectionPool; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.io.File; +import java.io.IOException; +import java.sql.*; +import java.time.Instant; +import java.util.*; +import java.util.logging.Level; + +/** + * An H2 implementation of the plugin {@link Database}. + */ +@SuppressWarnings("DuplicatedCode") +public class H2Database extends Database { + + /** + * Path to the H2 HuskHomesData.h2 file. + */ + private final File databaseFile; + + /** + * The name of the database file. + */ + private static final String DATABASE_FILE_NAME = "HuskHomesData.h2"; + + private JdbcConnectionPool connectionPool; + + public H2Database(@NotNull HuskHomes plugin) { + super(plugin); + this.databaseFile = new File(plugin.getDataFolder(), DATABASE_FILE_NAME); + } + + /** + * Fetch the auto-closeable connection from the H2 Connection Pool. + * + * @return The {@link Connection} to the H2 database + * @throws SQLException if the connection fails for some reason + */ + private Connection getConnection() throws SQLException { + return connectionPool.getConnection(); + } + + @Override + public void initialize() throws IllegalStateException { + // Prepare the database flat file + final String url = String.format("jdbc:h2:%s", databaseFile.getAbsolutePath()); + this.connectionPool = JdbcConnectionPool.create(url, "sa", "sa"); + + // Prepare database schema; make tables if they don't exist + try (Connection connection = getConnection()) { + final String[] databaseSchema = getSchemaStatements("database/h2_schema.sql"); + try (Statement statement = connection.createStatement()) { + for (String tableCreationStatement : databaseSchema) { + statement.execute(tableCreationStatement); + } + } + } catch (SQLException | IOException e) { + throw new IllegalStateException("Failed to initialize the H2 database", e); + } + } + + @Override + protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + INSERT INTO `%positions_table%` + (`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`) + VALUES + (?,?,?,?,?,?,?,?);"""), + Statement.RETURN_GENERATED_KEYS)) { + + statement.setDouble(1, position.getX()); + statement.setDouble(2, position.getY()); + statement.setDouble(3, position.getZ()); + statement.setFloat(4, position.getYaw()); + statement.setFloat(5, position.getPitch()); + statement.setString(6, position.getWorld().getName()); + statement.setString(7, position.getWorld().getUuid().toString()); + statement.setString(8, position.getServer()); + statement.executeUpdate(); + + final ResultSet resultSet = statement.getGeneratedKeys(); + if (resultSet.next()) { + return resultSet.getInt(1); + } + throw new SQLException("Failed to insert position into database"); + } + } + + @Override + protected void updatePosition(int positionId, @NotNull Position position, + @NotNull Connection connection) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + UPDATE `%positions_table%` + SET `x`=?, + `y`=?, + `z`=?, + `yaw`=?, + `pitch`=?, + `world_uuid`=?, + `world_name`=?, + `server_name`=? + WHERE `id`=?"""))) { + statement.setDouble(1, position.getX()); + statement.setDouble(2, position.getY()); + statement.setDouble(3, position.getZ()); + statement.setFloat(4, position.getYaw()); + statement.setFloat(5, position.getPitch()); + statement.setString(6, position.getWorld().getUuid().toString()); + statement.setString(7, position.getWorld().getName()); + statement.setString(8, position.getServer()); + statement.setDouble(9, positionId); + statement.executeUpdate(); + } + } + + @Override + protected int setSavedPosition(@NotNull SavedPosition position, + @NotNull Connection connection) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + INSERT INTO `%saved_positions_table%` + (`position_id`, `name`, `description`, `tags`, `timestamp`) + VALUES + (?,?,?,?,?);"""), + Statement.RETURN_GENERATED_KEYS)) { + + statement.setInt(1, setPosition(position, connection)); + statement.setString(2, position.getName()); + statement.setString(3, position.getMeta().getDescription()); + statement.setString(4, position.getMeta().getSerializedTags()); + statement.setTimestamp(5, Timestamp.from(position.getMeta().getCreationTime())); + statement.executeUpdate(); + + final ResultSet resultSet = statement.getGeneratedKeys(); + if (resultSet.next()) { + return resultSet.getInt(1); + } + throw new SQLException("Failed to insert saved position into database"); + } + } + + @Override + protected void updateSavedPosition(int savedPositionId, @NotNull SavedPosition position, + @NotNull Connection connection) throws SQLException { + try (PreparedStatement selectStatement = connection.prepareStatement(formatStatementTables(""" + SELECT `position_id` + FROM `%saved_positions_table%` + WHERE `id`=?;"""))) { + selectStatement.setInt(1, savedPositionId); + + final ResultSet resultSet = selectStatement.executeQuery(); + if (resultSet.next()) { + final int positionId = resultSet.getInt("position_id"); + updatePosition(positionId, position, connection); + + try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" + UPDATE `%saved_positions_table%` + SET `name`=?, + `description`=?, + `tags`=? + WHERE `id`=?;"""))) { + updateStatement.setString(1, position.getName()); + updateStatement.setString(2, position.getMeta().getDescription()); + updateStatement.setString(3, position.getMeta().getSerializedTags()); + updateStatement.setInt(4, savedPositionId); + updateStatement.executeUpdate(); + } + } + } + } + + @Override + public void ensureUser(@NotNull User onlineUser) { + getUserData(onlineUser.getUuid()).ifPresentOrElse( + existingUserData -> { + if (!existingUserData.getUsername().equals(onlineUser.getUsername())) { + // Update a player's name if it has changed in the database + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + UPDATE `%players_table%` + SET `username`=? + WHERE `uuid`=?"""))) { + + statement.setString(1, onlineUser.getUsername()); + statement.setString(2, existingUserData.getUserUuid().toString()); + statement.executeUpdate(); + } + plugin.log(Level.INFO, "Updated " + onlineUser.getUsername() + + "'s name in the database (" + existingUserData.getUsername() + + " -> " + onlineUser.getUsername() + ")"); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to update a player's name on the database", e); + } + } + }, + () -> { + // Insert new player data into the database + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + INSERT INTO `%players_table%` (`uuid`,`username`) + VALUES (?,?);"""))) { + + statement.setString(1, onlineUser.getUuid().toString()); + statement.setString(2, onlineUser.getUsername()); + statement.executeUpdate(); + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to insert a player into the database", e); + } + }); + } + + @Override + public Optional getUserDataByName(@NotNull String name) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `uuid`, `username`, `home_slots`, `ignoring_requests` + FROM `%players_table%` + WHERE `username`=?"""))) { + statement.setString(1, name); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new SavedUser( + User.of(UUID.fromString(resultSet.getString("uuid")), + resultSet.getString("username")), + resultSet.getInt("home_slots"), + resultSet.getBoolean("ignoring_requests") + )); + } + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to fetch a player by name from the database", e); + } + return Optional.empty(); + } + + @Override + public Optional getUserData(@NotNull UUID uuid) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `uuid`, `username`, `home_slots`, `ignoring_requests` + FROM `%players_table%` + WHERE `uuid`=?"""))) { + + statement.setString(1, uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new SavedUser( + User.of(UUID.fromString(resultSet.getString("uuid")), + resultSet.getString("username")), + resultSet.getInt("home_slots"), + resultSet.getBoolean("ignoring_requests") + )); + } + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to fetch a player from uuid from the database", e); + } + return Optional.empty(); + } + + @Override + public Optional getCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `type`, `start_timestamp`, `end_timestamp` + FROM `%cooldowns_table%` + WHERE `player_uuid`=? AND `type`=? + ORDER BY `start_timestamp` DESC + LIMIT 1;"""))) { + statement.setString(1, user.getUuid().toString()); + statement.setString(2, action.name().toLowerCase(Locale.ENGLISH)); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(resultSet.getTimestamp("end_timestamp").toInstant()); + } + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to fetch a player's cooldown from the database", e); + } + return Optional.empty(); + } + + @Override + public void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user, + @NotNull Instant cooldownExpiry) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + INSERT INTO `%cooldowns_table%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`) + VALUES (?,?,?,?);"""))) { + statement.setString(1, user.getUuid().toString()); + statement.setString(2, action.name().toLowerCase(Locale.ENGLISH)); + statement.setTimestamp(3, Timestamp.from(Instant.now())); + statement.setTimestamp(4, Timestamp.from(cooldownExpiry)); + statement.executeUpdate(); + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to set a player's cooldown in the database", e); + } + } + + @Override + public void removeCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + DELETE FROM `%cooldowns_table%` + WHERE `player_uuid`=? AND `type`=?;"""))) { + + statement.setString(1, user.getUuid().toString()); + statement.setString(2, action.name().toLowerCase(Locale.ENGLISH)); + statement.executeUpdate(); + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to remove a player's cooldown from the database", e); + } + } + + @Override + public List getHomes(@NotNull User user) { + final List userHomes = new ArrayList<>(); + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`, + `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `public` + FROM `%homes_table%` + INNER JOIN `%saved_positions_table%` + ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` + ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%players_table%` + ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + WHERE `owner_uuid`=? + ORDER BY `name`;"""))) { + + statement.setString(1, user.getUuid().toString()); + + final ResultSet resultSet = statement.executeQuery(); + while (resultSet.next()) { + userHomes.add(Home.from(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + World.from(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + resultSet.getString("server_name"), + PositionMeta.from(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("home_uuid")), + user, + resultSet.getBoolean("public"))); + } + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getUsername()); + } + return userHomes; + } + + @Override + public List getWarps() { + final List warps = new ArrayList<>(); + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, + `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%warps_table%` + INNER JOIN `%saved_positions_table%` + ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` + ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + ORDER BY `name`;"""))) { + + final ResultSet resultSet = statement.executeQuery(); + while (resultSet.next()) { + warps.add(Warp.from(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + World.from(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + resultSet.getString("server_name"), + PositionMeta.from(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("warp_uuid")))); + } + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to query the database for warp data."); + } + return warps; + } + + @Override + public List getPublicHomes() { + final List userHomes = new ArrayList<>(); + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, `name`, + `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, + `server_name`, `public` + FROM `%homes_table%` + INNER JOIN `%saved_positions_table%` + ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` + ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%players_table%` + ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + WHERE `public`=true + ORDER BY `name`;"""))) { + final ResultSet resultSet = statement.executeQuery(); + while (resultSet.next()) { + userHomes.add(Home.from(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + World.from(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + resultSet.getString("server_name"), + PositionMeta.from(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("home_uuid")), + User.of(UUID.fromString(resultSet.getString("owner_uuid")), + resultSet.getString("owner_username")), + resultSet.getBoolean("public"))); + } + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to query the database for public home data"); + } + return userHomes; + } + + @Override + public Optional getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, + `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, + `world_uuid`, `server_name`, `public` + FROM `%homes_table%` + INNER JOIN `%saved_positions_table%` + ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` + ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%players_table%` + ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + WHERE `owner_uuid`=? + AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { + statement.setString(1, user.getUuid().toString()); + statement.setBoolean(2, caseInsensitive); + statement.setString(3, homeName); + statement.setString(4, homeName); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(Home.from(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + World.from(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + resultSet.getString("server_name"), + PositionMeta.from(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("home_uuid")), + user, + resultSet.getBoolean("public"))); + } + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to query a player's home", e); + } + return Optional.empty(); + } + + @Override + public Optional getHome(@NotNull UUID uuid) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`, + `name`, `description`, `tags`, `timestamp`, `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, + `world_uuid`, `server_name`, `public` + FROM `%homes_table%` + INNER JOIN `%saved_positions_table%` + ON `%homes_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` + ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + INNER JOIN `%players_table%` + ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid` + WHERE `%homes_table%`.`uuid`=?;"""))) { + statement.setString(1, uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(Home.from(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + World.from(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + resultSet.getString("server_name"), + PositionMeta.from(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("home_uuid")), + User.of(UUID.fromString(resultSet.getString("owner_uuid")), + resultSet.getString("owner_username")), + resultSet.getBoolean("public"))); + } + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to query a player's home by uuid", e); + } + return Optional.empty(); + } + + @Override + public Optional getWarp(@NotNull String warpName, boolean caseInsensitive) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, + `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%warps_table%` + INNER JOIN `%saved_positions_table%` + ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` + ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) { + statement.setBoolean(1, caseInsensitive); + statement.setString(2, warpName); + statement.setString(3, warpName); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(Warp.from(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + World.from(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + resultSet.getString("server_name"), + PositionMeta.from(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("warp_uuid")))); + } + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to query a server warp", e); + } + return Optional.empty(); + } + + @Override + public Optional getWarp(@NotNull UUID uuid) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`, + `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%warps_table%` + INNER JOIN `%saved_positions_table%` + ON `%warps_table%`.`saved_position_id`=`%saved_positions_table%`.`id` + INNER JOIN `%positions_table%` + ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id` + WHERE `%warps_table%`.uuid=?;"""))) { + statement.setString(1, uuid.toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(Warp.from(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + World.from(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + resultSet.getString("server_name"), + PositionMeta.from(resultSet.getString("name"), + resultSet.getString("description"), + resultSet.getTimestamp("timestamp").toInstant(), + resultSet.getString("tags")), + UUID.fromString(resultSet.getString("warp_uuid")))); + } + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to query a server warp", e); + } + return Optional.empty(); + } + + @Override + public Optional getCurrentTeleport(@NotNull OnlineUser onlineUser) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name`, `type` + FROM `%teleports_table%` + INNER JOIN `%positions_table%` ON `%teleports_table%`.`destination_id` = `%positions_table%`.`id` + WHERE `player_uuid`=?"""))) { + statement.setString(1, onlineUser.getUuid().toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(Teleport.builder(plugin) + .teleporter(onlineUser) + .target(Position.at(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + World.from(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + resultSet.getString("server_name"))) + .type(Teleport.Type.getTeleportType(resultSet.getInt("type")) + .orElse(Teleport.Type.TELEPORT)) + .updateLastPosition(false) + .toTeleport()); + } + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getUsername(), e); + } catch (TeleportationException e) { + e.displayMessage(onlineUser); + } + return Optional.empty(); + } + + @Override + public void updateUserData(@NotNull SavedUser savedUser) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + UPDATE `%players_table%` + SET `home_slots`=?, `ignoring_requests`=? + WHERE `uuid`=?"""))) { + + statement.setInt(1, savedUser.getHomeSlots()); + statement.setBoolean(2, savedUser.isIgnoringTeleports()); + statement.setString(3, savedUser.getUserUuid().toString()); + statement.executeUpdate(); + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to update user data for " + savedUser.getUsername(), e); + } + } + + @Override + public void setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport) { + try (Connection connection = getConnection()) { + // Clear the user's current teleport + try (PreparedStatement deleteStatement = connection.prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `id`=( + SELECT `destination_id` + FROM `%teleports_table%` + WHERE `%teleports_table%`.`player_uuid`=? + );"""))) { + deleteStatement.setString(1, user.getUuid().toString()); + deleteStatement.executeUpdate(); + } + + // Set the user's teleport into the database (if it's not null) + if (teleport != null) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`) + VALUES (?,?,?);"""))) { + statement.setString(1, user.getUuid().toString()); + statement.setInt(2, setPosition((Position) teleport.getTarget(), connection)); + statement.setInt(3, teleport.getType().getTypeId()); + + statement.executeUpdate(); + } + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getUsername(), e); + } + } + + @Override + public Optional getLastPosition(@NotNull User user) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%players_table%` + INNER JOIN `%positions_table%` ON `%players_table%`.`last_position` = `%positions_table%`.`id` + WHERE `uuid`=?"""))) { + statement.setString(1, user.getUuid().toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(Position.at(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + World.from(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + resultSet.getString("server_name"))); + } + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to query the last teleport position of " + user.getUsername(), e); + } + return Optional.empty(); + } + + @Override + public void setLastPosition(@NotNull User user, @NotNull Position position) { + try (Connection connection = getConnection()) { + try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables(""" + SELECT `last_position` + FROM `%players_table%` + INNER JOIN `%positions_table%` ON `%players_table%`.last_position = `%positions_table%`.`id` + WHERE `uuid`=?;"""))) { + queryStatement.setString(1, user.getUuid().toString()); + + final ResultSet resultSet = queryStatement.executeQuery(); + if (resultSet.next()) { + // Update the last position + updatePosition(resultSet.getInt("last_position"), position, connection); + } else { + // Set the last position + try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" + UPDATE `%players_table%` + SET `last_position`=? + WHERE `uuid`=?;"""))) { + updateStatement.setInt(1, setPosition(position, connection)); + updateStatement.setString(2, user.getUuid().toString()); + updateStatement.executeUpdate(); + } + } + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getUsername(), e); + } + } + + @Override + public Optional getOfflinePosition(@NotNull User user) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%players_table%` + INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id` + WHERE `uuid`=?"""))) { + statement.setString(1, user.getUuid().toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(Position.at(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + World.from(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + resultSet.getString("server_name"))); + } + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to query the offline position of " + user.getUsername(), e); + } + return Optional.empty(); + } + + @Override + public void setOfflinePosition(@NotNull User user, @NotNull Position position) { + try (Connection connection = getConnection()) { + try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables(""" + SELECT `offline_position` FROM `%players_table%` + INNER JOIN `%positions_table%` ON `%players_table%`.`offline_position` = `%positions_table%`.`id` + WHERE `uuid`=?;"""))) { + queryStatement.setString(1, user.getUuid().toString()); + + final ResultSet resultSet = queryStatement.executeQuery(); + if (resultSet.next()) { + // Update the offline position + updatePosition(resultSet.getInt("offline_position"), position, connection); + } else { + // Set the offline position + try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" + UPDATE `%players_table%` + SET `offline_position`=? + WHERE `uuid`=?;"""))) { + updateStatement.setInt(1, setPosition(position, connection)); + updateStatement.setString(2, user.getUuid().toString()); + updateStatement.executeUpdate(); + } + } + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to set the offline position of " + user.getUsername(), e); + } + } + + @Override + public Optional getRespawnPosition(@NotNull User user) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `x`, `y`, `z`, `yaw`, `pitch`, `world_name`, `world_uuid`, `server_name` + FROM `%players_table%` + INNER JOIN `%positions_table%` ON `%players_table%`.`respawn_position` = `%positions_table%`.`id` + WHERE `uuid`=?"""))) { + statement.setString(1, user.getUuid().toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(Position.at(resultSet.getDouble("x"), + resultSet.getDouble("y"), + resultSet.getDouble("z"), + resultSet.getFloat("yaw"), + resultSet.getFloat("pitch"), + World.from(resultSet.getString("world_name"), + UUID.fromString(resultSet.getString("world_uuid"))), + resultSet.getString("server_name"))); + } + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to query the respawn position of " + user.getUsername(), e); + } + return Optional.empty(); + } + + @Override + public void setRespawnPosition(@NotNull User user, @Nullable Position position) { + try (Connection connection = getConnection()) { + try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables(""" + SELECT `respawn_position` FROM `%players_table%` + INNER JOIN `%positions_table%` ON `%players_table%`.respawn_position = `%positions_table%`.`id` + WHERE `uuid`=?;"""))) { + queryStatement.setString(1, user.getUuid().toString()); + + final ResultSet resultSet = queryStatement.executeQuery(); + if (resultSet.next()) { + if (position == null) { + // Delete a respawn position + try (PreparedStatement deleteStatement = connection.prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `id`=( + SELECT `respawn_position` + FROM `%players_table%` + WHERE `%players_table%`.`uuid`=? + );"""))) { + deleteStatement.setString(1, user.getUuid().toString()); + deleteStatement.executeUpdate(); + } + } else { + // Update the respawn position + updatePosition(resultSet.getInt("respawn_position"), position, connection); + } + } else { + if (position != null) { + // Set a respawn position + try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables(""" + UPDATE `%players_table%` + SET `respawn_position`=? + WHERE `uuid`=?;"""))) { + updateStatement.setInt(1, setPosition(position, connection)); + updateStatement.setString(2, user.getUuid().toString()); + updateStatement.executeUpdate(); + } + } + } + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to set the respawn position of " + user.getUsername(), e); + } + } + + @Override + public void saveHome(@NotNull Home home) { + getHome(home.getUuid()).ifPresentOrElse(presentHome -> { + try (Connection connection = getConnection()) { + // Update the home's saved position, including metadata + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `saved_position_id` FROM `%homes_table%` + WHERE `uuid`=?;"""))) { + statement.setString(1, home.getUuid().toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + updateSavedPosition(resultSet.getInt("saved_position_id"), home, connection); + } + } + + // Update the home privacy + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + UPDATE `%homes_table%` + SET `public`=? + WHERE `uuid`=?;"""))) { + statement.setBoolean(1, home.isPublic()); + statement.setString(2, home.getUuid().toString()); + statement.executeUpdate(); + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, + "Failed to update a home in the database for " + home.getOwner().getUsername(), e); + } + }, () -> { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + INSERT INTO `%homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`) + VALUES (?,?,?,?);"""))) { + statement.setString(1, home.getUuid().toString()); + statement.setInt(2, setSavedPosition(home, connection)); + statement.setString(3, home.getOwner().getUuid().toString()); + statement.setBoolean(4, home.isPublic()); + + statement.executeUpdate(); + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, + "Failed to set a home to the database for " + home.getOwner().getUsername(), e); + } + }); + } + + @Override + public void saveWarp(@NotNull Warp warp) { + getWarp(warp.getUuid()).ifPresentOrElse(presentWarp -> { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `saved_position_id` FROM `%warps_table%` + WHERE `uuid`=?;"""))) { + statement.setString(1, warp.getUuid().toString()); + + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + updateSavedPosition(resultSet.getInt("saved_position_id"), warp, connection); + } + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to update a warp in the database", e); + } + }, () -> { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + INSERT INTO `%warps_table%` (`uuid`, `saved_position_id`) + VALUES (?,?);"""))) { + statement.setString(1, warp.getUuid().toString()); + statement.setInt(2, setSavedPosition(warp, connection)); + + statement.executeUpdate(); + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to add a warp to the database", e); + } + }); + } + + @Override + public void deleteHome(@NotNull UUID uuid) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `%positions_table%`.`id`=( + SELECT `position_id` + FROM `%saved_positions_table%` + WHERE `%saved_positions_table%`.`id`=( + SELECT `saved_position_id` + FROM `%homes_table%` + WHERE `uuid`=? + ) + );"""))) { + statement.setString(1, uuid.toString()); + + statement.executeUpdate(); + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to delete a home from the database", e); + } + } + + @Override + public int deleteAllHomes(@NotNull User user) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `%positions_table%`.`id` IN ( + SELECT `position_id` + FROM `%saved_positions_table%` + WHERE `%saved_positions_table%`.`id` IN ( + SELECT `saved_position_id` + FROM `%homes_table%` + WHERE `owner_uuid`=? + ) + );"""))) { + + statement.setString(1, user.getUuid().toString()); + return statement.executeUpdate(); + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to delete all homes for " + user.getUsername() + " from the database", e); + } + return 0; + } + + @Override + public void deleteWarp(@NotNull UUID uuid) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `%positions_table%`.`id`=( + SELECT `position_id` + FROM `%saved_positions_table%` + WHERE `%saved_positions_table%`.`id`=( + SELECT `saved_position_id` + FROM `%warps_table%` + WHERE `uuid`=? + ) + );"""))) { + statement.setString(1, uuid.toString()); + + statement.executeUpdate(); + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to delete a warp from the database", e); + } + } + + @Override + public int deleteAllWarps() { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + DELETE FROM `%positions_table%` + WHERE `%positions_table%`.`id` IN ( + SELECT `position_id` + FROM `%saved_positions_table%` + WHERE `%saved_positions_table%`.`id` IN ( + SELECT `saved_position_id` + FROM `%warps_table%` + ) + );"""))) { + return statement.executeUpdate(); + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to delete all warps from the database", e); + } + return 0; + } + + @Override + public void terminate() { + if (connectionPool != null) { + connectionPool.dispose(); + } + } + +} diff --git a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java index 51bbbb82..6f6f3333 100644 --- a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java @@ -38,16 +38,18 @@ import java.util.*; import java.util.logging.Level; /** - * A MySQL implementation of the plugin {@link Database}. + * A MySQL / MariaDB implementation of the plugin {@link Database}. */ @SuppressWarnings("DuplicatedCode") public class MySqlDatabase extends Database { private static final String DATA_POOL_NAME = "HuskHomesHikariPool"; + private final String flavor; private HikariDataSource dataSource; public MySqlDatabase(@NotNull HuskHomes plugin) { super(plugin); + this.flavor = plugin.getSettings().getDatabaseType() == Type.MARIADB ? "mariadb" : "mysql"; } /** @@ -64,15 +66,13 @@ public class MySqlDatabase extends Database { public void initialize() throws IllegalStateException { // Initialize the Hikari pooled connection dataSource = new HikariDataSource(); - dataSource.setJdbcUrl("jdbc:" + (plugin.getSettings().getDatabaseType() == Type.MARIADB ? "mariadb" : "mysql") - + "://" - + plugin.getSettings().getMySqlHost() - + ":" - + plugin.getSettings().getMySqlPort() - + "/" - + plugin.getSettings().getMySqlDatabase() - + plugin.getSettings().getMySqlConnectionParameters() - ); + dataSource.setJdbcUrl(String.format("jdbc:%s://%s:%s/%s%s", + flavor, + plugin.getSettings().getMySqlHost(), + plugin.getSettings().getMySqlPort(), + plugin.getSettings().getMySqlDatabase(), + plugin.getSettings().getMySqlConnectionParameters() + )); // Authenticate with the database dataSource.setUsername(plugin.getSettings().getMySqlUsername()); @@ -108,7 +108,7 @@ public class MySqlDatabase extends Database { // Prepare database schema; make tables if they don't exist try (Connection connection = dataSource.getConnection()) { - final String[] databaseSchema = getSchemaStatements("database/mysql_schema.sql"); + final String[] databaseSchema = getSchemaStatements(String.format("database/%s_schema.sql", flavor)); try (Statement statement = connection.createStatement()) { for (String tableCreationStatement : databaseSchema) { statement.execute(tableCreationStatement); diff --git a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java index 67c16263..e1e18ab7 100644 --- a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java +++ b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java @@ -81,7 +81,7 @@ public class SqLiteDatabase extends Database { plugin.log(Level.INFO, "Created the SQLite database file"); } - // Specify use of the JDBC SQLite driver + // Specify use of the JDBC SQLite driver for legacy compatibility Class.forName("org.sqlite.JDBC"); // Set SQLite database properties @@ -92,10 +92,11 @@ public class SqLiteDatabase extends Database { // Establish the connection connection = DriverManager.getConnection( - "jdbc:sqlite:" + databaseFile.getAbsolutePath(), config.toProperties() + String.format("jdbc:sqlite:%s", databaseFile.getAbsolutePath()), + config.toProperties() ); } catch (IOException e) { - plugin.log(Level.SEVERE, "An exception occurred creating the database file", e); + plugin.log(Level.SEVERE, "An exception occurred creating the SQLite database file", e); } catch (SQLException e) { plugin.log(Level.SEVERE, "An SQL exception occurred initializing the SQLite database", e); } catch (ClassNotFoundException e) { diff --git a/common/src/main/resources/database/h2_schema.sql b/common/src/main/resources/database/h2_schema.sql new file mode 100644 index 00000000..2bd68d4a --- /dev/null +++ b/common/src/main/resources/database/h2_schema.sql @@ -0,0 +1,94 @@ +/* Create the positions table if it does not exist */ +CREATE TABLE IF NOT EXISTS `%positions_table%` +( + `id` INT NOT NULL AUTO_INCREMENT, + `x` DOUBLE NOT NULL, + `y` DOUBLE NOT NULL, + `z` DOUBLE NOT NULL, + `yaw` REAL NOT NULL, + `pitch` REAL NOT NULL, + `world_name` VARCHAR(255) NOT NULL, + `world_uuid` UUID NOT NULL, + `server_name` VARCHAR(255) NOT NULL, + + PRIMARY KEY (`id`) +); + +/* Create the players table if it does not exist */ +CREATE TABLE IF NOT EXISTS `%players_table%` +( + `uuid` UUID NOT NULL PRIMARY KEY, + `username` VARCHAR(16) NOT NULL, + `last_position` INT NULL, + `offline_position` INT NULL, + `respawn_position` INT NULL, + `home_slots` INT NOT NULL DEFAULT 0, + `ignoring_requests` BOOLEAN NOT NULL DEFAULT FALSE, + + FOREIGN KEY (`last_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, + FOREIGN KEY (`offline_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, + FOREIGN KEY (`respawn_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION +); +CREATE INDEX IF NOT EXISTS `%players_table%_username` ON `%players_table%` (`username`); + +/* Create the cooldowns table if it does not exist */ +CREATE TABLE IF NOT EXISTS `%cooldowns_table%` +( + `id` INT NOT NULL AUTO_INCREMENT, + `player_uuid` UUID NOT NULL, + `type` VARCHAR(255) NOT NULL, + `start_timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + `end_timestamp` TIMESTAMP NOT NULL, + + PRIMARY KEY (`id`), + FOREIGN KEY (`player_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE +); +CREATE INDEX IF NOT EXISTS `%cooldowns_table%_player_uuid` ON `%cooldowns_table%` (`player_uuid`); + +/* Create the current cross-server teleports table if it does not exist */ +CREATE TABLE IF NOT EXISTS `%teleports_table%` +( + `player_uuid` UUID NOT NULL PRIMARY KEY, + `destination_id` INT NOT NULL, + `type` INT NOT NULL DEFAULT 0, + + FOREIGN KEY (`player_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (`destination_id`) REFERENCES `%positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION +); + +/* Create the saved positions table if it does not exist */ +CREATE TABLE IF NOT EXISTS `%saved_positions_table%` +( + `id` INT NOT NULL AUTO_INCREMENT, + `position_id` INT NOT NULL, + `name` VARCHAR(64) NOT NULL, + `description` VARCHAR(255) NOT NULL, + `tags` CLOB NULL, + `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + + PRIMARY KEY (`id`), + FOREIGN KEY (`position_id`) REFERENCES `%positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION +); +CREATE INDEX IF NOT EXISTS `%saved_positions_table%_name` ON `%saved_positions_table%` (`name`); + +/* Create the homes table if it does not exist */ +CREATE TABLE IF NOT EXISTS `%homes_table%` +( + `uuid` UUID NOT NULL PRIMARY KEY, + `saved_position_id` INT NOT NULL, + `owner_uuid` UUID NOT NULL, + `public` BOOLEAN NOT NULL DEFAULT FALSE, + + FOREIGN KEY (`owner_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (`saved_position_id`) REFERENCES `%saved_positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION +); +CREATE INDEX IF NOT EXISTS `%homes_table%_owner_uuid` ON `%homes_table%` (`owner_uuid`); + +/* Create the warps table if it does not exist */ +CREATE TABLE IF NOT EXISTS `%warps_table%` +( + `uuid` UUID NOT NULL PRIMARY KEY, + `saved_position_id` INT NOT NULL, + + FOREIGN KEY (`saved_position_id`) REFERENCES `%saved_positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION +); \ No newline at end of file diff --git a/common/src/main/resources/database/mariadb_schema.sql b/common/src/main/resources/database/mariadb_schema.sql new file mode 100644 index 00000000..a1ec8d74 --- /dev/null +++ b/common/src/main/resources/database/mariadb_schema.sql @@ -0,0 +1,118 @@ +-- Set the storage engine +SET DEFAULT_STORAGE_ENGINE = InnoDB; + +-- Enable foreign key constraints +SET FOREIGN_KEY_CHECKS = 1; + +-- Create the positions table if it does not exist +CREATE TABLE IF NOT EXISTS `%positions_table%` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `x` DOUBLE NOT NULL, + `y` DOUBLE NOT NULL, + `z` DOUBLE NOT NULL, + `yaw` FLOAT NOT NULL, + `pitch` FLOAT NOT NULL, + `world_name` VARCHAR(255) NOT NULL, + `world_uuid` CHAR(36) NOT NULL, + `server_name` VARCHAR(255) NOT NULL, + + PRIMARY KEY (`id`) +) ENGINE = InnoDB + DEFAULT CHARSET = utf8mb4 + COLLATE = utf8mb4_unicode_ci; + +-- Create the players table if it does not exist +CREATE TABLE IF NOT EXISTS `%players_table%` +( + `uuid` CHAR(36) NOT NULL, + `username` VARCHAR(16) NOT NULL, + `last_position` INTEGER DEFAULT NULL, + `offline_position` INTEGER DEFAULT NULL, + `respawn_position` INTEGER DEFAULT NULL, + `home_slots` INTEGER NOT NULL DEFAULT 0, + `ignoring_requests` BOOLEAN NOT NULL DEFAULT FALSE, + + PRIMARY KEY (`uuid`), + FOREIGN KEY (`last_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, + FOREIGN KEY (`offline_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, + FOREIGN KEY (`respawn_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION +) ENGINE = InnoDB + DEFAULT CHARSET = utf8mb4 + COLLATE = utf8mb4_unicode_ci; +CREATE INDEX IF NOT EXISTS `%players_table%_username` ON `%players_table%` (`username`); + +-- Create the cooldowns table if it does not exist +CREATE TABLE IF NOT EXISTS `%cooldowns_table%` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `player_uuid` CHAR(36) NOT NULL, + `type` VARCHAR(255) NOT NULL, + `start_timestamp` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `end_timestamp` DATETIME NOT NULL, + + PRIMARY KEY (`id`), + FOREIGN KEY (`player_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB + DEFAULT CHARSET = utf8mb4 + COLLATE = utf8mb4_unicode_ci; +CREATE INDEX IF NOT EXISTS `%cooldowns_table%_player_uuid` ON `%cooldowns_table%` (`player_uuid`); + +-- Create the current cross-server teleports table if it does not exist +CREATE TABLE IF NOT EXISTS `%teleports_table%` +( + `player_uuid` CHAR(36) NOT NULL, + `destination_id` INTEGER NOT NULL, + `type` INTEGER NOT NULL DEFAULT 0, + + PRIMARY KEY (`player_uuid`), + FOREIGN KEY (`player_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (`destination_id`) REFERENCES `%positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION +) ENGINE = InnoDB + DEFAULT CHARSET = utf8mb4 + COLLATE = utf8mb4_unicode_ci; + +-- Create the saved positions table if it does not exist +CREATE TABLE IF NOT EXISTS `%saved_positions_table%` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `position_id` INTEGER NOT NULL, + `name` VARCHAR(64) NOT NULL, + `description` VARCHAR(255) NOT NULL, + `tags` MEDIUMTEXT DEFAULT NULL, + `timestamp` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + + PRIMARY KEY (`id`), + FOREIGN KEY (`position_id`) REFERENCES `%positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION +) ENGINE = InnoDB + DEFAULT CHARSET = utf8mb4 + COLLATE = utf8mb4_unicode_ci; +CREATE INDEX IF NOT EXISTS `%saved_positions_table%_name` ON `%saved_positions_table%` (`name`); + +-- Create the homes table if it does not exist +CREATE TABLE IF NOT EXISTS `%homes_table%` +( + `uuid` CHAR(36) NOT NULL, + `saved_position_id` INTEGER NOT NULL, + `owner_uuid` CHAR(36) NOT NULL, + `public` BOOLEAN NOT NULL DEFAULT FALSE, + + PRIMARY KEY (`uuid`), + FOREIGN KEY (`owner_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (`saved_position_id`) REFERENCES `%saved_positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION +) ENGINE = InnoDB + DEFAULT CHARSET = utf8mb4 + COLLATE = utf8mb4_unicode_ci; +CREATE INDEX IF NOT EXISTS `%homes_table%_owner_uuid` ON `%homes_table%` (`owner_uuid`); + +-- Create the warps table if it does not exist +CREATE TABLE IF NOT EXISTS `%warps_table%` +( + `uuid` CHAR(36) NOT NULL, + `saved_position_id` INTEGER NOT NULL, + + PRIMARY KEY (`uuid`), + FOREIGN KEY (`saved_position_id`) REFERENCES `%saved_positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION +) ENGINE = InnoDB + DEFAULT CHARSET = utf8mb4 + COLLATE = utf8mb4_unicode_ci; \ No newline at end of file diff --git a/common/src/main/resources/database/sqlite_schema.sql b/common/src/main/resources/database/sqlite_schema.sql index 813091be..0486c0ed 100644 --- a/common/src/main/resources/database/sqlite_schema.sql +++ b/common/src/main/resources/database/sqlite_schema.sql @@ -30,6 +30,7 @@ CREATE TABLE IF NOT EXISTS `%players_table%` FOREIGN KEY (`offline_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION, FOREIGN KEY (`respawn_position`) REFERENCES `%positions_table%` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION ); +CREATE INDEX IF NOT EXISTS `%players_table%_username` ON `%players_table%` (`username`); /* Create the cooldowns table if it does not exist */ CREATE TABLE IF NOT EXISTS `%cooldowns_table%` @@ -43,6 +44,7 @@ CREATE TABLE IF NOT EXISTS `%cooldowns_table%` PRIMARY KEY (`id`), FOREIGN KEY (`player_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE ); +CREATE INDEX IF NOT EXISTS `%cooldowns_table%_player_uuid` ON `%cooldowns_table%` (`player_uuid`); /* Create the current cross-server teleports table if it does not exist */ CREATE TABLE IF NOT EXISTS `%teleports_table%` @@ -69,6 +71,7 @@ CREATE TABLE IF NOT EXISTS `%saved_positions_table%` PRIMARY KEY (`id`), FOREIGN KEY (`position_id`) REFERENCES `%positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION ); +CREATE INDEX IF NOT EXISTS `%saved_positions_table%_name` ON `%saved_positions_table%` (`name`); /* Create the homes table if it does not exist */ CREATE TABLE IF NOT EXISTS `%homes_table%` @@ -82,6 +85,7 @@ CREATE TABLE IF NOT EXISTS `%homes_table%` FOREIGN KEY (`owner_uuid`) REFERENCES `%players_table%` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (`saved_position_id`) REFERENCES `%saved_positions_table%` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION ); +CREATE INDEX IF NOT EXISTS `%homes_table%_owner_uuid` ON `%homes_table%` (`owner_uuid`); /* Create the warps table if it does not exist */ CREATE TABLE IF NOT EXISTS `%warps_table%` diff --git a/docs/Config-Files.md b/docs/Config-Files.md index e2a486f0..c389e584 100644 --- a/docs/Config-Files.md +++ b/docs/Config-Files.md @@ -24,11 +24,11 @@ language: en-gb # Whether to automatically check for plugin updates on startup check_for_updates: true database: - # Type of database to use (MYSQL, SQLITE) + # Type of database to use (SQLITE, H2, MYSQL or MARIADB) type: SQLITE mysql: credentials: - # Specify credentials here if you are using MYSQL as your database type + # Specify credentials here if you are using MYSQL or MARIADB as your database type host: localhost port: 3306 database: HuskHomes @@ -36,7 +36,7 @@ database: password: pa55w0rd parameters: ?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8 connection_pool: - # MYSQL database Hikari connection pool properties. Don't modify this unless you know what you're doing! + # MYSQL / MARIADB database Hikari connection pool properties. Don't modify this unless you know what you're doing! size: 12 idle: 12 lifetime: 1800000 diff --git a/docs/Database.md b/docs/Database.md new file mode 100644 index 00000000..45294d60 --- /dev/null +++ b/docs/Database.md @@ -0,0 +1,48 @@ +HuskHomes stores player data, homes, warps, and teleports in a database of your choosing. For cross-server setups, you'll need to configure a MySQL or MariaDB database to allow homes to be accessed globally. + +## Database types +> **Warning:** There is currently no automatic way of migrating between _database_ types. Changing the database type will cause data to be lost. + +| Type | File or Server | Description | Supports cross-server | +|:----------|----------------|:----------------------------------------------------------------------------|:---------------------:| +| `SQLITE` | File | A file-based database. This is the default (recommended) option. | ❌ | +| `H2` | File | A file-based database, similar to SQLITE, with slightly faster query times. | ❌ | +| `MYSQL` | Server | A database hosted on a MySQL server. | ✅ | +| `MARIADB` | Server | A database hosted on a MariaDB server. | ✅ | + +### Cross-server +If you are using HuskHomes on a cross-server network, you will need to use a database type that supports cross-server setups. This is because cross-server setups require a single database to be shared between all servers so that HuskHomes can access the same data on each server. + +## Configuring +To change the database type, navigate to your [`config.yml`](Config-Files) file and modify the properties under `database`. + +
+Database options (config.yml) + +```yaml +database: + # Type of database to use (SQLITE, H2, MYSQL or MARIADB) + type: SQLITE + mysql: + credentials: + # Specify credentials here if you are using MYSQL or MARIADB as your database type + host: localhost + port: 3306 + database: HuskHomes + username: root + password: pa55w0rd + parameters: ?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8 + connection_pool: + # MYSQL / MARIADB database Hikari connection pool properties. Don't modify this unless you know what you're doing! + size: 12 + idle: 12 + lifetime: 1800000 + keepalive: 30000 + timeout: 20000 +``` +
+ +### Credentials (MariaDB & MySQL) +You will need to specify the credentials (hostname, port, username, password and the database) if you are using MariaDB or MySQL. These credentials are used to connect to your database server. + +Additionally, you can modify the HikariCP connection pool properties if you know what you're doing. The default values should be fine for most users. \ No newline at end of file diff --git a/docs/Home.md b/docs/Home.md index 6171f1cc..53306919 100644 --- a/docs/Home.md +++ b/docs/Home.md @@ -10,6 +10,7 @@ Welcome to the plugin documentation for HuskHomes v4.x+, the powerful and intuit * 📜 [[Command Conflicts]] ## Documentation +* 📁 [[Database]] * ⛅ [[Redis Support]] * 📝 [[Translations]] * 🟩 [[Plan Hook]] diff --git a/docs/Setup.md b/docs/Setup.md index 5ee0cfd5..81927484 100644 --- a/docs/Setup.md +++ b/docs/Setup.md @@ -2,7 +2,7 @@ This will walk you through installing HuskHomes on your Spigot, Fabric or Sponge ## Requirements * A Spigot (1.16.5+), Fabric (latest Minecraft version), or Sponge (Implementing API v8) _Minecraft: Java Edition_ server running on Java 16+ -* (For proxy network support) A proxy server (Velocity, BungeeCord) and MySQL (v8.0+) database +* (For proxy network support) A proxy server (Velocity, BungeeCord) and MySQL (v8.0+)/MariaDB database * (For optional [[Redis support]]) A Redis database (v5.0+) ## Download HuskHomes for your server @@ -18,7 +18,7 @@ These instructions are for simply installing HuskHomes on one Spigot, Fabric or - Place the plugin jar file in the `/plugins/` directory of your Spigot server, or the `/mods` directory of your Fabric/Sponge server. ### 2. Restart the server and configure - Start, then stop your server to let HuskHomes generate the config file. -- You can now edit the config and locales to your liking. +- You can now edit the [config](Config-Files) and locales to your liking. ### 3. Turn on your server - Start your server again and enjoy HuskHomes! @@ -34,9 +34,9 @@ These instructions are for installing HuskHomes on multiple Spigot, Fabric or Sp - Start, then stop every server to let HuskHomes generate the config file. - Advanced users: If you'd prefer, you can just create one config.yml file and create symbolic links in each `/plugins/HuskHomes/` (`/config/huskhomes/` on Fabric/Sponge) folder to it to make updating it easier. ### 3. Configure servers to use cross-server mode -- Navigate to the HuskHomes config file on each server (`~/plugins/HuskHomes/config.yml` on Spigot, `~/config/huskhomes/config.yml` on Fabric/Sponge) -- Under `database`, set `type` to `MYSQL` -- Under `mysql`/`credentials`, enter the credentials of your MySQL database server. +- Navigate to the HuskHomes [config](Config-Files) file on each server (`~/plugins/HuskHomes/config.yml` on Spigot, `~/config/huskhomes/config.yml` on Fabric/Sponge) +- Under `database`, set `type` to `MYSQL` or `MARIADB` (depending on which type of database you wish to use) +- Under `mysql`/`credentials`, enter the credentials of your MySQL or MariaDB database server. - Scroll down and look for the `cross_server` section. Set `enabled` to `true`. - You can additionally configure a Redis server to use for network messaging, if you prefer (set the `messenger_type` to `REDIS` if you do this). - Save the config file. Make sure you have updated the file on every server. @@ -50,5 +50,6 @@ These instructions are for installing HuskHomes on multiple Spigot, Fabric or Sp ## Next steps * [Commands & Permissions](Commands) * [[Config Files]] +* [[Database]] * [[Redis Support]] * [[Translations]] \ No newline at end of file diff --git a/docs/_Sidebar.md b/docs/_Sidebar.md index 030f559a..93181a0d 100644 --- a/docs/_Sidebar.md +++ b/docs/_Sidebar.md @@ -7,6 +7,7 @@ * 📜 [[Command Conflicts]] ## Documentation +* 📁 [[Database]] * ⛅ [[Redis Support]] * 📝 [[Translations]] * 🟩 [[Plan Hook]] diff --git a/fabric/build.gradle b/fabric/build.gradle index a3dd6a1b..ac8f2631 100644 --- a/fabric/build.gradle +++ b/fabric/build.gradle @@ -28,7 +28,9 @@ dependencies { implementation include("redis.clients:jedis:$jedis_version") implementation include("org.apache.commons:commons-pool2:$commons_pool_version") implementation include("com.mysql:mysql-connector-j:$mysql_driver_version") + implementation include("org.mariadb.jdbc:mariadb-java-client:$mariadb_driver_version") implementation include("org.xerial:sqlite-jdbc:$sqlite_driver_version") + implementation include("com.h2database:h2:$h2_driver_version") compileOnly 'org.jetbrains:annotations:24.0.1' diff --git a/fabric/src/main/java/net/william278/huskhomes/FabricHuskHomes.java b/fabric/src/main/java/net/william278/huskhomes/FabricHuskHomes.java index de94a5b0..65caae45 100644 --- a/fabric/src/main/java/net/william278/huskhomes/FabricHuskHomes.java +++ b/fabric/src/main/java/net/william278/huskhomes/FabricHuskHomes.java @@ -43,6 +43,7 @@ import net.william278.huskhomes.config.Server; import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.config.Spawn; import net.william278.huskhomes.database.Database; +import net.william278.huskhomes.database.H2Database; import net.william278.huskhomes.database.MySqlDatabase; import net.william278.huskhomes.database.SqLiteDatabase; import net.william278.huskhomes.event.FabricEventDispatcher; @@ -139,17 +140,12 @@ public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes // Create adventure audience this.audiences = FabricServerAudiences.of(minecraftServer); - // Temporarily log about sounds being disabled - todo: Remove when adventure-platform-fabric is updated - if (getSettings().doPlaySoundEffects()) { - log(Level.WARNING, "Sound effects are currently disabled for HuskHomes v" + getVersion() - + " on Fabric servers running Minecraft " + getMinecraftServer().getVersion()); - } - // Initialize the database initialize(getSettings().getDatabaseType().getDisplayName() + " database connection", (plugin) -> { this.database = switch (getSettings().getDatabaseType()) { case MYSQL, MARIADB -> new MySqlDatabase(this); case SQLITE -> new SqLiteDatabase(this); + case H2 -> new H2Database(this); }; database.initialize(); diff --git a/fabric/src/main/java/net/william278/huskhomes/user/FabricUser.java b/fabric/src/main/java/net/william278/huskhomes/user/FabricUser.java index 32b7a8e2..c75e8965 100644 --- a/fabric/src/main/java/net/william278/huskhomes/user/FabricUser.java +++ b/fabric/src/main/java/net/william278/huskhomes/user/FabricUser.java @@ -124,11 +124,6 @@ public class FabricUser extends OnlineUser { return player; } - @Override - public void playSound(@NotNull String soundEffect) throws IllegalArgumentException { - // Do nothing - todo: Fix sounds when adventure-platform-fabric is updated. - } - @Override public void teleportLocally(@NotNull Location location, boolean async) throws TeleportationException { final MinecraftServer server = player.getServer(); diff --git a/gradle.properties b/gradle.properties index 05251ac7..de3caebd 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ javaVersion=16 org.gradle.jvmargs='-Dfile.encoding=UTF-8' org.gradle.daemon=true -plugin_version=4.4.3 +plugin_version=4.4.4 plugin_archive=huskhomes plugin_description=The powerful and intuitive homes, warps, and teleports plugin/mod @@ -11,7 +11,9 @@ plugin_description=The powerful and intuitive homes, warps, and teleports plugin jedis_version=4.4.2 commons_pool_version=2.11.1 sqlite_driver_version=3.42.0.0 +h2_driver_version=2.2.220 mysql_driver_version=8.0.33 +mariadb_driver_version=3.1.4 # Fabric settings fabric_loom_version=1.3-SNAPSHOT @@ -22,4 +24,4 @@ fabric_yarn_mappings=1.20.1+build.2 fabric_api_version=0.83.1+1.20.1 fabric_permissions_api_version=0.2-SNAPSHOT -adventure_platform_fabric_version=5.9.0-SNAPSHOT \ No newline at end of file +adventure_platform_fabric_version=5.9.0 \ No newline at end of file diff --git a/paper/build.gradle b/paper/build.gradle index 66ccefe3..bd094734 100644 --- a/paper/build.gradle +++ b/paper/build.gradle @@ -11,7 +11,7 @@ dependencies { compileOnly 'org.bstats:bstats-bukkit:3.0.2' compileOnly 'org.jetbrains:annotations:24.0.1' compileOnly 'de.themoep:minedown-adventure:1.7.2-SNAPSHOT' - compileOnly 'net.william278:Annotaml:2.0.1' + compileOnly 'net.william278:annotaml:2.0.4' compileOnly 'net.william278:DesertWell:2.0.4' compileOnly 'me.lucko:commodore:2.2' compileOnly 'com.github.MilkBowl:VaultAPI:1.7.1' diff --git a/paper/src/main/resources/paper-libraries.yml b/paper/src/main/resources/paper-libraries.yml index b50120dd..8e96fb14 100644 --- a/paper/src/main/resources/paper-libraries.yml +++ b/paper/src/main/resources/paper-libraries.yml @@ -2,4 +2,6 @@ libraries: - 'redis.clients:jedis:${jedis_version}' - 'com.mysql:mysql-connector-j:${mysql_driver_version}' - - 'org.xerial:sqlite-jdbc:${sqlite_driver_version}' \ No newline at end of file + - 'org.mariadb.jdbc:mariadb-java-client:${mariadb_driver_version}' + - 'org.xerial:sqlite-jdbc:${sqlite_driver_version}' + - 'com.h2database:h2:${h2_driver_version}' \ No newline at end of file diff --git a/sponge/build.gradle b/sponge/build.gradle index 0ee44727..5b3ef12a 100644 --- a/sponge/build.gradle +++ b/sponge/build.gradle @@ -9,9 +9,11 @@ dependencies { implementation project(path: ':common') implementation 'org.bstats:bstats-sponge:3.0.2' - implementation 'redis.clients:jedis:' + jedis_version - implementation 'com.mysql:mysql-connector-j:' + mysql_driver_version - implementation 'org.xerial:sqlite-jdbc:' + sqlite_driver_version + implementation "redis.clients:jedis:$jedis_version" + implementation "com.mysql:mysql-connector-j:$mysql_driver_version" + implementation "org.mariadb.jdbc:mariadb-java-client:$mariadb_driver_version" + implementation "org.xerial:sqlite-jdbc:$sqlite_driver_version" + implementation "com.h2database:h2:$h2_driver_version" } sponge { diff --git a/sponge/src/main/java/net/william278/huskhomes/SpongeHuskHomes.java b/sponge/src/main/java/net/william278/huskhomes/SpongeHuskHomes.java index 47260588..2d11c4de 100644 --- a/sponge/src/main/java/net/william278/huskhomes/SpongeHuskHomes.java +++ b/sponge/src/main/java/net/william278/huskhomes/SpongeHuskHomes.java @@ -29,6 +29,7 @@ import net.william278.huskhomes.config.Server; import net.william278.huskhomes.config.Settings; import net.william278.huskhomes.config.Spawn; import net.william278.huskhomes.database.Database; +import net.william278.huskhomes.database.H2Database; import net.william278.huskhomes.database.MySqlDatabase; import net.william278.huskhomes.database.SqLiteDatabase; import net.william278.huskhomes.event.SpongeEventDispatcher; @@ -141,6 +142,7 @@ public class SpongeHuskHomes implements HuskHomes, SpongeTask.Supplier, SpongeSa this.database = switch (getSettings().getDatabaseType()) { case MYSQL, MARIADB -> new MySqlDatabase(this); case SQLITE -> new SqLiteDatabase(this); + case H2 -> new H2Database(this); }; database.initialize();