conditions) {
this.executeUpdate(UpdateQuery.create(table, values, conditions));
}
@@ -163,11 +159,6 @@ public abstract class AbstractDataHandler extends Abs
SQLQueries.executeUpdate(this.connector, query);
}
-// @Deprecated
-// public void executeUpdates(@NotNull UpdateQuery queries) {
-// SQLQueries.executeUpdates(this.connector, queries);
-// }
-
diff --git a/src/main/java/su/nightexpress/nightcore/database/AbstractUser.java b/src/main/java/su/nightexpress/nightcore/database/AbstractUser.java
index ba8122a..df8a4eb 100644
--- a/src/main/java/su/nightexpress/nightcore/database/AbstractUser.java
+++ b/src/main/java/su/nightexpress/nightcore/database/AbstractUser.java
@@ -8,6 +8,7 @@ import su.nightexpress.nightcore.NightCorePlugin;
import java.util.UUID;
+@Deprecated
public abstract class AbstractUser
implements DataUser {
protected final P plugin;
diff --git a/src/main/java/su/nightexpress/nightcore/database/AbstractUserDataHandler.java b/src/main/java/su/nightexpress/nightcore/database/AbstractUserDataHandler.java
index 382d1d6..5981d3f 100644
--- a/src/main/java/su/nightexpress/nightcore/database/AbstractUserDataHandler.java
+++ b/src/main/java/su/nightexpress/nightcore/database/AbstractUserDataHandler.java
@@ -9,7 +9,6 @@ import su.nightexpress.nightcore.database.sql.SQLCondition;
import su.nightexpress.nightcore.database.sql.SQLQueries;
import su.nightexpress.nightcore.database.sql.SQLValue;
import su.nightexpress.nightcore.database.sql.column.ColumnType;
-import su.nightexpress.nightcore.core.CoreConfig;
import su.nightexpress.nightcore.database.sql.query.UpdateEntity;
import su.nightexpress.nightcore.database.sql.query.UpdateQuery;
import su.nightexpress.nightcore.util.Lists;
@@ -21,6 +20,7 @@ import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
+@Deprecated
public abstract class AbstractUserDataHandler
, U extends DataUser> extends AbstractDataHandler
{
protected static final SQLColumn COLUMN_USER_ID = SQLColumn.of("uuid", ColumnType.STRING);
@@ -83,8 +83,7 @@ public abstract class AbstractUserDataHandler
, U ex
}
public boolean isNameIdCacheEnabled() {
- // TODO NOT WORKING FOR MYSQL DUE TO LOCAL CACHE, OTHER SERVERS THINK THAT PLAYER NOT EXISTS
- return CoreConfig.USER_CACHE_NAME_AND_UUID.get() && this.getDatabaseType() == DatabaseType.SQLITE;
+ return false;//CoreConfig.USER_CACHE_NAME_AND_UUID.get() && this.getDatabaseType() == DatabaseType.SQLITE;
}
public void cacheNamesAndIds() {
diff --git a/src/main/java/su/nightexpress/nightcore/database/AbstractUserManager.java b/src/main/java/su/nightexpress/nightcore/database/AbstractUserManager.java
index 7992012..f289f14 100644
--- a/src/main/java/su/nightexpress/nightcore/database/AbstractUserManager.java
+++ b/src/main/java/su/nightexpress/nightcore/database/AbstractUserManager.java
@@ -15,6 +15,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Supplier;
+@Deprecated
public abstract class AbstractUserManager
, U extends DataUser> extends AbstractManager
{
private final UserdataConfig config;
@@ -34,7 +35,7 @@ public abstract class AbstractUserManager
, U extend
@Override
protected void onLoad() {
this.addListener(new UserListener<>(this.plugin));
- this.addTask(this.plugin.createAsyncTask(this::saveScheduled).setTicksInterval(this.config.getScheduledSaveInterval()));
+ this.addTask(this.plugin.createAsyncTask(this::saveScheduled).setTicksInterval(this.config.getSaveInterval()));
}
@Override
@@ -74,7 +75,7 @@ public abstract class AbstractUserManager
, U extend
users.forEach(user -> {
user.cancelAutoSave(); // Reset autosave timestamp.
- user.setNextSyncIn(this.config.getScheduledSaveSyncPause()); // Unlock synchronization only when all data was pushed to the database.
+ user.setNextSyncIn(this.config.getSaveSyncPause()); // Unlock synchronization only when all data was pushed to the database.
});
this.scheduledSaves.values().removeAll(users);
@@ -99,10 +100,10 @@ public abstract class AbstractUserManager
, U extend
if (Players.isReal(player)) {
user = this.getUserData(uuid);
if (user != null) {
- if (CoreConfig.USER_DEBUG_ENABLED.get()) {
- new Throwable().printStackTrace();
- this.plugin.warn("Main thread user data load for '" + uuid + "' aka '" + player.getName() + "'.");
- }
+// if (CoreConfig.USER_DEBUG_ENABLED.get()) {
+// new Throwable().printStackTrace();
+// this.plugin.warn("Main thread user data load for '" + uuid + "' aka '" + player.getName() + "'.");
+// }
return user;
}
}
@@ -253,7 +254,7 @@ public abstract class AbstractUserManager
, U extend
}
public void scheduleSave(@NotNull U user) {
- user.setAutoSaveIn(this.config.getScheduledSaveDelay());
+ user.setAutoSaveIn(this.config.getSaveDelay());
user.cancelSynchronization();
this.scheduledSaves.put(user.getId(), user);
}
diff --git a/src/main/java/su/nightexpress/nightcore/database/DataUser.java b/src/main/java/su/nightexpress/nightcore/database/DataUser.java
index 527831f..7bc6ce4 100644
--- a/src/main/java/su/nightexpress/nightcore/database/DataUser.java
+++ b/src/main/java/su/nightexpress/nightcore/database/DataUser.java
@@ -7,6 +7,7 @@ import org.jetbrains.annotations.Nullable;
import java.util.UUID;
+@Deprecated
public interface DataUser {
void onLoad();
diff --git a/src/main/java/su/nightexpress/nightcore/database/DatabaseConfig.java b/src/main/java/su/nightexpress/nightcore/database/DatabaseConfig.java
index a58844c..7e36b72 100644
--- a/src/main/java/su/nightexpress/nightcore/database/DatabaseConfig.java
+++ b/src/main/java/su/nightexpress/nightcore/database/DatabaseConfig.java
@@ -8,9 +8,10 @@ import su.nightexpress.nightcore.util.StringUtil;
import java.util.stream.Stream;
+@Deprecated
public class DatabaseConfig {
- private final int saveInterval;
+ @Deprecated private final int saveInterval;
private final int syncInterval;
private final DatabaseType databaseType;
private final String tablePrefix;
@@ -152,6 +153,7 @@ public class DatabaseConfig {
return tablePrefix;
}
+ @Deprecated
public int getSaveInterval() {
return saveInterval;
}
diff --git a/src/main/java/su/nightexpress/nightcore/database/DatabaseType.java b/src/main/java/su/nightexpress/nightcore/database/DatabaseType.java
index c850fcd..df54904 100644
--- a/src/main/java/su/nightexpress/nightcore/database/DatabaseType.java
+++ b/src/main/java/su/nightexpress/nightcore/database/DatabaseType.java
@@ -1,5 +1,6 @@
package su.nightexpress.nightcore.database;
+@Deprecated
public enum DatabaseType {
MYSQL,
diff --git a/src/main/java/su/nightexpress/nightcore/database/UserdataConfig.java b/src/main/java/su/nightexpress/nightcore/database/UserdataConfig.java
index 5e6c27d..e7f385a 100644
--- a/src/main/java/su/nightexpress/nightcore/database/UserdataConfig.java
+++ b/src/main/java/su/nightexpress/nightcore/database/UserdataConfig.java
@@ -5,23 +5,37 @@ import su.nightexpress.nightcore.NightPlugin;
import su.nightexpress.nightcore.config.ConfigValue;
import su.nightexpress.nightcore.config.FileConfig;
+@Deprecated
public class UserdataConfig {
- private final long scheduledSaveInterval;
- private final double scheduledSaveDelay;
- private final int scheduledSaveSyncPause;
+ private final long cacheLifetime;
- public UserdataConfig(long scheduledSaveInterval, double scheduledSaveDelay, int scheduledSaveSyncPause) {
- this.scheduledSaveInterval = scheduledSaveInterval;
- this.scheduledSaveDelay = scheduledSaveDelay;
- this.scheduledSaveSyncPause = scheduledSaveSyncPause;
+ private final long saveInterval;
+ private final double saveDelay;
+ private final int saveSyncPause;
+
+ public UserdataConfig(long cacheLifetime, long saveInterval, double saveDelay, int saveSyncPause) {
+ this.cacheLifetime = cacheLifetime;
+ this.saveInterval = saveInterval;
+ this.saveDelay = saveDelay;
+ this.saveSyncPause = saveSyncPause;
}
@NotNull
public static UserdataConfig read(@NotNull NightPlugin plugin) {
FileConfig config = plugin.getConfig();
- long scheduledSaveInterval = ConfigValue.create("Database.UserData.Scheduled_Save_Interval",
+ long cacheLifetime = ConfigValue.create("Database.UserData.Cache_LifeTime",
+ 300L,
+ "Sets cache lifetime for player's data.",
+ "Data loaded for offline players and data of previously online players will be cached in the memory for that time.",
+ "When cache is expired, data have to be loaded from the database again.",
+ "[*] Set to 0 to disable data cache for offline players.",
+ "[*] Set to -1 for permanent data cache for offline players.",
+ "[Default is 300 (5 minutes)]"
+ ).read(config);
+
+ long saveInterval = ConfigValue.create("Database.UserData.Scheduled_Save_Interval",
20L,
"Sets how often (in ticks) plugin will attempt to save data of users marked to be saved.",
"This will save only users that are 'ready' to save (see 'Scheduled_Save_Delay').",
@@ -30,7 +44,7 @@ public class UserdataConfig {
"[Default is 20]"
).read(config);
- double scheduledSaveDelay = ConfigValue.create("Database.UserData.Scheduled_Save_Delay",
+ double saveDelay = ConfigValue.create("Database.UserData.Scheduled_Save_Delay",
1D,
"Sets scheduled save delay (in seconds) for a user when marked to be saved.",
"This means that a user will be saved X seconds later after being marked.",
@@ -46,7 +60,7 @@ public class UserdataConfig {
"[Default is 1]"
).read(config);
- int scheduledSaveSynchronizationPause = ConfigValue.create("Database.UserData.Scheduled_Save_Sync_Pause",
+ int saveSyncPause = ConfigValue.create("Database.UserData.Scheduled_Save_Sync_Pause",
3,
"Sets synchronization delay (in seconds) before the plugin can continue syncing data for a user after its scheduled save.",
"When a user marked for saving has been saved, their synchronization will be unlocked but delayed for this value.",
@@ -55,27 +69,31 @@ public class UserdataConfig {
).read(config);
- return new UserdataConfig(scheduledSaveInterval, scheduledSaveDelay, scheduledSaveSynchronizationPause);
+ return new UserdataConfig(cacheLifetime, saveInterval, saveDelay, saveSyncPause);
}
- public long getScheduledSaveInterval() {
- return scheduledSaveInterval;
+ public long getCacheLifetime() {
+ return this.cacheLifetime;
}
- public double getScheduledSaveDelay() {
- return scheduledSaveDelay;
+ public long getSaveInterval() {
+ return this.saveInterval;
}
- public int getScheduledSaveSyncPause() {
- return scheduledSaveSyncPause;
+ public double getSaveDelay() {
+ return this.saveDelay;
+ }
+
+ public int getSaveSyncPause() {
+ return this.saveSyncPause;
}
@Override
public String toString() {
return "UserdataConfig{" +
- "scheduledSaveInterval=" + scheduledSaveInterval +
- ", scheduledSaveDelay=" + scheduledSaveDelay +
- ", scheduledSaveSyncPause=" + scheduledSaveSyncPause +
+ "scheduledSaveInterval=" + saveInterval +
+ ", scheduledSaveDelay=" + saveDelay +
+ ", scheduledSaveSyncPause=" + saveSyncPause +
'}';
}
}
diff --git a/src/main/java/su/nightexpress/nightcore/database/connection/MySQLConnector.java b/src/main/java/su/nightexpress/nightcore/database/connection/MySQLConnector.java
index 59782c1..f42f33c 100644
--- a/src/main/java/su/nightexpress/nightcore/database/connection/MySQLConnector.java
+++ b/src/main/java/su/nightexpress/nightcore/database/connection/MySQLConnector.java
@@ -5,6 +5,7 @@ import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.database.AbstractConnector;
import su.nightexpress.nightcore.database.DatabaseConfig;
+@Deprecated
public class MySQLConnector extends AbstractConnector {
public MySQLConnector(@NotNull NightCorePlugin plugin, @NotNull DatabaseConfig config) {
diff --git a/src/main/java/su/nightexpress/nightcore/database/connection/SQLiteConnector.java b/src/main/java/su/nightexpress/nightcore/database/connection/SQLiteConnector.java
index 6749698..4a4da56 100644
--- a/src/main/java/su/nightexpress/nightcore/database/connection/SQLiteConnector.java
+++ b/src/main/java/su/nightexpress/nightcore/database/connection/SQLiteConnector.java
@@ -5,6 +5,7 @@ import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.database.AbstractConnector;
import su.nightexpress.nightcore.database.DatabaseConfig;
+@Deprecated
public class SQLiteConnector extends AbstractConnector {
public SQLiteConnector(@NotNull NightCorePlugin plugin, @NotNull DatabaseConfig config) {
diff --git a/src/main/java/su/nightexpress/nightcore/database/listener/UserListener.java b/src/main/java/su/nightexpress/nightcore/database/listener/UserListener.java
index 4f1a13a..a5385d9 100644
--- a/src/main/java/su/nightexpress/nightcore/database/listener/UserListener.java
+++ b/src/main/java/su/nightexpress/nightcore/database/listener/UserListener.java
@@ -6,13 +6,13 @@ import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightDataPlugin;
-import su.nightexpress.nightcore.core.CoreConfig;
+import su.nightexpress.nightcore.database.AbstractUserManager;
import su.nightexpress.nightcore.database.DataUser;
import su.nightexpress.nightcore.manager.AbstractListener;
-import su.nightexpress.nightcore.database.AbstractUserManager;
import java.util.UUID;
+@Deprecated
public class UserListener
, U extends DataUser> extends AbstractListener
{
private final AbstractUserManager extends NightDataPlugin, U> userManager;
@@ -31,9 +31,9 @@ public class UserListener
, U extends DataUser> exte
if (!this.userManager.isCreated(uuid)) {
user = this.userManager.createUserData(uuid, event.getName());
plugin.getData().addUser(user);
- if (CoreConfig.USER_DEBUG_ENABLED.get()) {
+ //if (CoreConfig.USER_DEBUG_ENABLED.get()) {
plugin.info("Created new data for: '" + uuid + "'");
- }
+ //}
}
else user = this.userManager.getUserData(uuid);
diff --git a/src/main/java/su/nightexpress/nightcore/database/serialize/ItemStackSerializer.java b/src/main/java/su/nightexpress/nightcore/database/serialize/ItemStackSerializer.java
index c514967..c17f23c 100644
--- a/src/main/java/su/nightexpress/nightcore/database/serialize/ItemStackSerializer.java
+++ b/src/main/java/su/nightexpress/nightcore/database/serialize/ItemStackSerializer.java
@@ -6,6 +6,7 @@ import su.nightexpress.nightcore.util.ItemNbt;
import java.lang.reflect.Type;
+@Deprecated
public class ItemStackSerializer implements JsonSerializer, JsonDeserializer {
@Override
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/SQLColumn.java b/src/main/java/su/nightexpress/nightcore/database/sql/SQLColumn.java
index b3a5b65..c0c316f 100644
--- a/src/main/java/su/nightexpress/nightcore/database/sql/SQLColumn.java
+++ b/src/main/java/su/nightexpress/nightcore/database/sql/SQLColumn.java
@@ -4,6 +4,7 @@ import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.database.DatabaseType;
import su.nightexpress.nightcore.database.sql.column.ColumnType;
+@Deprecated
public class SQLColumn {
private final String name;
@@ -33,6 +34,7 @@ public class SQLColumn {
}
@NotNull
+ @Deprecated
public SQLColumn asLowerCase() {
String name = "LOWER(" + this.getName() + ")";
@@ -49,6 +51,12 @@ public class SQLColumn {
return this.nameEscaped;
}
+ @NotNull
+ public String getNameLowercase() {
+ return "LOWER(" + this.getName() + ")";
+ }
+
+
@NotNull
public ColumnType getType() {
return type;
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/SQLCondition.java b/src/main/java/su/nightexpress/nightcore/database/sql/SQLCondition.java
index af832ad..508726c 100644
--- a/src/main/java/su/nightexpress/nightcore/database/sql/SQLCondition.java
+++ b/src/main/java/su/nightexpress/nightcore/database/sql/SQLCondition.java
@@ -2,6 +2,7 @@ package su.nightexpress.nightcore.database.sql;
import org.jetbrains.annotations.NotNull;
+@Deprecated
public class SQLCondition {
private final SQLValue value;
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/SQLExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/SQLExecutor.java
index 586b25f..ad62d19 100644
--- a/src/main/java/su/nightexpress/nightcore/database/sql/SQLExecutor.java
+++ b/src/main/java/su/nightexpress/nightcore/database/sql/SQLExecutor.java
@@ -3,6 +3,7 @@ package su.nightexpress.nightcore.database.sql;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.database.AbstractConnector;
+@Deprecated
public abstract class SQLExecutor {
protected final String table;
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/SQLQueries.java b/src/main/java/su/nightexpress/nightcore/database/sql/SQLQueries.java
index e92f459..b4eea43 100644
--- a/src/main/java/su/nightexpress/nightcore/database/sql/SQLQueries.java
+++ b/src/main/java/su/nightexpress/nightcore/database/sql/SQLQueries.java
@@ -9,6 +9,7 @@ import java.sql.*;
import java.util.*;
import java.util.function.Function;
+@Deprecated
public class SQLQueries {
public static boolean hasTable(@NotNull AbstractConnector connector, @NotNull String table) {
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/SQLUtils.java b/src/main/java/su/nightexpress/nightcore/database/sql/SQLUtils.java
index 7b7d039..07e10b9 100644
--- a/src/main/java/su/nightexpress/nightcore/database/sql/SQLUtils.java
+++ b/src/main/java/su/nightexpress/nightcore/database/sql/SQLUtils.java
@@ -1,7 +1,9 @@
package su.nightexpress.nightcore.database.sql;
import org.jetbrains.annotations.NotNull;
+import su.nightexpress.nightcore.db.sql.util.WhereOperator;
+@Deprecated
public class SQLUtils {
@NotNull
@@ -11,4 +13,14 @@ public class SQLUtils {
return "`" + string + "`";
}
+
+ @NotNull
+ public static String forWhere(@NotNull SQLColumn column, @NotNull WhereOperator operator) {
+ return column.getNameEscaped() + " " + operator.getLiteral() + " ?";
+ }
+
+ @NotNull
+ public static String forWhereLowercase(@NotNull SQLColumn column, @NotNull WhereOperator operator) {
+ return column.getNameLowercase() + " " + operator.getLiteral() + " ?";
+ }
}
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/SQLValue.java b/src/main/java/su/nightexpress/nightcore/database/sql/SQLValue.java
index 3b8c9e5..dfa0d30 100644
--- a/src/main/java/su/nightexpress/nightcore/database/sql/SQLValue.java
+++ b/src/main/java/su/nightexpress/nightcore/database/sql/SQLValue.java
@@ -2,6 +2,7 @@ package su.nightexpress.nightcore.database.sql;
import org.jetbrains.annotations.NotNull;
+@Deprecated
public class SQLValue {
private final SQLColumn column;
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnFormer.java b/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnFormer.java
index 976d99f..51842dd 100644
--- a/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnFormer.java
+++ b/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnFormer.java
@@ -3,6 +3,7 @@ package su.nightexpress.nightcore.database.sql.column;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.database.DatabaseType;
+@Deprecated
public interface ColumnFormer {
ColumnFormer STRING = (storageType, length) -> {
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnType.java b/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnType.java
index 0b8c0b7..6e02336 100644
--- a/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnType.java
+++ b/src/main/java/su/nightexpress/nightcore/database/sql/column/ColumnType.java
@@ -2,6 +2,7 @@ package su.nightexpress.nightcore.database.sql.column;
import org.jetbrains.annotations.NotNull;
+@Deprecated
public class ColumnType {
public static final ColumnType INTEGER = new ColumnType(ColumnFormer.INTEGER);
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/executor/AlterTableExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/executor/AlterTableExecutor.java
index 9348ccc..77c6e4d 100644
--- a/src/main/java/su/nightexpress/nightcore/database/sql/executor/AlterTableExecutor.java
+++ b/src/main/java/su/nightexpress/nightcore/database/sql/executor/AlterTableExecutor.java
@@ -14,6 +14,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+@Deprecated
public final class AlterTableExecutor extends SQLExecutor {
private final DatabaseType databaseType;
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/executor/CreateTableExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/executor/CreateTableExecutor.java
index 34066ec..c20c917 100644
--- a/src/main/java/su/nightexpress/nightcore/database/sql/executor/CreateTableExecutor.java
+++ b/src/main/java/su/nightexpress/nightcore/database/sql/executor/CreateTableExecutor.java
@@ -13,6 +13,7 @@ import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
+@Deprecated
public final class CreateTableExecutor extends SQLExecutor {
private final DatabaseType databaseType;
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/executor/DeleteQueryExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/executor/DeleteQueryExecutor.java
index 17d3502..42bca7e 100644
--- a/src/main/java/su/nightexpress/nightcore/database/sql/executor/DeleteQueryExecutor.java
+++ b/src/main/java/su/nightexpress/nightcore/database/sql/executor/DeleteQueryExecutor.java
@@ -12,6 +12,7 @@ import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
+@Deprecated
public final class DeleteQueryExecutor extends SQLExecutor {
private final List wheres;
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/executor/InsertQueryExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/executor/InsertQueryExecutor.java
index 8b47b7d..e71fd4e 100644
--- a/src/main/java/su/nightexpress/nightcore/database/sql/executor/InsertQueryExecutor.java
+++ b/src/main/java/su/nightexpress/nightcore/database/sql/executor/InsertQueryExecutor.java
@@ -12,6 +12,7 @@ import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
+@Deprecated
public final class InsertQueryExecutor extends SQLExecutor {
private final List values;
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/executor/RenameTableExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/executor/RenameTableExecutor.java
index 6c4eb8e..5196c25 100644
--- a/src/main/java/su/nightexpress/nightcore/database/sql/executor/RenameTableExecutor.java
+++ b/src/main/java/su/nightexpress/nightcore/database/sql/executor/RenameTableExecutor.java
@@ -6,6 +6,7 @@ import su.nightexpress.nightcore.database.AbstractConnector;
import su.nightexpress.nightcore.database.sql.SQLExecutor;
import su.nightexpress.nightcore.database.sql.SQLQueries;
+@Deprecated
public final class RenameTableExecutor extends SQLExecutor {
private final DatabaseType databaseType;
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/executor/SelectQueryExecutor.java b/src/main/java/su/nightexpress/nightcore/database/sql/executor/SelectQueryExecutor.java
index a0cf8ad..21b828b 100644
--- a/src/main/java/su/nightexpress/nightcore/database/sql/executor/SelectQueryExecutor.java
+++ b/src/main/java/su/nightexpress/nightcore/database/sql/executor/SelectQueryExecutor.java
@@ -11,6 +11,7 @@ import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
+@Deprecated
public final class SelectQueryExecutor extends SQLExecutor> {
private final List columns;
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/query/AbstractQuery.java b/src/main/java/su/nightexpress/nightcore/database/sql/query/AbstractQuery.java
deleted file mode 100644
index 6f65951..0000000
--- a/src/main/java/su/nightexpress/nightcore/database/sql/query/AbstractQuery.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package su.nightexpress.nightcore.database.sql.query;
-
-import org.jetbrains.annotations.NotNull;
-import su.nightexpress.nightcore.database.sql.SQLUtils;
-
-public class AbstractQuery {
-
- protected final String table;
- protected final String sql;
-
- protected AbstractQuery(@NotNull String table, @NotNull String sql) {
- this.table = SQLUtils.escape(table);
- this.sql = sql;
- }
-
- @NotNull
- public String getTable() {
- return table;
- }
-
- @NotNull
- public String getSQL() {
- return sql;
- }
-}
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateEntity.java b/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateEntity.java
index f9565db..44a4dcb 100644
--- a/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateEntity.java
+++ b/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateEntity.java
@@ -8,6 +8,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+@Deprecated
public class UpdateEntity {
private final List columnNames;
diff --git a/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateQuery.java b/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateQuery.java
index 0c51bc6..09f44c4 100644
--- a/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateQuery.java
+++ b/src/main/java/su/nightexpress/nightcore/database/sql/query/UpdateQuery.java
@@ -10,6 +10,7 @@ import java.util.Collection;
import java.util.Collections;
import java.util.List;
+@Deprecated
public class UpdateQuery /*extends AbstractQuery*/ {
private final List entities;
@@ -73,48 +74,4 @@ public class UpdateQuery /*extends AbstractQuery*/ {
public List getEntities() {
return entities;
}
-
- /*@NotNull
- public static UpdateQuery create(@NotNull String table, @NotNull List values) {
- return create(table, values, Collections.emptyList());
- }
-
- @NotNull
- public static UpdateQuery create(@NotNull String table, @NotNull List values, @NotNull List conditions) {
- List columnNames = new ArrayList<>();
- List columnValues = new ArrayList<>();
- List whereColumns = new ArrayList<>();
- List whereValues = new ArrayList<>();
-
- values.forEach(value -> {
- columnNames.add(value.getColumn().getNameEscaped() + " = ?");
- columnValues.add(value.getValue());
- });
-
- conditions.forEach(condition -> {
- whereColumns.add(condition.getColumn().getNameEscaped() + " " + condition.getType().getOperator() + " ?");
- whereValues.add(condition.getValue().getValue());
- });
-
- StringBuilder builder = new StringBuilder();
- builder.append("UPDATE ").append(SQLUtils.escape(table));
- builder.append(" SET ").append(String.join(",", columnNames));
- if (!whereColumns.isEmpty()) {
- builder.append(" WHERE ").append(String.join(" AND ", whereColumns));
- }
-
- String sql = builder.toString();
-
- return new UpdateQuery(sql, columnValues, whereValues);
- }
-
- @NotNull
- public List getValues() {
- return values;
- }
-
- @NotNull
- public List getWheres() {
- return wheres;
- }*/
}
diff --git a/src/main/java/su/nightexpress/nightcore/db/AbstractDataManager.java b/src/main/java/su/nightexpress/nightcore/db/AbstractDataManager.java
new file mode 100644
index 0000000..fce8da9
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/db/AbstractDataManager.java
@@ -0,0 +1,217 @@
+package su.nightexpress.nightcore.db;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import su.nightexpress.nightcore.NightPlugin;
+import su.nightexpress.nightcore.db.config.DatabaseConfig;
+import su.nightexpress.nightcore.db.config.DatabaseType;
+import su.nightexpress.nightcore.db.connection.AbstractConnector;
+import su.nightexpress.nightcore.db.sql.column.Column;
+import su.nightexpress.nightcore.db.sql.query.SQLQueries;
+import su.nightexpress.nightcore.db.sql.query.type.AbstractQuery;
+import su.nightexpress.nightcore.db.sql.query.impl.DeleteQuery;
+import su.nightexpress.nightcore.db.sql.query.impl.InsertQuery;
+import su.nightexpress.nightcore.db.sql.query.impl.SelectQuery;
+import su.nightexpress.nightcore.db.sql.query.impl.UpdateQuery;
+import su.nightexpress.nightcore.manager.AbstractManager;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Collection;
+import java.util.List;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+public abstract class AbstractDataManager extends AbstractManager
{
+
+ protected final DatabaseConfig config;
+ protected final AbstractConnector connector;
+ protected final Gson gson;
+
+ public AbstractDataManager(@NotNull P plugin) {
+ this(plugin, getDataConfig(plugin));
+ }
+
+ public AbstractDataManager(@NotNull P plugin, @NotNull DatabaseConfig config) {
+ super(plugin);
+ this.config = config;
+ this.connector = AbstractConnector.create(plugin, config);
+ this.gson = this.registerAdapters(new GsonBuilder().setPrettyPrinting()).create();
+ }
+
+ @NotNull
+ protected static DatabaseConfig getDataConfig(@NotNull NightPlugin plugin) {
+// DbConfig dataConfig = plugin.getDetails().getDatabaseConfig();
+// if (dataConfig == null) {
+// plugin.warn("The plugin didn't have database configuration. Fixing it now...");
+// dataConfig = DbConfig.read(plugin);
+// }
+// return dataConfig;
+//
+ return DatabaseConfig.read(plugin);
+ }
+
+ @Override
+ protected void onLoad() {
+ if (this.config.getSyncInterval() > 0 && this.getStorageType() != DatabaseType.SQLITE) {
+ this.addAsyncTask(this::onSynchronize, this.config.getSyncInterval());
+ this.plugin.info("Enabled data synchronization with " + config.getSyncInterval() + " seconds interval.");
+ }
+
+ this.onInitialize();
+
+ if (this.config.isPurgeEnabled() && this.config.getPurgePeriod() > 0) {
+ this.onPurge();
+ }
+ }
+
+ @Override
+ protected void onShutdown() {
+ this.onClose();
+ this.connector.close();
+ }
+
+ @NotNull
+ protected abstract GsonBuilder registerAdapters(@NotNull GsonBuilder builder);
+
+ protected abstract void onInitialize();
+
+ protected abstract void onClose();
+
+ public abstract void onSynchronize();
+
+ public abstract void onPurge();
+
+ @NotNull
+ public DatabaseConfig getConfig() {
+ return this.config;
+ }
+
+ @NotNull
+ public DatabaseType getStorageType() {
+ return this.config.getStorageType();
+ }
+
+ @NotNull
+ public String getTablePrefix() {
+ return this.config.getTablePrefix();
+ }
+
+ @NotNull
+ public AbstractConnector getConnector() {
+ return this.connector;
+ }
+
+ @NotNull
+ protected final Connection getConnection() throws SQLException {
+ return this.getConnector().getConnection();
+ }
+
+ public void createTable(@NotNull String table, @NotNull List columns) {
+ SQLQueries.createTable(this.connector, this.getStorageType(), table, columns);
+ }
+
+ public void renameTable(@NotNull String table, @NotNull String toName) {
+ SQLQueries.renameTable(this.connector, this.getStorageType(), toName, toName);
+ }
+
+ public void addColumn(@NotNull String table, @NotNull Column column, @NotNull String defaultValue) {
+ SQLQueries.addColumn(this.connector, this.getStorageType(), table, column, defaultValue);
+ }
+
+ public void renameColumn(@NotNull String table, @NotNull Column column, @NotNull String toName) {
+ SQLQueries.renameColumn(this.connector, table, column, toName);
+ }
+
+ public void renameColumn(@NotNull String table, @NotNull String column, @NotNull String toName) {
+ SQLQueries.renameColumn(this.connector, table, column, toName);
+ }
+
+ public void dropColumn(@NotNull String table, @NotNull Column... columns) {
+ for (Column column : columns) {
+ SQLQueries.dropColumn(this.connector, table, column);
+ }
+ }
+
+ public void dropColumn(@NotNull String table, @NotNull String... columns) {
+ for (String column : columns) {
+ SQLQueries.dropColumn(this.connector, table, column);
+ }
+ }
+
+ public boolean hasColumn(@NotNull String table, @NotNull Column column) {
+ return SQLQueries.hasColumn(this.connector, table, column);
+ }
+
+
+
+ public void insert(@NotNull String table, @NotNull InsertQuery query, @NotNull T entity) {
+ this.executeUpdate(table, query, entity);
+ }
+
+ public void insert(@NotNull String table, @NotNull InsertQuery query, @NotNull Collection entities) {
+ this.executeUpdate(table, query, entities);
+ }
+
+ public void update(@NotNull String table, @NotNull UpdateQuery query, @NotNull T entity) {
+ this.executeUpdate(table, query, entity);
+ }
+
+ public void update(@NotNull String table, @NotNull UpdateQuery query, @NotNull Collection entities) {
+ this.executeUpdate(table, query, entities);
+ }
+
+ public void delete(@NotNull String table, @NotNull DeleteQuery query, @NotNull T entity) {
+ this.executeUpdate(table, query, entity);
+ }
+
+ public void delete(@NotNull String table, @NotNull DeleteQuery query, @NotNull Collection entities) {
+ this.executeUpdate(table, query, entities);
+ }
+
+ public void executeUpdate(@NotNull String table, @NotNull AbstractQuery query, @NotNull T entity) {
+ SQLQueries.executeQuery(this.connector, table, query, entity);
+ }
+
+ public void executeUpdate(@NotNull String table, @NotNull AbstractQuery query, @NotNull Collection entities) {
+ SQLQueries.executeQuery(this.connector, table, query, entities);
+ }
+
+
+
+ public boolean contains(@NotNull String table, @NotNull Consumer> consumer) {
+ return this.selectFirst(table, resultSet -> true, consumer) != null;
+ }
+
+ @Nullable
+ public T selectFirst(@NotNull String table, @NotNull Function function, @NotNull Consumer> consumer) {
+ SelectQuery query = new SelectQuery<>(function);
+
+ consumer.accept(query);
+
+ return this.selectFirst(table, query);
+ }
+
+ @NotNull
+ public List select(@NotNull String table, @NotNull Function function, @NotNull Consumer> consumer) {
+ SelectQuery query = new SelectQuery<>(function);
+
+ consumer.accept(query);
+
+ return this.select(table, query);
+ }
+
+ @Nullable
+ public T selectFirst(@NotNull String table, @NotNull SelectQuery query) {
+ List list = this.select(table, query);
+ return list.isEmpty() ? null : list.get(0);
+ }
+
+ @NotNull
+ public List select(@NotNull String table, @NotNull SelectQuery query) {
+ return SQLQueries.executeSelect(this.connector, table, query);
+ }
+}
diff --git a/src/main/java/su/nightexpress/nightcore/db/AbstractUser.java b/src/main/java/su/nightexpress/nightcore/db/AbstractUser.java
new file mode 100644
index 0000000..f430730
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/db/AbstractUser.java
@@ -0,0 +1,147 @@
+package su.nightexpress.nightcore.db;
+
+import org.bukkit.Bukkit;
+import org.bukkit.OfflinePlayer;
+import org.bukkit.entity.Player;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import su.nightexpress.nightcore.util.TimeUtil;
+
+import java.util.UUID;
+
+public abstract class AbstractUser {
+
+ protected final UUID uuid;
+
+ protected String name;
+ protected long dateCreated;
+ protected long lastOnline;
+ protected long cacheExpireTime;
+ protected long autoSaveTime;
+ protected long autoSyncTime;
+
+ public AbstractUser(@NotNull UUID uuid, @NotNull String name, long dateCreated, long lastOnline) {
+ this.uuid = uuid;
+ this.name = name;
+ this.setDateCreated(dateCreated);
+ this.setLastOnline(lastOnline);
+
+ this.setPermanentCache();
+ this.disableAutoSave();
+ }
+
+ public abstract void onLoad();
+
+ public abstract void onUnload();
+
+
+ public boolean isCacheExpired() {
+ return TimeUtil.isPassed(this.cacheExpireTime);
+ }
+
+ public boolean isAutoSaveReady() {
+ return TimeUtil.isPassed(this.autoSaveTime);
+ }
+
+ public boolean isAutoSyncReady() {
+ return TimeUtil.isPassed(this.autoSyncTime);
+ }
+
+
+ public void setPermanentCache() {
+ this.setCacheFor(-1);
+ }
+
+ public void disableAutoSave() {
+ this.setAutoSaveIn(-1);
+ }
+
+ public void disableAutoSync() {
+ this.setAutoSyncIn(-1);
+ }
+
+
+ public long getCacheExpireTime() {
+ return this.cacheExpireTime;
+ }
+
+ public void setCacheFor(long seconds) {
+ this.cacheExpireTime = TimeUtil.createFutureTimestamp(seconds);
+ }
+
+
+ public boolean isAutoSavePlanned() {
+ return this.autoSaveTime > 0;
+ }
+
+ public long getAutoSaveTime() {
+ return this.autoSaveTime;
+ }
+
+ public void setAutoSaveIn(double seconds) {
+ this.autoSaveTime = TimeUtil.createFutureTimestamp(seconds);
+ }
+
+
+ public boolean isAutoSyncPlanned() {
+ return this.autoSyncTime > 0;
+ }
+
+ public long getAutoSyncTime() {
+ return this.autoSyncTime;
+ }
+
+ public void setAutoSyncIn(int seconds) {
+ this.autoSyncTime = TimeUtil.createFutureTimestamp(seconds);
+ }
+
+
+ @NotNull
+ public final UUID getId() {
+ return this.uuid;
+ }
+
+ @NotNull
+ public final String getName() {
+ return this.name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public final long getDateCreated() {
+ return dateCreated;
+ }
+
+ public final void setDateCreated(long dateCreated) {
+ this.dateCreated = dateCreated;
+ }
+
+ public final long getLastOnline() {
+ return this.lastOnline;
+ }
+
+ public final void setLastOnline(long lastOnline) {
+ this.lastOnline = lastOnline;
+ }
+
+ public final boolean isOnline() {
+ return this.getPlayer() != null;
+ }
+
+ @NotNull
+ public final OfflinePlayer getOfflinePlayer() {
+ return Bukkit.getOfflinePlayer(this.getId());
+ }
+
+ @Nullable
+ public final Player getPlayer() {
+ return Bukkit.getPlayer(this.getId());
+ }
+
+ @Override
+ public String toString() {
+ return "AbstractUser [uuid=" + this.uuid + ", name=" + this.name + ", lastOnline=" + this.lastOnline + "]";
+ }
+}
diff --git a/src/main/java/su/nightexpress/nightcore/db/AbstractUserDataManager.java b/src/main/java/su/nightexpress/nightcore/db/AbstractUserDataManager.java
new file mode 100644
index 0000000..5126fee
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/db/AbstractUserDataManager.java
@@ -0,0 +1,161 @@
+package su.nightexpress.nightcore.db;
+
+import org.bukkit.entity.Player;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import su.nightexpress.nightcore.NightPlugin;
+import su.nightexpress.nightcore.db.config.DatabaseConfig;
+import su.nightexpress.nightcore.db.sql.query.UserQueries;
+import su.nightexpress.nightcore.db.sql.column.Column;
+import su.nightexpress.nightcore.db.sql.column.ColumnType;
+import su.nightexpress.nightcore.db.sql.query.type.ValuedQuery;
+import su.nightexpress.nightcore.db.sql.util.WhereOperator;
+import su.nightexpress.nightcore.db.sql.query.impl.InsertQuery;
+import su.nightexpress.nightcore.db.sql.query.impl.SelectQuery;
+import su.nightexpress.nightcore.db.sql.query.impl.UpdateQuery;
+import su.nightexpress.nightcore.util.Lists;
+import su.nightexpress.nightcore.util.TimeUtil;
+
+import java.sql.ResultSet;
+import java.time.LocalDateTime;
+import java.util.*;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+public abstract class AbstractUserDataManager extends AbstractDataManager
{
+
+ public static final Column COLUMN_USER_ID = Column.of("uuid", ColumnType.STRING);
+ public static final Column COLUMN_USER_NAME = Column.of("name", ColumnType.STRING);
+ public static final Column COLUMN_USER_DATE_CREATED = Column.of("dateCreated", ColumnType.LONG);
+ public static final Column COLUMN_USER_LAST_ONLINE = Column.of("last_online", ColumnType.LONG);
+
+ protected final String tableUsers;
+
+ protected final Function userFunction;
+
+ public AbstractUserDataManager(@NotNull P plugin) {
+ this(plugin, getDataConfig(plugin));
+ }
+
+ public AbstractUserDataManager(@NotNull P plugin, @NotNull DatabaseConfig config) {
+ super(plugin, config);
+ this.tableUsers = this.getTablePrefix() + "_users";
+
+ this.userFunction = this.createUserFunction();
+ }
+
+ @Override
+ protected void onInitialize() {
+ this.createUserTable();
+ }
+
+ @Override
+ protected void onClose() {
+
+ }
+
+ @Override
+ public void onPurge() {
+ LocalDateTime deadline = LocalDateTime.now().minusDays(this.getConfig().getPurgePeriod());
+ long deadlineMs = TimeUtil.toEpochMillis(deadline);
+
+ this.delete(this.tableUsers, UserQueries.deleteByLastOnline(), deadlineMs);
+ }
+
+ @NotNull
+ protected abstract Function createUserFunction();
+
+ protected void createUserTable() {
+ List columns = new ArrayList<>();
+ columns.add(COLUMN_USER_ID);
+ columns.add(COLUMN_USER_NAME);
+ columns.add(COLUMN_USER_DATE_CREATED);
+ columns.add(COLUMN_USER_LAST_ONLINE);
+ this.addTableColumns(columns);
+
+ this.createTable(this.tableUsers, columns);
+ }
+
+ protected abstract void addUpsertQueryData(@NotNull ValuedQuery, U> query);
+
+ //protected abstract void addInsertQueryData(@NotNull InsertQuery query);
+
+ //protected abstract void addUpdateQueryData(@NotNull UpdateQuery query);
+
+ protected abstract void addSelectQueryData(@NotNull SelectQuery query);
+
+ protected abstract void addTableColumns(@NotNull List columns);
+
+ @NotNull
+ public List getUsers() {
+ return this.select(this.tableUsers, this.userFunction, SelectQuery::all);
+ }
+
+ @Nullable
+ public U getUser(@NotNull Player player) {
+ return this.getUser(player.getUniqueId());
+ }
+
+ @Nullable
+ public final U getUser(@NotNull String name) {
+ return this.selectUser(query -> query.whereIgnoreCase(COLUMN_USER_NAME, WhereOperator.EQUAL, name.toLowerCase()));
+ }
+
+ @Nullable
+ public final U getUser(@NotNull UUID uuid) {
+ return this.selectUser(query -> query.where(COLUMN_USER_ID, WhereOperator.EQUAL, uuid.toString()));
+ }
+
+ private U selectUser(@NotNull Consumer> consumer) {
+ SelectQuery query = new SelectQuery<>(this.userFunction);
+ query.column(COLUMN_USER_ID);
+ query.column(COLUMN_USER_NAME);
+ query.column(COLUMN_USER_LAST_ONLINE);
+ query.column(COLUMN_USER_DATE_CREATED);
+ this.addSelectQueryData(query);
+
+ consumer.accept(query);
+
+ return this.selectFirst(this.tableUsers, query);
+ }
+
+ public boolean isUserExists(@NotNull String name) {
+ return this.contains(this.tableUsers, query -> query
+ .column(COLUMN_USER_NAME)
+ .whereIgnoreCase(COLUMN_USER_NAME, WhereOperator.EQUAL, name.toLowerCase())
+ );
+ }
+
+ public boolean isUserExists(@NotNull UUID uuid) {
+ return this.contains(this.tableUsers, query -> query
+ .column(COLUMN_USER_ID)
+ .where(COLUMN_USER_ID, WhereOperator.EQUAL, uuid.toString())
+ );
+ }
+
+ public void saveUser(@NotNull U user) {
+ this.saveUsers(Lists.newList(user));
+ }
+
+ public void saveUsers(@NotNull Collection users) {
+ UpdateQuery query = UserQueries.update();
+ this.addUpsertQueryData(query);
+
+ this.update(this.tableUsers, query, users);
+ }
+
+ public void insertUser(@NotNull U user) {
+ InsertQuery query = UserQueries.insert();
+ this.addUpsertQueryData(query);
+
+ this.insert(this.tableUsers, query, user);
+ }
+
+ public void deleteUser(@NotNull U user) {
+ this.deleteUser(user.getId());
+ }
+
+ public void deleteUser(@NotNull UUID userId) {
+ this.delete(this.tableUsers, UserQueries.deleteByUUID(), userId);
+ }
+}
diff --git a/src/main/java/su/nightexpress/nightcore/db/AbstractUserManager.java b/src/main/java/su/nightexpress/nightcore/db/AbstractUserManager.java
new file mode 100644
index 0000000..cf4c1da
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/db/AbstractUserManager.java
@@ -0,0 +1,332 @@
+package su.nightexpress.nightcore.db;
+
+import org.bukkit.entity.Player;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import su.nightexpress.nightcore.NightPlugin;
+import su.nightexpress.nightcore.db.config.UserdataConfig;
+import su.nightexpress.nightcore.db.listener.UserListener;
+import su.nightexpress.nightcore.manager.AbstractManager;
+import su.nightexpress.nightcore.util.Players;
+
+import java.util.*;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+
+public abstract class AbstractUserManager extends AbstractManager
{
+
+ private final UserdataConfig config;
+ private final AbstractUserDataManager
dataManager;
+
+ private final Map loadedByIdMap;
+ private final Map loadedByNameMap;
+
+ public AbstractUserManager(@NotNull P plugin, @NotNull AbstractUserDataManager dataManager) {
+ super(plugin);
+ this.config = UserdataConfig.read(plugin);
+ this.dataManager = dataManager;
+ this.loadedByIdMap = new ConcurrentHashMap<>();
+ this.loadedByNameMap = new ConcurrentHashMap<>();
+ }
+
+ @Override
+ protected void onLoad() {
+ this.addListener(new UserListener<>(this.plugin, this));
+ this.addAsyncTask(this::saveScheduled, this.config.getSaveInterval());
+ this.addAsyncTask(this::unloadExpired, this.config.getCacheCleanupInterval());
+
+ this.plugin.onPostLoad(this::loadOnline);
+ }
+
+ @Override
+ protected void onShutdown() {
+ this.saveLoaded();
+ this.loadedByIdMap.clear();
+ this.loadedByNameMap.clear();
+ }
+
+ public void loadOnline() {
+ //plugin.debug("Load data for online players");
+ Players.getOnline().forEach(player -> {
+ U user = this.getOrFetch(player.getUniqueId());
+ if (user != null) this.cachePermanent(user);
+ });
+ }
+
+ public void unloadExpired() {
+ this.getLoaded().forEach(user -> {
+ if (user.isCacheExpired() && !user.isOnline()) {
+ this.unload(user);
+ //plugin.debug("Unloaded expired cached: " + user.getName());
+ }
+ });
+ }
+
+ public final void handleJoin(@NotNull Player player) {
+ U user = this.getLoaded(player);
+ if (user == null) return;
+
+ this.cachePermanent(user);
+ }
+
+ public final void handleQuit(@NotNull Player player) {
+ U user = this.getLoaded(player.getUniqueId());
+ if (user == null) return;
+
+ user.setName(player.getName());
+ user.setLastOnline(System.currentTimeMillis());
+
+ this.plugin.runTaskAsync(task -> this.saveInDatabase(user));
+ this.cacheTemporary(user);
+ }
+
+ public void saveScheduled() {
+ Set users = this.getLoaded().stream().filter(AbstractUser::isAutoSaveReady).collect(Collectors.toCollection(HashSet::new));
+ if (users.isEmpty()) return;
+
+ this.dataManager.saveUsers(users);
+ //this.plugin.debug("Saved " + users.size() + " users");
+
+ users.forEach(user -> {
+ user.disableAutoSave(); // Reset autosave timestamp.
+ user.setAutoSyncIn(this.config.getSaveSyncPause()); // Unlock synchronization only when all data was pushed to the database.
+ });
+ }
+
+ public void saveLoaded() {
+ this.dataManager.saveUsers(this.getLoaded());
+ }
+
+ public void save(@NotNull Player player) {
+ U user = this.getLoaded(player.getUniqueId());
+ if (user == null) return;
+
+ this.save(user);
+ }
+
+ public void save(@NotNull U user) {
+ user.setAutoSaveIn(this.config.getSaveDelay());
+ user.disableAutoSync();
+ }
+
+ private void load(@NotNull U user) {
+ user.onLoad();
+ this.cacheTemporary(user);
+ }
+
+ private void unload(@NotNull U user) {
+ user.onUnload();
+
+ this.loadedByIdMap.remove(user.getId());
+ this.loadedByNameMap.remove(user.getName().toLowerCase());
+ }
+
+ @NotNull
+ public abstract U create(@NotNull UUID uuid, @NotNull String name);
+
+ public void cacheTemporary(@NotNull U user) {
+ user.setCacheFor(this.config.getCacheLifetime());
+ this.cache(user);
+ //this.plugin.debug("Temp user cache: " + user.getName());
+ }
+
+ public void cachePermanent(@NotNull U user) {
+ user.setPermanentCache();
+ this.cache(user);
+ //this.plugin.debug("Permanent user cache: " + user.getName());
+ }
+
+ private void cache(@NotNull U user) {
+ this.loadedByIdMap.putIfAbsent(user.getId(), user);
+ this.loadedByNameMap.putIfAbsent(user.getName().toLowerCase(), user);
+ }
+
+ public boolean isInDatabase(@NotNull String name) {
+ return this.dataManager.isUserExists(name);
+ }
+
+ public boolean isInDatabase(@NotNull UUID uuid) {
+ return this.dataManager.isUserExists(uuid);
+ }
+
+ public void addInDatabase(@NotNull U user) {
+ this.dataManager.insertUser(user);
+ }
+
+ public void saveInDatabase(@NotNull U user) {
+ this.dataManager.saveUser(user);
+ }
+
+ @Nullable
+ public U getFromDatabase(@NotNull String name) {
+ return this.dataManager.getUser(name);
+ }
+
+ @Nullable
+ public U getFromDatabase(@NotNull UUID uuid) {
+ return this.dataManager.getUser(uuid);
+ }
+
+ @NotNull
+ public final U getOrFetch(@NotNull Player player) {
+ UUID uuid = player.getUniqueId();
+
+ U user = this.getLoaded(uuid);
+ if (user != null) return user;
+
+ if (Players.isReal(player)) {
+ user = this.getOrFetch(uuid);
+ if (user != null) {
+ //new Throwable().printStackTrace();
+ this.plugin.warn("Main thread user data load for '" + uuid + "' aka '" + player.getName() + "'.");
+ return user;
+ }
+ }
+
+ return this.create(uuid, player.getName());
+ }
+
+ @Nullable
+ public final U getOrFetch(@NotNull String name) {
+ U user = this.getLoaded(name);
+ if (user != null) return user;
+
+ user = this.getFromDatabase(name);
+ if (user != null) {
+ //this.plugin.debug("Loaded from DB by Name: " + user.getName());
+ this.load(user);
+ }
+
+ return user;
+ }
+
+ @Nullable
+ public final U getOrFetch(@NotNull UUID uuid) {
+ U user = this.getLoaded(uuid);
+ if (user != null) return user;
+
+ user = this.getFromDatabase(uuid);
+ if (user != null) {
+ //this.plugin.debug("Loaded from DB by UUID: " + user.getName());
+ this.load(user);
+ }
+
+ return user;
+ }
+
+ public final CompletableFuture getUserDataAsync(@NotNull String name) {
+ return CompletableFuture.supplyAsync(() -> this.getOrFetch(name));
+ }
+
+ public final CompletableFuture getUserDataAsync(@NotNull UUID uuid) {
+ return CompletableFuture.supplyAsync(() -> this.getOrFetch(uuid));
+ }
+
+ /**
+ * Performs an operation on the given user.
+ * Runs immediately in the current thread if player is online or data is already loaded.
+ * Otherwise fetches player data asynchronously and performs an operation in async CompletableFuture thread.
+ * @param name Name of a player.
+ */
+ public void manageUser(@NotNull String name, Consumer consumer) {
+ this.manageUser(() -> this.getLoaded(name), () -> this.getUserDataAsync(name), consumer);
+ }
+
+ /**
+ * Performs an operation on the given user.
+ * Runs immediately in the current thread if player is online or data is already loaded.
+ * Otherwise fetches player data asynchronously and performs an operation in async CompletableFuture thread.
+ * @param playerId UUID of a player.
+ */
+ public void manageUser(@NotNull UUID playerId, Consumer consumer) {
+ this.manageUser(() -> this.getLoaded(playerId), () -> this.getUserDataAsync(playerId), consumer);
+ }
+
+ /**
+ * Performs an operation on the given user.
+ * Runs immediately in the current thread if player is online or data is already loaded.
+ * Otherwise fetches player data asynchronously and performs an operation next tick in the main thread.
+ * @param name Name of a player.
+ */
+ public void manageUserSynchronized(@NotNull String name, Consumer consumer) {
+ this.manageUserSynchronized(() -> this.getLoaded(name), () -> this.getUserDataAsync(name), consumer);
+ }
+
+ /**
+ * Performs an operation on the given user.
+ * Runs immediately in the current thread if player is online or data is already loaded.
+ * Otherwise fetches player data asynchronously and performs an operation next tick in the main thread.
+ * @param playerId UUID of a player.
+ */
+ public void manageUserSynchronized(@NotNull UUID playerId, Consumer consumer) {
+ this.manageUserSynchronized(() -> this.getLoaded(playerId), () -> this.getUserDataAsync(playerId), consumer);
+ }
+
+ private void manageUser(@NotNull Supplier loadedSupplier, @NotNull Supplier> fetchSupplier, @NotNull Consumer consumer) {
+ U user = loadedSupplier.get();
+ if (user != null) {
+ consumer.accept(user);
+ }
+ else fetchSupplier.get().thenAccept(consumer);
+ }
+
+ private void manageUserSynchronized(@NotNull Supplier loadedSupplier, @NotNull Supplier> fetchSupplier, @NotNull Consumer consumer) {
+ this.manageUser(loadedSupplier, fetchSupplier, user -> this.plugin.runTask(task -> consumer.accept(user)));
+ }
+
+ /**
+ * @return Fetches all users from the database and returns them in as a single set.
+ * Users that are already loaded won't be replaced by ones from the database, however they will be fetched anyway.
+ */
+ @NotNull
+ public Set getAll() {
+ Set users = this.getLoaded();
+ this.dataManager.getUsers().stream().filter(user -> !this.isLoaded(user.getId())).forEach(users::add);
+ return users;
+ }
+
+ @NotNull
+ public Set getLoaded() {
+ return new HashSet<>(this.loadedByIdMap.values());
+ }
+
+ @NotNull
+ public Map getLoadedByIdMap() {
+ return this.loadedByIdMap;
+ }
+
+ @NotNull
+ public Map getLoadedByNameMap() {
+ return this.loadedByNameMap;
+ }
+
+ @Nullable
+ public U getLoaded(@NotNull Player player) {
+ return this.getLoaded(player.getUniqueId());
+ }
+
+ @Nullable
+ public U getLoaded(@NotNull UUID uuid) {
+ return this.loadedByIdMap.get(uuid);
+ }
+
+ @Nullable
+ public U getLoaded(@NotNull String name) {
+ return this.loadedByNameMap.get(name.toLowerCase());
+ }
+
+ public boolean isLoaded(@NotNull Player player) {
+ return this.isLoaded(player.getUniqueId());
+ }
+
+ public boolean isLoaded(@NotNull UUID id) {
+ return this.loadedByIdMap.containsKey(id);
+ }
+
+ public boolean isLoaded(@NotNull String name) {
+ return this.loadedByNameMap.containsKey(name.toLowerCase());
+ }
+}
diff --git a/src/main/java/su/nightexpress/nightcore/db/config/DatabaseConfig.java b/src/main/java/su/nightexpress/nightcore/db/config/DatabaseConfig.java
new file mode 100644
index 0000000..36eee5a
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/db/config/DatabaseConfig.java
@@ -0,0 +1,187 @@
+package su.nightexpress.nightcore.db.config;
+
+import org.jetbrains.annotations.NotNull;
+import su.nightexpress.nightcore.NightPlugin;
+import su.nightexpress.nightcore.config.ConfigValue;
+import su.nightexpress.nightcore.config.FileConfig;
+import su.nightexpress.nightcore.util.StringUtil;
+
+import java.util.stream.Stream;
+
+public class DatabaseConfig {
+
+ private final int syncInterval;
+ private final DatabaseType databaseType;
+ private final String tablePrefix;
+ private final boolean purgeEnabled;
+ private final int purgePeriod;
+
+ private final String username;
+ private final String password;
+ private final String host;
+ private final String database;
+ private final String urlOptions;
+
+ private final String filename;
+
+ public DatabaseConfig(
+ int syncInterval,
+ @NotNull DatabaseType databaseType,
+ @NotNull String tablePrefix,
+ boolean purgeEnabled,
+ int purgePeriod,
+
+ @NotNull String username,
+ @NotNull String password,
+ @NotNull String host,
+ @NotNull String database,
+ @NotNull String urlOptions,
+
+ @NotNull String filename
+ ) {
+ this.syncInterval = syncInterval;
+ this.databaseType = databaseType;
+ this.tablePrefix = tablePrefix;
+ this.purgeEnabled = purgeEnabled;
+ this.purgePeriod = purgePeriod;
+
+ this.username = username;
+ this.password = password;
+ this.host = host;
+ this.database = database;
+ this.urlOptions = urlOptions;
+
+ this.filename = filename;
+ }
+
+ @NotNull
+ public static DatabaseConfig read(@NotNull NightPlugin plugin) {
+ String defPrefix = StringUtil.lowerCaseUnderscore(plugin.getName());
+ return read(plugin.getConfig(), defPrefix);
+ }
+
+ @NotNull
+ public static DatabaseConfig read(@NotNull FileConfig config, @NotNull String defaultPrefix) {
+ return read(config, defaultPrefix, "data.db");
+ }
+
+ @NotNull
+ public static DatabaseConfig read(@NotNull FileConfig config, @NotNull String defaultPrefix, @NotNull String defFileName) {
+ String path = "Database.";
+
+ DatabaseType databaseType = ConfigValue.create(path + "Type", DatabaseType.class, DatabaseType.SQLITE,
+ "Sets database type.",
+ "Available values: " + String.join(",", Stream.of(DatabaseType.values()).map(Enum::name).toList()))
+ .read(config);
+
+ int syncInterval = ConfigValue.create(path + "Sync_Interval", -1,
+ "Sets how often (in seconds) plugin data will be fetched and loaded from the remote database.",
+ "Useless for " + DatabaseType.SQLITE.name() + ".",
+ "Set to '-1' to disable.")
+ .read(config);
+
+ String tablePrefix = ConfigValue.create(path + "Table_Prefix", defaultPrefix,
+ "Custom prefix for plugin tables in database.")
+ .read(config);
+
+ String mysqlUser = ConfigValue.create(path + "MySQL.Username", "root",
+ "Database user name.")
+ .read(config);
+
+ String mysqlPassword = ConfigValue.create(path + "MySQL.Password", "root",
+ "Database password.")
+ .read(config);
+
+ String mysqlHost = ConfigValue.create(path + "MySQL.Host", "localhost:3306",
+ "Database host. Example: localhost:3306, 127.0.0.1:3306")
+ .read(config);
+
+ String mysqlBase = ConfigValue.create(path + "MySQL.Database", "minecraft",
+ "Name of the MySQL database where plugin will create tables.")
+ .read(config);
+
+ String urlOptions = ConfigValue.create(path + "MySQL.Options",
+ "?allowPublicKeyRetrieval=true&useSSL=false",
+ "Connection options. Do not touch unless you know what you're doing."
+ ).read(config);
+
+ String sqliteFilename = ConfigValue.create(path + "SQLite.FileName", defFileName,
+ "File name for the SQLite database file.",
+ "Actually it's a path to the file, so you can use directories here.")
+ .read(config);
+
+
+ path = "Database.Purge.";
+ boolean purgeEnabled = ConfigValue.create(path + "Enabled", false,
+ "Enables the purge feature.",
+ "Purge will remove all records from the plugin tables that are 'old' enough.")
+ .read(config);
+
+ int purgePeriod = ConfigValue.create(path + "For_Period", 60,
+ "Sets maximal 'age' for the database records before they will be purged.",
+ "This option may have different behavior depends on the plugin.",
+ "By default it's days of inactivity for the plugin users.")
+ .read(config);
+
+ return new DatabaseConfig(syncInterval,
+ databaseType, tablePrefix,
+ purgeEnabled, purgePeriod,
+
+ mysqlUser, mysqlPassword, mysqlHost, mysqlBase, urlOptions,
+
+ sqliteFilename
+ );
+ }
+
+ @NotNull
+ public DatabaseType getStorageType() {
+ return databaseType;
+ }
+
+ @NotNull
+ public String getTablePrefix() {
+ return tablePrefix;
+ }
+
+ public int getSyncInterval() {
+ return syncInterval;
+ }
+
+ public boolean isPurgeEnabled() {
+ return purgeEnabled;
+ }
+
+ public int getPurgePeriod() {
+ return purgePeriod;
+ }
+
+ @NotNull
+ public String getUsername() {
+ return username;
+ }
+
+ @NotNull
+ public String getPassword() {
+ return password;
+ }
+
+ @NotNull
+ public String getHost() {
+ return host;
+ }
+
+ @NotNull
+ public String getDatabase() {
+ return database;
+ }
+
+ @NotNull
+ public String getUrlOptions() {
+ return urlOptions;
+ }
+
+ @NotNull
+ public String getFilename() {
+ return filename;
+ }
+}
diff --git a/src/main/java/su/nightexpress/nightcore/db/config/DatabaseType.java b/src/main/java/su/nightexpress/nightcore/db/config/DatabaseType.java
new file mode 100644
index 0000000..0e7642a
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/db/config/DatabaseType.java
@@ -0,0 +1,7 @@
+package su.nightexpress.nightcore.db.config;
+
+public enum DatabaseType {
+
+ MYSQL,
+ SQLITE,
+}
diff --git a/src/main/java/su/nightexpress/nightcore/db/config/UserdataConfig.java b/src/main/java/su/nightexpress/nightcore/db/config/UserdataConfig.java
new file mode 100644
index 0000000..66f6302
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/db/config/UserdataConfig.java
@@ -0,0 +1,112 @@
+package su.nightexpress.nightcore.db.config;
+
+import org.jetbrains.annotations.NotNull;
+import su.nightexpress.nightcore.NightPlugin;
+import su.nightexpress.nightcore.config.ConfigValue;
+import su.nightexpress.nightcore.config.FileConfig;
+
+public class UserdataConfig {
+
+ private final long cacheLifetime;
+ private final int cacheCleanupInterval;
+
+ private final long saveInterval;
+ private final double saveDelay;
+ private final int saveSyncPause;
+
+ public UserdataConfig(long cacheLifetime, int cacheCleanupInterval, long saveInterval, double saveDelay, int saveSyncPause) {
+ this.cacheLifetime = cacheLifetime;
+ this.cacheCleanupInterval = cacheCleanupInterval;
+ this.saveInterval = saveInterval;
+ this.saveDelay = saveDelay;
+ this.saveSyncPause = saveSyncPause;
+ }
+
+ @NotNull
+ public static UserdataConfig read(@NotNull NightPlugin plugin) {
+ FileConfig config = plugin.getConfig();
+
+ long cacheLifetime = ConfigValue.create("Database.UserData.Cache.LifeTime",
+ 300L,
+ "Sets cache lifetime for player's data.",
+ "Data loaded for offline players and data of previously online players will be cached in the memory for that time.",
+ "When cache is expired, data have to be loaded from the database again.",
+ "[*] Set to 0 to disable data cache for offline players.",
+ "[*] Set to -1 for permanent data cache for offline players.",
+ "[Default is 300 (5 minutes)]"
+ ).read(config);
+
+ int cacheCleanupInterval = ConfigValue.create("Database.UserData.Cache.CleanUp_Interval",
+ 300,
+ "Sets how often (in seconds) plugin will clean up user data cache.",
+ "Cache contains data loaded for offline players and data of previously online players",
+ "[*] Set to -1 to disable cache clean up and keep user data loaded until reboot.",
+ "[Default is 300 (5 minutes)]"
+ ).read(config);
+
+ long saveInterval = ConfigValue.create("Database.UserData.Scheduled_Save_Interval",
+ 20L,
+ "Sets how often (in ticks) plugin will attempt to save data of users marked to be saved.",
+ "This will save only users that are 'ready' to save (see 'Scheduled_Save_Delay').",
+ "[DO NOT DISABLE UNDER ANY CIRCUMSTANCES!]",
+ "[20 ticks = 1 second]",
+ "[Default is 20]"
+ ).read(config);
+
+ double saveDelay = ConfigValue.create("Database.UserData.Scheduled_Save_Delay",
+ 1D,
+ "Sets scheduled save delay (in seconds) for a user when marked to be saved.",
+ "This means that a user will be saved X seconds later after being marked.",
+ "Generally, you should keep this value less than 'Scheduled_Save_Interval' for best results,",
+ "and not setting it extremely high, otherwise you may result in user data never saved & synchronized.",
+ "",
+ "IMPORTANT NOTE #1: When a user is marked for saving, this will prevent them from syncing until saving occurs!",
+ "IMPORTANT NOTE #2: Every time a user is marked for saving, their save time will be updated with this value!",
+ "",
+ "Users marked for save when their data has been changed/affected in some way.",
+ "However this is higly depends on the plugin.",
+ "[Decimals allowed]",
+ "[Default is 1]"
+ ).read(config);
+
+ int saveSyncPause = ConfigValue.create("Database.UserData.Scheduled_Save_Sync_Pause",
+ 3,
+ "Sets synchronization delay (in seconds) before the plugin can continue syncing data for a user after its scheduled save.",
+ "When a user marked for saving has been saved, their synchronization will be unlocked but delayed for this value.",
+ "This might be helpful to prevent possible issues when synchronization process access the database before user data was fully saved.",
+ "[Default is 3]"
+ ).read(config);
+
+
+ return new UserdataConfig(cacheLifetime, cacheCleanupInterval, saveInterval, saveDelay, saveSyncPause);
+ }
+
+ public long getCacheLifetime() {
+ return this.cacheLifetime;
+ }
+
+ public int getCacheCleanupInterval() {
+ return this.cacheCleanupInterval;
+ }
+
+ public long getSaveInterval() {
+ return this.saveInterval;
+ }
+
+ public double getSaveDelay() {
+ return this.saveDelay;
+ }
+
+ public int getSaveSyncPause() {
+ return this.saveSyncPause;
+ }
+
+ @Override
+ public String toString() {
+ return "UserdataConfig{" +
+ "scheduledSaveInterval=" + saveInterval +
+ ", scheduledSaveDelay=" + saveDelay +
+ ", scheduledSaveSyncPause=" + saveSyncPause +
+ '}';
+ }
+}
diff --git a/src/main/java/su/nightexpress/nightcore/db/connection/AbstractConnector.java b/src/main/java/su/nightexpress/nightcore/db/connection/AbstractConnector.java
new file mode 100644
index 0000000..7b9841b
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/db/connection/AbstractConnector.java
@@ -0,0 +1,50 @@
+package su.nightexpress.nightcore.db.connection;
+
+import com.zaxxer.hikari.HikariConfig;
+import com.zaxxer.hikari.HikariDataSource;
+import org.jetbrains.annotations.NotNull;
+import su.nightexpress.nightcore.NightPlugin;
+import su.nightexpress.nightcore.db.config.DatabaseConfig;
+import su.nightexpress.nightcore.db.config.DatabaseType;
+import su.nightexpress.nightcore.db.connection.impl.MySQLConnector;
+import su.nightexpress.nightcore.db.connection.impl.SQLiteConnector;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+
+public abstract class AbstractConnector {
+
+ protected final NightPlugin plugin;
+ protected final HikariConfig config;
+ protected final HikariDataSource dataSource;
+
+ public AbstractConnector(@NotNull NightPlugin plugin, @NotNull DatabaseConfig config) {
+ this.plugin = plugin;
+
+ this.config = new HikariConfig();
+ this.config.setJdbcUrl(this.getURL(config));
+ this.setupConfig(config);
+ this.config.addDataSourceProperty("cachePrepStmts", "true");
+ this.config.addDataSourceProperty("prepStmtCacheSize", "250");
+ this.config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
+ this.dataSource = new HikariDataSource(this.config);
+ }
+
+ @NotNull
+ public static AbstractConnector create(@NotNull NightPlugin plugin, @NotNull DatabaseConfig config) {
+ return config.getStorageType() == DatabaseType.SQLITE ? new SQLiteConnector(plugin, config) : new MySQLConnector(plugin, config);
+ }
+
+ protected abstract String getURL(@NotNull DatabaseConfig config);
+
+ protected abstract void setupConfig(@NotNull DatabaseConfig config);
+
+ public void close() {
+ this.dataSource.close();
+ }
+
+ @NotNull
+ public final Connection getConnection() throws SQLException {
+ return this.dataSource.getConnection();
+ }
+}
diff --git a/src/main/java/su/nightexpress/nightcore/db/connection/impl/MySQLConnector.java b/src/main/java/su/nightexpress/nightcore/db/connection/impl/MySQLConnector.java
new file mode 100644
index 0000000..5774455
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/db/connection/impl/MySQLConnector.java
@@ -0,0 +1,28 @@
+package su.nightexpress.nightcore.db.connection.impl;
+
+import org.jetbrains.annotations.NotNull;
+import su.nightexpress.nightcore.NightPlugin;
+import su.nightexpress.nightcore.db.config.DatabaseConfig;
+import su.nightexpress.nightcore.db.connection.AbstractConnector;
+
+public class MySQLConnector extends AbstractConnector {
+
+ public MySQLConnector(@NotNull NightPlugin plugin, @NotNull DatabaseConfig config) {
+ super(plugin, config);
+ }
+
+ @Override
+ protected String getURL(@NotNull DatabaseConfig config) {
+ String host = config.getHost();
+ String database = config.getDatabase();
+ String options = config.getUrlOptions();
+
+ return "jdbc:mysql://" + host + "/" + database + options;
+ }
+
+ @Override
+ protected void setupConfig(@NotNull DatabaseConfig config) {
+ this.config.setUsername(config.getUsername());
+ this.config.setPassword(config.getPassword());
+ }
+}
diff --git a/src/main/java/su/nightexpress/nightcore/db/connection/impl/SQLiteConnector.java b/src/main/java/su/nightexpress/nightcore/db/connection/impl/SQLiteConnector.java
new file mode 100644
index 0000000..781d002
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/db/connection/impl/SQLiteConnector.java
@@ -0,0 +1,24 @@
+package su.nightexpress.nightcore.db.connection.impl;
+
+import org.jetbrains.annotations.NotNull;
+import su.nightexpress.nightcore.NightPlugin;
+import su.nightexpress.nightcore.db.config.DatabaseConfig;
+import su.nightexpress.nightcore.db.connection.AbstractConnector;
+
+public class SQLiteConnector extends AbstractConnector {
+
+ public SQLiteConnector(@NotNull NightPlugin plugin, @NotNull DatabaseConfig config) {
+ super(plugin, config);
+ }
+
+ @Override
+ protected String getURL(@NotNull DatabaseConfig config) {
+ String filePath = plugin.getDataFolder().getAbsolutePath() + "/" + config.getFilename();
+ return "jdbc:sqlite:" + filePath;
+ }
+
+ @Override
+ protected void setupConfig(@NotNull DatabaseConfig config) {
+ this.config.setMaximumPoolSize(1);
+ }
+}
diff --git a/src/main/java/su/nightexpress/nightcore/db/listener/UserListener.java b/src/main/java/su/nightexpress/nightcore/db/listener/UserListener.java
new file mode 100644
index 0000000..d4e4155
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/db/listener/UserListener.java
@@ -0,0 +1,50 @@
+package su.nightexpress.nightcore.db.listener;
+
+import org.bukkit.event.EventHandler;
+import org.bukkit.event.EventPriority;
+import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
+import org.bukkit.event.player.PlayerJoinEvent;
+import org.bukkit.event.player.PlayerQuitEvent;
+import org.jetbrains.annotations.NotNull;
+import su.nightexpress.nightcore.NightPlugin;
+import su.nightexpress.nightcore.db.AbstractUser;
+import su.nightexpress.nightcore.db.AbstractUserManager;
+import su.nightexpress.nightcore.manager.AbstractListener;
+
+import java.util.UUID;
+
+public class UserListener extends AbstractListener
{
+
+ private final AbstractUserManager
manager;
+
+ public UserListener(@NotNull P plugin, @NotNull AbstractUserManager
manager) {
+ super(plugin);
+ this.manager = manager;
+ }
+
+ @EventHandler(priority = EventPriority.MONITOR)
+ public void onUserLogin(AsyncPlayerPreLoginEvent event) {
+ if (event.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) return;
+
+ UUID uuid = event.getUniqueId();
+ if (!this.manager.isInDatabase(uuid)) {
+ U user = this.manager.create(uuid, event.getName());
+ this.manager.addInDatabase(user);
+ this.manager.cacheTemporary(user);
+ //this.plugin.debug("Created new data for: '" + uuid + "'");
+ return;
+ }
+
+ this.manager.getOrFetch(uuid); // Fetch and cache temporary.
+ }
+
+ @EventHandler(priority = EventPriority.MONITOR)
+ public void onUserQuit(PlayerJoinEvent event) {
+ this.manager.handleJoin(event.getPlayer()); // Get loaded and cache permanent.
+ }
+
+ @EventHandler(priority = EventPriority.MONITOR)
+ public void onUserQuit(PlayerQuitEvent event) {
+ this.manager.handleQuit(event.getPlayer()); // Get loaded and cache temporary.
+ }
+}
diff --git a/src/main/java/su/nightexpress/nightcore/db/sql/column/Column.java b/src/main/java/su/nightexpress/nightcore/db/sql/column/Column.java
new file mode 100644
index 0000000..cec6be3
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/db/sql/column/Column.java
@@ -0,0 +1,57 @@
+package su.nightexpress.nightcore.db.sql.column;
+
+import org.jetbrains.annotations.NotNull;
+import su.nightexpress.nightcore.db.config.DatabaseType;
+import su.nightexpress.nightcore.db.sql.util.SQLUtils;
+
+public class Column {
+
+ private final String name;
+ private final ColumnType type;
+ private final int length;
+
+ public Column(@NotNull String name, @NotNull ColumnType type, int length) {
+ this.name = name;
+ this.type = type;
+ this.length = length;
+ }
+
+ @NotNull
+ public String formatType(@NotNull DatabaseType databaseType) {
+ return this.type.build(databaseType, this.length);
+ }
+
+ @NotNull
+ public static Column of(@NotNull String name, @NotNull ColumnType type) {
+ return Column.of(name, type, -1);
+ }
+
+ @NotNull
+ public static Column of(@NotNull String name, @NotNull ColumnType type, int length) {
+ return new Column(name, type, length);
+ }
+
+ @NotNull
+ public String getName() {
+ return this.name;
+ }
+
+ @NotNull
+ public String getNameEscaped() {
+ return SQLUtils.escape(this.name);
+ }
+
+ @NotNull
+ public String getNameLowercase() {
+ return "LOWER(" + this.name + ")";
+ }
+
+ @NotNull
+ public ColumnType getType() {
+ return this.type;
+ }
+
+ public int getLength() {
+ return this.length;
+ }
+}
diff --git a/src/main/java/su/nightexpress/nightcore/db/sql/column/ColumnType.java b/src/main/java/su/nightexpress/nightcore/db/sql/column/ColumnType.java
new file mode 100644
index 0000000..e468216
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/db/sql/column/ColumnType.java
@@ -0,0 +1,35 @@
+package su.nightexpress.nightcore.db.sql.column;
+
+import org.jetbrains.annotations.NotNull;
+import su.nightexpress.nightcore.db.config.DatabaseType;
+
+public interface ColumnType {
+
+ ColumnType STRING = (type, length) -> {
+ if (length < 1 || type == DatabaseType.SQLITE) {
+ return type == DatabaseType.SQLITE ? "TEXT NOT NULL" : "MEDIUMTEXT NOT NULL";
+ }
+ return "varchar(" + length + ") CHARACTER SET utf8 NOT NULL";
+ };
+
+ ColumnType INTEGER = (type, length) -> {
+ if (length < 1 || type == DatabaseType.SQLITE) {
+ return "INTEGER NOT NULL";
+ }
+ return "int(" + length + ") NOT NULL";
+ };
+
+ ColumnType DOUBLE = (type, length) -> {
+ return type == DatabaseType.SQLITE ? "REAL NOT NULL" : "double NOT NULL";
+ };
+
+ ColumnType LONG = (type, length) -> {
+ return length < 1 || type == DatabaseType.SQLITE ? "BIGINT NOT NULL" : "bigint(" + length + ") NOT NULL";
+ };
+
+ ColumnType BOOLEAN = (type, length) -> {
+ return type == DatabaseType.SQLITE ? "INTEGER NOT NULL" : "tinyint(1) NOT NULL";
+ };
+
+ @NotNull String build(@NotNull DatabaseType type, int length);
+}
diff --git a/src/main/java/su/nightexpress/nightcore/db/sql/query/QueryValue.java b/src/main/java/su/nightexpress/nightcore/db/sql/query/QueryValue.java
new file mode 100644
index 0000000..dc16c86
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/db/sql/query/QueryValue.java
@@ -0,0 +1,31 @@
+package su.nightexpress.nightcore.db.sql.query;
+
+import org.jetbrains.annotations.NotNull;
+
+import java.util.function.Function;
+
+public class QueryValue {
+
+ private final String sqlPart;
+ private final Function statementPart;
+
+ public QueryValue(String sqlPart, Function statementPart) {
+ this.sqlPart = sqlPart;
+ this.statementPart = statementPart;
+ }
+
+ @NotNull
+ public String getSQLPart() {
+ return this.sqlPart;
+ }
+
+ @NotNull
+ public String getStatementPart(T entity) {
+ return this.statementPart.apply(entity);
+ }
+
+ @NotNull
+ public Function getStatementPart() {
+ return this.statementPart;
+ }
+}
diff --git a/src/main/java/su/nightexpress/nightcore/db/sql/query/SQLQueries.java b/src/main/java/su/nightexpress/nightcore/db/sql/query/SQLQueries.java
new file mode 100644
index 0000000..ea499b5
--- /dev/null
+++ b/src/main/java/su/nightexpress/nightcore/db/sql/query/SQLQueries.java
@@ -0,0 +1,200 @@
+package su.nightexpress.nightcore.db.sql.query;
+
+import org.jetbrains.annotations.NotNull;
+import su.nightexpress.nightcore.db.config.DatabaseType;
+import su.nightexpress.nightcore.db.connection.AbstractConnector;
+import su.nightexpress.nightcore.db.connection.impl.SQLiteConnector;
+import su.nightexpress.nightcore.db.sql.column.Column;
+import su.nightexpress.nightcore.db.sql.column.ColumnType;
+import su.nightexpress.nightcore.db.sql.query.type.AbstractQuery;
+import su.nightexpress.nightcore.db.sql.query.impl.SelectQuery;
+import su.nightexpress.nightcore.db.sql.util.SQLUtils;
+import su.nightexpress.nightcore.util.Lists;
+
+import java.sql.*;
+import java.util.*;
+import java.util.stream.Collectors;
+
+public class SQLQueries {
+
+ public static boolean hasTable(@NotNull AbstractConnector connector, @NotNull String table) {
+ try (Connection connection = connector.getConnection()) {
+
+ boolean has;
+ DatabaseMetaData metaData = connection.getMetaData();
+ ResultSet tables = metaData.getTables(null, null, table, null);
+ has = tables.next();
+ tables.close();
+ return has;
+ }
+ catch (SQLException exception) {
+ exception.printStackTrace();
+ return false;
+ }
+ }
+
+ public static boolean hasColumn(@NotNull AbstractConnector connector, @NotNull String table, @NotNull Column column) {
+ return hasColumn(connector, table, column.getName());
+ }
+
+ public static boolean hasColumn(@NotNull AbstractConnector connector, @NotNull String table, @NotNull String columnName) {
+ String sql = "SELECT * FROM " + table;
+ try (Connection connection = connector.getConnection();
+ Statement statement = connection.createStatement()) {
+
+ ResultSet resultSet = statement.executeQuery(sql);
+ ResultSetMetaData metaData = resultSet.getMetaData();
+ int columns = metaData.getColumnCount();
+ for (int index = 1; index <= columns; index++) {
+ if (columnName.equals(metaData.getColumnName(index))) {
+ return true;
+ }
+ }
+ return false;
+ }
+ catch (SQLException exception) {
+ exception.printStackTrace();
+ return false;
+ }
+ }
+
+ public static void addColumn(@NotNull AbstractConnector connector,
+ @NotNull DatabaseType type,
+ @NotNull String table,
+ @NotNull Column column,
+ @NotNull String defVal) {
+ if (SQLQueries.hasColumn(connector, table, column)) return;
+
+ StringBuilder builder = new StringBuilder()
+ .append("ALTER TABLE ").append(table).append(" ADD ")
+ .append(column.getName()).append(" ").append(column.formatType(type));
+
+ if (connector instanceof SQLiteConnector || column.getType() != ColumnType.STRING) {
+ builder.append(" DEFAULT ").append("'").append(defVal).append("'");
+ }
+
+ SQLQueries.executeSimpleQuery(connector, builder.toString());
+ }
+
+ public static void renameColumn(@NotNull AbstractConnector connector, @NotNull String table, @NotNull Column column, @NotNull String toName) {
+ renameColumn(connector, table, column.getName(), toName);
+ }
+
+ public static void renameColumn(@NotNull AbstractConnector connector, @NotNull String table, @NotNull String columnName, @NotNull String toName) {
+ if (!SQLQueries.hasColumn(connector, table, columnName)) return;
+
+ String sql = "ALTER TABLE " + table + " RENAME COLUMN " + columnName + " TO " + toName;
+
+ SQLQueries.executeSimpleQuery(connector, sql);
+ }
+
+ public static void dropColumn(@NotNull AbstractConnector connector, @NotNull String table, @NotNull Column column) {
+ dropColumn(connector, table, column.getName());
+ }
+
+ public static void dropColumn(@NotNull AbstractConnector connector, @NotNull String table, @NotNull String columnName) {
+ if (!SQLQueries.hasColumn(connector, table, columnName)) return;
+
+ String sql = "ALTER TABLE " + table + " DROP COLUMN " + columnName;
+
+ SQLQueries.executeSimpleQuery(connector, sql);
+ }
+
+ public static void createTable(@NotNull AbstractConnector connector, @NotNull DatabaseType type, @NotNull String table, @NotNull List columns) {
+ if (columns.isEmpty()) return;
+
+ StringBuilder idBuilder = new StringBuilder(SQLUtils.escape("id")).append(" ").append(ColumnType.INTEGER.build(type, 11));
+
+ if (type == DatabaseType.SQLITE) {
+ idBuilder.append(" PRIMARY KEY AUTOINCREMENT");
+ }
+ else {
+ idBuilder.append(" PRIMARY KEY AUTO_INCREMENT");
+ }
+
+ String columnNames = columns.stream()
+ .map(column -> column.getNameEscaped() + " " + column.formatType(type)).collect(Collectors.joining(", "));
+
+ String allColumns = idBuilder + ", " + columnNames;
+
+ String sql = "CREATE TABLE IF NOT EXISTS " + table + "(" + allColumns + ");";
+
+ SQLQueries.executeSimpleQuery(connector, sql);
+ }
+
+ public static void renameTable(@NotNull AbstractConnector connector, @NotNull DatabaseType type, @NotNull String table, @NotNull String toName) {
+ if (!SQLQueries.hasTable(connector, table)) return;
+
+ StringBuilder sql = new StringBuilder();
+ if (type == DatabaseType.MYSQL) {
+ sql.append("RENAME TABLE ").append(table).append(" TO ").append(toName).append(";");
+ }
+ else {
+ sql.append("ALTER TABLE ").append(table).append(" RENAME TO ").append(toName);
+ }
+ SQLQueries.executeSimpleQuery(connector, sql.toString());
+ }
+
+ public static void executeSimpleQuery(@NotNull AbstractConnector connector, @NotNull String sql) {
+ try (Connection connection = connector.getConnection();
+ PreparedStatement statement = connection.prepareStatement(sql)) {
+
+ //System.out.println("simpleQuery: " + statement.toString());
+
+ statement.executeUpdate();
+ }
+ catch (SQLException exception) {
+ exception.printStackTrace();
+ }
+ }
+
+ public static