Refactor player insert queries

This commit is contained in:
GeorgH93 2021-05-22 23:47:48 +02:00
parent 77bb0d1326
commit 41a74ee758
No known key found for this signature in database
GPG Key ID: D1630D37F9E4B3C8
3 changed files with 24 additions and 24 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2020 GeorgH93
* Copyright (C) 2021 GeorgH93
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -40,6 +40,9 @@ protected void updateQueriesForDialect()
{
queryDeleteOldBackpacks = "DELETE FROM {TableBackpacks} WHERE {FieldBPLastUpdate} + INTERVAL {VarMaxAge} day < NOW()";
queryUpdateBp = queryUpdateBp.replaceAll("\\{NOW}", "NOW()");
// Prevent auto id incrementing if no insert was performed
queryInsertPlayer = "INSERT IGNORE INTO {TablePlayers} ({FieldName},{FieldUUID}) SELECT ?,? FROM (SELECT 1) AS `tmp` WHERE NOT EXISTS (SELECT {FieldUUID} FROM {TablePlayers} WHERE {FieldUUID}=?);";
}
@Override
@ -49,16 +52,16 @@ protected void checkDB()
{
DBTools.updateDB(connection, replacePlaceholders("CREATE TABLE IF NOT EXISTS {TablePlayers} (\n{FieldPlayerID} INT UNSIGNED NOT NULL AUTO_INCREMENT,\n{FieldName} VARCHAR(16) NOT NULL,\n" +
"{FieldUUID} CHAR(" + ((useUUIDSeparators) ? "36" : "32") + ") DEFAULT NULL," + "\nPRIMARY KEY ({FieldPlayerID}),\n" +
"UNIQUE INDEX {FieldUUID}_UNIQUE ({FieldUUID})\n);"));
"UNIQUE INDEX {FieldUUID}_UNIQUE ({FieldUUID})\n) ENGINE=InnoDB;"));
DBTools.updateDB(connection, replacePlaceholders("CREATE TABLE IF NOT EXISTS {TableBackpacks} (\n{FieldBPOwner} INT UNSIGNED NOT NULL,\n{FieldBPITS} BLOB,\n{FieldBPVersion} INT DEFAULT 0,\n" +
"{FieldBPLastUpdate} TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n" +
"PRIMARY KEY ({FieldBPOwner}),\nCONSTRAINT fk_{TableBackpacks}_{TablePlayers}_{FieldBPOwner} FOREIGN KEY ({FieldBPOwner}) " +
"REFERENCES {TablePlayers} ({FieldPlayerID}) ON DELETE CASCADE ON UPDATE CASCADE\n);"));
"REFERENCES {TablePlayers} ({FieldPlayerID}) ON DELETE CASCADE ON UPDATE CASCADE\n) ENGINE=InnoDB;"));
if(syncCooldown)
{
DBTools.updateDB(connection, replacePlaceholders("CREATE TABLE IF NOT EXISTS {TableCooldowns} (\n{FieldCDPlayer} INT UNSIGNED NOT NULL,\n{FieldCDTime} DATETIME NOT NULL,\nPRIMARY KEY ({FieldCDPlayer}),\n" +
"CONSTRAINT fk_{TableCooldowns}_{TablePlayers}_{FieldCDPlayer} FOREIGN KEY ({FieldCDPlayer}) " +
"REFERENCES {TablePlayers} ({FieldPlayerID}) ON DELETE CASCADE ON UPDATE CASCADE\n);"));
"REFERENCES {TablePlayers} ({FieldPlayerID}) ON DELETE CASCADE ON UPDATE CASCADE\n) ENGINE=InnoDB;"));
}
}
catch (SQLException e)

View File

