Refactor database field names loading

This commit is contained in:
GeorgH93 2021-05-20 22:07:10 +02:00
parent 4c2cc72023
commit 7536994e50
No known key found for this signature in database
GPG Key ID: D1630D37F9E4B3C8
4 changed files with 54 additions and 41 deletions

View File

@ -91,7 +91,7 @@ Database:
Tables:
# Table names
# Don't change the players table if you have backpacks stored in your database already! Player id's might won't match anymore resulting data inconsistency.
User: backpack_players
Player: backpack_players
Backpack: backpacks
Cooldown: backpack_cooldowns
# Field settings for the tables
@ -99,16 +99,16 @@ Database:
# If you like to change them after the tables have been generated alter the tables manually or delete them (the system then will regenerate them).
Fields:
User:
Player_ID: player_id
PlayerID: player_id
Name: name
UUID: uuid
Backpack:
Owner_ID: owner
OwnerID: owner
ItemStacks: itemstacks
Version: version
LastUpdate: lastupdate
Cooldown:
Player_ID: id
PlayerID: id
Time: time
# Settings controlling the cache behavior of the plugin. You may optimize it a little depending on your player count, ram or cpu bottlenecks.
Cache:
@ -217,4 +217,4 @@ Misc:
UseBungeeCord: false
# Config file version. Don't touch it!
Version: 35
Version: 36

View File

