warps = plugin.getDatabase().getWarps();
if (plugin.getSettings().getGeneral().isPermissionRestrictWarps()
- && !executor.hasPermission(Warp.getWildcardPermission())) {
+ && !executor.hasPermission(Warp.getWildcardPermission())) {
warps = warps.stream().filter(warp -> executor.hasPermission(warp.getPermission())).toList();
}
return warps;
diff --git a/common/src/main/java/net/william278/huskhomes/config/Locales.java b/common/src/main/java/net/william278/huskhomes/config/Locales.java
index 908d46c4..745864d4 100644
--- a/common/src/main/java/net/william278/huskhomes/config/Locales.java
+++ b/common/src/main/java/net/william278/huskhomes/config/Locales.java
@@ -47,7 +47,7 @@ public class Locales {
┃ Developed by William278 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┣╸ See plugin about menu for international locale credits
- ┣╸ Formatted in MineDown: https://github.com/Phoenix616/MineDown
+ ┣╸ Formatted in MineDown: https://github.com/WiIIiam278/MineDown
┗╸ Translate HuskHomes: https://william278.net/docs/huskhomes/translations""";
protected static final String DEFAULT_LOCALE = "en-gb";
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 16d4f18a..b154360c 100644
--- a/common/src/main/java/net/william278/huskhomes/database/Database.java
+++ b/common/src/main/java/net/william278/huskhomes/database/Database.java
@@ -19,11 +19,12 @@
package net.william278.huskhomes.database;
+import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
+import lombok.Setter;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Server;
-import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.SavedPosition;
@@ -33,80 +34,162 @@ 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.intellij.lang.annotations.Language;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
+import java.io.File;
import java.io.IOException;
+import java.io.InputStream;
import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.Instant;
import java.util.*;
+import java.util.logging.Level;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import java.util.stream.Collectors;
-/**
- * An abstract representation of the plugin database, storing home, warp and player data.
- *
- * Implemented by different database platforms - MySQL, SQLite, etc. - as configured by the administrator.
- */
+
+@AllArgsConstructor(access = AccessLevel.PROTECTED)
public abstract class Database {
- protected final HuskHomes plugin;
+ protected HuskHomes plugin;
- /**
- * Loads SQL table creation schema statements from a resource file as a string array.
- *
- * @param schemaFileName database script resource file to load from
- * @return Array of string-formatted table creation schema statements
- * @throws IOException if the resource could not be read
- */
- protected final String[] getSchemaStatements(@NotNull String schemaFileName) throws IOException {
- return formatStatementTables(
- new String(Objects.requireNonNull(plugin.getResource(schemaFileName)).readAllBytes(),
- StandardCharsets.UTF_8))
- .split(";");
- }
+ @Getter
+ @Setter
+ private boolean loaded;
- /**
- * Format all table name placeholder strings in an SQL statement.
- *
- * @param sql the SQL statement with unformatted table name placeholders
- * @return the formatted statement, with table placeholders replaced with the correct names
- */
- protected final String formatStatementTables(@NotNull String sql) {
- final Settings.DatabaseSettings settings = plugin.getSettings().getDatabase();
- return sql
- .replaceAll("%positions_table%", settings
- .getTableName(Table.POSITION_DATA))
- .replaceAll("%players_table%", settings
- .getTableName(Table.PLAYER_DATA))
- .replaceAll("%cooldowns_table%", settings
- .getTableName(Table.PLAYER_COOLDOWNS_DATA))
- .replaceAll("%teleports_table%", settings
- .getTableName(Table.TELEPORT_DATA))
- .replaceAll("%saved_positions_table%", settings
- .getTableName(Table.SAVED_POSITION_DATA))
- .replaceAll("%homes_table%", settings
- .getTableName(Table.HOME_DATA))
- .replaceAll("%warps_table%", settings
- .getTableName(Table.WARP_DATA));
- }
-
- /**
- * Create a database instance, pulling table names from the plugin config.
- *
- * @param plugin the implementing plugin instance
- */
protected Database(@NotNull HuskHomes plugin) {
this.plugin = plugin;
}
/**
- * Initialize the database and ensure tables are present; create tables if they do not exist.
+ * Get the schema statements from the schema file.
+ *
+ * @return the {@link #format formatted} schema statements
+ */
+ @NotNull
+ protected final String[] getScript(@NotNull String name) {
+ name = (name.startsWith("database/") ? "" : "database/") + name + (name.endsWith(".sql") ? "" : ".sql");
+ try (InputStream file = Objects.requireNonNull(plugin.getResource(name), "Invalid script %s".formatted(name))) {
+ @Language("SQL") final String schema = new String(file.readAllBytes(), StandardCharsets.UTF_8);
+ return format(schema).split(";");
+ } catch (IOException e) {
+ plugin.log(Level.SEVERE, "Failed to load database schema", e);
+ }
+ return new String[0];
+ }
+
+ protected abstract void executeScript(@NotNull Connection connection, @NotNull String name) throws SQLException;
+
+ /**
+ * Format a string for use in an SQL query.
+ *
+ * @param statement The SQL statement to format
+ * @return The formatted SQL statement
+ */
+ @NotNull
+ protected final String format(@NotNull @Language("SQL") String statement) {
+ final Pattern pattern = Pattern.compile("%(\\w+)%");
+ final Matcher matcher = pattern.matcher(statement);
+ final StringBuilder sb = new StringBuilder();
+ while (matcher.find()) {
+ final Table table = Table.match(matcher.group(1));
+ matcher.appendReplacement(sb, plugin.getSettings().getDatabase().getTableName(table));
+ }
+ matcher.appendTail(sb);
+ return sb.toString();
+ }
+
+ /**
+ * Backup a flat file database.
+ *
+ * @param file the file to back up
+ */
+ protected final void backupFlatFile(@NotNull Path file) {
+ if (!file.toFile().exists()) {
+ return;
+ }
+
+ final Path backup = file.getParent().resolve(String.format("%s.bak", file.getFileName().toString()));
+ try {
+ final File backupFile = backup.toFile();
+ if (!backupFile.exists() || backupFile.delete()) {
+ Files.copy(file, backup);
+ }
+ } catch (IOException e) {
+ plugin.log(Level.WARNING, "Failed to backup flat file database", e);
+ }
+ }
+
+ /**
+ * Initialize the database connection.
+ *
+ * @throws IllegalStateException if the database initialization fails
*/
public abstract void initialize() throws IllegalStateException;
+ /**
+ * Check if the database has been created.
+ *
+ * @return {@code true} if the database has been created; {@code false} otherwise
+ */
+ public abstract boolean isCreated();
+
+ /**
+ * Perform database migrations.
+ *
+ * @param connection the database connection
+ * @throws SQLException if an SQL error occurs during migration
+ */
+ protected final void performMigrations(@NotNull Connection connection, @NotNull Type type) throws SQLException {
+ final int currentVersion = getSchemaVersion();
+ final int latestVersion = Migration.getLatestVersion();
+ if (currentVersion < latestVersion) {
+ plugin.log(Level.INFO, "Performing database migrations (Target version: v" + latestVersion + ")");
+ for (Migration migration : Migration.getOrderedMigrations()) {
+ if (!migration.isSupported(type)) {
+ continue;
+ }
+ if (migration.getVersion() > currentVersion) {
+ try {
+ plugin.log(Level.INFO, "Performing database migration: " + migration.getMigrationName()
+ + " (v" + migration.getVersion() + ")");
+ executeScript(connection, "migrations/%s-%s-%s.sql".formatted(
+ migration.getVersion(),
+ type.name().toLowerCase(Locale.ENGLISH),
+ migration.getMigrationName()
+ ));
+ } catch (SQLException e) {
+ plugin.log(Level.WARNING, "Migration " + migration.getMigrationName()
+ + " (v" + migration.getVersion() + ") failed; skipping", e);
+ }
+ }
+ }
+ setSchemaVersion(latestVersion);
+ plugin.log(Level.INFO, "Completed database migration (Target version: v" + latestVersion + ")");
+ }
+ }
+
+ /**
+ * Get the database schema version.
+ *
+ * @return the database schema version
+ */
+ public abstract int getSchemaVersion();
+
+ /**
+ * Set the database schema version.
+ *
+ * @param version the database schema version
+ */
+ public abstract void setSchemaVersion(int version);
+
/**
* (Internal use only) - Sets a position to the position table in the database.
*
@@ -166,7 +249,7 @@ public abstract class Database {
* @param name Username of the {@link SavedUser} to get (case-insensitive)
* @return An optional with the {@link SavedUser} present if they exist
*/
- public abstract Optional getUserDataByName(@NotNull String name);
+ public abstract Optional getUser(@NotNull String name);
/**
* Get {@link SavedUser} for a user by their Minecraft account {@link UUID}.
@@ -174,14 +257,14 @@ public abstract class Database {
* @param uuid Minecraft account {@link UUID} of the {@link SavedUser} to get
* @return An optional with the {@link SavedUser} present if they exist
*/
- public abstract Optional getUserData(@NotNull UUID uuid);
+ public abstract Optional getUser(@NotNull UUID uuid);
/**
* Delete a {@link SavedUser} from the database.
*
* @param uuid The {@link UUID} of the {@link SavedUser} to delete
*/
- public abstract void deleteUserData(@NotNull UUID uuid);
+ public abstract void deleteUser(@NotNull UUID uuid);
/**
* Get the currently active cooldown of a {@link User} for a specific {@link TransactionResolver.Action}.
@@ -479,10 +562,9 @@ public abstract class Database {
public abstract int deleteAllWarps(@NotNull String worldName, @NotNull String serverName);
/**
- * Close any remaining connection to the database source.
+ * Close the database connection.
*/
- public abstract void terminate();
-
+ public abstract void close();
/**
* Identifies types of databases.
@@ -506,6 +588,7 @@ public abstract class Database {
@Getter
@AllArgsConstructor
public enum Table {
+ META_DATA("huskhomes_metadata"),
PLAYER_DATA("huskhomes_users"),
PLAYER_COOLDOWNS_DATA("huskhomes_user_cooldowns"),
POSITION_DATA("huskhomes_position_data"),
@@ -514,8 +597,19 @@ public abstract class Database {
WARP_DATA("huskhomes_warps"),
TELEPORT_DATA("huskhomes_teleports");
+ @NotNull
private final String defaultName;
+ @NotNull
+ public static Database.Table match(@NotNull String placeholder) throws IllegalArgumentException {
+ return Table.valueOf(placeholder.toUpperCase(Locale.ENGLISH));
+ }
+
+ @NotNull
+ public String getDefaultName() {
+ return defaultName;
+ }
+
@NotNull
public static Map getConfigMap() {
return Arrays.stream(values()).collect(
@@ -524,4 +618,49 @@ public abstract class Database {
}
}
+
+ /**
+ * Represents database migrations that need to be run.
+ */
+ public enum Migration {
+ ADD_METADATA_TABLE(
+ 0, "add_metadata_table",
+ Type.MYSQL, Type.MARIADB, Type.POSTGRESQL, Type.SQLITE, Type.H2
+ );
+
+ private final int version;
+ private final String migrationName;
+ private final Type[] supportedTypes;
+
+ Migration(int version, @NotNull String migrationName, @NotNull Type... supportedTypes) {
+ this.version = version;
+ this.migrationName = migrationName;
+ this.supportedTypes = supportedTypes;
+ }
+
+ private int getVersion() {
+ return version;
+ }
+
+ private String getMigrationName() {
+ return migrationName;
+ }
+
+ private boolean isSupported(@NotNull Type type) {
+ return Arrays.stream(supportedTypes).anyMatch(supportedType -> supportedType == type);
+ }
+
+ @NotNull
+ public static List getOrderedMigrations() {
+ return Arrays.stream(Migration.values())
+ .sorted(Comparator.comparingInt(Migration::getVersion))
+ .collect(Collectors.toList());
+ }
+
+ public static int getLatestVersion() {
+ return getOrderedMigrations().get(getOrderedMigrations().size() - 1).getVersion();
+ }
+
+ }
+
}
diff --git a/common/src/main/java/net/william278/huskhomes/database/DatabaseProvider.java b/common/src/main/java/net/william278/huskhomes/database/DatabaseProvider.java
new file mode 100644
index 00000000..7e69e399
--- /dev/null
+++ b/common/src/main/java/net/william278/huskhomes/database/DatabaseProvider.java
@@ -0,0 +1,74 @@
+/*
+ * 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 org.jetbrains.annotations.NotNull;
+
+public interface DatabaseProvider {
+
+ @NotNull
+ String DATA_POOL_NAME = "HuskHomesHikariPool";
+
+ @NotNull
+ Database getDatabase();
+
+ void setDatabase(@NotNull Database database);
+
+ void closeDatabase();
+
+ default void loadDatabase() throws IllegalStateException {
+ // Create database instance
+ final Database database = createDatabase();
+
+ // Initialize database
+ database.initialize();
+ if (!database.isLoaded()) {
+ throw new IllegalStateException("Failed to initialize database");
+ }
+
+ // Set database
+ setDatabase(database);
+ }
+
+ @NotNull
+ private Database createDatabase() {
+ final Database.Type type = getPlugin().getSettings().getDatabase().getType();
+ switch (type) {
+ case MYSQL, MARIADB -> {
+ return new MySqlDatabase(getPlugin());
+ }
+ case POSTGRESQL -> {
+ return new PostgreSqlDatabase(getPlugin());
+ }
+ case SQLITE -> {
+ return new SqLiteDatabase(getPlugin());
+ }
+ case H2 -> {
+ return new H2Database(getPlugin());
+ }
+ default -> throw new IllegalStateException("Unexpected value: " + type);
+ }
+ }
+
+ @NotNull
+ HuskHomes getPlugin();
+
+}
diff --git a/common/src/main/java/net/william278/huskhomes/database/H2Database.java b/common/src/main/java/net/william278/huskhomes/database/H2Database.java
index b4d6b3af..8ecf123b 100644
--- a/common/src/main/java/net/william278/huskhomes/database/H2Database.java
+++ b/common/src/main/java/net/william278/huskhomes/database/H2Database.java
@@ -31,8 +31,7 @@ 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.nio.file.Path;
import java.sql.*;
import java.time.Instant;
import java.util.*;
@@ -47,7 +46,7 @@ public class H2Database extends Database {
/**
* Path to the H2 HuskHomesData.h2 file.
*/
- private final File databaseFile;
+ private final Path databaseFile;
/**
* The name of the database file.
@@ -58,7 +57,7 @@ public class H2Database extends Database {
public H2Database(@NotNull HuskHomes plugin) {
super(plugin);
- this.databaseFile = plugin.getConfigDirectory().resolve(DATABASE_FILE_NAME).toFile();
+ this.databaseFile = plugin.getConfigDirectory().resolve(DATABASE_FILE_NAME);
}
/**
@@ -71,29 +70,112 @@ public class H2Database extends Database {
return connectionPool.getConnection();
}
+ @SuppressWarnings("SqlSourceToSinkFlow")
@Override
- public void initialize() throws IllegalStateException {
+ protected void executeScript(@NotNull Connection connection, @NotNull String name) throws SQLException {
+ try (Statement statement = connection.createStatement()) {
+ for (String schemaStatement : getScript(name)) {
+ statement.execute(schemaStatement);
+ }
+ }
+ }
+
+ @Override
+ public void initialize() throws RuntimeException {
+ // Backup database file
+ this.backupFlatFile(databaseFile);
+
// Prepare the database flat file
- final String url = String.format("jdbc:h2:%s", databaseFile.getAbsolutePath());
+ final String url = String.format("jdbc:h2:%s", databaseFile.toAbsolutePath());
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);
- }
+ // Create tables
+ if (!isCreated()) {
+ plugin.log(Level.INFO, "Creating H2 database tables");
+ try {
+ executeScript(getConnection(), "h2_schema.sql");
+ } catch (SQLException e) {
+ plugin.log(Level.SEVERE, "Failed to create H2 database tables");
+ setLoaded(false);
+ return;
}
- } catch (SQLException | IOException e) {
- throw new IllegalStateException("Failed to initialize the H2 database", e);
+ setSchemaVersion(Migration.getLatestVersion());
+ plugin.log(Level.INFO, "H2 database tables created!");
+ setLoaded(true);
+ return;
+ }
+
+ // Perform migrations
+ try {
+ performMigrations(getConnection(), Type.H2);
+ setLoaded(true);
+ } catch (SQLException e) {
+ plugin.log(Level.SEVERE, "Failed to perform H2 database migrations");
+ setLoaded(false);
+ }
+ }
+
+ @Override
+ public boolean isCreated() {
+ if (!databaseFile.toFile().exists()) {
+ return false;
+ }
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ SELECT `uuid`
+ FROM `%player_data%`
+ LIMIT 1;"""))) {
+ statement.executeQuery();
+ return true;
+ } catch (SQLException e) {
+ return false;
+ }
+ }
+
+ @Override
+ public int getSchemaVersion() {
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ SELECT `schema_version`
+ FROM `%meta_data%`
+ LIMIT 1;"""))) {
+ final ResultSet resultSet = statement.executeQuery();
+ if (resultSet.next()) {
+ return resultSet.getInt("schema_version");
+ }
+ } catch (SQLException e) {
+ plugin.log(Level.WARNING, "The database schema version could not be fetched; "
+ + "migrations will be carried out.");
+ }
+ return -1;
+ }
+
+ @Override
+ public void setSchemaVersion(int version) {
+ if (getSchemaVersion() == -1) {
+ try (PreparedStatement insertStatement = getConnection().prepareStatement(format("""
+ INSERT INTO `%meta_data%` (`schema_version`)
+ VALUES (?);"""))) {
+ insertStatement.setInt(1, version);
+ insertStatement.executeUpdate();
+ } catch (SQLException e) {
+ plugin.log(Level.SEVERE, "Failed to insert schema version in table", e);
+ }
+ return;
+ }
+
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ UPDATE `%meta_data%`
+ SET `schema_version` = ?;"""))) {
+ statement.setInt(1, version);
+ statement.executeUpdate();
+ } catch (SQLException e) {
+ plugin.log(Level.SEVERE, "Failed to update schema version in table", e);
}
}
@Override
protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- INSERT INTO `%positions_table%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO `%position_data%`
(`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`)
VALUES
(?,?,?,?,?,?,?,?);"""),
@@ -120,8 +202,8 @@ public class H2Database extends Database {
@Override
protected void updatePosition(int positionId, @NotNull Position position,
@NotNull Connection connection) throws SQLException {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- UPDATE `%positions_table%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ UPDATE `%position_data%`
SET `x`=?,
`y`=?,
`z`=?,
@@ -147,8 +229,8 @@ public class H2Database extends Database {
@Override
protected int setSavedPosition(@NotNull SavedPosition position,
@NotNull Connection connection) throws SQLException {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- INSERT INTO `%saved_positions_table%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO `%saved_position_data%`
(`position_id`, `name`, `description`, `tags`, `timestamp`)
VALUES
(?,?,?,?,?);"""),
@@ -172,9 +254,9 @@ public class H2Database extends Database {
@Override
protected void updateSavedPosition(int savedPositionId, @NotNull SavedPosition position,
@NotNull Connection connection) throws SQLException {
- try (PreparedStatement selectStatement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement selectStatement = connection.prepareStatement(format("""
SELECT `position_id`
- FROM `%saved_positions_table%`
+ FROM `%saved_position_data%`
WHERE `id`=?;"""))) {
selectStatement.setInt(1, savedPositionId);
@@ -183,8 +265,8 @@ public class H2Database extends Database {
final int positionId = resultSet.getInt("position_id");
updatePosition(positionId, position, connection);
- try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables("""
- UPDATE `%saved_positions_table%`
+ try (PreparedStatement updateStatement = connection.prepareStatement(format("""
+ UPDATE `%saved_position_data%`
SET `name`=?,
`description`=?,
`tags`=?
@@ -201,23 +283,23 @@ public class H2Database extends Database {
@Override
public void ensureUser(@NotNull User onlineUser) {
- getUserData(onlineUser.getUuid()).ifPresentOrElse(
+ getUser(onlineUser.getUuid()).ifPresentOrElse(
existingUserData -> {
- if (!existingUserData.getUsername().equals(onlineUser.getUsername())) {
+ if (!existingUserData.getUsername().equals(onlineUser.getName())) {
// 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%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ UPDATE `%player_data%`
SET `username`=?
WHERE `uuid`=?"""))) {
- statement.setString(1, onlineUser.getUsername());
+ statement.setString(1, onlineUser.getName());
statement.setString(2, existingUserData.getUserUuid().toString());
statement.executeUpdate();
}
- plugin.log(Level.INFO, "Updated " + onlineUser.getUsername()
- + "'s name in the database (" + existingUserData.getUsername()
- + " -> " + onlineUser.getUsername() + ")");
+ plugin.log(Level.INFO, "Updated " + onlineUser.getName()
+ + "'s name in the database (" + existingUserData.getUsername()
+ + " -> " + onlineUser.getName() + ")");
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to update a player's name on the database", e);
}
@@ -226,12 +308,12 @@ public class H2Database extends Database {
() -> {
// Insert new player data into the database
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- INSERT INTO `%players_table%` (`uuid`,`username`)
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO `%player_data%` (`uuid`,`username`)
VALUES (?,?);"""))) {
statement.setString(1, onlineUser.getUuid().toString());
- statement.setString(2, onlineUser.getUsername());
+ statement.setString(2, onlineUser.getName());
statement.executeUpdate();
}
} catch (SQLException e) {
@@ -241,11 +323,11 @@ public class H2Database extends Database {
}
@Override
- public Optional getUserDataByName(@NotNull String name) {
+ public Optional getUser(@NotNull String name) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`
- FROM `%players_table%`
+ FROM `%player_data%`
WHERE `username`=?"""))) {
statement.setString(1, name);
@@ -266,11 +348,11 @@ public class H2Database extends Database {
}
@Override
- public Optional getUserData(@NotNull UUID uuid) {
+ public Optional getUser(@NotNull UUID uuid) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`
- FROM `%players_table%`
+ FROM `%player_data%`
WHERE `uuid`=?"""))) {
statement.setString(1, uuid.toString());
@@ -292,22 +374,22 @@ public class H2Database extends Database {
}
@Override
- public void deleteUserData(@NotNull UUID uuid) {
+ public void deleteUser(@NotNull UUID uuid) {
try (Connection connection = getConnection()) {
// Delete Position
- PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- DELETE FROM `%positions_table%`
+ PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM `%position_data%`
WHERE `id`
- IN ((SELECT `last_position` FROM `%players_table%` WHERE `uuid` = ?),
- (SELECT `offline_position` FROM `%players_table%` WHERE `uuid` = ?),
- (SELECT `respawn_position` FROM `%players_table%` WHERE `uuid` = ?));"""));
+ IN ((SELECT `last_position` FROM `%player_data%` WHERE `uuid` = ?),
+ (SELECT `offline_position` FROM `%player_data%` WHERE `uuid` = ?),
+ (SELECT `respawn_position` FROM `%player_data%` WHERE `uuid` = ?));"""));
statement.setString(1, uuid.toString());
statement.setString(2, uuid.toString());
statement.setString(3, uuid.toString());
statement.executeUpdate();
- statement = connection.prepareStatement(formatStatementTables("""
- DELETE FROM `%players_table%`
+ statement = connection.prepareStatement(format("""
+ DELETE FROM `%player_data%`
WHERE `uuid`=?;"""));
statement.setString(1, uuid.toString());
statement.executeUpdate();
@@ -320,9 +402,9 @@ public class H2Database extends Database {
@Override
public Optional getCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `type`, `start_timestamp`, `end_timestamp`
- FROM `%cooldowns_table%`
+ FROM `%player_cooldowns_data%`
WHERE `player_uuid`=? AND `type`=?
ORDER BY `start_timestamp` DESC
LIMIT 1;"""))) {
@@ -344,8 +426,8 @@ public class H2Database extends Database {
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`)
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO `%player_cooldowns_data%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`)
VALUES (?,?,?,?);"""))) {
statement.setString(1, user.getUuid().toString());
statement.setString(2, action.name().toLowerCase(Locale.ENGLISH));
@@ -361,8 +443,8 @@ public class H2Database extends Database {
@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%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM `%player_cooldowns_data%`
WHERE `player_uuid`=? AND `type`=?;"""))) {
statement.setString(1, user.getUuid().toString());
@@ -378,16 +460,16 @@ public class H2Database extends Database {
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`,
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `%home_data%`.`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`
+ FROM `%home_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
+ INNER JOIN `%player_data%`
+ ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid`
WHERE `owner_uuid`=?
ORDER BY `name`;"""))) {
@@ -413,7 +495,7 @@ public class H2Database extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getUsername());
+ plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getName());
}
return userHomes;
}
@@ -422,14 +504,14 @@ public class H2Database extends Database {
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`,
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `%warp_data%`.`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`
+ FROM `%warp_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%warp_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
ORDER BY `name`;"""))) {
final ResultSet resultSet = statement.executeQuery();
@@ -459,17 +541,17 @@ public class H2Database extends Database {
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`,
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `%home_data%`.`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`
+ FROM `%home_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
+ INNER JOIN `%player_data%`
+ ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid`
WHERE `public`=true
ORDER BY `name`;"""))) {
final ResultSet resultSet = statement.executeQuery();
@@ -502,17 +584,17 @@ public class H2Database extends Database {
public List getPublicHomes(@NotNull String name, boolean caseInsensitive) {
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`,
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `%home_data%`.`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`
+ FROM `%home_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id`
INNER JOIN `%positions_table`
- ON `%saved_positions_table%`.`position_id`=`%positions_table%`.`id`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
INNER JOIN `%players_table`
- ON `%homes_table%`.`owner_uuid`=`%players_table%`.`uuid`
+ ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid`
WHERE `public`=true
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))
ORDER BY `name`;"""))) {
@@ -549,17 +631,17 @@ public class H2Database extends Database {
@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`,
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `%home_data%`.`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`
+ FROM `%home_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
+ INNER JOIN `%player_data%`
+ ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid`
WHERE `owner_uuid`=?
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) {
statement.setString(1, user.getUuid().toString());
@@ -595,18 +677,18 @@ public class H2Database extends Database {
@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`,
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `%home_data%`.`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`=?;"""))) {
+ FROM `%home_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
+ INNER JOIN `%player_data%`
+ ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid`
+ WHERE `%home_data%`.`uuid`=?;"""))) {
statement.setString(1, uuid.toString());
final ResultSet resultSet = statement.executeQuery();
@@ -638,14 +720,14 @@ public class H2Database extends Database {
@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`,
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `%warp_data%`.`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`
+ FROM `%warp_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%warp_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) {
statement.setBoolean(1, caseInsensitive);
statement.setString(2, warpName);
@@ -677,15 +759,15 @@ public class H2Database extends Database {
@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`,
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `%warp_data%`.`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=?;"""))) {
+ FROM `%warp_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%warp_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
+ WHERE `%warp_data%`.uuid=?;"""))) {
statement.setString(1, uuid.toString());
final ResultSet resultSet = statement.executeQuery();
@@ -714,10 +796,10 @@ public class H2Database extends Database {
@Override
public Optional getCurrentTeleport(@NotNull OnlineUser onlineUser) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = connection.prepareStatement(format("""
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`
+ FROM `%teleport_data%`
+ INNER JOIN `%position_data%` ON `%teleport_data%`.`destination_id` = `%position_data%`.`id`
WHERE `player_uuid`=?"""))) {
statement.setString(1, onlineUser.getUuid().toString());
@@ -740,7 +822,7 @@ public class H2Database extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getName(), e);
} catch (TeleportationException e) {
e.displayMessage(onlineUser);
}
@@ -750,8 +832,8 @@ public class H2Database extends Database {
@Override
public void updateUserData(@NotNull SavedUser savedUser) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- UPDATE `%players_table%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ UPDATE `%player_data%`
SET `home_slots`=?, `ignoring_requests`=?
WHERE `uuid`=?"""))) {
@@ -769,12 +851,12 @@ public class H2Database extends Database {
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%`
+ try (PreparedStatement deleteStatement = connection.prepareStatement(format("""
+ DELETE FROM `%position_data%`
WHERE `id`=(
SELECT `destination_id`
- FROM `%teleports_table%`
- WHERE `%teleports_table%`.`player_uuid`=?
+ FROM `%teleport_data%`
+ WHERE `%teleport_data%`.`player_uuid`=?
);"""))) {
deleteStatement.setString(1, user.getUuid().toString());
deleteStatement.executeUpdate();
@@ -782,8 +864,8 @@ public class H2Database extends Database {
// 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`)
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO `%teleport_data%` (`player_uuid`, `destination_id`, `type`)
VALUES (?,?,?);"""))) {
statement.setString(1, user.getUuid().toString());
statement.setInt(2, setPosition((Position) teleport.getTarget(), connection));
@@ -793,17 +875,17 @@ public class H2Database extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getName(), e);
}
}
@Override
public Optional getLastPosition(@NotNull User user) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = connection.prepareStatement(format("""
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`
+ FROM `%player_data%`
+ INNER JOIN `%position_data%` ON `%player_data%`.`last_position` = `%position_data%`.`id`
WHERE `uuid`=?"""))) {
statement.setString(1, user.getUuid().toString());
@@ -820,7 +902,7 @@ public class H2Database extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to query the last teleport position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to query the last teleport position of " + user.getName(), e);
}
return Optional.empty();
}
@@ -828,10 +910,10 @@ public class H2Database extends Database {
@Override
public void setLastPosition(@NotNull User user, @NotNull Position position) {
try (Connection connection = getConnection()) {
- try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement queryStatement = connection.prepareStatement(format("""
SELECT `last_position`
- FROM `%players_table%`
- INNER JOIN `%positions_table%` ON `%players_table%`.last_position = `%positions_table%`.`id`
+ FROM `%player_data%`
+ INNER JOIN `%position_data%` ON `%player_data%`.last_position = `%position_data%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.getUuid().toString());
@@ -841,8 +923,8 @@ public class H2Database extends Database {
updatePosition(resultSet.getInt("last_position"), position, connection);
} else {
// Set the last position
- try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables("""
- UPDATE `%players_table%`
+ try (PreparedStatement updateStatement = connection.prepareStatement(format("""
+ UPDATE `%player_data%`
SET `last_position`=?
WHERE `uuid`=?;"""))) {
updateStatement.setInt(1, setPosition(position, connection));
@@ -852,17 +934,17 @@ public class H2Database extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getName(), e);
}
}
@Override
public Optional getOfflinePosition(@NotNull User user) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = connection.prepareStatement(format("""
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`
+ FROM `%player_data%`
+ INNER JOIN `%position_data%` ON `%player_data%`.`offline_position` = `%position_data%`.`id`
WHERE `uuid`=?"""))) {
statement.setString(1, user.getUuid().toString());
@@ -879,7 +961,7 @@ public class H2Database extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to query the offline position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to query the offline position of " + user.getName(), e);
}
return Optional.empty();
}
@@ -887,9 +969,9 @@ public class H2Database extends Database {
@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`
+ try (PreparedStatement queryStatement = connection.prepareStatement(format("""
+ SELECT `offline_position` FROM `%player_data%`
+ INNER JOIN `%position_data%` ON `%player_data%`.`offline_position` = `%position_data%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.getUuid().toString());
@@ -899,8 +981,8 @@ public class H2Database extends Database {
updatePosition(resultSet.getInt("offline_position"), position, connection);
} else {
// Set the offline position
- try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables("""
- UPDATE `%players_table%`
+ try (PreparedStatement updateStatement = connection.prepareStatement(format("""
+ UPDATE `%player_data%`
SET `offline_position`=?
WHERE `uuid`=?;"""))) {
updateStatement.setInt(1, setPosition(position, connection));
@@ -910,17 +992,17 @@ public class H2Database extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to set the offline position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to set the offline position of " + user.getName(), e);
}
}
@Override
public Optional getRespawnPosition(@NotNull User user) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = connection.prepareStatement(format("""
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`
+ FROM `%player_data%`
+ INNER JOIN `%position_data%` ON `%player_data%`.`respawn_position` = `%position_data%`.`id`
WHERE `uuid`=?"""))) {
statement.setString(1, user.getUuid().toString());
@@ -937,7 +1019,7 @@ public class H2Database extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to query the respawn position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to query the respawn position of " + user.getName(), e);
}
return Optional.empty();
}
@@ -945,9 +1027,9 @@ public class H2Database extends Database {
@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`
+ try (PreparedStatement queryStatement = connection.prepareStatement(format("""
+ SELECT `respawn_position` FROM `%player_data%`
+ INNER JOIN `%position_data%` ON `%player_data%`.respawn_position = `%position_data%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.getUuid().toString());
@@ -955,12 +1037,12 @@ public class H2Database extends Database {
if (resultSet.next()) {
if (position == null) {
// Delete a respawn position
- try (PreparedStatement deleteStatement = connection.prepareStatement(formatStatementTables("""
- DELETE FROM `%positions_table%`
+ try (PreparedStatement deleteStatement = connection.prepareStatement(format("""
+ DELETE FROM `%position_data%`
WHERE `id`=(
SELECT `respawn_position`
- FROM `%players_table%`
- WHERE `%players_table%`.`uuid`=?
+ FROM `%player_data%`
+ WHERE `%player_data%`.`uuid`=?
);"""))) {
deleteStatement.setString(1, user.getUuid().toString());
deleteStatement.executeUpdate();
@@ -972,8 +1054,8 @@ public class H2Database extends Database {
} else {
if (position != null) {
// Set a respawn position
- try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables("""
- UPDATE `%players_table%`
+ try (PreparedStatement updateStatement = connection.prepareStatement(format("""
+ UPDATE `%player_data%`
SET `respawn_position`=?
WHERE `uuid`=?;"""))) {
updateStatement.setInt(1, setPosition(position, connection));
@@ -984,7 +1066,7 @@ public class H2Database extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to set the respawn position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to set the respawn position of " + user.getName(), e);
}
}
@@ -993,8 +1075,8 @@ public class H2Database extends Database {
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%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `saved_position_id` FROM `%home_data%`
WHERE `uuid`=?;"""))) {
statement.setString(1, home.getUuid().toString());
@@ -1005,8 +1087,8 @@ public class H2Database extends Database {
}
// Update the home privacy
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- UPDATE `%homes_table%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ UPDATE `%home_data%`
SET `public`=?
WHERE `uuid`=?;"""))) {
statement.setBoolean(1, home.isPublic());
@@ -1015,12 +1097,12 @@ public class H2Database extends Database {
}
} catch (SQLException e) {
plugin.log(Level.SEVERE,
- "Failed to update a home in the database for " + home.getOwner().getUsername(), e);
+ "Failed to update a home in the database for " + home.getOwner().getName(), e);
}
}, () -> {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- INSERT INTO `%homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`)
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO `%home_data%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`)
VALUES (?,?,?,?);"""))) {
statement.setString(1, home.getUuid().toString());
statement.setInt(2, setSavedPosition(home, connection));
@@ -1031,7 +1113,7 @@ public class H2Database extends Database {
}
} catch (SQLException e) {
plugin.log(Level.SEVERE,
- "Failed to set a home to the database for " + home.getOwner().getUsername(), e);
+ "Failed to set a home to the database for " + home.getOwner().getName(), e);
}
});
}
@@ -1040,8 +1122,8 @@ public class H2Database extends Database {
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%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `saved_position_id` FROM `%warp_data%`
WHERE `uuid`=?;"""))) {
statement.setString(1, warp.getUuid().toString());
@@ -1055,8 +1137,8 @@ public class H2Database extends Database {
}
}, () -> {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- INSERT INTO `%warps_table%` (`uuid`, `saved_position_id`)
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO `%warp_data%` (`uuid`, `saved_position_id`)
VALUES (?,?);"""))) {
statement.setString(1, warp.getUuid().toString());
statement.setInt(2, setSavedPosition(warp, connection));
@@ -1072,14 +1154,14 @@ public class H2Database extends Database {
@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`=(
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM `%position_data%`
+ WHERE `%position_data%`.`id`=(
SELECT `position_id`
- FROM `%saved_positions_table%`
- WHERE `%saved_positions_table%`.`id`=(
+ FROM `%saved_position_data%`
+ WHERE `%saved_position_data%`.`id`=(
SELECT `saved_position_id`
- FROM `%homes_table%`
+ FROM `%home_data%`
WHERE `uuid`=?
)
);"""))) {
@@ -1095,14 +1177,14 @@ public class H2Database extends Database {
@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 (
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM `%position_data%`
+ WHERE `%position_data%`.`id` IN (
SELECT `position_id`
- FROM `%saved_positions_table%`
- WHERE `%saved_positions_table%`.`id` IN (
+ FROM `%saved_position_data%`
+ WHERE `%saved_position_data%`.`id` IN (
SELECT `saved_position_id`
- FROM `%homes_table%`
+ FROM `%home_data%`
WHERE `owner_uuid`=?
)
);"""))) {
@@ -1111,7 +1193,7 @@ public class H2Database extends Database {
return statement.executeUpdate();
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to delete all homes for " + user.getUsername() + " from the database", e);
+ plugin.log(Level.SEVERE, "Failed to delete all homes for " + user.getName() + " from the database", e);
}
return 0;
}
@@ -1119,14 +1201,14 @@ public class H2Database extends Database {
@Override
public int deleteAllHomes(@NotNull String worldName, @NotNull String serverName) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- DELETE FROM `%positions_table%`
- WHERE `%positions_table%`.`id` IN (
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM `%position_data%`
+ WHERE `%position_data%`.`id` IN (
SELECT `position_id`
- FROM `%saved_positions_table%`
- WHERE `%saved_positions_table%`.`id` IN (
+ FROM `%saved_position_data%`
+ WHERE `%saved_position_data%`.`id` IN (
SELECT `saved_position_id`
- FROM `%homes_table%`
+ FROM `%home_data%`
WHERE `world_name`=?
AND `server_name`=?
)
@@ -1138,7 +1220,7 @@ public class H2Database extends Database {
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete homes in the world " + worldName + " on the server "
- + serverName + " from the database", e);
+ + serverName + " from the database", e);
}
return 0;
}
@@ -1146,14 +1228,14 @@ public class H2Database extends Database {
@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`=(
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM `%position_data%`
+ WHERE `%position_data%`.`id`=(
SELECT `position_id`
- FROM `%saved_positions_table%`
- WHERE `%saved_positions_table%`.`id`=(
+ FROM `%saved_position_data%`
+ WHERE `%saved_position_data%`.`id`=(
SELECT `saved_position_id`
- FROM `%warps_table%`
+ FROM `%warp_data%`
WHERE `uuid`=?
)
);"""))) {
@@ -1169,14 +1251,14 @@ public class H2Database extends Database {
@Override
public int deleteAllWarps() {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- DELETE FROM `%positions_table%`
- WHERE `%positions_table%`.`id` IN (
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM `%position_data%`
+ WHERE `%position_data%`.`id` IN (
SELECT `position_id`
- FROM `%saved_positions_table%`
- WHERE `%saved_positions_table%`.`id` IN (
+ FROM `%saved_position_data%`
+ WHERE `%saved_position_data%`.`id` IN (
SELECT `saved_position_id`
- FROM `%warps_table%`
+ FROM `%warp_data%`
)
);"""))) {
return statement.executeUpdate();
@@ -1190,14 +1272,14 @@ public class H2Database extends Database {
@Override
public int deleteAllWarps(@NotNull String worldName, @NotNull String serverName) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- DELETE FROM `%positions_table%`
- WHERE `%positions_table%`.`id` IN (
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM `%position_data%`
+ WHERE `%position_data%`.`id` IN (
SELECT `position_id`
- FROM `%saved_positions_table%`
- WHERE `%saved_positions_table%`.`id` IN (
+ FROM `%saved_position_data%`
+ WHERE `%saved_position_data%`.`id` IN (
SELECT `saved_position_id`
- FROM `%warps_table%`
+ FROM `%warp_data%`
WHERE `world_name`=?
AND `server_name`=?
)
@@ -1209,13 +1291,13 @@ public class H2Database extends Database {
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete warps in the world " + worldName + " on the server "
- + serverName + " from the database", e);
+ + serverName + " from the database", e);
}
return 0;
}
@Override
- public void terminate() {
+ public void close() {
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 c9b1d9d5..4a0d13df 100644
--- a/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java
+++ b/common/src/main/java/net/william278/huskhomes/database/MySqlDatabase.java
@@ -28,17 +28,16 @@ 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.jetbrains.annotations.Blocking;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-import java.io.IOException;
import java.sql.*;
import java.time.Instant;
import java.util.*;
import java.util.logging.Level;
import static net.william278.huskhomes.config.Settings.DatabaseSettings;
+import static net.william278.huskhomes.database.DatabaseProvider.DATA_POOL_NAME;
/**
* A MySQL / MariaDB implementation of the plugin {@link Database}.
@@ -46,39 +45,27 @@ import static net.william278.huskhomes.config.Settings.DatabaseSettings;
@SuppressWarnings("DuplicatedCode")
public class MySqlDatabase extends Database {
- private static final String DATA_POOL_NAME = "HuskHomesHikariPool";
private final String flavor;
private final String driverClass;
private HikariDataSource dataSource;
public MySqlDatabase(@NotNull HuskHomes plugin) {
super(plugin);
-
- final Type type = plugin.getSettings().getDatabase().getType();
- this.flavor = type.getProtocol();
- this.driverClass = type == Type.MARIADB ? "org.mariadb.jdbc.Driver" : "com.mysql.cj.jdbc.Driver";
+ this.flavor = plugin.getSettings().getDatabase().getType() == Type.MARIADB
+ ? "mariadb" : "mysql";
+ this.driverClass = plugin.getSettings().getDatabase().getType() == Type.MARIADB
+ ? "org.mariadb.jdbc.Driver" : "com.mysql.cj.jdbc.Driver";
}
- /**
- * Fetch the auto-closeable connection from the hikariDataSource.
- *
- * @return The {@link Connection} to the MySQL database
- * @throws SQLException if the connection fails for some reason
- */
- @Blocking
- @NotNull
private Connection getConnection() throws SQLException {
- if (dataSource == null) {
- throw new IllegalStateException("The database has not been initialized");
- }
return dataSource.getConnection();
}
- @Blocking
- @Override
- public void initialize() throws IllegalStateException {
+ private void setConnection() {
// Initialize the Hikari pooled connection
- final DatabaseSettings.DatabaseCredentials credentials = plugin.getSettings().getDatabase().getCredentials();
+ final DatabaseSettings databaseSettings = plugin.getSettings().getDatabase();
+ final DatabaseSettings.DatabaseCredentials credentials = databaseSettings.getCredentials();
+
dataSource = new HikariDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setJdbcUrl(String.format("jdbc:%s://%s:%s/%s%s",
@@ -94,12 +81,12 @@ public class MySqlDatabase extends Database {
dataSource.setPassword(credentials.getPassword());
// Set connection pool options
- final DatabaseSettings.PoolOptions pool = plugin.getSettings().getDatabase().getPoolOptions();
- dataSource.setMaximumPoolSize(pool.getSize());
- dataSource.setMinimumIdle(pool.getIdle());
- dataSource.setMaxLifetime(pool.getLifetime());
- dataSource.setKeepaliveTime(pool.getKeepAlive());
- dataSource.setConnectionTimeout(pool.getTimeout());
+ final DatabaseSettings.PoolOptions poolOptions = databaseSettings.getPoolOptions();
+ dataSource.setMaximumPoolSize(poolOptions.getSize());
+ dataSource.setMinimumIdle(poolOptions.getIdle());
+ dataSource.setMaxLifetime(poolOptions.getLifetime());
+ dataSource.setKeepaliveTime(poolOptions.getKeepAlive());
+ dataSource.setConnectionTimeout(poolOptions.getTimeout());
dataSource.setPoolName(DATA_POOL_NAME);
// Set additional connection pool properties
@@ -121,28 +108,115 @@ public class MySqlDatabase extends Database {
"maintainTimeStats", "false")
);
dataSource.setDataSourceProperties(properties);
+ }
- // Prepare database schema; make tables if they don't exist
- try (Connection connection = dataSource.getConnection()) {
- final String[] databaseSchema = getSchemaStatements(String.format("database/%s_schema.sql", flavor));
- try (Statement statement = connection.createStatement()) {
- for (String tableCreationStatement : databaseSchema) {
- statement.execute(tableCreationStatement);
+ @SuppressWarnings("SqlSourceToSinkFlow")
+ @Override
+ protected void executeScript(@NotNull Connection connection, @NotNull String name) throws SQLException {
+ try (Statement statement = connection.createStatement()) {
+ for (String schemaStatement : getScript(name)) {
+ statement.execute(schemaStatement);
+ }
+ }
+ }
+
+ @Override
+ public void initialize() throws RuntimeException {
+ // Establish connection
+ this.setConnection();
+
+ // Create tables
+ if (!isCreated()) {
+ plugin.log(Level.INFO, "Creating MySQL database tables");
+ try {
+ executeScript(getConnection(), String.format("%s_schema.sql", flavor));
+ } catch (SQLException e) {
+ plugin.log(Level.SEVERE, "Failed to create MySQL database tables", e);
+ setLoaded(false);
+ return;
+ }
+ setSchemaVersion(Migration.getLatestVersion());
+ plugin.log(Level.INFO, "MySQL database tables created!");
+ setLoaded(true);
+ return;
+ }
+
+ // Perform migrations
+ try {
+ performMigrations(getConnection(), plugin.getSettings().getDatabase().getType());
+ setLoaded(true);
+ } catch (SQLException e) {
+ plugin.log(Level.SEVERE, "Failed to perform MySQL database migrations", e);
+ setLoaded(false);
+ }
+ }
+
+ @Override
+ public boolean isCreated() {
+ try (Connection connection = getConnection()) {
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `uuid`
+ FROM `%player_data%`
+ LIMIT 1;"""))) {
+ statement.executeQuery();
+ return true;
+ }
+ } catch (SQLException e) {
+ return false;
+ }
+ }
+
+ @Override
+ public int getSchemaVersion() {
+ try (Connection connection = getConnection()) {
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `schema_version`
+ FROM `%meta_data%`
+ LIMIT 1;"""))) {
+ final ResultSet resultSet = statement.executeQuery();
+ if (resultSet.next()) {
+ return resultSet.getInt("schema_version");
+ }
+ }
+ } catch (SQLException e) {
+ plugin.log(Level.WARNING, "The database schema version could not be fetched; "
+ + "migrations will be carried out.");
+ }
+ return -1;
+ }
+
+ @Override
+ public void setSchemaVersion(int version) {
+ if (getSchemaVersion() == -1) {
+ try (Connection connection = getConnection()) {
+ try (PreparedStatement insertStatement = connection.prepareStatement(format("""
+ INSERT INTO `%meta_data%` (`schema_version`)
+ VALUES (?)"""))) {
+ insertStatement.setInt(1, version);
+ insertStatement.executeUpdate();
}
} catch (SQLException e) {
- throw new IllegalStateException("Failed to create database tables. Please ensure you are running "
- + "MySQL v8.0+ and that your connecting user account has privileges to create tables.", e);
+ plugin.log(Level.SEVERE, "Failed to insert schema version in table", e);
}
- } catch (SQLException | IOException e) {
- throw new IllegalStateException("Failed to establish a connection to the MySQL database. "
- + "Please check the supplied database credentials in the config file", e);
+ return;
+ }
+
+ try (Connection connection = getConnection()) {
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ UPDATE `%meta_data%`
+ SET `schema_version` = ?;"""))) {
+ statement.setInt(1, version);
+ statement.executeUpdate();
+ }
+ } catch (SQLException e) {
+ plugin.log(Level.SEVERE, "Failed to update schema version in table", e);
}
}
@Override
protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- INSERT INTO `%positions_table%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO `%position_data%`
(`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`)
VALUES
(?,?,?,?,?,?,?,?);"""),
@@ -169,8 +243,8 @@ public class MySqlDatabase extends Database {
@Override
protected void updatePosition(int positionId, @NotNull Position position,
@NotNull Connection connection) throws SQLException {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- UPDATE `%positions_table%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ UPDATE `%position_data%`
SET `x`=?,
`y`=?,
`z`=?,
@@ -196,8 +270,8 @@ public class MySqlDatabase extends Database {
@Override
protected int setSavedPosition(@NotNull SavedPosition position,
@NotNull Connection connection) throws SQLException {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- INSERT INTO `%saved_positions_table%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO `%saved_position_data%`
(`position_id`, `name`, `description`, `tags`, `timestamp`)
VALUES
(?,?,?,?,?);"""),
@@ -221,9 +295,9 @@ public class MySqlDatabase extends Database {
@Override
protected void updateSavedPosition(int savedPositionId, @NotNull SavedPosition position,
@NotNull Connection connection) throws SQLException {
- try (PreparedStatement selectStatement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement selectStatement = connection.prepareStatement(format("""
SELECT `position_id`
- FROM `%saved_positions_table%`
+ FROM `%saved_position_data%`
WHERE `id`=?;"""))) {
selectStatement.setInt(1, savedPositionId);
@@ -232,8 +306,8 @@ public class MySqlDatabase extends Database {
final int positionId = resultSet.getInt("position_id");
updatePosition(positionId, position, connection);
- try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables("""
- UPDATE `%saved_positions_table%`
+ try (PreparedStatement updateStatement = connection.prepareStatement(format("""
+ UPDATE `%saved_position_data%`
SET `name`=?,
`description`=?,
`tags`=?
@@ -250,23 +324,23 @@ public class MySqlDatabase extends Database {
@Override
public void ensureUser(@NotNull User onlineUser) {
- getUserData(onlineUser.getUuid()).ifPresentOrElse(
+ getUser(onlineUser.getUuid()).ifPresentOrElse(
existingUserData -> {
- if (!existingUserData.getUsername().equals(onlineUser.getUsername())) {
+ if (!existingUserData.getUsername().equals(onlineUser.getName())) {
// 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%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ UPDATE `%player_data%`
SET `username`=?
WHERE `uuid`=?"""))) {
- statement.setString(1, onlineUser.getUsername());
+ statement.setString(1, onlineUser.getName());
statement.setString(2, existingUserData.getUserUuid().toString());
statement.executeUpdate();
}
- plugin.log(Level.INFO, "Updated " + onlineUser.getUsername()
- + "'s name in the database (" + existingUserData.getUsername()
- + " -> " + onlineUser.getUsername() + ")");
+ plugin.log(Level.INFO, "Updated " + onlineUser.getName()
+ + "'s name in the database (" + existingUserData.getUsername()
+ + " -> " + onlineUser.getName() + ")");
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to update a player's name on the database", e);
}
@@ -275,12 +349,12 @@ public class MySqlDatabase extends Database {
() -> {
// Insert new player data into the database
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- INSERT INTO `%players_table%` (`uuid`,`username`)
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO `%player_data%` (`uuid`,`username`)
VALUES (?,?);"""))) {
statement.setString(1, onlineUser.getUuid().toString());
- statement.setString(2, onlineUser.getUsername());
+ statement.setString(2, onlineUser.getName());
statement.executeUpdate();
}
} catch (SQLException e) {
@@ -290,11 +364,11 @@ public class MySqlDatabase extends Database {
}
@Override
- public Optional getUserDataByName(@NotNull String name) {
+ public Optional getUser(@NotNull String name) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`
- FROM `%players_table%`
+ FROM `%player_data%`
WHERE `username`=?"""))) {
statement.setString(1, name);
@@ -315,11 +389,11 @@ public class MySqlDatabase extends Database {
}
@Override
- public Optional getUserData(@NotNull UUID uuid) {
+ public Optional getUser(@NotNull UUID uuid) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`
- FROM `%players_table%`
+ FROM `%player_data%`
WHERE `uuid`=?"""))) {
statement.setString(1, uuid.toString());
@@ -341,14 +415,14 @@ public class MySqlDatabase extends Database {
}
@Override
- public void deleteUserData(@NotNull UUID uuid) {
+ public void deleteUser(@NotNull UUID uuid) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- DELETE FROM `%positions_table%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM `%position_data%`
WHERE `id`
- IN ((SELECT `last_position` FROM `%players_table%` WHERE `uuid` = ?),
- (SELECT `offline_position` FROM `%players_table%` WHERE `uuid` = ?),
- (SELECT `respawn_position` FROM `%players_table%` WHERE `uuid` = ?));"""))) {
+ IN ((SELECT `last_position` FROM `%player_data%` WHERE `uuid` = ?),
+ (SELECT `offline_position` FROM `%player_data%` WHERE `uuid` = ?),
+ (SELECT `respawn_position` FROM `%player_data%` WHERE `uuid` = ?));"""))) {
statement.setString(1, uuid.toString());
statement.setString(2, uuid.toString());
statement.setString(3, uuid.toString());
@@ -358,8 +432,8 @@ public class MySqlDatabase extends Database {
return;
}
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- DELETE FROM `%players_table%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM `%player_data%`
WHERE `uuid`=?;"""))) {
statement.setString(1, uuid.toString());
statement.executeUpdate();
@@ -374,9 +448,9 @@ public class MySqlDatabase extends Database {
@Override
public Optional getCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT `type`, `start_timestamp`, `end_timestamp`
- FROM `%cooldowns_table%`
+ FROM `%player_cooldowns_data%`
WHERE `player_uuid`=? AND `type`=?
ORDER BY `start_timestamp` DESC
LIMIT 1;"""))) {
@@ -398,8 +472,8 @@ public class MySqlDatabase extends Database {
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`)
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO `%player_cooldowns_data%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`)
VALUES (?,?,?,?);"""))) {
statement.setString(1, user.getUuid().toString());
statement.setString(2, action.name().toLowerCase(Locale.ENGLISH));
@@ -415,8 +489,8 @@ public class MySqlDatabase extends Database {
@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%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM `%player_cooldowns_data%`
WHERE `player_uuid`=? AND `type`=?;"""))) {
statement.setString(1, user.getUuid().toString());
@@ -432,16 +506,16 @@ public class MySqlDatabase extends Database {
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`,
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `%home_data%`.`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`
+ FROM `%home_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
+ INNER JOIN `%player_data%`
+ ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid`
WHERE `owner_uuid`=?
ORDER BY `name`;"""))) {
@@ -467,7 +541,7 @@ public class MySqlDatabase extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getUsername());
+ plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getName());
}
return userHomes;
}
@@ -476,14 +550,14 @@ public class MySqlDatabase extends Database {
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`,
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `%warp_data%`.`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`
+ FROM `%warp_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%warp_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
ORDER BY `name`;"""))) {
final ResultSet resultSet = statement.executeQuery();
@@ -513,17 +587,17 @@ public class MySqlDatabase extends Database {
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`,
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `%home_data%`.`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`
+ FROM `%home_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
+ INNER JOIN `%player_data%`
+ ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid`
WHERE `public`=true
ORDER BY `name`;"""))) {
final ResultSet resultSet = statement.executeQuery();
@@ -556,17 +630,17 @@ public class MySqlDatabase extends Database {
public List getPublicHomes(@NotNull String name, boolean caseInsensitive) {
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`,
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `%home_data%`.`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`
+ FROM `%home_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
+ INNER JOIN `%player_data%`
+ ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid`
WHERE `public`=true
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))
ORDER BY `name`;"""))) {
@@ -603,17 +677,17 @@ public class MySqlDatabase extends Database {
@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`,
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `%home_data%`.`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`
+ FROM `%home_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
+ INNER JOIN `%player_data%`
+ ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid`
WHERE `owner_uuid`=?
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) {
statement.setString(1, user.getUuid().toString());
@@ -649,18 +723,18 @@ public class MySqlDatabase extends Database {
@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`,
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `%home_data%`.`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`=?;"""))) {
+ FROM `%home_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
+ INNER JOIN `%player_data%`
+ ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid`
+ WHERE `%home_data%`.`uuid`=?;"""))) {
statement.setString(1, uuid.toString());
final ResultSet resultSet = statement.executeQuery();
@@ -692,14 +766,14 @@ public class MySqlDatabase extends Database {
@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`,
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `%warp_data%`.`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`
+ FROM `%warp_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%warp_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) {
statement.setBoolean(1, caseInsensitive);
statement.setString(2, warpName);
@@ -731,15 +805,15 @@ public class MySqlDatabase extends Database {
@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`,
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `%warp_data%`.`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=?;"""))) {
+ FROM `%warp_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%warp_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
+ WHERE `%warp_data%`.uuid=?;"""))) {
statement.setString(1, uuid.toString());
final ResultSet resultSet = statement.executeQuery();
@@ -768,10 +842,10 @@ public class MySqlDatabase extends Database {
@Override
public Optional getCurrentTeleport(@NotNull OnlineUser onlineUser) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = connection.prepareStatement(format("""
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`
+ FROM `%teleport_data%`
+ INNER JOIN `%position_data%` ON `%teleport_data%`.`destination_id` = `%position_data%`.`id`
WHERE `player_uuid`=?"""))) {
statement.setString(1, onlineUser.getUuid().toString());
@@ -794,7 +868,7 @@ public class MySqlDatabase extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getName(), e);
} catch (TeleportationException e) {
e.displayMessage(onlineUser);
}
@@ -804,8 +878,8 @@ public class MySqlDatabase extends Database {
@Override
public void updateUserData(@NotNull SavedUser savedUser) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- UPDATE `%players_table%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ UPDATE `%player_data%`
SET `home_slots`=?, `ignoring_requests`=?
WHERE `uuid`=?"""))) {
@@ -823,12 +897,12 @@ public class MySqlDatabase extends Database {
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%`
+ try (PreparedStatement deleteStatement = connection.prepareStatement(format("""
+ DELETE FROM `%position_data%`
WHERE `id`=(
SELECT `destination_id`
- FROM `%teleports_table%`
- WHERE `%teleports_table%`.`player_uuid`=?
+ FROM `%teleport_data%`
+ WHERE `%teleport_data%`.`player_uuid`=?
);"""))) {
deleteStatement.setString(1, user.getUuid().toString());
deleteStatement.executeUpdate();
@@ -836,8 +910,8 @@ public class MySqlDatabase extends Database {
// 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`)
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO `%teleport_data%` (`player_uuid`, `destination_id`, `type`)
VALUES (?,?,?);"""))) {
statement.setString(1, user.getUuid().toString());
statement.setInt(2, setPosition((Position) teleport.getTarget(), connection));
@@ -847,17 +921,17 @@ public class MySqlDatabase extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getName(), e);
}
}
@Override
public Optional getLastPosition(@NotNull User user) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = connection.prepareStatement(format("""
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`
+ FROM `%player_data%`
+ INNER JOIN `%position_data%` ON `%player_data%`.`last_position` = `%position_data%`.`id`
WHERE `uuid`=?"""))) {
statement.setString(1, user.getUuid().toString());
@@ -874,7 +948,7 @@ public class MySqlDatabase extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to query the last teleport position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to query the last teleport position of " + user.getName(), e);
}
return Optional.empty();
}
@@ -882,10 +956,10 @@ public class MySqlDatabase extends Database {
@Override
public void setLastPosition(@NotNull User user, @NotNull Position position) {
try (Connection connection = getConnection()) {
- try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement queryStatement = connection.prepareStatement(format("""
SELECT `last_position`
- FROM `%players_table%`
- INNER JOIN `%positions_table%` ON `%players_table%`.last_position = `%positions_table%`.`id`
+ FROM `%player_data%`
+ INNER JOIN `%position_data%` ON `%player_data%`.last_position = `%position_data%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.getUuid().toString());
@@ -895,8 +969,8 @@ public class MySqlDatabase extends Database {
updatePosition(resultSet.getInt("last_position"), position, connection);
} else {
// Set the last position
- try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables("""
- UPDATE `%players_table%`
+ try (PreparedStatement updateStatement = connection.prepareStatement(format("""
+ UPDATE `%player_data%`
SET `last_position`=?
WHERE `uuid`=?;"""))) {
updateStatement.setInt(1, setPosition(position, connection));
@@ -906,17 +980,17 @@ public class MySqlDatabase extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getName(), e);
}
}
@Override
public Optional getOfflinePosition(@NotNull User user) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = connection.prepareStatement(format("""
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`
+ FROM `%player_data%`
+ INNER JOIN `%position_data%` ON `%player_data%`.`offline_position` = `%position_data%`.`id`
WHERE `uuid`=?"""))) {
statement.setString(1, user.getUuid().toString());
@@ -933,7 +1007,7 @@ public class MySqlDatabase extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to query the offline position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to query the offline position of " + user.getName(), e);
}
return Optional.empty();
}
@@ -941,9 +1015,9 @@ public class MySqlDatabase extends Database {
@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`
+ try (PreparedStatement queryStatement = connection.prepareStatement(format("""
+ SELECT `offline_position` FROM `%player_data%`
+ INNER JOIN `%position_data%` ON `%player_data%`.`offline_position` = `%position_data%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.getUuid().toString());
@@ -953,8 +1027,8 @@ public class MySqlDatabase extends Database {
updatePosition(resultSet.getInt("offline_position"), position, connection);
} else {
// Set the offline position
- try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables("""
- UPDATE `%players_table%`
+ try (PreparedStatement updateStatement = connection.prepareStatement(format("""
+ UPDATE `%player_data%`
SET `offline_position`=?
WHERE `uuid`=?;"""))) {
updateStatement.setInt(1, setPosition(position, connection));
@@ -964,17 +1038,17 @@ public class MySqlDatabase extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to set the offline position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to set the offline position of " + user.getName(), e);
}
}
@Override
public Optional getRespawnPosition(@NotNull User user) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = connection.prepareStatement(format("""
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`
+ FROM `%player_data%`
+ INNER JOIN `%position_data%` ON `%player_data%`.`respawn_position` = `%position_data%`.`id`
WHERE `uuid`=?"""))) {
statement.setString(1, user.getUuid().toString());
@@ -991,7 +1065,7 @@ public class MySqlDatabase extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to query the respawn position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to query the respawn position of " + user.getName(), e);
}
return Optional.empty();
}
@@ -999,9 +1073,9 @@ public class MySqlDatabase extends Database {
@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`
+ try (PreparedStatement queryStatement = connection.prepareStatement(format("""
+ SELECT `respawn_position` FROM `%player_data%`
+ INNER JOIN `%position_data%` ON `%player_data%`.respawn_position = `%position_data%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.getUuid().toString());
@@ -1009,12 +1083,12 @@ public class MySqlDatabase extends Database {
if (resultSet.next()) {
if (position == null) {
// Delete a respawn position
- try (PreparedStatement deleteStatement = connection.prepareStatement(formatStatementTables("""
- DELETE FROM `%positions_table%`
+ try (PreparedStatement deleteStatement = connection.prepareStatement(format("""
+ DELETE FROM `%position_data%`
WHERE `id`=(
SELECT `respawn_position`
- FROM `%players_table%`
- WHERE `%players_table%`.`uuid`=?
+ FROM `%player_data%`
+ WHERE `%player_data%`.`uuid`=?
);"""))) {
deleteStatement.setString(1, user.getUuid().toString());
deleteStatement.executeUpdate();
@@ -1026,8 +1100,8 @@ public class MySqlDatabase extends Database {
} else {
if (position != null) {
// Set a respawn position
- try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables("""
- UPDATE `%players_table%`
+ try (PreparedStatement updateStatement = connection.prepareStatement(format("""
+ UPDATE `%player_data%`
SET `respawn_position`=?
WHERE `uuid`=?;"""))) {
updateStatement.setInt(1, setPosition(position, connection));
@@ -1038,7 +1112,7 @@ public class MySqlDatabase extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to set the respawn position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to set the respawn position of " + user.getName(), e);
}
}
@@ -1047,8 +1121,8 @@ public class MySqlDatabase extends Database {
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%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `saved_position_id` FROM `%home_data%`
WHERE `uuid`=?;"""))) {
statement.setString(1, home.getUuid().toString());
@@ -1059,8 +1133,8 @@ public class MySqlDatabase extends Database {
}
// Update the home privacy
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- UPDATE `%homes_table%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ UPDATE `%home_data%`
SET `public`=?
WHERE `uuid`=?;"""))) {
statement.setBoolean(1, home.isPublic());
@@ -1069,12 +1143,12 @@ public class MySqlDatabase extends Database {
}
} catch (SQLException e) {
plugin.log(Level.SEVERE,
- "Failed to update a home in the database for " + home.getOwner().getUsername(), e);
+ "Failed to update a home in the database for " + home.getOwner().getName(), e);
}
}, () -> {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- INSERT INTO `%homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`)
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO `%home_data%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`)
VALUES (?,?,?,?);"""))) {
statement.setString(1, home.getUuid().toString());
statement.setInt(2, setSavedPosition(home, connection));
@@ -1085,7 +1159,7 @@ public class MySqlDatabase extends Database {
}
} catch (SQLException e) {
plugin.log(Level.SEVERE,
- "Failed to set a home to the database for " + home.getOwner().getUsername(), e);
+ "Failed to set a home to the database for " + home.getOwner().getName(), e);
}
});
}
@@ -1094,8 +1168,8 @@ public class MySqlDatabase extends Database {
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%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT `saved_position_id` FROM `%warp_data%`
WHERE `uuid`=?;"""))) {
statement.setString(1, warp.getUuid().toString());
@@ -1109,8 +1183,8 @@ public class MySqlDatabase extends Database {
}
}, () -> {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- INSERT INTO `%warps_table%` (`uuid`, `saved_position_id`)
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO `%warp_data%` (`uuid`, `saved_position_id`)
VALUES (?,?);"""))) {
statement.setString(1, warp.getUuid().toString());
statement.setInt(2, setSavedPosition(warp, connection));
@@ -1126,14 +1200,14 @@ public class MySqlDatabase extends Database {
@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`=(
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM `%position_data%`
+ WHERE `%position_data%`.`id`=(
SELECT `position_id`
- FROM `%saved_positions_table%`
- WHERE `%saved_positions_table%`.`id`=(
+ FROM `%saved_position_data%`
+ WHERE `%saved_position_data%`.`id`=(
SELECT `saved_position_id`
- FROM `%homes_table%`
+ FROM `%home_data%`
WHERE `uuid`=?
)
);"""))) {
@@ -1149,14 +1223,14 @@ public class MySqlDatabase extends Database {
@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 (
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM `%position_data%`
+ WHERE `%position_data%`.`id` IN (
SELECT `position_id`
- FROM `%saved_positions_table%`
- WHERE `%saved_positions_table%`.`id` IN (
+ FROM `%saved_position_data%`
+ WHERE `%saved_position_data%`.`id` IN (
SELECT `saved_position_id`
- FROM `%homes_table%`
+ FROM `%home_data%`
WHERE `owner_uuid`=?
)
);"""))) {
@@ -1165,7 +1239,7 @@ public class MySqlDatabase extends Database {
return statement.executeUpdate();
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to delete all homes for " + user.getUsername() + " from the database", e);
+ plugin.log(Level.SEVERE, "Failed to delete all homes for " + user.getName() + " from the database", e);
}
return 0;
}
@@ -1173,14 +1247,14 @@ public class MySqlDatabase extends Database {
@Override
public int deleteAllHomes(@NotNull String worldName, @NotNull String serverName) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- DELETE FROM `%positions_table%`
- WHERE `%positions_table%`.`id` IN (
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM `%position_data%`
+ WHERE `%position_data%`.`id` IN (
SELECT `position_id`
- FROM `%saved_positions_table%`
- WHERE `%saved_positions_table%`.`id` IN (
+ FROM `%saved_position_data%`
+ WHERE `%saved_position_data%`.`id` IN (
SELECT `saved_position_id`
- FROM `%homes_table%`
+ FROM `%home_data%`
WHERE `world_name`=?
AND `server_name`=?
)
@@ -1192,7 +1266,7 @@ public class MySqlDatabase extends Database {
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete homes in the world " + worldName + " on the server "
- + serverName + " from the database", e);
+ + serverName + " from the database", e);
}
return 0;
}
@@ -1200,14 +1274,14 @@ public class MySqlDatabase extends Database {
@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`=(
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM `%position_data%`
+ WHERE `%position_data%`.`id`=(
SELECT `position_id`
- FROM `%saved_positions_table%`
- WHERE `%saved_positions_table%`.`id`=(
+ FROM `%saved_position_data%`
+ WHERE `%saved_position_data%`.`id`=(
SELECT `saved_position_id`
- FROM `%warps_table%`
+ FROM `%warp_data%`
WHERE `uuid`=?
)
);"""))) {
@@ -1223,14 +1297,14 @@ public class MySqlDatabase extends Database {
@Override
public int deleteAllWarps() {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- DELETE FROM `%positions_table%`
- WHERE `%positions_table%`.`id` IN (
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM `%position_data%`
+ WHERE `%position_data%`.`id` IN (
SELECT `position_id`
- FROM `%saved_positions_table%`
- WHERE `%saved_positions_table%`.`id` IN (
+ FROM `%saved_position_data%`
+ WHERE `%saved_position_data%`.`id` IN (
SELECT `saved_position_id`
- FROM `%warps_table%`
+ FROM `%warp_data%`
)
);"""))) {
return statement.executeUpdate();
@@ -1244,14 +1318,14 @@ public class MySqlDatabase extends Database {
@Override
public int deleteAllWarps(@NotNull String worldName, @NotNull String serverName) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- DELETE FROM `%positions_table%`
- WHERE `%positions_table%`.`id` IN (
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM `%position_data%`
+ WHERE `%position_data%`.`id` IN (
SELECT `position_id`
- FROM `%saved_positions_table%`
- WHERE `%saved_positions_table%`.`id` IN (
+ FROM `%saved_position_data%`
+ WHERE `%saved_position_data%`.`id` IN (
SELECT `saved_position_id`
- FROM `%warps_table%`
+ FROM `%warp_data%`
WHERE `world_name`=?
AND `server_name`=?
)
@@ -1263,13 +1337,13 @@ public class MySqlDatabase extends Database {
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete warps in the world " + worldName + " on the server "
- + serverName + " from the database", e);
+ + serverName + " from the database", e);
}
return 0;
}
@Override
- public void terminate() {
+ public void close() {
if (dataSource != null) {
if (!dataSource.isClosed()) {
dataSource.close();
diff --git a/common/src/main/java/net/william278/huskhomes/database/PostgreSqlDatabase.java b/common/src/main/java/net/william278/huskhomes/database/PostgreSqlDatabase.java
index b98090a8..9f18faac 100644
--- a/common/src/main/java/net/william278/huskhomes/database/PostgreSqlDatabase.java
+++ b/common/src/main/java/net/william278/huskhomes/database/PostgreSqlDatabase.java
@@ -28,17 +28,16 @@ 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.jetbrains.annotations.Blocking;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-import java.io.IOException;
import java.sql.*;
import java.time.Instant;
import java.util.*;
import java.util.logging.Level;
import static net.william278.huskhomes.config.Settings.DatabaseSettings;
+import static net.william278.huskhomes.database.DatabaseProvider.DATA_POOL_NAME;
/**
* A PostgreSQL implementation of the plugin {@link Database}.
@@ -46,38 +45,23 @@ import static net.william278.huskhomes.config.Settings.DatabaseSettings;
@SuppressWarnings("DuplicatedCode")
public class PostgreSqlDatabase extends Database {
- private static final String DATA_POOL_NAME = "HuskHomesHikariPool";
- private final String driverClass;
private HikariDataSource dataSource;
public PostgreSqlDatabase(@NotNull HuskHomes plugin) {
super(plugin);
-
- this.driverClass = "org.postgresql.Driver";
}
- /**
- * Fetch the auto-closeable connection from the hikariDataSource.
- *
- * @return The {@link Connection} to the PostgreSQL database
- * @throws SQLException if the connection fails for some reason
- */
- @Blocking
- @NotNull
private Connection getConnection() throws SQLException {
- if (dataSource == null) {
- throw new IllegalStateException("The database has not been initialized");
- }
return dataSource.getConnection();
}
- @Blocking
- @Override
- public void initialize() throws IllegalStateException {
+ private void setConnection() {
// Initialize the Hikari pooled connection
- final DatabaseSettings.DatabaseCredentials credentials = plugin.getSettings().getDatabase().getCredentials();
+ final DatabaseSettings databaseSettings = plugin.getSettings().getDatabase();
+ final DatabaseSettings.DatabaseCredentials credentials = databaseSettings.getCredentials();
+
dataSource = new HikariDataSource();
- dataSource.setDriverClassName(driverClass);
+ dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setJdbcUrl(String.format("jdbc:postgresql://%s:%s/%s%s",
credentials.getHost(),
credentials.getPort(),
@@ -90,12 +74,12 @@ public class PostgreSqlDatabase extends Database {
dataSource.setPassword(credentials.getPassword());
// Set connection pool options
- final DatabaseSettings.PoolOptions pool = plugin.getSettings().getDatabase().getPoolOptions();
- dataSource.setMaximumPoolSize(pool.getSize());
- dataSource.setMinimumIdle(pool.getIdle());
- dataSource.setMaxLifetime(pool.getLifetime());
- dataSource.setKeepaliveTime(pool.getKeepAlive());
- dataSource.setConnectionTimeout(pool.getTimeout());
+ final DatabaseSettings.PoolOptions poolOptions = databaseSettings.getPoolOptions();
+ dataSource.setMaximumPoolSize(poolOptions.getSize());
+ dataSource.setMinimumIdle(poolOptions.getIdle());
+ dataSource.setMaxLifetime(poolOptions.getLifetime());
+ dataSource.setKeepaliveTime(poolOptions.getKeepAlive());
+ dataSource.setConnectionTimeout(poolOptions.getTimeout());
dataSource.setPoolName(DATA_POOL_NAME);
// Set additional connection pool properties
@@ -117,28 +101,115 @@ public class PostgreSqlDatabase extends Database {
"maintainTimeStats", "false")
);
dataSource.setDataSourceProperties(properties);
+ }
- // Prepare database schema; make tables if they don't exist
- try (Connection connection = dataSource.getConnection()) {
- final String[] databaseSchema = getSchemaStatements("database/postgresql_schema.sql");
- try (Statement statement = connection.createStatement()) {
- for (String tableCreationStatement : databaseSchema) {
- statement.execute(tableCreationStatement);
+ @SuppressWarnings("SqlSourceToSinkFlow")
+ @Override
+ protected void executeScript(@NotNull Connection connection, @NotNull String name) throws SQLException {
+ try (Statement statement = connection.createStatement()) {
+ for (String schemaStatement : getScript(name)) {
+ statement.execute(schemaStatement);
+ }
+ }
+ }
+
+ @Override
+ public void initialize() throws RuntimeException {
+ // Establish connection
+ this.setConnection();
+
+ // Create tables
+ if (!isCreated()) {
+ plugin.log(Level.INFO, "Creating PostgreSQL database tables");
+ try {
+ executeScript(getConnection(), "postgresql_schema.sql");
+ } catch (SQLException e) {
+ plugin.log(Level.SEVERE, "Failed to create PostgreSQL database tables", e);
+ setLoaded(false);
+ return;
+ }
+ setSchemaVersion(Migration.getLatestVersion());
+ plugin.log(Level.INFO, "PostgreSQL database tables created!");
+ setLoaded(true);
+ return;
+ }
+
+ // Perform migrations
+ try {
+ performMigrations(getConnection(), plugin.getSettings().getDatabase().getType());
+ setLoaded(true);
+ } catch (SQLException e) {
+ plugin.log(Level.SEVERE, "Failed to perform PostgreSQL database migrations", e);
+ setLoaded(false);
+ }
+ }
+
+ @Override
+ public boolean isCreated() {
+ try (Connection connection = getConnection()) {
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT uuid
+ FROM "%player_data%"
+ LIMIT 1;"""))) {
+ statement.executeQuery();
+ return true;
+ }
+ } catch (SQLException e) {
+ return false;
+ }
+ }
+
+ @Override
+ public int getSchemaVersion() {
+ try (Connection connection = getConnection()) {
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT schema_version
+ FROM "%meta_data%"
+ LIMIT 1;"""))) {
+ final ResultSet resultSet = statement.executeQuery();
+ if (resultSet.next()) {
+ return resultSet.getInt("schema_version");
+ }
+ }
+ } catch (SQLException e) {
+ plugin.log(Level.WARNING, "The database schema version could not be fetched; "
+ + "migrations will be carried out.");
+ }
+ return -1;
+ }
+
+ @Override
+ public void setSchemaVersion(int version) {
+ if (getSchemaVersion() == -1) {
+ try (Connection connection = getConnection()) {
+ try (PreparedStatement insertStatement = connection.prepareStatement(format("""
+ INSERT INTO "%meta_data%" (`schema_version`)
+ VALUES (?)"""))) {
+ insertStatement.setInt(1, version);
+ insertStatement.executeUpdate();
}
} catch (SQLException e) {
- throw new IllegalStateException("Failed to create database tables. Please ensure that your connecting "
- + "user account has privileges to create tables.", e);
+ plugin.log(Level.SEVERE, "Failed to insert schema version in table", e);
}
- } catch (SQLException | IOException e) {
- throw new IllegalStateException("Failed to establish a connection to the PostgreSQL database. "
- + "Please check the supplied database credentials in the config file", e);
+ return;
+ }
+
+ try (Connection connection = getConnection()) {
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ UPDATE "%meta_data%"
+ SET `schema_version` = ?;"""))) {
+ statement.setInt(1, version);
+ statement.executeUpdate();
+ }
+ } catch (SQLException e) {
+ plugin.log(Level.SEVERE, "Failed to update schema version in table", e);
}
}
@Override
protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- INSERT INTO "%positions_table%"
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO "%position_data%"
("x","y","z","yaw","pitch","world_name","world_uuid","server_name")
VALUES
(?,?,?,?,?,?,?,?);"""),
@@ -165,8 +236,8 @@ public class PostgreSqlDatabase extends Database {
@Override
protected void updatePosition(int positionId, @NotNull Position position,
@NotNull Connection connection) throws SQLException {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- UPDATE "%positions_table%"
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ UPDATE "%position_data%"
SET "x"=?,
"y"=?,
"z"=?,
@@ -192,8 +263,8 @@ public class PostgreSqlDatabase extends Database {
@Override
protected int setSavedPosition(@NotNull SavedPosition position,
@NotNull Connection connection) throws SQLException {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- INSERT INTO "%saved_positions_table%"
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO "%saved_position_data%"
("position_id", "name", "description", "tags", "timestamp")
VALUES
(?,?,?,?,?);"""),
@@ -217,9 +288,9 @@ public class PostgreSqlDatabase extends Database {
@Override
protected void updateSavedPosition(int savedPositionId, @NotNull SavedPosition position,
@NotNull Connection connection) throws SQLException {
- try (PreparedStatement selectStatement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement selectStatement = connection.prepareStatement(format("""
SELECT "position_id"
- FROM "%saved_positions_table%"
+ FROM "%saved_position_data%"
WHERE "id"=?;"""))) {
selectStatement.setInt(1, savedPositionId);
@@ -228,8 +299,8 @@ public class PostgreSqlDatabase extends Database {
final int positionId = resultSet.getInt("position_id");
updatePosition(positionId, position, connection);
- try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables("""
- UPDATE "%saved_positions_table%"
+ try (PreparedStatement updateStatement = connection.prepareStatement(format("""
+ UPDATE "%saved_position_data%"
SET "name"=?,
"description"=?,
"tags"=?
@@ -246,23 +317,23 @@ public class PostgreSqlDatabase extends Database {
@Override
public void ensureUser(@NotNull User onlineUser) {
- getUserData(onlineUser.getUuid()).ifPresentOrElse(
+ getUser(onlineUser.getUuid()).ifPresentOrElse(
existingUserData -> {
- if (!existingUserData.getUsername().equals(onlineUser.getUsername())) {
+ if (!existingUserData.getUsername().equals(onlineUser.getName())) {
// 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%"
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ UPDATE "%player_data%"
SET "username"=?
WHERE "uuid"=?"""))) {
- statement.setString(1, onlineUser.getUsername());
+ statement.setString(1, onlineUser.getName());
statement.setString(2, existingUserData.getUserUuid().toString());
statement.executeUpdate();
}
- plugin.log(Level.INFO, "Updated " + onlineUser.getUsername()
- + "'s name in the database (" + existingUserData.getUsername()
- + " -> " + onlineUser.getUsername() + ")");
+ plugin.log(Level.INFO, "Updated " + onlineUser.getName()
+ + "'s name in the database (" + existingUserData.getUsername()
+ + " -> " + onlineUser.getName() + ")");
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to update a player's name on the database", e);
}
@@ -271,12 +342,12 @@ public class PostgreSqlDatabase extends Database {
() -> {
// Insert new player data into the database
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- INSERT INTO "%players_table%" ("uuid","username")
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO "%player_data%" ("uuid","username")
VALUES (?,?);"""))) {
statement.setString(1, onlineUser.getUuid().toString());
- statement.setString(2, onlineUser.getUsername());
+ statement.setString(2, onlineUser.getName());
statement.executeUpdate();
}
} catch (SQLException e) {
@@ -286,11 +357,11 @@ public class PostgreSqlDatabase extends Database {
}
@Override
- public Optional getUserDataByName(@NotNull String name) {
+ public Optional getUser(@NotNull String name) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT "uuid", "username", "home_slots", "ignoring_requests"
- FROM "%players_table%"
+ FROM "%player_data%"
WHERE "username"=?"""))) {
statement.setString(1, name);
@@ -311,11 +382,11 @@ public class PostgreSqlDatabase extends Database {
}
@Override
- public Optional getUserData(@NotNull UUID uuid) {
+ public Optional getUser(@NotNull UUID uuid) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT "uuid", "username", "home_slots", "ignoring_requests"
- FROM "%players_table%"
+ FROM "%player_data%"
WHERE "uuid"=?"""))) {
statement.setString(1, uuid.toString());
@@ -337,14 +408,14 @@ public class PostgreSqlDatabase extends Database {
}
@Override
- public void deleteUserData(@NotNull UUID uuid) {
+ public void deleteUser(@NotNull UUID uuid) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- DELETE FROM "%positions_table%"
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM "%position_data%"
WHERE "id"
- IN ((SELECT "last_position" FROM "%players_table%" WHERE "uuid" = ?),
- (SELECT "offline_position" FROM "%players_table%" WHERE "uuid" = ?),
- (SELECT "respawn_position" FROM "%players_table%" WHERE "uuid" = ?));"""))) {
+ IN ((SELECT "last_position" FROM "%player_data%" WHERE "uuid" = ?),
+ (SELECT "offline_position" FROM "%player_data%" WHERE "uuid" = ?),
+ (SELECT "respawn_position" FROM "%player_data%" WHERE "uuid" = ?));"""))) {
statement.setString(1, uuid.toString());
statement.setString(2, uuid.toString());
statement.setString(3, uuid.toString());
@@ -354,8 +425,8 @@ public class PostgreSqlDatabase extends Database {
return;
}
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- DELETE FROM "%players_table%"
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM "%player_data%"
WHERE "uuid"=?;"""))) {
statement.setString(1, uuid.toString());
statement.executeUpdate();
@@ -370,9 +441,9 @@ public class PostgreSqlDatabase extends Database {
@Override
public Optional getCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = connection.prepareStatement(format("""
SELECT "type", "start_timestamp", "end_timestamp"
- FROM "%cooldowns_table%"
+ FROM "%player_cooldowns_data%"
WHERE "player_uuid"=? AND "type"=?
ORDER BY "start_timestamp" DESC
LIMIT 1;"""))) {
@@ -394,8 +465,8 @@ public class PostgreSqlDatabase extends Database {
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")
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO "%player_cooldowns_data%" ("player_uuid", "type", "start_timestamp", "end_timestamp")
VALUES (?,?,?,?);"""))) {
statement.setString(1, user.getUuid().toString());
statement.setString(2, action.name().toLowerCase(Locale.ENGLISH));
@@ -411,8 +482,8 @@ public class PostgreSqlDatabase extends Database {
@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%"
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM "%player_cooldowns_data%"
WHERE "player_uuid"=? AND "type"=?;"""))) {
statement.setString(1, user.getUuid().toString());
@@ -428,16 +499,16 @@ public class PostgreSqlDatabase extends Database {
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",
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT "%home_data%"."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"
+ FROM "%home_data%"
+ INNER JOIN "%saved_position_data%"
+ ON "%home_data%"."saved_position_id"="%saved_position_data%"."id"
+ INNER JOIN "%position_data%"
+ ON "%saved_position_data%"."position_id"="%position_data%"."id"
+ INNER JOIN "%player_data%"
+ ON "%home_data%"."owner_uuid"="%player_data%"."uuid"
WHERE "owner_uuid"=?
ORDER BY "name";"""))) {
@@ -463,7 +534,7 @@ public class PostgreSqlDatabase extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getUsername());
+ plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getName());
}
return userHomes;
}
@@ -472,14 +543,14 @@ public class PostgreSqlDatabase extends Database {
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",
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT "%warp_data%"."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"
+ FROM "%warp_data%"
+ INNER JOIN "%saved_position_data%"
+ ON "%warp_data%"."saved_position_id"="%saved_position_data%"."id"
+ INNER JOIN "%position_data%"
+ ON "%saved_position_data%"."position_id"="%position_data%"."id"
ORDER BY "name";"""))) {
final ResultSet resultSet = statement.executeQuery();
@@ -509,17 +580,17 @@ public class PostgreSqlDatabase extends Database {
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",
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT "%home_data%"."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"
+ FROM "%home_data%"
+ INNER JOIN "%saved_position_data%"
+ ON "%home_data%"."saved_position_id"="%saved_position_data%"."id"
+ INNER JOIN "%position_data%"
+ ON "%saved_position_data%"."position_id"="%position_data%"."id"
+ INNER JOIN "%player_data%"
+ ON "%home_data%"."owner_uuid"="%player_data%"."uuid"
WHERE "public"=true
ORDER BY "name";"""))) {
final ResultSet resultSet = statement.executeQuery();
@@ -552,17 +623,17 @@ public class PostgreSqlDatabase extends Database {
public List getPublicHomes(@NotNull String name, boolean caseInsensitive) {
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",
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT "%home_data%"."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"
+ FROM "%home_data%"
+ INNER JOIN "%saved_position_data%"
+ ON "%home_data%"."saved_position_id"="%saved_position_data%"."id"
+ INNER JOIN "%position_data%"
+ ON "%saved_position_data%"."position_id"="%position_data%"."id"
+ INNER JOIN "%player_data%"
+ ON "%home_data%"."owner_uuid"="%player_data%"."uuid"
WHERE "public"=true
AND ((? AND UPPER("name") LIKE UPPER(?)) OR ("name"=?))
ORDER BY "name";"""))) {
@@ -599,17 +670,17 @@ public class PostgreSqlDatabase extends Database {
@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",
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT "%home_data%"."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"
+ FROM "%home_data%"
+ INNER JOIN "%saved_position_data%"
+ ON "%home_data%"."saved_position_id"="%saved_position_data%"."id"
+ INNER JOIN "%position_data%"
+ ON "%saved_position_data%"."position_id"="%position_data%"."id"
+ INNER JOIN "%player_data%"
+ ON "%home_data%"."owner_uuid"="%player_data%"."uuid"
WHERE "owner_uuid"=?
AND ((? AND UPPER("name") LIKE UPPER(?)) OR ("name"=?))"""))) {
statement.setString(1, user.getUuid().toString());
@@ -645,18 +716,18 @@ public class PostgreSqlDatabase extends Database {
@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",
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT "%home_data%"."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"=?;"""))) {
+ FROM "%home_data%"
+ INNER JOIN "%saved_position_data%"
+ ON "%home_data%"."saved_position_id"="%saved_position_data%"."id"
+ INNER JOIN "%position_data%"
+ ON "%saved_position_data%"."position_id"="%position_data%"."id"
+ INNER JOIN "%player_data%"
+ ON "%home_data%"."owner_uuid"="%player_data%"."uuid"
+ WHERE "%home_data%"."uuid"=?;"""))) {
statement.setString(1, uuid.toString());
final ResultSet resultSet = statement.executeQuery();
@@ -688,14 +759,14 @@ public class PostgreSqlDatabase extends Database {
@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",
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT "%warp_data%"."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"
+ FROM "%warp_data%"
+ INNER JOIN "%saved_position_data%"
+ ON "%warp_data%"."saved_position_id"="%saved_position_data%"."id"
+ INNER JOIN "%position_data%"
+ ON "%saved_position_data%"."position_id"="%position_data%"."id"
AND ((? AND UPPER("name") LIKE UPPER(?)) OR ("name"=?))"""))) {
statement.setBoolean(1, caseInsensitive);
statement.setString(2, warpName);
@@ -727,15 +798,15 @@ public class PostgreSqlDatabase extends Database {
@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",
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT "%warp_data%"."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=?;"""))) {
+ FROM "%warp_data%"
+ INNER JOIN "%saved_position_data%"
+ ON "%warp_data%"."saved_position_id"="%saved_position_data%"."id"
+ INNER JOIN "%position_data%"
+ ON "%saved_position_data%"."position_id"="%position_data%"."id"
+ WHERE "%warp_data%".uuid=?;"""))) {
statement.setString(1, uuid.toString());
final ResultSet resultSet = statement.executeQuery();
@@ -764,10 +835,10 @@ public class PostgreSqlDatabase extends Database {
@Override
public Optional getCurrentTeleport(@NotNull OnlineUser onlineUser) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = connection.prepareStatement(format("""
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"
+ FROM "%teleport_data%"
+ INNER JOIN "%position_data%" ON "%teleport_data%"."destination_id" = "%position_data%"."id"
WHERE "player_uuid"=?"""))) {
statement.setString(1, onlineUser.getUuid().toString());
@@ -790,7 +861,7 @@ public class PostgreSqlDatabase extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getName(), e);
} catch (TeleportationException e) {
e.displayMessage(onlineUser);
}
@@ -800,8 +871,8 @@ public class PostgreSqlDatabase extends Database {
@Override
public void updateUserData(@NotNull SavedUser savedUser) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- UPDATE "%players_table%"
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ UPDATE "%player_data%"
SET "home_slots"=?, "ignoring_requests"=?
WHERE "uuid"=?"""))) {
@@ -819,12 +890,12 @@ public class PostgreSqlDatabase extends Database {
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%"
+ try (PreparedStatement deleteStatement = connection.prepareStatement(format("""
+ DELETE FROM "%position_data%"
WHERE "id"=(
SELECT "destination_id"
- FROM "%teleports_table%"
- WHERE "%teleports_table%"."player_uuid"=?
+ FROM "%teleport_data%"
+ WHERE "%teleport_data%"."player_uuid"=?
);"""))) {
deleteStatement.setString(1, user.getUuid().toString());
deleteStatement.executeUpdate();
@@ -832,8 +903,8 @@ public class PostgreSqlDatabase extends Database {
// 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")
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO "%teleport_data%" ("player_uuid", "destination_id", "type")
VALUES (?,?,?);"""))) {
statement.setString(1, user.getUuid().toString());
statement.setInt(2, setPosition((Position) teleport.getTarget(), connection));
@@ -843,17 +914,17 @@ public class PostgreSqlDatabase extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getName(), e);
}
}
@Override
public Optional getLastPosition(@NotNull User user) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = connection.prepareStatement(format("""
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"
+ FROM "%player_data%"
+ INNER JOIN "%position_data%" ON "%player_data%"."last_position" = "%position_data%"."id"
WHERE "uuid"=?"""))) {
statement.setString(1, user.getUuid().toString());
@@ -870,7 +941,7 @@ public class PostgreSqlDatabase extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to query the last teleport position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to query the last teleport position of " + user.getName(), e);
}
return Optional.empty();
}
@@ -878,10 +949,10 @@ public class PostgreSqlDatabase extends Database {
@Override
public void setLastPosition(@NotNull User user, @NotNull Position position) {
try (Connection connection = getConnection()) {
- try (PreparedStatement queryStatement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement queryStatement = connection.prepareStatement(format("""
SELECT "last_position"
- FROM "%players_table%"
- INNER JOIN "%positions_table%" ON "%players_table%".last_position = "%positions_table%"."id"
+ FROM "%player_data%"
+ INNER JOIN "%position_data%" ON "%player_data%".last_position = "%position_data%"."id"
WHERE "uuid"=?;"""))) {
queryStatement.setString(1, user.getUuid().toString());
@@ -891,8 +962,8 @@ public class PostgreSqlDatabase extends Database {
updatePosition(resultSet.getInt("last_position"), position, connection);
} else {
// Set the last position
- try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables("""
- UPDATE "%players_table%"
+ try (PreparedStatement updateStatement = connection.prepareStatement(format("""
+ UPDATE "%player_data%"
SET "last_position"=?
WHERE "uuid"=?;"""))) {
updateStatement.setInt(1, setPosition(position, connection));
@@ -902,17 +973,17 @@ public class PostgreSqlDatabase extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getName(), e);
}
}
@Override
public Optional getOfflinePosition(@NotNull User user) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = connection.prepareStatement(format("""
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"
+ FROM "%player_data%"
+ INNER JOIN "%position_data%" ON "%player_data%"."offline_position" = "%position_data%"."id"
WHERE "uuid"=?"""))) {
statement.setString(1, user.getUuid().toString());
@@ -929,7 +1000,7 @@ public class PostgreSqlDatabase extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to query the offline position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to query the offline position of " + user.getName(), e);
}
return Optional.empty();
}
@@ -937,9 +1008,9 @@ public class PostgreSqlDatabase extends Database {
@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"
+ try (PreparedStatement queryStatement = connection.prepareStatement(format("""
+ SELECT "offline_position" FROM "%player_data%"
+ INNER JOIN "%position_data%" ON "%player_data%"."offline_position" = "%position_data%"."id"
WHERE "uuid"=?;"""))) {
queryStatement.setString(1, user.getUuid().toString());
@@ -949,8 +1020,8 @@ public class PostgreSqlDatabase extends Database {
updatePosition(resultSet.getInt("offline_position"), position, connection);
} else {
// Set the offline position
- try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables("""
- UPDATE "%players_table%"
+ try (PreparedStatement updateStatement = connection.prepareStatement(format("""
+ UPDATE "%player_data%"
SET "offline_position"=?
WHERE "uuid"=?;"""))) {
updateStatement.setInt(1, setPosition(position, connection));
@@ -960,17 +1031,17 @@ public class PostgreSqlDatabase extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to set the offline position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to set the offline position of " + user.getName(), e);
}
}
@Override
public Optional getRespawnPosition(@NotNull User user) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = connection.prepareStatement(format("""
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"
+ FROM "%player_data%"
+ INNER JOIN "%position_data%" ON "%player_data%"."respawn_position" = "%position_data%"."id"
WHERE "uuid"=?"""))) {
statement.setString(1, user.getUuid().toString());
@@ -987,7 +1058,7 @@ public class PostgreSqlDatabase extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to query the respawn position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to query the respawn position of " + user.getName(), e);
}
return Optional.empty();
}
@@ -995,9 +1066,9 @@ public class PostgreSqlDatabase extends Database {
@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"
+ try (PreparedStatement queryStatement = connection.prepareStatement(format("""
+ SELECT "respawn_position" FROM "%player_data%"
+ INNER JOIN "%position_data%" ON "%player_data%".respawn_position = "%position_data%"."id"
WHERE "uuid"=?;"""))) {
queryStatement.setString(1, user.getUuid().toString());
@@ -1005,12 +1076,12 @@ public class PostgreSqlDatabase extends Database {
if (resultSet.next()) {
if (position == null) {
// Delete a respawn position
- try (PreparedStatement deleteStatement = connection.prepareStatement(formatStatementTables("""
- DELETE FROM "%positions_table%"
+ try (PreparedStatement deleteStatement = connection.prepareStatement(format("""
+ DELETE FROM "%position_data%"
WHERE "id"=(
SELECT "respawn_position"
- FROM "%players_table%"
- WHERE "%players_table%"."uuid"=?
+ FROM "%player_data%"
+ WHERE "%player_data%"."uuid"=?
);"""))) {
deleteStatement.setString(1, user.getUuid().toString());
deleteStatement.executeUpdate();
@@ -1022,8 +1093,8 @@ public class PostgreSqlDatabase extends Database {
} else {
if (position != null) {
// Set a respawn position
- try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables("""
- UPDATE "%players_table%"
+ try (PreparedStatement updateStatement = connection.prepareStatement(format("""
+ UPDATE "%player_data%"
SET "respawn_position"=?
WHERE "uuid"=?;"""))) {
updateStatement.setInt(1, setPosition(position, connection));
@@ -1034,7 +1105,7 @@ public class PostgreSqlDatabase extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to set the respawn position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to set the respawn position of " + user.getName(), e);
}
}
@@ -1043,8 +1114,8 @@ public class PostgreSqlDatabase extends Database {
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%"
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT "saved_position_id" FROM "%home_data%"
WHERE "uuid"=?;"""))) {
statement.setString(1, home.getUuid().toString());
@@ -1055,8 +1126,8 @@ public class PostgreSqlDatabase extends Database {
}
// Update the home privacy
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- UPDATE "%homes_table%"
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ UPDATE "%home_data%"
SET "public"=?
WHERE "uuid"=?;"""))) {
statement.setBoolean(1, home.isPublic());
@@ -1065,12 +1136,12 @@ public class PostgreSqlDatabase extends Database {
}
} catch (SQLException e) {
plugin.log(Level.SEVERE,
- "Failed to update a home in the database for " + home.getOwner().getUsername(), e);
+ "Failed to update a home in the database for " + home.getOwner().getName(), e);
}
}, () -> {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- INSERT INTO "%homes_table%" ("uuid", "saved_position_id", "owner_uuid", "public")
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO "%home_data%" ("uuid", "saved_position_id", "owner_uuid", "public")
VALUES (?,?,?,?);"""))) {
statement.setString(1, home.getUuid().toString());
statement.setInt(2, setSavedPosition(home, connection));
@@ -1081,7 +1152,7 @@ public class PostgreSqlDatabase extends Database {
}
} catch (SQLException e) {
plugin.log(Level.SEVERE,
- "Failed to set a home to the database for " + home.getOwner().getUsername(), e);
+ "Failed to set a home to the database for " + home.getOwner().getName(), e);
}
});
}
@@ -1090,8 +1161,8 @@ public class PostgreSqlDatabase extends Database {
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%"
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ SELECT "saved_position_id" FROM "%warp_data%"
WHERE "uuid"=?;"""))) {
statement.setString(1, warp.getUuid().toString());
@@ -1105,8 +1176,8 @@ public class PostgreSqlDatabase extends Database {
}
}, () -> {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- INSERT INTO "%warps_table%" ("uuid", "saved_position_id")
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO "%warp_data%" ("uuid", "saved_position_id")
VALUES (?,?);"""))) {
statement.setString(1, warp.getUuid().toString());
statement.setInt(2, setSavedPosition(warp, connection));
@@ -1122,14 +1193,14 @@ public class PostgreSqlDatabase extends Database {
@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"=(
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM "%position_data%"
+ WHERE "%position_data%"."id"=(
SELECT "position_id"
- FROM "%saved_positions_table%"
- WHERE "%saved_positions_table%"."id"=(
+ FROM "%saved_position_data%"
+ WHERE "%saved_position_data%"."id"=(
SELECT "saved_position_id"
- FROM "%homes_table%"
+ FROM "%home_data%"
WHERE "uuid"=?
)
);"""))) {
@@ -1145,14 +1216,14 @@ public class PostgreSqlDatabase extends Database {
@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 (
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM "%position_data%"
+ WHERE "%position_data%"."id" IN (
SELECT "position_id"
- FROM "%saved_positions_table%"
- WHERE "%saved_positions_table%"."id" IN (
+ FROM "%saved_position_data%"
+ WHERE "%saved_position_data%"."id" IN (
SELECT "saved_position_id"
- FROM "%homes_table%"
+ FROM "%home_data%"
WHERE "owner_uuid"=?
)
);"""))) {
@@ -1161,7 +1232,7 @@ public class PostgreSqlDatabase extends Database {
return statement.executeUpdate();
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to delete all homes for " + user.getUsername() + " from the database", e);
+ plugin.log(Level.SEVERE, "Failed to delete all homes for " + user.getName() + " from the database", e);
}
return 0;
}
@@ -1169,14 +1240,14 @@ public class PostgreSqlDatabase extends Database {
@Override
public int deleteAllHomes(@NotNull String worldName, @NotNull String serverName) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- DELETE FROM "%positions_table%"
- WHERE "%positions_table%"."id" IN (
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM "%position_data%"
+ WHERE "%position_data%"."id" IN (
SELECT "position_id"
- FROM "%saved_positions_table%"
- WHERE "%saved_positions_table%"."id" IN (
+ FROM "%saved_position_data%"
+ WHERE "%saved_position_data%"."id" IN (
SELECT "saved_position_id"
- FROM "%homes_table%"
+ FROM "%home_data%"
WHERE "world_name"=?
AND "server_name"=?
)
@@ -1188,7 +1259,7 @@ public class PostgreSqlDatabase extends Database {
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete homes in the world " + worldName + " on the server "
- + serverName + " from the database", e);
+ + serverName + " from the database", e);
}
return 0;
}
@@ -1196,14 +1267,14 @@ public class PostgreSqlDatabase extends Database {
@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"=(
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM "%position_data%"
+ WHERE "%position_data%"."id"=(
SELECT "position_id"
- FROM "%saved_positions_table%"
- WHERE "%saved_positions_table%"."id"=(
+ FROM "%saved_position_data%"
+ WHERE "%saved_position_data%"."id"=(
SELECT "saved_position_id"
- FROM "%warps_table%"
+ FROM "%warp_data%"
WHERE "uuid"=?
)
);"""))) {
@@ -1219,14 +1290,14 @@ public class PostgreSqlDatabase extends Database {
@Override
public int deleteAllWarps() {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- DELETE FROM "%positions_table%"
- WHERE "%positions_table%"."id" IN (
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM "%position_data%"
+ WHERE "%position_data%"."id" IN (
SELECT "position_id"
- FROM "%saved_positions_table%"
- WHERE "%saved_positions_table%"."id" IN (
+ FROM "%saved_position_data%"
+ WHERE "%saved_position_data%"."id" IN (
SELECT "saved_position_id"
- FROM "%warps_table%"
+ FROM "%warp_data%"
)
);"""))) {
return statement.executeUpdate();
@@ -1240,14 +1311,14 @@ public class PostgreSqlDatabase extends Database {
@Override
public int deleteAllWarps(@NotNull String worldName, @NotNull String serverName) {
try (Connection connection = getConnection()) {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- DELETE FROM "%positions_table%"
- WHERE "%positions_table%"."id" IN (
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ DELETE FROM "%position_data%"
+ WHERE "%position_data%"."id" IN (
SELECT "position_id"
- FROM "%saved_positions_table%"
- WHERE "%saved_positions_table%"."id" IN (
+ FROM "%saved_position_data%"
+ WHERE "%saved_position_data%"."id" IN (
SELECT "saved_position_id"
- FROM "%warps_table%"
+ FROM "%warp_data%"
WHERE "world_name"=?
AND "server_name"=?
)
@@ -1259,13 +1330,13 @@ public class PostgreSqlDatabase extends Database {
}
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete warps in the world " + worldName + " on the server "
- + serverName + " from the database", e);
+ + serverName + " from the database", e);
}
return 0;
}
@Override
- public void terminate() {
+ public void close() {
if (dataSource != null) {
if (!dataSource.isClosed()) {
dataSource.close();
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 4b8938bd..cf2ba191 100644
--- a/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java
+++ b/common/src/main/java/net/william278/huskhomes/database/SqLiteDatabase.java
@@ -31,8 +31,8 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.sqlite.SQLiteConfig;
-import java.io.File;
import java.io.IOException;
+import java.nio.file.Path;
import java.sql.*;
import java.time.Instant;
import java.util.*;
@@ -47,7 +47,7 @@ public class SqLiteDatabase extends Database {
/**
* Path to the SQLite HuskHomesData.db file.
*/
- private final File databaseFile;
+ private final Path databaseFile;
/**
* The name of the database file.
@@ -59,16 +59,14 @@ public class SqLiteDatabase extends Database {
*/
private Connection connection;
-
public SqLiteDatabase(@NotNull HuskHomes plugin) {
super(plugin);
- this.databaseFile = plugin.getConfigDirectory().resolve(DATABASE_FILE_NAME).toFile();
+ this.databaseFile = plugin.getConfigDirectory().resolve(DATABASE_FILE_NAME);
}
+ @NotNull
private Connection getConnection() throws SQLException {
- if (connection == null) {
- setConnection();
- } else if (connection.isClosed()) {
+ if (connection == null || connection.isClosed()) {
setConnection();
}
return connection;
@@ -77,7 +75,7 @@ public class SqLiteDatabase extends Database {
private void setConnection() {
try {
// Ensure that the database file exists
- if (databaseFile.createNewFile()) {
+ if (databaseFile.toFile().createNewFile()) {
plugin.log(Level.INFO, "Created the SQLite database file");
}
@@ -88,16 +86,15 @@ public class SqLiteDatabase extends Database {
SQLiteConfig config = new SQLiteConfig();
config.enforceForeignKeys(true);
config.setEncoding(SQLiteConfig.Encoding.UTF8);
- config.setJournalMode(SQLiteConfig.JournalMode.WAL);
- config.setSynchronous(SQLiteConfig.SynchronousMode.NORMAL);
+ config.setSynchronous(SQLiteConfig.SynchronousMode.FULL);
// Establish the connection
connection = DriverManager.getConnection(
- String.format("jdbc:sqlite:%s", databaseFile.getAbsolutePath()),
+ String.format("jdbc:sqlite:%s", databaseFile.toAbsolutePath()),
config.toProperties()
);
} catch (IOException e) {
- plugin.log(Level.SEVERE, "An exception occurred creating the SQLite database file", e);
+ plugin.log(Level.SEVERE, "An exception occurred creating the database file", e);
} catch (SQLException e) {
plugin.log(Level.SEVERE, "An SQL exception occurred initializing the SQLite database", e);
} catch (ClassNotFoundException e) {
@@ -105,29 +102,111 @@ public class SqLiteDatabase extends Database {
}
}
+ @SuppressWarnings("SqlSourceToSinkFlow")
@Override
- public void initialize() throws IllegalStateException {
- // Set up the connection
- setConnection();
-
- // Prepare database schema; make tables if they don't exist
- try {
- // Load the database schema CREATE statements from schema file
- final String[] databaseSchema = getSchemaStatements("database/sqlite_schema.sql");
- try (Statement statement = getConnection().createStatement()) {
- for (String tableCreationStatement : databaseSchema) {
- statement.execute(tableCreationStatement);
- }
+ protected void executeScript(@NotNull Connection connection, @NotNull String name) throws SQLException {
+ try (Statement statement = connection.createStatement()) {
+ for (String schemaStatement : getScript(name)) {
+ statement.execute(schemaStatement);
}
- } catch (SQLException | IOException e) {
- throw new IllegalStateException("Failed to initialize the SQLite database", e);
+ }
+ }
+
+ @Override
+ public void initialize() throws RuntimeException {
+ // Establish connection
+ this.setConnection();
+
+ // Backup database file
+ this.backupFlatFile(databaseFile);
+
+ // Create tables
+ if (!isCreated()) {
+ plugin.log(Level.INFO, "Creating SQLite database tables");
+ try {
+ executeScript(getConnection(), "sqlite_schema.sql");
+ } catch (SQLException e) {
+ plugin.log(Level.SEVERE, "Failed to create SQLite database tables");
+ setLoaded(false);
+ return;
+ }
+ setSchemaVersion(Migration.getLatestVersion());
+ plugin.log(Level.INFO, "SQLite database tables created!");
+ setLoaded(true);
+ return;
+ }
+
+ // Perform migrations
+ try {
+ performMigrations(getConnection(), Type.SQLITE);
+ setLoaded(true);
+ } catch (SQLException e) {
+ plugin.log(Level.SEVERE, "Failed to perform SQLite database migrations");
+ setLoaded(false);
+ }
+ }
+
+ @Override
+ public boolean isCreated() {
+ if (!databaseFile.toFile().exists()) {
+ return false;
+ }
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ SELECT `uuid`
+ FROM `%player_data%`
+ LIMIT 1;"""))) {
+ statement.executeQuery();
+ return true;
+ } catch (SQLException e) {
+ return false;
+ }
+ }
+
+ @Override
+ public int getSchemaVersion() {
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ SELECT `schema_version`
+ FROM `%meta_data%`
+ LIMIT 1;"""))) {
+ final ResultSet resultSet = statement.executeQuery();
+ if (resultSet.next()) {
+ return resultSet.getInt("schema_version");
+ }
+ } catch (SQLException e) {
+ plugin.log(Level.WARNING, "The database schema version could not be fetched; "
+ + "migrations will be carried out.");
+ }
+ return -1;
+ }
+
+ @Override
+ public void setSchemaVersion(int version) {
+ if (getSchemaVersion() == -1) {
+ try (PreparedStatement insertStatement = getConnection().prepareStatement(format("""
+ INSERT INTO `%meta_data%` (`schema_version`)
+ VALUES (?);"""))) {
+ insertStatement.setInt(1, version);
+ insertStatement.executeUpdate();
+ } catch (SQLException e) {
+ plugin.log(Level.SEVERE, "Failed to insert schema version in table", e);
+ }
+ return;
+ }
+
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ UPDATE `%meta_data%`
+ SET `schema_version` = ?;"""))) {
+ statement.setInt(1, version);
+ statement.executeUpdate();
+ } catch (SQLException e) {
+ plugin.log(Level.SEVERE, "Failed to update schema version in table", e);
}
}
@Override
protected int setPosition(@NotNull Position position, @NotNull Connection connection) throws SQLException {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- INSERT INTO `%positions_table%`
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ INSERT INTO `%position_data%`
(`x`,`y`,`z`,`yaw`,`pitch`,`world_name`,`world_uuid`,`server_name`)
VALUES
(?,?,?,?,?,?,?,?)
@@ -155,8 +234,8 @@ public class SqLiteDatabase extends Database {
@Override
protected void updatePosition(int positionId, @NotNull Position position,
@NotNull Connection connection) throws SQLException {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- UPDATE `%positions_table%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ UPDATE `%position_data%`
SET `x`=?,
`y`=?,
`z`=?,
@@ -182,8 +261,8 @@ public class SqLiteDatabase extends Database {
@Override
protected int setSavedPosition(@NotNull SavedPosition position,
@NotNull Connection connection) throws SQLException {
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- INSERT INTO `%saved_positions_table%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ INSERT INTO `%saved_position_data%`
(`position_id`, `name`, `description`, `tags`, `timestamp`)
VALUES
(?,?,?,?,?)
@@ -208,9 +287,9 @@ public class SqLiteDatabase extends Database {
@Override
protected void updateSavedPosition(int savedPositionId, @NotNull SavedPosition position,
@NotNull Connection connection) throws SQLException {
- try (PreparedStatement selectStatement = connection.prepareStatement(formatStatementTables("""
+ try (PreparedStatement selectStatement = connection.prepareStatement(format("""
SELECT `position_id`
- FROM `%saved_positions_table%`
+ FROM `%saved_position_data%`
WHERE `id`=?;"""))) {
selectStatement.setInt(1, savedPositionId);
@@ -219,8 +298,8 @@ public class SqLiteDatabase extends Database {
final int positionId = resultSet.getInt("position_id");
updatePosition(positionId, position, connection);
- try (PreparedStatement updateStatement = connection.prepareStatement(formatStatementTables("""
- UPDATE `%saved_positions_table%`
+ try (PreparedStatement updateStatement = connection.prepareStatement(format("""
+ UPDATE `%saved_position_data%`
SET `name`=?,
`description`=?,
`tags`=?
@@ -237,21 +316,21 @@ public class SqLiteDatabase extends Database {
@Override
public void ensureUser(@NotNull User onlineUser) {
- getUserData(onlineUser.getUuid()).ifPresentOrElse(
+ getUser(onlineUser.getUuid()).ifPresentOrElse(
existingUser -> {
- if (!existingUser.getUsername().equals(onlineUser.getUsername())) {
+ if (!existingUser.getUsername().equals(onlineUser.getName())) {
// Update a player's name if it has changed in the database
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- UPDATE `%players_table%`
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ UPDATE `%player_data%`
SET `username`=?
WHERE `uuid`=?"""))) {
- statement.setString(1, onlineUser.getUsername());
+ statement.setString(1, onlineUser.getName());
statement.setString(2, existingUser.getUserUuid().toString());
statement.executeUpdate();
- plugin.log(Level.INFO, "Updated " + onlineUser.getUsername()
- + "'s name in the database (" + existingUser.getUsername()
- + " -> " + onlineUser.getUsername() + ")");
+ plugin.log(Level.INFO, "Updated " + onlineUser.getName()
+ + "'s name in the database (" + existingUser.getUsername()
+ + " -> " + onlineUser.getName() + ")");
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to update a player's name on the database", e);
}
@@ -259,12 +338,12 @@ public class SqLiteDatabase extends Database {
},
() -> {
// Insert new player data into the database
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- INSERT INTO `%players_table%` (`uuid`,`username`)
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ INSERT INTO `%player_data%` (`uuid`,`username`)
VALUES (?,?);"""))) {
statement.setString(1, onlineUser.getUuid().toString());
- statement.setString(2, onlineUser.getUsername());
+ statement.setString(2, onlineUser.getName());
statement.executeUpdate();
} catch (SQLException e) {
@@ -274,10 +353,10 @@ public class SqLiteDatabase extends Database {
}
@Override
- public Optional getUserDataByName(@NotNull String name) {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
+ public Optional getUser(@NotNull String name) {
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`
- FROM `%players_table%`
+ FROM `%player_data%`
WHERE `username`=?"""))) {
statement.setString(1, name);
@@ -297,10 +376,10 @@ public class SqLiteDatabase extends Database {
}
@Override
- public Optional getUserData(@NotNull UUID uuid) {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
+ public Optional getUser(@NotNull UUID uuid) {
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
SELECT `uuid`, `username`, `home_slots`, `ignoring_requests`
- FROM `%players_table%`
+ FROM `%player_data%`
WHERE `uuid`=?"""))) {
statement.setString(1, uuid.toString());
@@ -321,13 +400,13 @@ public class SqLiteDatabase extends Database {
}
@Override
- public void deleteUserData(@NotNull UUID uuid) {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- DELETE FROM `%positions_table%`
+ public void deleteUser(@NotNull UUID uuid) {
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ DELETE FROM `%position_data%`
WHERE `id`
- IN ((SELECT `last_position` FROM `%players_table%` WHERE `uuid` = ?),
- (SELECT `offline_position` FROM `%players_table%` WHERE `uuid` = ?),
- (SELECT `respawn_position` FROM `%players_table%` WHERE `uuid` = ?));"""))) {
+ IN ((SELECT `last_position` FROM `%player_data%` WHERE `uuid` = ?),
+ (SELECT `offline_position` FROM `%player_data%` WHERE `uuid` = ?),
+ (SELECT `respawn_position` FROM `%player_data%` WHERE `uuid` = ?));"""))) {
statement.setString(1, uuid.toString());
statement.setString(2, uuid.toString());
statement.setString(3, uuid.toString());
@@ -337,8 +416,8 @@ public class SqLiteDatabase extends Database {
return;
}
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- DELETE FROM `%players_table%`
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ DELETE FROM `%player_data%`
WHERE `uuid`=?;"""))) {
statement.setString(1, uuid.toString());
statement.executeUpdate();
@@ -349,9 +428,9 @@ public class SqLiteDatabase extends Database {
@Override
public Optional getCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
SELECT `type`, `start_timestamp`, `end_timestamp`
- FROM `%cooldowns_table%`
+ FROM `%player_cooldowns_data%`
WHERE `player_uuid`=? AND `type`=?
ORDER BY `start_timestamp` DESC
LIMIT 1;"""))) {
@@ -370,8 +449,8 @@ public class SqLiteDatabase extends Database {
@Override
public void removeCooldown(@NotNull TransactionResolver.Action action, @NotNull User user) {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- DELETE FROM `%cooldowns_table%`
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ DELETE FROM `%player_cooldowns_data%`
WHERE `player_uuid`=? AND `type`=?;"""))) {
statement.setString(1, user.getUuid().toString());
statement.setString(2, action.name().toLowerCase(Locale.ENGLISH));
@@ -384,8 +463,8 @@ public class SqLiteDatabase extends Database {
@Override
public void setCooldown(@NotNull TransactionResolver.Action action, @NotNull User user,
@NotNull Instant cooldownExpiry) {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- INSERT INTO `%cooldowns_table%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`)
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ INSERT INTO `%player_cooldowns_data%` (`player_uuid`, `type`, `start_timestamp`, `end_timestamp`)
VALUES (?,?,?,?);"""))) {
statement.setString(1, user.getUuid().toString());
statement.setString(2, action.name().toLowerCase(Locale.ENGLISH));
@@ -400,16 +479,16 @@ public class SqLiteDatabase extends Database {
@Override
public List getHomes(@NotNull User user) {
final List userHomes = new ArrayList<>();
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `name`, `description`, `tags`, `timestamp`,
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ SELECT `%home_data%`.`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`
+ FROM `%home_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
+ INNER JOIN `%player_data%`
+ ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid`
WHERE `owner_uuid`=?
ORDER BY `name`;"""))) {
statement.setString(1, user.getUuid().toString());
@@ -434,7 +513,7 @@ public class SqLiteDatabase extends Database {
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getUsername());
+ plugin.log(Level.SEVERE, "Failed to query the database for home data for:" + user.getName());
}
return userHomes;
}
@@ -442,14 +521,14 @@ public class SqLiteDatabase extends Database {
@Override
public List getWarps() {
final List warps = new ArrayList<>();
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`,
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ SELECT `%warp_data%`.`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`
+ FROM `%warp_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%warp_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
ORDER BY `name`;"""))) {
final ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
@@ -476,17 +555,17 @@ public class SqLiteDatabase extends Database {
@Override
public List getPublicHomes() {
final List userHomes = new ArrayList<>();
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`,
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ SELECT `%home_data%`.`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`
+ FROM `%home_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
+ INNER JOIN `%player_data%`
+ ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid`
WHERE `public`=true
ORDER BY `name`;"""))) {
final ResultSet resultSet = statement.executeQuery();
@@ -518,17 +597,17 @@ public class SqLiteDatabase extends Database {
@Override
public List getPublicHomes(@NotNull String name, boolean caseInsensitive) {
final List userHomes = new ArrayList<>();
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`,
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ SELECT `%home_data%`.`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`
+ FROM `%home_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
+ INNER JOIN `%player_data%`
+ ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid`
WHERE `public`=true
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))
ORDER BY `name`;"""))) {
@@ -563,17 +642,17 @@ public class SqLiteDatabase extends Database {
@Override
public Optional getHome(@NotNull User user, @NotNull String homeName, boolean caseInsensitive) {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`,
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ SELECT `%home_data%`.`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`
+ FROM `%home_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
+ INNER JOIN `%player_data%`
+ ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid`
WHERE `owner_uuid`=?
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) {
statement.setString(1, user.getUuid().toString());
@@ -607,18 +686,18 @@ public class SqLiteDatabase extends Database {
@Override
public Optional getHome(@NotNull UUID uuid) {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- SELECT `%homes_table%`.`uuid` AS `home_uuid`, `owner_uuid`, `username` AS `owner_username`,
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ SELECT `%home_data%`.`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`=?;"""))) {
+ FROM `%home_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%home_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
+ INNER JOIN `%player_data%`
+ ON `%home_data%`.`owner_uuid`=`%player_data%`.`uuid`
+ WHERE `%home_data%`.`uuid`=?;"""))) {
statement.setString(1, uuid.toString());
final ResultSet resultSet = statement.executeQuery();
@@ -648,14 +727,14 @@ public class SqLiteDatabase extends Database {
@Override
public Optional getWarp(@NotNull String warpName, boolean caseInsensitive) {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`,
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ SELECT `%warp_data%`.`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`
+ FROM `%warp_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%warp_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
AND ((? AND UPPER(`name`) LIKE UPPER(?)) OR (`name`=?))"""))) {
statement.setBoolean(1, caseInsensitive);
statement.setString(2, warpName);
@@ -685,15 +764,15 @@ public class SqLiteDatabase extends Database {
@Override
public Optional getWarp(@NotNull UUID uuid) {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- SELECT `%warps_table%`.`uuid` AS `warp_uuid`, `name`, `description`, `tags`, `timestamp`,
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ SELECT `%warp_data%`.`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=?;"""))) {
+ FROM `%warp_data%`
+ INNER JOIN `%saved_position_data%`
+ ON `%warp_data%`.`saved_position_id`=`%saved_position_data%`.`id`
+ INNER JOIN `%position_data%`
+ ON `%saved_position_data%`.`position_id`=`%position_data%`.`id`
+ WHERE `%warp_data%`.uuid=?;"""))) {
statement.setString(1, uuid.toString());
final ResultSet resultSet = statement.executeQuery();
@@ -720,10 +799,10 @@ public class SqLiteDatabase extends Database {
@Override
public Optional getCurrentTeleport(@NotNull OnlineUser onlineUser) {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
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`
+ FROM `%teleport_data%`
+ INNER JOIN `%position_data%` ON `%teleport_data%`.`destination_id` = `%position_data%`.`id`
WHERE `player_uuid`=?"""))) {
statement.setString(1, onlineUser.getUuid().toString());
@@ -745,7 +824,7 @@ public class SqLiteDatabase extends Database {
.toTeleport());
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to query the current teleport of " + onlineUser.getName(), e);
} catch (TeleportationException e) {
e.displayMessage(onlineUser);
}
@@ -754,8 +833,8 @@ public class SqLiteDatabase extends Database {
@Override
public void updateUserData(@NotNull SavedUser savedUser) {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- UPDATE `%players_table%`
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ UPDATE `%player_data%`
SET `home_slots`=?, `ignoring_requests`=?
WHERE `uuid`=?"""))) {
@@ -771,40 +850,40 @@ public class SqLiteDatabase extends Database {
@Override
public void setCurrentTeleport(@NotNull User user, @Nullable Teleport teleport) {
// Clear the user's current teleport
- try (PreparedStatement deleteStatement = getConnection().prepareStatement(formatStatementTables("""
- DELETE FROM `%positions_table%`
+ try (PreparedStatement deleteStatement = getConnection().prepareStatement(format("""
+ DELETE FROM `%position_data%`
WHERE `id`=(
SELECT `destination_id`
- FROM `%teleports_table%`
- WHERE `%teleports_table%`.`player_uuid`=?
+ FROM `%teleport_data%`
+ WHERE `%teleport_data%`.`player_uuid`=?
);"""))) {
deleteStatement.setString(1, user.getUuid().toString());
deleteStatement.executeUpdate();
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to clear the current teleport of " + user.getName(), e);
}
// Set the user's teleport into the database (if it's not null)
if (teleport != null) {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- INSERT INTO `%teleports_table%` (`player_uuid`, `destination_id`, `type`)
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ INSERT INTO `%teleport_data%` (`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 set the current teleport of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to set the current teleport of " + user.getName(), e);
}
}
}
@Override
public Optional getLastPosition(@NotNull User user) {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
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`
+ FROM `%player_data%`
+ INNER JOIN `%position_data%` ON `%player_data%`.`last_position` = `%position_data%`.`id`
WHERE `uuid`=?"""))) {
statement.setString(1, user.getUuid().toString());
@@ -820,16 +899,16 @@ public class SqLiteDatabase extends Database {
resultSet.getString("server_name")));
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to query the last teleport position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to query the last teleport position of " + user.getName(), e);
}
return Optional.empty();
}
@Override
public void setLastPosition(@NotNull User user, @NotNull Position position) {
- try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables("""
- SELECT `last_position` FROM `%players_table%`
- INNER JOIN `%positions_table%` ON `%players_table%`.last_position = `%positions_table%`.`id`
+ try (PreparedStatement queryStatement = getConnection().prepareStatement(format("""
+ SELECT `last_position` FROM `%player_data%`
+ INNER JOIN `%position_data%` ON `%player_data%`.last_position = `%position_data%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.getUuid().toString());
@@ -839,8 +918,8 @@ public class SqLiteDatabase extends Database {
updatePosition(resultSet.getInt("last_position"), position, connection);
} else {
// Set the last position
- try (PreparedStatement updateStatement = getConnection().prepareStatement(formatStatementTables("""
- UPDATE `%players_table%`
+ try (PreparedStatement updateStatement = getConnection().prepareStatement(format("""
+ UPDATE `%player_data%`
SET `last_position`=?
WHERE `uuid`=?;"""))) {
updateStatement.setInt(1, setPosition(position, connection));
@@ -849,16 +928,16 @@ public class SqLiteDatabase extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to set the last position of " + user.getName(), e);
}
}
@Override
public Optional getOfflinePosition(@NotNull User user) {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
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`
+ FROM `%player_data%`
+ INNER JOIN `%position_data%` ON `%player_data%`.`offline_position` = `%position_data%`.`id`
WHERE `uuid`=?"""))) {
statement.setString(1, user.getUuid().toString());
@@ -875,16 +954,16 @@ public class SqLiteDatabase extends Database {
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to query the offline position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to query the offline position of " + user.getName(), e);
}
return Optional.empty();
}
@Override
public void setOfflinePosition(@NotNull User user, @NotNull Position position) {
- try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables("""
- SELECT `offline_position` FROM `%players_table%`
- INNER JOIN `%positions_table%` ON `%players_table%`.offline_position = `%positions_table%`.`id`
+ try (PreparedStatement queryStatement = getConnection().prepareStatement(format("""
+ SELECT `offline_position` FROM `%player_data%`
+ INNER JOIN `%position_data%` ON `%player_data%`.offline_position = `%position_data%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.getUuid().toString());
@@ -894,8 +973,8 @@ public class SqLiteDatabase extends Database {
updatePosition(resultSet.getInt("offline_position"), position, connection);
} else {
// Set the offline position
- try (PreparedStatement updateStatement = getConnection().prepareStatement(formatStatementTables("""
- UPDATE `%players_table%`
+ try (PreparedStatement updateStatement = getConnection().prepareStatement(format("""
+ UPDATE `%player_data%`
SET `offline_position`=?
WHERE `uuid`=?;"""))) {
updateStatement.setInt(1, setPosition(position, connection));
@@ -904,16 +983,16 @@ public class SqLiteDatabase extends Database {
}
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to set the offline position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to set the offline position of " + user.getName(), e);
}
}
@Override
public Optional getRespawnPosition(@NotNull User user) {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
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`
+ FROM `%player_data%`
+ INNER JOIN `%position_data%` ON `%player_data%`.`respawn_position` = `%position_data%`.`id`
WHERE `uuid`=?"""))) {
statement.setString(1, user.getUuid().toString());
@@ -929,16 +1008,16 @@ public class SqLiteDatabase extends Database {
resultSet.getString("server_name")));
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to query the respawn position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to query the respawn position of " + user.getName(), e);
}
return Optional.empty();
}
@Override
public void setRespawnPosition(@NotNull User user, @Nullable Position position) {
- try (PreparedStatement queryStatement = getConnection().prepareStatement(formatStatementTables("""
- SELECT `respawn_position` FROM `%players_table%`
- INNER JOIN `%positions_table%` ON `%players_table%`.respawn_position = `%positions_table%`.`id`
+ try (PreparedStatement queryStatement = getConnection().prepareStatement(format("""
+ SELECT `respawn_position` FROM `%player_data%`
+ INNER JOIN `%position_data%` ON `%player_data%`.respawn_position = `%position_data%`.`id`
WHERE `uuid`=?;"""))) {
queryStatement.setString(1, user.getUuid().toString());
@@ -946,12 +1025,12 @@ public class SqLiteDatabase extends Database {
if (resultSet.next()) {
if (position == null) {
// Delete a respawn position
- try (PreparedStatement deleteStatement = getConnection().prepareStatement(formatStatementTables("""
- DELETE FROM `%positions_table%`
+ try (PreparedStatement deleteStatement = getConnection().prepareStatement(format("""
+ DELETE FROM `%position_data%`
WHERE `id`=(
SELECT `respawn_position`
- FROM `%players_table%`
- WHERE `%players_table%`.`uuid`=?
+ FROM `%player_data%`
+ WHERE `%player_data%`.`uuid`=?
);"""))) {
deleteStatement.setString(1, user.getUuid().toString());
deleteStatement.executeUpdate();
@@ -963,8 +1042,8 @@ public class SqLiteDatabase extends Database {
} else {
if (position != null) {
// Set a respawn position
- try (PreparedStatement updateStatement = getConnection().prepareStatement(formatStatementTables("""
- UPDATE `%players_table%`
+ try (PreparedStatement updateStatement = getConnection().prepareStatement(format("""
+ UPDATE `%player_data%`
SET `respawn_position`=?
WHERE `uuid`=?;"""))) {
updateStatement.setInt(1, setPosition(position, connection));
@@ -975,7 +1054,7 @@ public class SqLiteDatabase extends Database {
}
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to set the respawn position of " + user.getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to set the respawn position of " + user.getName(), e);
}
}
@@ -984,8 +1063,8 @@ public class SqLiteDatabase extends Database {
getHome(home.getUuid()).ifPresentOrElse(presentHome -> {
try {
// Update the home's saved position, including metadata
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- SELECT `saved_position_id` FROM `%homes_table%`
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ SELECT `saved_position_id` FROM `%home_data%`
WHERE `uuid`=?;"""))) {
statement.setString(1, home.getUuid().toString());
@@ -996,8 +1075,8 @@ public class SqLiteDatabase extends Database {
}
// Update the home privacy
- try (PreparedStatement statement = connection.prepareStatement(formatStatementTables("""
- UPDATE `%homes_table%`
+ try (PreparedStatement statement = connection.prepareStatement(format("""
+ UPDATE `%home_data%`
SET `public`=?
WHERE `uuid`=?;"""))) {
statement.setBoolean(1, home.isPublic());
@@ -1006,11 +1085,11 @@ public class SqLiteDatabase extends Database {
}
} catch (SQLException e) {
plugin.log(Level.SEVERE,
- "Failed to update a home in the database for " + home.getOwner().getUsername(), e);
+ "Failed to update a home in the database for " + home.getOwner().getName(), e);
}
}, () -> {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- INSERT INTO `%homes_table%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`)
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ INSERT INTO `%home_data%` (`uuid`, `saved_position_id`, `owner_uuid`, `public`)
VALUES (?,?,?,?);"""))) {
statement.setString(1, home.getUuid().toString());
statement.setInt(2, setSavedPosition(home, connection));
@@ -1019,7 +1098,7 @@ public class SqLiteDatabase extends Database {
statement.executeUpdate();
} catch (SQLException e) {
- plugin.log(Level.SEVERE, "Failed to set home for " + home.getOwner().getUsername(), e);
+ plugin.log(Level.SEVERE, "Failed to set home for " + home.getOwner().getName(), e);
}
});
}
@@ -1028,8 +1107,8 @@ public class SqLiteDatabase extends Database {
public void saveWarp(@NotNull Warp warp) {
getWarp(warp.getUuid())
.ifPresentOrElse(presentWarp -> {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- SELECT `saved_position_id` FROM `%warps_table%`
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ SELECT `saved_position_id` FROM `%warp_data%`
WHERE `uuid`=?;"""))) {
statement.setString(1, warp.getUuid().toString());
@@ -1041,8 +1120,8 @@ public class SqLiteDatabase extends Database {
plugin.log(Level.SEVERE, "Failed to update a warp in the database", e);
}
}, () -> {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- INSERT INTO `%warps_table%` (`uuid`, `saved_position_id`)
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ INSERT INTO `%warp_data%` (`uuid`, `saved_position_id`)
VALUES (?,?);"""))) {
statement.setString(1, warp.getUuid().toString());
statement.setInt(2, setSavedPosition(warp, connection));
@@ -1056,14 +1135,14 @@ public class SqLiteDatabase extends Database {
@Override
public void deleteHome(@NotNull UUID uuid) {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- DELETE FROM `%positions_table%`
- WHERE `%positions_table%`.`id`=(
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ DELETE FROM `%position_data%`
+ WHERE `%position_data%`.`id`=(
SELECT `position_id`
- FROM `%saved_positions_table%`
- WHERE `%saved_positions_table%`.`id`=(
+ FROM `%saved_position_data%`
+ WHERE `%saved_position_data%`.`id`=(
SELECT `saved_position_id`
- FROM `%homes_table%`
+ FROM `%home_data%`
WHERE `uuid`=?
)
);"""))) {
@@ -1076,14 +1155,14 @@ public class SqLiteDatabase extends Database {
@Override
public int deleteAllHomes(@NotNull User user) {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- DELETE FROM `%positions_table%`
- WHERE `%positions_table%`.`id` IN (
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ DELETE FROM `%position_data%`
+ WHERE `%position_data%`.`id` IN (
SELECT `position_id`
- FROM `%saved_positions_table%`
- WHERE `%saved_positions_table%`.`id` IN (
+ FROM `%saved_position_data%`
+ WHERE `%saved_position_data%`.`id` IN (
SELECT `saved_position_id`
- FROM `%homes_table%`
+ FROM `%home_data%`
WHERE `owner_uuid`=?
)
);"""))) {
@@ -1091,21 +1170,21 @@ public class SqLiteDatabase extends Database {
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);
+ plugin.log(Level.SEVERE, "Failed to delete all homes for " + user.getName() + " from the database", e);
}
return 0;
}
@Override
public int deleteAllHomes(@NotNull String worldName, @NotNull String serverName) {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- DELETE FROM `%positions_table%`
- WHERE `%positions_table%`.`id` IN (
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ DELETE FROM `%position_data%`
+ WHERE `%position_data%`.`id` IN (
SELECT `position_id`
- FROM `%saved_positions_table%`
- WHERE `%saved_positions_table%`.`id` IN (
+ FROM `%saved_position_data%`
+ WHERE `%saved_position_data%`.`id` IN (
SELECT `saved_position_id`
- FROM `%homes_table%`
+ FROM `%home_data%`
WHERE `world_name`=?
AND `server_name`=?
)
@@ -1115,21 +1194,21 @@ public class SqLiteDatabase extends Database {
return statement.executeUpdate();
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete homes in the world " + worldName + " on the server "
- + serverName + " from the database", e);
+ + serverName + " from the database", e);
}
return 0;
}
@Override
public void deleteWarp(@NotNull UUID uuid) {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- DELETE FROM `%positions_table%`
- WHERE `%positions_table%`.`id`=(
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ DELETE FROM `%position_data%`
+ WHERE `%position_data%`.`id`=(
SELECT `position_id`
- FROM `%saved_positions_table%`
- WHERE `%saved_positions_table%`.`id`=(
+ FROM `%saved_position_data%`
+ WHERE `%saved_position_data%`.`id`=(
SELECT `saved_position_id`
- FROM `%warps_table%`
+ FROM `%warp_data%`
WHERE `uuid`=?
)
);"""))) {
@@ -1142,14 +1221,14 @@ public class SqLiteDatabase extends Database {
@Override
public int deleteAllWarps() {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- DELETE FROM `%positions_table%`
- WHERE `%positions_table%`.`id` IN (
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ DELETE FROM `%position_data%`
+ WHERE `%position_data%`.`id` IN (
SELECT `position_id`
- FROM `%saved_positions_table%`
- WHERE `%saved_positions_table%`.`id` IN (
+ FROM `%saved_position_data%`
+ WHERE `%saved_position_data%`.`id` IN (
SELECT `saved_position_id`
- FROM `%warps_table%`
+ FROM `%warp_data%`
)
);"""))) {
return statement.executeUpdate();
@@ -1161,14 +1240,14 @@ public class SqLiteDatabase extends Database {
@Override
public int deleteAllWarps(@NotNull String worldName, @NotNull String serverName) {
- try (PreparedStatement statement = getConnection().prepareStatement(formatStatementTables("""
- DELETE FROM `%positions_table%`
- WHERE `%positions_table%`.`id` IN (
+ try (PreparedStatement statement = getConnection().prepareStatement(format("""
+ DELETE FROM `%position_data%`
+ WHERE `%position_data%`.`id` IN (
SELECT `position_id`
- FROM `%saved_positions_table%`
- WHERE `%saved_positions_table%`.`id` IN (
+ FROM `%saved_position_data%`
+ WHERE `%saved_position_data%`.`id` IN (
SELECT `saved_position_id`
- FROM `%warps_table%`
+ FROM `%warp_data%`
WHERE `world_name`=?
AND `server_name`=?
)
@@ -1178,13 +1257,13 @@ public class SqLiteDatabase extends Database {
return statement.executeUpdate();
} catch (SQLException e) {
plugin.log(Level.SEVERE, "Failed to delete warps in the world " + worldName + " on the server "
- + serverName + " from the database", e);
+ + serverName + " from the database", e);
}
return 0;
}
@Override
- public void terminate() {
+ public void close() {
try {
if (connection != null) {
if (!connection.isClosed()) {
diff --git a/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java b/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java
index 7722e43c..48b3d77f 100644
--- a/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java
+++ b/common/src/main/java/net/william278/huskhomes/hook/BlueMapHook.java
@@ -43,20 +43,21 @@ import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
-/**
- * Hook to display warps and public homes on BlueMap maps.
- */
+@PluginHook(
+ name = "BlueMap",
+ register = PluginHook.Register.ON_ENABLE
+)
public class BlueMapHook extends MapHook {
private Map publicHomesMarkerSets;
private Map warpsMarkerSets;
public BlueMapHook(@NotNull HuskHomes plugin) {
- super(plugin, "BlueMap");
+ super(plugin);
}
@Override
- public void initialize() {
+ public void load() {
BlueMapAPI.onEnable(api -> {
this.publicHomesMarkerSets = new ConcurrentHashMap<>();
this.warpsMarkerSets = new ConcurrentHashMap<>();
@@ -81,7 +82,7 @@ public class BlueMapHook extends MapHook {
}
@Override
- public void updateHome(@NotNull Home home) {
+ public void addHome(@NotNull Home home) {
if (!isValidPosition(home)) {
return;
}
@@ -121,7 +122,7 @@ public class BlueMapHook extends MapHook {
}
@Override
- public void updateWarp(@NotNull Warp warp) {
+ public void addWarp(@NotNull Warp warp) {
if (!isValidPosition(warp)) {
return;
}
diff --git a/common/src/main/java/net/william278/huskhomes/hook/DynmapHook.java b/common/src/main/java/net/william278/huskhomes/hook/DynmapHook.java
index a1d030a1..b94b4d15 100644
--- a/common/src/main/java/net/william278/huskhomes/hook/DynmapHook.java
+++ b/common/src/main/java/net/william278/huskhomes/hook/DynmapHook.java
@@ -34,9 +34,10 @@ import org.jetbrains.annotations.Nullable;
import java.util.Optional;
-/**
- * Hook to display warps and public homes on Dynmap.
- */
+@PluginHook(
+ name = "Dynmap",
+ register = PluginHook.Register.ON_ENABLE
+)
public class DynmapHook extends MapHook {
private static final String ICON_PATH = "/tiles/_markers_/";
@@ -48,11 +49,11 @@ public class DynmapHook extends MapHook {
private MarkerSet warpsMarkers;
public DynmapHook(@NotNull HuskHomes plugin) {
- super(plugin, "Dynmap");
+ super(plugin);
}
@Override
- public void initialize() {
+ public void load() {
DynmapCommonAPIListener.register(new DynmapCommonAPIListener() {
@Override
public void apiEnabled(@NotNull DynmapCommonAPI dynmapCommonAPI) {
@@ -76,7 +77,7 @@ public class DynmapHook extends MapHook {
}
@Override
- public void updateHome(@NotNull Home home) {
+ public void addHome(@NotNull Home home) {
if (!isValidPosition(home)) {
return;
}
@@ -122,7 +123,7 @@ public class DynmapHook extends MapHook {
}
@Override
- public void updateWarp(@NotNull Warp warp) {
+ public void addWarp(@NotNull Warp warp) {
if (!isValidPosition(warp)) {
return;
}
diff --git a/common/src/main/java/net/william278/huskhomes/hook/EconomyHook.java b/common/src/main/java/net/william278/huskhomes/hook/EconomyHook.java
index 011de2db..936d0d8d 100644
--- a/common/src/main/java/net/william278/huskhomes/hook/EconomyHook.java
+++ b/common/src/main/java/net/william278/huskhomes/hook/EconomyHook.java
@@ -32,8 +32,8 @@ import java.util.Locale;
*/
public abstract class EconomyHook extends Hook {
- protected EconomyHook(@NotNull HuskHomes plugin, @NotNull String hookName) {
- super(plugin, hookName);
+ protected EconomyHook(@NotNull HuskHomes plugin) {
+ super(plugin);
}
/**
diff --git a/common/src/main/java/net/william278/huskhomes/hook/Hook.java b/common/src/main/java/net/william278/huskhomes/hook/Hook.java
index 5ae68b88..54c7546a 100644
--- a/common/src/main/java/net/william278/huskhomes/hook/Hook.java
+++ b/common/src/main/java/net/william278/huskhomes/hook/Hook.java
@@ -19,47 +19,35 @@
package net.william278.huskhomes.hook;
+import com.google.common.base.Preconditions;
+import lombok.Getter;
import net.william278.huskhomes.HuskHomes;
import org.jetbrains.annotations.NotNull;
-/**
- * A plugin hook, where HuskHomes hooks into another plugin.
- */
+@Getter
public abstract class Hook {
- /**
- * The plugin that this hook is for.
- */
protected final HuskHomes plugin;
+ protected final PluginHook hook;
- /**
- * The name of the hook.
- */
- protected final String name;
-
- /**
- * Construct a new {@link Hook}.
- *
- * @param plugin the {@link HuskHomes} instance
- */
- protected Hook(@NotNull HuskHomes plugin, @NotNull String name) {
+ protected Hook(@NotNull HuskHomes plugin) {
this.plugin = plugin;
- this.name = name;
+ this.hook = getClass().getAnnotation(PluginHook.class);
+ Preconditions.checkNotNull(hook, "Hook class must be annotated with PluginHook");
}
- /**
- * Initialize the hook and return {@code true} if it could be enabled.
- */
- public abstract void initialize();
-
- /**
- * Get the name of the hook.
- *
- * @return the name of the hook
- */
@NotNull
public String getName() {
- return name;
+ return hook.name();
}
-}
+ @NotNull
+ public PluginHook.Register getRegister() {
+ return hook.register();
+ }
+
+ public abstract void load();
+
+ public abstract void unload();
+
+}
\ No newline at end of file
diff --git a/common/src/main/java/net/william278/huskhomes/hook/HookProvider.java b/common/src/main/java/net/william278/huskhomes/hook/HookProvider.java
new file mode 100644
index 00000000..ba89fdf2
--- /dev/null
+++ b/common/src/main/java/net/william278/huskhomes/hook/HookProvider.java
@@ -0,0 +1,120 @@
+/*
+ * 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.hook;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import net.william278.huskhomes.HuskHomes;
+import net.william278.huskhomes.importer.Importer;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Unmodifiable;
+
+import java.util.*;
+import java.util.logging.Level;
+import java.util.stream.Collectors;
+
+public interface HookProvider extends MapHookProvider {
+
+ @NotNull
+ Set getHooks();
+
+ default Optional getHook(@NotNull Class hookClass) {
+ return getHooks().stream()
+ .filter(hook -> hookClass.isAssignableFrom(hook.getClass()))
+ .map(hookClass::cast)
+ .findFirst();
+ }
+
+ @NotNull
+ @Unmodifiable
+ default Set getImporters() {
+ return getHooks().stream()
+ .filter(hook -> hook instanceof Importer)
+ .map(hook -> (Importer) hook)
+ .collect(Collectors.toSet());
+ }
+
+ default Optional getImporterByName(@NotNull String name) {
+ return getImporters().stream()
+ .filter(i -> i.getName().toLowerCase(Locale.ENGLISH).equals(name.toLowerCase(Locale.ENGLISH)))
+ .findFirst();
+ }
+
+ void setHooks(@NotNull Set hooks);
+
+ default void loadHooks() {
+ setHooks(Sets.newHashSet(getAvailableHooks()));
+ }
+
+ default void registerHooks(@NotNull PluginHook.Register... register) {
+ final Set registers = Arrays.stream(register).collect(Collectors.toSet());
+ getHooks().removeIf(hook -> {
+ if (!registers.contains(hook.getRegister())) {
+ return false;
+ }
+ try {
+ hook.load();
+ return false;
+ } catch (Throwable e) {
+ getPlugin().log(Level.SEVERE, "Failed to register the %s hook".formatted(hook.getName()), e);
+ }
+ return true;
+ });
+ getPlugin().log(Level.INFO, "Registered '%s' hooks".formatted(registers.stream()
+ .map(h -> h.name().toLowerCase(Locale.ENGLISH)).collect(Collectors.joining(" & "))));
+ }
+
+ default void unloadHooks() {
+ getHooks().removeIf(hook -> {
+ try {
+ hook.unload();
+ } catch (Throwable e) {
+ getPlugin().log(Level.SEVERE, "Failed to unload the %s hook".formatted(hook.getName()), e);
+ }
+ return true;
+ });
+ }
+
+ @NotNull
+ default List getAvailableHooks() {
+ final List hooks = Lists.newArrayList();
+
+ if (getPlugin().getSettings().getMapHook().isEnabled()) {
+ if (isDependencyAvailable("Dynmap")) {
+ getHooks().add(new DynmapHook(getPlugin()));
+ } else if (isDependencyAvailable("BlueMap")) {
+ getHooks().add(new BlueMapHook(getPlugin()));
+ } else if (isDependencyAvailable("Pl3xMap")) {
+ getHooks().add(new Pl3xMapHook(getPlugin()));
+ }
+ }
+ if (isDependencyAvailable("Plan")) {
+ getHooks().add(new PlanHook(getPlugin()));
+ }
+
+ return hooks;
+ }
+
+ boolean isDependencyAvailable(@NotNull String name);
+
+ @NotNull
+ HuskHomes getPlugin();
+
+}
diff --git a/common/src/main/java/net/william278/huskhomes/hook/MapHook.java b/common/src/main/java/net/william278/huskhomes/hook/MapHook.java
index 139c76d4..fc803e62 100644
--- a/common/src/main/java/net/william278/huskhomes/hook/MapHook.java
+++ b/common/src/main/java/net/william278/huskhomes/hook/MapHook.java
@@ -40,8 +40,14 @@ public abstract class MapHook extends Hook {
protected static final String WARP_MARKER_IMAGE_NAME = "warp";
protected static final String PUBLIC_HOME_MARKER_IMAGE_NAME = "public-home";
- protected MapHook(@NotNull HuskHomes plugin, @NotNull String name) {
- super(plugin, name);
+ protected MapHook(@NotNull HuskHomes plugin) {
+ super(plugin);
+ }
+
+ @Override
+ public void unload() {
+ getPlugin().getWorlds().forEach(world -> clearHomes(world.getName()));
+ clearWarps();
}
/**
@@ -52,12 +58,12 @@ public abstract class MapHook extends Hook {
if (settings.isShowPublicHomes()) {
plugin.getDatabase()
.getLocalPublicHomes(plugin)
- .forEach(this::updateHome);
+ .forEach(this::addHome);
}
if (settings.isShowWarps()) {
plugin.getDatabase()
.getLocalWarps(plugin)
- .forEach(this::updateWarp);
+ .forEach(this::addWarp);
}
}
@@ -66,7 +72,7 @@ public abstract class MapHook extends Hook {
*
* @param home the home to update
*/
- public abstract void updateHome(@NotNull Home home);
+ public abstract void addHome(@NotNull Home home);
/**
* Removes a home from the map.
@@ -94,7 +100,7 @@ public abstract class MapHook extends Hook {
*
* @param warp the warp to update
*/
- public abstract void updateWarp(@NotNull Warp warp);
+ public abstract void addWarp(@NotNull Warp warp);
/**
* Removes a warp from the map.
@@ -191,7 +197,7 @@ public abstract class MapHook extends Hook {
protected static MarkerInformationPopup publicHome(@NotNull Home home, @NotNull String thumbnail) {
final MarkerInformationPopup popup = MarkerInformationPopup.create(home.getName())
.thumbnail(thumbnail)
- .field("Owner", home.getOwner().getUsername())
+ .field("Owner", home.getOwner().getName())
.field("Location", home.toString())
.field("Command", "/phome " + home.getSafeIdentifier());
if (!home.getMeta().getDescription().isBlank()) {
diff --git a/common/src/main/java/net/william278/huskhomes/hook/MapHookProvider.java b/common/src/main/java/net/william278/huskhomes/hook/MapHookProvider.java
new file mode 100644
index 00000000..b4fe9953
--- /dev/null
+++ b/common/src/main/java/net/william278/huskhomes/hook/MapHookProvider.java
@@ -0,0 +1,77 @@
+/*
+ * 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.hook;
+
+import net.william278.huskhomes.position.Home;
+import net.william278.huskhomes.position.Warp;
+import net.william278.huskhomes.user.User;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Unmodifiable;
+
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public interface MapHookProvider {
+
+ @NotNull
+ @Unmodifiable
+ default Set getMapHooks() {
+ return getHooks().stream()
+ .filter(hook -> hook instanceof MapHook)
+ .map(hook -> (MapHook) hook)
+ .collect(Collectors.toSet());
+ }
+
+ default void addMappedHome(@NotNull Home home) {
+ getMapHooks().forEach(h -> h.addHome(home));
+ }
+
+ default void removeMappedHome(@NotNull Home home) {
+ getMapHooks().forEach(h -> h.removeHome(home));
+ }
+
+ default void removeAllMappedHomes(@NotNull String worldName) {
+ getMapHooks().forEach(h -> h.clearHomes(worldName));
+ }
+
+ default void removeAllMappedHomes(@NotNull User user) {
+ getMapHooks().forEach(h -> h.clearHomes(user));
+ }
+
+ default void addMappedWarp(@NotNull Warp warp) {
+ getMapHooks().forEach(h -> h.addWarp(warp));
+ }
+
+ default void removeMappedWarp(@NotNull Warp warp) {
+ getMapHooks().forEach(h -> h.removeWarp(warp));
+ }
+
+ default void removeAllMappedWarps(@NotNull String worldName) {
+ getMapHooks().forEach(h -> h.clearWarps(worldName));
+ }
+
+ default void removeAllMappedWarps() {
+ getMapHooks().forEach(MapHook::clearWarps);
+ }
+
+ @NotNull
+ Set getHooks();
+
+}
diff --git a/common/src/main/java/net/william278/huskhomes/hook/Pl3xMapHook.java b/common/src/main/java/net/william278/huskhomes/hook/Pl3xMapHook.java
index 33af5fc8..79717374 100644
--- a/common/src/main/java/net/william278/huskhomes/hook/Pl3xMapHook.java
+++ b/common/src/main/java/net/william278/huskhomes/hook/Pl3xMapHook.java
@@ -62,11 +62,11 @@ public class Pl3xMapHook extends MapHook implements EventListener {
private final ConcurrentLinkedQueue warps = new ConcurrentLinkedQueue<>();
public Pl3xMapHook(@NotNull HuskHomes plugin) {
- super(plugin, "Pl3xMap");
+ super(plugin);
}
@Override
- public void initialize() {
+ public void load() {
Pl3xMap.api().getEventRegistry().register(this);
if (Pl3xMap.api().isEnabled()) {
onPl3xMapEnabled(new Pl3xMapEnabledEvent());
@@ -74,7 +74,7 @@ public class Pl3xMapHook extends MapHook implements EventListener {
}
@Override
- public void updateHome(@NotNull Home home) {
+ public void addHome(@NotNull Home home) {
publicHomes.remove(home);
if (isValidPosition(home)) {
publicHomes.add(home);
@@ -97,7 +97,7 @@ public class Pl3xMapHook extends MapHook implements EventListener {
}
@Override
- public void updateWarp(@NotNull Warp warp) {
+ public void addWarp(@NotNull Warp warp) {
warps.remove(warp);
if (isValidPosition(warp)) {
warps.add(warp);
@@ -159,8 +159,8 @@ public class Pl3xMapHook extends MapHook implements EventListener {
// Update home positions
plugin.runAsync(() -> {
- plugin.getDatabase().getLocalPublicHomes(plugin).forEach(this::updateHome);
- plugin.getDatabase().getLocalWarps(plugin).forEach(this::updateWarp);
+ plugin.getDatabase().getLocalPublicHomes(plugin).forEach(this::addHome);
+ plugin.getDatabase().getLocalWarps(plugin).forEach(this::addWarp);
});
}
diff --git a/common/src/main/java/net/william278/huskhomes/hook/PlanHook.java b/common/src/main/java/net/william278/huskhomes/hook/PlanHook.java
index 94d2dc80..029c475c 100644
--- a/common/src/main/java/net/william278/huskhomes/hook/PlanHook.java
+++ b/common/src/main/java/net/william278/huskhomes/hook/PlanHook.java
@@ -39,20 +39,17 @@ import org.jetbrains.annotations.NotNull;
import java.util.UUID;
import java.util.logging.Level;
-/**
- * Hooks into Plan to provide the {@link PlanDataExtension} with stats on the web panel.
- */
+@PluginHook(
+ name = "Plan",
+ register = PluginHook.Register.ON_ENABLE
+)
public class PlanHook extends Hook {
- private final HuskHomes plugin;
-
public PlanHook(@NotNull HuskHomes plugin) {
- super(plugin, "Plan");
- this.plugin = plugin;
+ super(plugin);
}
-
@Override
- public void initialize() {
+ public void load() {
if (!areAllCapabilitiesAvailable()) {
return;
}
@@ -60,6 +57,9 @@ public class PlanHook extends Hook {
handlePlanReload();
}
+ @Override
+ public void unload() {
+ }
private boolean areAllCapabilitiesAvailable() {
CapabilityService capabilities = CapabilityService.getInstance();
@@ -114,7 +114,7 @@ public class PlanHook extends Hook {
hidden = true
)
public boolean getHasUserData(@NotNull UUID uuid) {
- return database.getUserData(uuid).isPresent();
+ return database.getUser(uuid).isPresent();
}
@NumberProvider(
@@ -126,7 +126,7 @@ public class PlanHook extends Hook {
)
@Conditional("hasData")
public long getHomeCount(@NotNull UUID uuid) {
- return database.getUserData(uuid)
+ return database.getUser(uuid)
.map(userData -> (long) database.getHomes(userData.getUser()).size())
.orElse(0L);
}
@@ -140,7 +140,7 @@ public class PlanHook extends Hook {
)
@Conditional("hasData")
public long getPublicHomeCount(@NotNull UUID uuid) {
- return database.getUserData(uuid)
+ return database.getUser(uuid)
.map(userData -> database.getHomes(userData.getUser()).stream()
.filter(Home::isPublic).count())
.orElse(0L);
@@ -155,7 +155,7 @@ public class PlanHook extends Hook {
)
@Conditional("hasData")
public long getPurchasedHomeSlots(@NotNull UUID uuid) {
- return database.getUserData(uuid)
+ return database.getUser(uuid)
.map(userData -> (long) userData.getHomeSlots())
.orElse(0L);
}
@@ -169,7 +169,7 @@ public class PlanHook extends Hook {
)
@Conditional("hasData")
public boolean isIgnoringTeleportRequests(@NotNull UUID uuid) {
- return database.getUserData(uuid)
+ return database.getUser(uuid)
.map(SavedUser::isIgnoringTeleports)
.orElse(false);
}
@@ -183,7 +183,7 @@ public class PlanHook extends Hook {
)
@Conditional("hasData")
public String getOfflinePosition(@NotNull UUID uuid) {
- return database.getUserData(uuid)
+ return database.getUser(uuid)
.map(userData -> database.getOfflinePosition(userData.getUser())
.map(Position::toString)
.orElse(UNKNOWN_STRING))
diff --git a/common/src/main/java/net/william278/huskhomes/hook/PluginHook.java b/common/src/main/java/net/william278/huskhomes/hook/PluginHook.java
new file mode 100644
index 00000000..4e46853d
--- /dev/null
+++ b/common/src/main/java/net/william278/huskhomes/hook/PluginHook.java
@@ -0,0 +1,44 @@
+/*
+ * 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.hook;
+
+import org.jetbrains.annotations.NotNull;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target(value = ElementType.TYPE)
+@Retention(value = RetentionPolicy.RUNTIME)
+public @interface PluginHook {
+
+ @NotNull
+ String name();
+
+ @NotNull
+ Register register();
+
+ enum Register {
+ ON_LOAD,
+ ON_ENABLE
+ }
+
+}
diff --git a/common/src/main/java/net/william278/huskhomes/importer/Importer.java b/common/src/main/java/net/william278/huskhomes/importer/Importer.java
index 98d17059..67e24e07 100644
--- a/common/src/main/java/net/william278/huskhomes/importer/Importer.java
+++ b/common/src/main/java/net/william278/huskhomes/importer/Importer.java
@@ -35,24 +35,27 @@ import java.util.logging.Level;
public abstract class Importer extends Hook {
protected final HuskHomes plugin;
- private final String name;
private final List supportedImportData;
- protected Importer(@NotNull String name, @NotNull List supportedData, @NotNull HuskHomes plugin) {
- super(plugin, name + " Importer");
- this.name = name;
+ protected Importer(@NotNull List supportedData, @NotNull HuskHomes plugin) {
+ super(plugin);
this.supportedImportData = supportedData;
this.plugin = plugin;
}
@Override
- public void initialize() {
- // No initialization required
+ public void load() {
+ // Empty
+ }
+
+ @Override
+ public void unload() {
+ // Empty
}
public final void start(@NotNull CommandUser user) {
final LocalDateTime startTime = LocalDateTime.now();
- log(user, Level.INFO, "⌚ Starting " + name + " data import...");
+ log(user, Level.INFO, "⌚ Starting " + getName() + " data import...");
for (ImportData data : supportedImportData) {
try {
@@ -66,7 +69,7 @@ public abstract class Importer extends Hook {
}
final long timeTaken = startTime.until(LocalDateTime.now(), ChronoUnit.SECONDS);
- log(user, Level.INFO, "✔ Completed import from " + name + " (took " + timeTaken + "s)");
+ log(user, Level.INFO, "✔ Completed import from " + getName() + " (took " + timeTaken + "s)");
}
protected abstract int importData(@NotNull ImportData importData) throws Throwable;
@@ -83,11 +86,6 @@ public abstract class Importer extends Hook {
plugin.log(level, message, e);
}
- @NotNull
- public String getImporterName() {
- return name;
- }
-
@NotNull
public List getSupportedImportData() {
return supportedImportData;
diff --git a/common/src/main/java/net/william278/huskhomes/listener/EventListener.java b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java
index 43b826e4..dce513fe 100644
--- a/common/src/main/java/net/william278/huskhomes/listener/EventListener.java
+++ b/common/src/main/java/net/william278/huskhomes/listener/EventListener.java
@@ -20,6 +20,8 @@
package net.william278.huskhomes.listener;
import de.themoep.minedown.adventure.MineDown;
+import lombok.AccessLevel;
+import lombok.AllArgsConstructor;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.command.BackCommand;
import net.william278.huskhomes.command.Command;
@@ -32,23 +34,22 @@ import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportBuilder;
import net.william278.huskhomes.teleport.TeleportationException;
import net.william278.huskhomes.user.OnlineUser;
+import net.william278.huskhomes.user.User;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Optional;
-import java.util.logging.Level;
/**
* A handler for when events take place.
*/
-public class EventListener {
+@AllArgsConstructor(access = AccessLevel.PROTECTED)
+public abstract class EventListener {
@NotNull
- protected final HuskHomes plugin;
+ private final HuskHomes plugin;
- protected EventListener(@NotNull HuskHomes plugin) {
- this.plugin = plugin;
- }
+ public abstract void register();
/**
* Handle when a {@link OnlineUser} joins the server.
@@ -67,7 +68,7 @@ public class EventListener {
// Synchronize the global player list
plugin.runSyncDelayed(() -> this.synchronizeGlobalPlayerList(
- onlineUser, plugin.getLocalPlayerList()),
+ onlineUser, plugin.getOnlineUsers().stream().map(User::getName).toList()),
onlineUser, 40L
);
@@ -82,7 +83,7 @@ public class EventListener {
plugin.getManager().homes().cacheUserHomes(onlineUser);
// Set their ignoring requests state
- plugin.getDatabase().getUserData(onlineUser.getUuid()).ifPresent(userData -> {
+ plugin.getDatabase().getUser(onlineUser.getUuid()).ifPresent(userData -> {
plugin.getSavedUsers().add(userData);
// Send a reminder message if they are still ignoring requests
@@ -111,10 +112,8 @@ public class EventListener {
// Update global lists
if (plugin.getSettings().getCrossServer().isEnabled()) {
- final List localPlayerList = plugin.getLocalPlayerList().stream()
- .filter(player -> !player.equals(onlineUser.getUsername()))
- .toList();
-
+ final List localPlayerList = plugin.getOnlineUsers().stream().map(User::getName)
+ .filter(player -> !player.equals(onlineUser.getName())).toList();
if (plugin.getSettings().getCrossServer().getBrokerType() == Broker.Type.REDIS) {
this.synchronizeGlobalPlayerList(onlineUser, localPlayerList);
return;
@@ -125,6 +124,9 @@ public class EventListener {
.findAny()
.ifPresent(player -> this.synchronizeGlobalPlayerList(player, localPlayerList));
}
+
+ // Remove from user map
+ plugin.getOnlineUserMap().remove(onlineUser.getUuid());
});
}
@@ -164,7 +166,7 @@ public class EventListener {
if (bedPosition.isEmpty()) {
plugin.getSpawn().ifPresent(spawn -> {
if (plugin.getSettings().getCrossServer().isEnabled()
- && !spawn.getServer().equals(plugin.getServerName())) {
+ && !spawn.getServer().equals(plugin.getServerName())) {
plugin.runSyncDelayed(() -> Teleport.builder(plugin)
.teleporter(teleporter)
.target(spawn)
@@ -190,25 +192,27 @@ public class EventListener {
plugin.getDatabase().setRespawnPosition(teleporter, bedPosition.orElse(null));
}
- // Synchronize the global player list
+ // Synchronize the global player list TODO CHECK
private void synchronizeGlobalPlayerList(@NotNull OnlineUser user, @NotNull List localPlayerList) {
- // Send this server's player list to all servers
- Message.builder()
- .type(Message.Type.PLAYER_LIST)
- .scope(Message.Scope.SERVER)
- .target(Message.TARGET_ALL)
- .payload(Payload.withStringList(localPlayerList))
- .build().send(plugin.getMessenger(), user);
-
- // Clear cached global player lists and request updated lists from all servers
- if (plugin.getOnlineUsers().size() == 1) {
- plugin.getGlobalPlayerList().clear();
+ plugin.getBroker().ifPresent(broker -> {
+ // Send this server's player list to all servers
Message.builder()
- .type(Message.Type.REQUEST_PLAYER_LIST)
+ .type(Message.Type.PLAYER_LIST)
.scope(Message.Scope.SERVER)
.target(Message.TARGET_ALL)
- .build().send(plugin.getMessenger(), user);
- }
+ .payload(Payload.withStringList(localPlayerList))
+ .build().send(broker, user);
+
+ // Clear cached global player lists and request updated lists from all servers
+ if (plugin.getOnlineUsers().size() == 1) {
+ plugin.getGlobalUserList().clear();
+ Message.builder()
+ .type(Message.Type.REQUEST_PLAYER_LIST)
+ .scope(Message.Scope.SERVER)
+ .target(Message.TARGET_ALL)
+ .build().send(broker, user);
+ }
+ });
}
/**
@@ -233,7 +237,7 @@ public class EventListener {
// Display the return by death via /back notification
final boolean canReturnByDeath = plugin.getCommand(BackCommand.class)
.map(command -> onlineUser.hasPermission(command.getPermission())
- && onlineUser.hasPermission(command.getPermission("death")))
+ && onlineUser.hasPermission(command.getPermission("death")))
.orElse(false);
if (plugin.getSettings().getGeneral().getBackCommand().isReturnByDeath() && canReturnByDeath) {
plugin.getLocales().getLocale("return_by_death_notification")
@@ -288,7 +292,7 @@ public class EventListener {
return;
}
- plugin.runAsync(() -> plugin.getDatabase().getUserData(onlineUser.getUuid())
+ plugin.runAsync(() -> plugin.getDatabase().getUser(onlineUser.getUuid())
.ifPresent(data -> plugin.getDatabase().setLastPosition(data.getUser(), sourcePosition)));
}
@@ -300,17 +304,15 @@ public class EventListener {
*/
protected final void handlePlayerUpdateSpawnPoint(@NotNull OnlineUser onlineUser, @NotNull Position position) {
if (!plugin.getSettings().getGeneral().isAlwaysRespawnAtSpawn()
- && plugin.getSettings().getCrossServer().isEnabled()
- && plugin.getSettings().getCrossServer().isGlobalRespawning()) {
+ && plugin.getSettings().getCrossServer().isEnabled()
+ && plugin.getSettings().getCrossServer().isGlobalRespawning()) {
plugin.getDatabase().setRespawnPosition(onlineUser, position);
}
}
- /**
- * Handle when the plugin is disabling (server is shutting down).
- */
- public final void handlePluginDisable() {
- plugin.log(Level.INFO, "Successfully disabled HuskHomes v" + plugin.getVersion());
+ @NotNull
+ protected HuskHomes getPlugin() {
+ return plugin;
}
}
diff --git a/common/src/main/java/net/william278/huskhomes/listener/ListenerProvider.java b/common/src/main/java/net/william278/huskhomes/listener/ListenerProvider.java
new file mode 100644
index 00000000..52db913d
--- /dev/null
+++ b/common/src/main/java/net/william278/huskhomes/listener/ListenerProvider.java
@@ -0,0 +1,34 @@
+/*
+ * 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.listener;
+
+import org.jetbrains.annotations.NotNull;
+
+public interface ListenerProvider {
+
+ @NotNull
+ EventListener createListener();
+
+ default void loadListeners() {
+ createListener().register();
+ }
+
+
+}
diff --git a/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java b/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java
index f1d09d17..2392d3e5 100644
--- a/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java
+++ b/common/src/main/java/net/william278/huskhomes/manager/HomesManager.java
@@ -83,7 +83,7 @@ public class HomesManager {
public Map> getPublicHomes() {
return publicHomes.stream().collect(
HashMap::new,
- (m, e) -> m.put(e.getOwner().getUsername(), List.of(e.getName())),
+ (m, e) -> m.put(e.getOwner().getName(), List.of(e.getName())),
HashMap::putAll
);
}
@@ -123,7 +123,7 @@ public class HomesManager {
* @param user the user to cache homes for
*/
public void cacheUserHomes(@NotNull User user) {
- userHomes.put(user.getUsername(), new ConcurrentLinkedQueue<>(plugin.getDatabase().getHomes(user)));
+ userHomes.put(user.getName(), new ConcurrentLinkedQueue<>(plugin.getDatabase().getHomes(user)));
}
/**
@@ -133,17 +133,17 @@ public class HomesManager {
* @param propagate whether to propagate the cache update to other servers (if cross-server is enabled)
*/
public void cacheHome(@NotNull Home home, boolean propagate) {
- userHomes.computeIfPresent(home.getOwner().getUsername(), (k, v) -> {
+ userHomes.computeIfPresent(home.getOwner().getName(), (k, v) -> {
v.remove(home);
v.add(home);
return v;
});
if (publicHomes.remove(home) && !home.isPublic()) {
- plugin.getMapHook().ifPresent(hook -> hook.removeHome(home));
+ plugin.removeMappedHome(home);
}
if (home.isPublic()) {
publicHomes.add(home);
- plugin.getMapHook().ifPresent(hook -> hook.updateHome(home));
+ plugin.addMappedHome(home);
}
plugin.getCommands().stream()
@@ -159,7 +159,7 @@ public class HomesManager {
userHomes.values().forEach(homes -> homes.removeIf(home -> home.getUuid().equals(homeId)));
publicHomes.removeIf(home -> {
if (home.getUuid().equals(homeId)) {
- plugin.getMapHook().ifPresent(hook -> hook.removeHome(home));
+ plugin.removeMappedHome(home);
return true;
}
return false;
@@ -182,14 +182,13 @@ public class HomesManager {
* @param homeId the UUID of the home/warp to update
*/
private void propagateCacheUpdate(@NotNull UUID homeId) {
- if (plugin.getSettings().getCrossServer().isEnabled()) {
- plugin.getOnlineUsers().stream().findAny().ifPresent(user -> Message.builder()
- .type(Message.Type.UPDATE_HOME)
- .scope(Message.Scope.SERVER)
- .target(Message.TARGET_ALL)
- .payload(Payload.withString(homeId.toString()))
- .build().send(plugin.getMessenger(), user));
- }
+ plugin.getBroker().ifPresent(b -> plugin.getOnlineUsers().stream().findAny()
+ .ifPresent(user -> Message.builder()
+ .type(Message.Type.UPDATE_HOME)
+ .scope(Message.Scope.SERVER)
+ .target(Message.TARGET_ALL)
+ .payload(Payload.withString(homeId.toString()))
+ .build().send(b, user)));
}
public void updatePublicHomeCache() {
@@ -210,7 +209,7 @@ public class HomesManager {
}
// Validate the home name; throw an exception if invalid
- plugin.getValidator().validateName(name);
+ plugin.validateName(name);
// Determine what the new home count would be & validate against user max homes
int homes = plugin.getDatabase().getHomes(owner).size() + (existingHome.isPresent() ? 0 : 1);
@@ -220,10 +219,10 @@ public class HomesManager {
// Validate against user home slots
final SavedUser savedOwner = plugin.getSavedUser(owner)
- .or(() -> plugin.getDatabase().getUserData(owner.getUuid()))
+ .or(() -> plugin.getDatabase().getUser(owner.getUuid()))
.orElseThrow(() -> new IllegalStateException("User data not found for " + owner.getUuid()));
if (plugin.getSettings().getEconomy().isEnabled()
- && homes > getFreeHomes(owner) && homes > savedOwner.getHomeSlots()) {
+ && homes > getFreeHomes(owner) && homes > savedOwner.getHomeSlots()) {
if (!buyAdditionalSlots || plugin.getEconomyHook().isEmpty() || !(owner instanceof OnlineUser online)) {
throw new ValidationException(ValidationException.Type.NOT_ENOUGH_HOME_SLOTS);
}
@@ -233,7 +232,7 @@ public class HomesManager {
throw new ValidationException(ValidationException.Type.TRANSACTION_FAILED);
}
plugin.performTransaction(online, TransactionResolver.Action.ADDITIONAL_HOME_SLOT);
- plugin.editUserData(online, (SavedUser saved) -> saved.setHomeSlots(saved.getHomeSlots() + 1));
+ plugin.editSavedUser(online, (SavedUser saved) -> saved.setHomeSlots(saved.getHomeSlots() + 1));
}
final Home home = existingHome
@@ -272,12 +271,12 @@ public class HomesManager {
public int deleteAllHomes(@NotNull User owner) {
final int deleted = plugin.getDatabase().deleteAllHomes(owner);
- userHomes.computeIfPresent(owner.getUsername(), (k, v) -> {
+ userHomes.computeIfPresent(owner.getName(), (k, v) -> {
v.clear();
return v;
});
publicHomes.removeIf(h -> h.getOwner().getUuid().equals(owner.getUuid()));
- plugin.getMapHook().ifPresent(hook -> hook.clearHomes(owner));
+ plugin.removeAllMappedHomes(owner);
plugin.getCommands().stream()
.filter(command -> command instanceof ListCommand)
.map(command -> (ListCommand) command)
@@ -293,7 +292,7 @@ public class HomesManager {
));
publicHomes.removeIf(h -> h.getWorld().getName().equals(worldName) && h.getServer().equals(serverName));
if (plugin.getSettings().getCrossServer().isEnabled() && serverName.equals(plugin.getServerName())) {
- plugin.getMapHook().ifPresent(hook -> hook.clearHomes(worldName));
+ plugin.removeAllMappedHomes(worldName);
}
plugin.getCommands().stream()
.filter(command -> command instanceof ListCommand)
@@ -333,7 +332,7 @@ public class HomesManager {
if (plugin.getDatabase().getHome(home.getOwner(), newName).isPresent()) {
throw new ValidationException(ValidationException.Type.NAME_TAKEN);
}
- plugin.getValidator().validateName(newName);
+ plugin.validateName(newName);
home.getMeta().setName(newName);
plugin.getDatabase().saveHome(home);
this.cacheHome(home, true);
@@ -350,7 +349,7 @@ public class HomesManager {
}
public void setHomeDescription(@NotNull Home home, @NotNull String description) {
- plugin.getValidator().validateDescription(description);
+ plugin.validateDescription(description);
home.getMeta().setDescription(description);
plugin.getDatabase().saveHome(home);
this.cacheHome(home, true);
diff --git a/common/src/main/java/net/william278/huskhomes/manager/Manager.java b/common/src/main/java/net/william278/huskhomes/manager/Manager.java
index 8696e7e9..31d9c3d1 100644
--- a/common/src/main/java/net/william278/huskhomes/manager/Manager.java
+++ b/common/src/main/java/net/william278/huskhomes/manager/Manager.java
@@ -54,12 +54,11 @@ public class Manager {
// Update caches on all servers
protected void propagateCacheUpdate() {
- if (plugin.getSettings().getCrossServer().isEnabled()) {
- plugin.getOnlineUsers().stream().findAny().ifPresent(user -> Message.builder()
- .type(Message.Type.UPDATE_CACHES)
- .scope(Message.Scope.SERVER)
- .target(Message.TARGET_ALL)
- .build().send(plugin.getMessenger(), user));
- }
+ plugin.getBroker().ifPresent(b -> plugin.getOnlineUsers().stream()
+ .findAny().ifPresent(user -> Message.builder()
+ .type(Message.Type.UPDATE_CACHES)
+ .scope(Message.Scope.SERVER)
+ .target(Message.TARGET_ALL)
+ .build().send(b, user)));
}
}
diff --git a/common/src/main/java/net/william278/huskhomes/manager/ManagerProvider.java b/common/src/main/java/net/william278/huskhomes/manager/ManagerProvider.java
new file mode 100644
index 00000000..bc322386
--- /dev/null
+++ b/common/src/main/java/net/william278/huskhomes/manager/ManagerProvider.java
@@ -0,0 +1,39 @@
+/*
+ * This file is part of HuskHomes, licensed under the Apache License 2.0.
+ *
+ * Copyright (c) William278