@ -26,6 +26,7 @@
import at.pcgamingfreaks.Minepacks.Bukkit.Backpack;
import at.pcgamingfreaks.Minepacks.Bukkit.Database.BackupHandler;
import at.pcgamingfreaks.Minepacks.Bukkit.Database.MinepacksPlayerData;
import at.pcgamingfreaks.Minepacks.Bukkit.Item.ItemConfig;
import at.pcgamingfreaks.Minepacks.Bukkit.Minepacks;
import at.pcgamingfreaks.UUIDConverter;
import at.pcgamingfreaks.Utils;
@ -43,14 +44,14 @@
public abstract class SQL extends DatabaseBackend implements IStringFieldsWithPlaceholdersHolder, ILoadableStringFieldsHolder
{
private final ConnectionProvider dataSource;
private final ConnectionProvider connectionProvider;
@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 queryInsertPlayer, queryUpdatePlayer, queryInsertBp, queryUpdateBp, queryGetPlayer, queryGetBP, querySyncCooldown; // DB queries
@HasPlaceholders @Language("SQL") protected String queryDeleteOldCooldowns, queryDeleteOldBackpacks, queryGetUnsetOrInvalidUUIDs, queryFixUUIDs; // Maintenance queries
protected boolean syncCooldown;
@ -58,8 +59,8 @@ public SQL(@NotNull Minepacks plugin, @NotNull ConnectionProvider connectionProv
{
super(plugin);
dataSource = connectionProvider;
if(!dataSource.isAvailable()) throw new IllegalStateException("Failed to initialize database connection!");
this.connectionProvider = connectionProvider;
if(!this.connectionProvider.isAvailable()) throw new IllegalStateException("Failed to initialize database connection!");
loadSettings();
buildQueries();
@ -106,7 +107,7 @@ else if(fieldName.startsWith("BP") || fieldName.startsWith("Cd"))
public void close()
{
Utils.blockThread(1); // Give the database some time to perform async operations
dataSource.close();
connectionProvider.close();
}
protected void checkUUIDs()
@ -174,7 +175,7 @@ class UpdateData // Helper class for fixing UUIDs
public Connection getConnection() throws SQLException
{
return dataSource.getConnection();
return connectionProvider.getConnection();
}
protected abstract void checkDB();
@ -182,10 +183,13 @@ public Connection getConnection() throws SQLException
protected final void buildQueries()
{
// Build the SQL queries with placeholders for the table and field names
queryGetPlayer = "SELECT * FROM {TablePlayers}" +
(syncCooldown ? " LEFT JOIN {TableCooldowns} ON {TablePlayers}.{FieldPlayerID} = {TableCooldowns}.{FieldCDPlayer}" : "") +
" WHERE {FieldUUID}=?;";
queryUpdatePlayerAdd = "INSERT INTO {TablePlayers} ({FieldName},{FieldUUID}) VALUES (?,?) ON DUPLICATE KEY UPDATE {FieldName}=?;";
queryGetPlayer = "SELECT {TablePlayers}.{FieldPlayerID} AS {FieldPlayerID}, " +
(syncCooldown ? "{TableCooldowns}.{FieldCDTime} AS {FieldCDTime}, " : "") +
"FROM {TablePlayers} " +
(syncCooldown ? " LEFT JOIN {TableCooldowns} ON {TablePlayers}.{FieldPlayerID} = {TableCooldowns}.{FieldCDPlayer} " : "") +
"WHERE {FieldUUID}=?;";
queryInsertPlayer = "INSERT IGNORE INTO {TablePlayers} ({FieldName},{FieldUUID}) VALUES (?,?);";
queryUpdatePlayer = "UPDATE {TablePlayers} SET {FieldName}=? WHERE {FieldUUID}=?;";
queryGetBP = "SELECT * FROM {TableBackpacks} WHERE {FieldBPOwner}=?;";
querySyncCooldown = "INSERT INTO {TableCooldowns} ({FieldCDPlayer},{FieldCDTime}) VALUES (?,?) ON DUPLICATE KEY UPDATE {FieldCDTime}=?;";
queryDeleteOldCooldowns = "DELETE FROM {TableCooldowns} WHERE {FieldCDTime}<?;";
@ -243,7 +247,8 @@ protected void runStatement(final @NotNull @Language("SQL") String query, final
// Plugin Functions
protected void updatePlayer(final @NotNull Connection connection, final @NotNull MinepacksPlayerData player) throws SQLException
{
DBTools.runStatement(connection, queryUpdatePlayerAdd, player.getName(), formatUUID(player.getUUID()), player.getName());
DBTools.runStatement(connection, queryInsertPlayer, player.getName(), formatUUID(player.getUUID()));
DBTools.runStatement(connection, queryUpdatePlayer, player.getName(), formatUUID(player.getUUID()));
}
@Override

View File

@ -59,7 +59,6 @@ protected void updateQueriesForDialect()
queryInsertBp = queryInsertBp.replaceAll("\\) VALUES \\(\\?,\\?,\\?", ",{FieldBPLastUpdate}) VALUES (?,?,?,DATE('now')");
queryDeleteOldBackpacks = "DELETE FROM {TableBackpacks} WHERE {FieldBPLastUpdate} < DATE('now', '-{VarMaxAge} days')";
queryUpdateBp = queryUpdateBp.replaceAll("\\{NOW}", "DATE('now')");
queryUpdatePlayerAdd = "INSERT OR IGNORE INTO {TablePlayers} ({FieldName},{FieldUUID}) VALUES (?,?);";
querySyncCooldown = "INSERT OR REPLACE INTO {TableCooldowns} ({FieldCDPlayer},{FieldCDTime}) VALUES (?,?);";
}
@ -106,20 +105,13 @@ protected void checkDB()
{
if(rs.next()) return new Version(rs.getString("value"));
}
try(ResultSet rs = stmt.executeQuery("SELECT name FROM sqlite_master WHERE type='table' AND name='backpack_players';"))
try(ResultSet rs = stmt.executeQuery("SELECT `name` FROM `sqlite_master` WHERE `type`='table' AND `name`='backpack_players';"))
{ // Check if old players table exists
if(rs.next()) return new Version(2);
}
return plugin.getVersion();
}
@Override
protected void updatePlayer(@NotNull Connection connection, @NotNull MinepacksPlayerData player) throws SQLException
{
DBTools.runStatement(connection, queryUpdatePlayerAdd, player.getName(), formatUUID(player.getUUID()));
DBTools.runStatement(connection, "UPDATE `" + tablePlayers + "` SET `" + fieldPlayerName + "`=? WHERE `" + fieldPlayerUUID + "`=?;", player.getName(), formatUUID(player.getUUID()));
}
@Override
public void saveCooldown(final @NotNull MinepacksPlayerData player)
{