@ -18,7 +18,9 @@
package at.pcgamingfreaks.Minepacks.Bukkit.Database.Backend;
import at.pcgamingfreaks.DataHandler.HasPlaceholders;
import at.pcgamingfreaks.DataHandler.ILoadableStringFieldsHolder;
import at.pcgamingfreaks.DataHandler.IStringFieldsWithPlaceholdersHolder;
import at.pcgamingfreaks.DataHandler.Loadable;
import at.pcgamingfreaks.Database.ConnectionProvider.ConnectionProvider;
import at.pcgamingfreaks.Database.DBTools;
import at.pcgamingfreaks.Minepacks.Bukkit.Backpack;
@ -32,20 +34,21 @@
import org.bukkit.inventory.ItemStack;
import org.intellij.lang.annotations.Language;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import lombok.AllArgsConstructor;
import java.sql.*;
import java.util.*;
public abstract class SQL extends DatabaseBackend implements IStringFieldsWithPlaceholdersHolder
public abstract class SQL extends DatabaseBackend implements IStringFieldsWithPlaceholdersHolder, ILoadableStringFieldsHolder
{
private final ConnectionProvider dataSource;
protected String tablePlayers = "backpack_players", tableBackpacks = "backpacks", tableCooldowns = "backpack_cooldowns"; // Table Names
protected String fieldPlayerName = "name", fieldPlayerID = "id", fieldPlayerUUID = "uuid"; // Table players
protected String fieldBpOwner = "owner", fieldBpIts = "its", fieldBpVersion = "version", fieldBpLastUpdate = "lastupdate"; // Table Backpack
protected String fieldCdPlayer = "id", fieldCdTime = "time"; // Table Fields
@Loadable protected String tablePlayers = "minepacks_players", tableBackpacks = "minepacks_backpacks", tableCooldowns = "minepacks_cooldowns"; // Table names
@Loadable(metadata = "User") protected String fieldPlayerName = "name", fieldPlayerID = "id", fieldPlayerUUID = "uuid"; // Table fields players
@Loadable(metadata = "Backpack") protected String fieldBpOwnerID = "owner", fieldBpIts = "its", fieldBpVersion = "version", fieldBpLastUpdate = "lastupdate"; // Table fields backpack
@Loadable(metadata = "Cooldown") protected String fieldCdPlayerID = "id", fieldCdTime = "time"; // Table fields cooldown
@HasPlaceholders @Language("SQL") protected String queryUpdatePlayerAdd, queryInsertBp, queryUpdateBp, queryGetPlayer, queryGetBP, querySyncCooldown; // DB queries
@HasPlaceholders @Language("SQL") protected String queryDeleteOldCooldowns, queryDeleteOldBackpacks, queryGetUnsetOrInvalidUUIDs, queryFixUUIDs; // Maintenance queries
@ -73,20 +76,30 @@ public SQL(@NotNull Minepacks plugin, @NotNull ConnectionProvider connectionProv
protected void loadSettings()
{
// Load table and field names
tablePlayers = plugin.getConfiguration().getDBTable("User", tablePlayers);
tableBackpacks = plugin.getConfiguration().getDBTable("Backpack", tableBackpacks);
tableCooldowns = plugin.getConfiguration().getDBTable("Cooldown", tableCooldowns);
fieldPlayerID = plugin.getConfiguration().getDBFields("User.Player_ID", fieldPlayerID);
fieldPlayerName = plugin.getConfiguration().getDBFields("User.Name", fieldPlayerName);
fieldPlayerUUID = plugin.getConfiguration().getDBFields("User.UUID", fieldPlayerUUID);
fieldBpOwner = plugin.getConfiguration().getDBFields("Backpack.Owner_ID", fieldBpOwner);
fieldBpIts = plugin.getConfiguration().getDBFields("Backpack.ItemStacks", fieldBpIts);
fieldBpVersion = plugin.getConfiguration().getDBFields("Backpack.Version", fieldBpVersion);
fieldBpLastUpdate = plugin.getConfiguration().getDBFields("Backpack.LastUpdate", fieldBpLastUpdate);
fieldCdPlayer = plugin.getConfiguration().getDBFields("Cooldown.Player_ID", fieldCdPlayer);
fieldCdTime = plugin.getConfiguration().getDBFields("Cooldown.Time", fieldCdTime);
syncCooldown = plugin.getConfiguration().isCommandCooldownSyncEnabled();
loadFields(); // Load table and field names
syncCooldown = plugin.getConfiguration().isCommandCooldownSyncEnabled();
}
@Override
public String loadField(@NotNull String fieldName, @NotNull String metadata, @Nullable String currentValue)
{
if(fieldName.startsWith("table"))
{
return plugin.getConfiguration().getDBTable(fieldName.substring("table".length(), fieldName.length() - 1), currentValue);
}
else if(fieldName.startsWith("field"))
{
fieldName = fieldName.substring("field".length());
if(fieldName.startsWith("Player") && !fieldName.equals("PlayerID"))
{
fieldName = fieldName.substring("Player".length());
}
else if(fieldName.startsWith("BP") || fieldName.startsWith("Cd"))
fieldName = fieldName.substring(2);
return plugin.getConfiguration().getDBFields(metadata + "." + fieldName, currentValue);
}
return null;
}
@Override
@ -191,6 +204,7 @@ protected final void buildQueries()
updateQueriesForDialect();
queryDeleteOldBackpacks = queryDeleteOldBackpacks.replaceAll("\\{VarMaxAge}", maxAge + "");
replacePlaceholders();
}
@ -201,9 +215,9 @@ protected final void buildQueries()
{
query = query.replaceAll("(\\{\\w+})", "`$1`").replaceAll("`(\\{\\w+})`_(\\w+)", "`$1_$2`").replaceAll("fk_`(\\{\\w+})`_`(\\{\\w+})`_`(\\{\\w+})`", "`fk_$1_$2_$3`") // Fix name formatting
.replaceAll("\\{TablePlayers}", tablePlayers).replaceAll("\\{FieldName}", fieldPlayerName).replaceAll("\\{FieldUUID}", fieldPlayerUUID).replaceAll("\\{FieldPlayerID}", fieldPlayerID) // Players
.replaceAll("\\{TableBackpacks}", tableBackpacks).replaceAll("\\{FieldBPOwner}", fieldBpOwner).replaceAll("\\{FieldBPITS}", fieldBpIts) // Backpacks
.replaceAll("\\{TableBackpacks}", tableBackpacks).replaceAll("\\{FieldBPOwner}", fieldBpOwnerID).replaceAll("\\{FieldBPITS}", fieldBpIts) // Backpacks
.replaceAll("\\{FieldBPVersion}", fieldBpVersion).replaceAll("\\{FieldBPLastUpdate}", fieldBpLastUpdate) // Backpacks
.replaceAll("\\{TableCooldowns}", tableCooldowns).replaceAll("\\{FieldCDPlayer}", fieldCdPlayer).replaceAll("\\{FieldCDTime}", fieldCdTime); // Cooldowns
.replaceAll("\\{TableCooldowns}", tableCooldowns).replaceAll("\\{FieldCDPlayer}", fieldCdPlayerID).replaceAll("\\{FieldCDTime}", fieldCdTime); // Cooldowns
if(query.matches(".*\\{\\w+}.*")) plugin.getLogger().warning("Found unresolved placeholder in query:\n" + query);
return query;
}
@ -250,7 +264,7 @@ public void loadPlayer(final @NotNull MinepacksPlayerData player)
{
final int id = rs.getInt(fieldPlayerID);
long cooldown = 0;
if(syncCooldown) cooldown = rs.getTimestamp(fieldCdPlayer).getTime();
if(syncCooldown) cooldown = rs.getTimestamp(fieldCdPlayerID).getTime();
final long cd = cooldown;
plugin.getServer().getScheduler().runTask(plugin, () -> player.setLoaded(id, cd));
return;

View File

@ -39,7 +39,6 @@ public static String getDbFile(final @NotNull Minepacks plugin)
return plugin.getDataFolder().getAbsolutePath() + File.separator + "backpack.db";
}
//TODO add cooldown sync table
public SQLite(final @NotNull Minepacks plugin, final @Nullable ConnectionProvider connectionProvider) throws SQLException
{
super(plugin, (connectionProvider == null) ? new SQLiteConnectionProvider(plugin.getLogger(), plugin.getDescription().getName(), getDbFile(plugin)) : connectionProvider);
@ -48,17 +47,10 @@ public SQLite(final @NotNull Minepacks plugin, final @Nullable ConnectionProvide
@Override
protected void loadSettings()
{
// Set table and field names to fixed values to prevent users from destroying old databases.
fieldPlayerID = "player_id";
fieldBpOwner = "owner";
//noinspection SpellCheckingInspection
fieldBpIts = "itemstacks";
// Set fixed settings
useUUIDSeparators = false;
tablePlayers = "minepacks_players";
tableBackpacks = "minepacks_backpacks";
tableCooldowns = "minepacks_cooldowns";
syncCooldown = plugin.getConfiguration().isCommandCooldownSyncEnabled();
}
@Override
@ -94,8 +86,8 @@ protected void checkDB()
if(dbVersion.olderThan(new Version("3.0-ALPHA-SNAPSHOT")))
{ // Copy old data to new tables
plugin.getLogger().info(ConsoleColor.YELLOW + "Migrating data to new table structure. Please do not stop the server till it is done!" + ConsoleColor.RESET);
doPHQuery(stmt, "INSERT OR IGNORE INTO {TablePlayers} SELECT * FROM `backpack_players`;");
doPHQuery(stmt, "INSERT OR IGNORE INTO {TableBackpacks} ({FieldBPOwner}, {FieldBPITS}, {FieldBPVersion}, {FieldBPLastUpdate}) SELECT owner, itemstacks, version, lastupdate FROM backpacks WHERE owner IN (SELECT player_id FROM minepacks_players);");
doPHQuery(stmt, "INSERT OR IGNORE INTO {TablePlayers} ({FieldPlayerID}, {FieldName}, {FieldUUID}) SELECT player_id, name, uuid FROM `backpack_players`;");
doPHQuery(stmt, "INSERT OR IGNORE INTO {TableBackpacks} ({FieldBPOwner}, {FieldBPITS}, {FieldBPVersion}, {FieldBPLastUpdate}) SELECT owner, itemstacks, version, lastupdate FROM backpacks WHERE owner IN (SELECT {FieldPlayerID} FROM {TablePlayers});");
plugin.getLogger().info(ConsoleColor.GREEN + "Data migrated successful!" + ConsoleColor.RESET);
}

View File

@ -41,7 +41,7 @@
public class Config extends Configuration implements DatabaseConnectionConfiguration, IUnCacheStrategyConfig
{
private static final int CONFIG_VERSION = 35, UPGRADE_THRESHOLD = CONFIG_VERSION, PRE_V2_VERSION = 20;
private static final int CONFIG_VERSION = 36, UPGRADE_THRESHOLD = CONFIG_VERSION, PRE_V2_VERSION = 20;
public Config(JavaPlugin plugin)
{
@ -74,8 +74,15 @@ protected void doUpgrade(@NotNull YamlFileManager oldConfig)
remappedKeys.put("WorldSettings.BockMode", "WorldSettings.BlacklistMode");
}
if(oldConfig.version().olderOrEqualThan(new Version(34))) remappedKeys.put("Database.Cache.UnCache.Strategy", "Database.Cache.UnCache.Strategie");
if(oldConfig.version().olderOrEqualThan(new Version(35)))
{
remappedKeys.put("Database.Tables.User", "Database.Tables.Player");
remappedKeys.put("Database.Tables.Fields.User.PlayerID", "Database.Tables.Fields.User.Player_ID");
remappedKeys.put("Database.Tables.Fields.Backpack.OwnerID", "Database.Tables.Fields.Backpack.Owner_ID");
remappedKeys.put("Database.Tables.Fields.Cooldown.PlayerID", "Database.Tables.Fields.Cooldown.Player_ID");
}
Collection<String> keysToKeep = oldConfig.getYamlE().getKeysFiltered("Database\\.SQL\\.(MaxLifetime|IdleTimeout)");
keysToKeep.addAll(oldConfig.getYamlE().getKeysFiltered("Database\\.Tables\\.Fields\\..+"));
//keysToKeep.addAll(oldConfig.getYamlE().getKeysFiltered("Database\\.Tables\\.Fields\\..+"));
doUpgrade(oldConfig, remappedKeys, keysToKeep);
}
}
@ -110,7 +117,7 @@ public void setDatabaseType(String type)
}
}
public @NotNull String getDBTable(final @NotNull String table, final @NotNull String defaultValue)
public @NotNull String getDBTable(final @NotNull String table, final String defaultValue)
{
return getConfigE().getString("Database.Tables." + table, defaultValue);
}