Commit d7328dda authored by KingRainbow44's avatar KingRainbow44
Browse files

Update Morphia to 2.x

parent 1be01b52
...@@ -14,17 +14,16 @@ plugins { ...@@ -14,17 +14,16 @@ plugins {
id 'application' id 'application'
} }
sourceCompatibility = 1.8 sourceCompatibility = 17
targetCompatibility = 1.8 targetCompatibility = 17
repositories { repositories {
mavenCentral() mavenCentral()
jcenter()
} }
dependencies { dependencies {
implementation fileTree(dir: 'lib', include: ['*.jar']) implementation fileTree(dir: 'lib', include: ['*.jar'])
implementation group: 'org.slf4j', name: 'slf4j-api', version: '1.7.32' implementation group: 'org.slf4j', name: 'slf4j-api', version: '1.7.32'
implementation group: 'ch.qos.logback', name: 'logback-core', version: '1.2.6' implementation group: 'ch.qos.logback', name: 'logback-core', version: '1.2.6'
implementation group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.6' implementation group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.6'
...@@ -33,9 +32,9 @@ dependencies { ...@@ -33,9 +32,9 @@ dependencies {
implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.8' implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.8'
implementation group: 'com.google.protobuf', name: 'protobuf-java', version: '3.18.1' implementation group: 'com.google.protobuf', name: 'protobuf-java', version: '3.18.1'
implementation group: 'org.reflections', name: 'reflections', version: '0.9.12' implementation group: 'org.reflections', name: 'reflections', version: '0.10.2'
implementation group: 'dev.morphia.morphia', name: 'core', version: '1.6.1' implementation group: 'dev.morphia.morphia', name: 'morphia-core', version: '2.2.6'
implementation group: 'org.greenrobot', name: 'eventbus-java', version: '3.3.1' implementation group: 'org.greenrobot', name: 'eventbus-java', version: '3.3.1'
} }
......
...@@ -3,7 +3,7 @@ package emu.grasscutter.database; ...@@ -3,7 +3,7 @@ package emu.grasscutter.database;
import dev.morphia.annotations.Entity; import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Id; import dev.morphia.annotations.Id;
@Entity(value = "counters", noClassnameStored = true) @Entity(value = "counters", useDiscriminator = false)
public class DatabaseCounter { public class DatabaseCounter {
@Id @Id
private String id; private String id;
......
...@@ -2,41 +2,33 @@ package emu.grasscutter.database; ...@@ -2,41 +2,33 @@ package emu.grasscutter.database;
import java.util.List; import java.util.List;
import com.mongodb.WriteResult; import com.mongodb.client.result.DeleteResult;
import dev.morphia.query.experimental.filters.Filters;
import dev.morphia.query.FindOptions;
import dev.morphia.query.Query;
import dev.morphia.query.internal.MorphiaCursor;
import emu.grasscutter.GenshinConstants; import emu.grasscutter.GenshinConstants;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.game.Account; import emu.grasscutter.game.Account;
import emu.grasscutter.game.GenshinPlayer; import emu.grasscutter.game.GenshinPlayer;
import emu.grasscutter.game.avatar.GenshinAvatar; import emu.grasscutter.game.avatar.GenshinAvatar;
import emu.grasscutter.game.friends.Friendship; import emu.grasscutter.game.friends.Friendship;
import emu.grasscutter.game.inventory.GenshinItem; import emu.grasscutter.game.inventory.GenshinItem;
public class DatabaseHelper { public final class DatabaseHelper {
protected static FindOptions FIND_ONE = new FindOptions().limit(1);
public static Account createAccount(String username) { public static Account createAccount(String username) {
return createAccountWithId(username, 0); return createAccountWithId(username, 0);
} }
public static Account createAccountWithId(String username, int reservedId) { public static Account createAccountWithId(String username, int reservedId) {
// Unique names only // Unique names only
Account exists = DatabaseHelper.getAccountByName(username); Account exists = DatabaseHelper.getAccountByName(username);
if (exists != null) { if (exists != null) {
return null; return null;
} }
// Make sure there are no id collisions // Make sure there are no id collisions
if (reservedId > 0) { if (reservedId > 0) {
// Cannot make account with the same uid as the server console // Cannot make account with the same uid as the server console
if (reservedId == GenshinConstants.SERVER_CONSOLE_UID) { if (reservedId == GenshinConstants.SERVER_CONSOLE_UID) {
return null; return null;
} }
exists = DatabaseHelper.getAccountByPlayerId(reservedId); exists = DatabaseHelper.getAccountByPlayerId(reservedId);
if (exists != null) { if (exists != null) {
return null; return null;
...@@ -47,10 +39,10 @@ public class DatabaseHelper { ...@@ -47,10 +39,10 @@ public class DatabaseHelper {
Account account = new Account(); Account account = new Account();
account.setUsername(username); account.setUsername(username);
account.setId(Integer.toString(DatabaseManager.getNextId(account))); account.setId(Integer.toString(DatabaseManager.getNextId(account)));
if (reservedId > 0) { if (reservedId > 0) {
account.setPlayerId(reservedId); account.setPlayerId(reservedId);
} }
DatabaseHelper.saveAccount(account); DatabaseHelper.saveAccount(account);
return account; return account;
...@@ -63,65 +55,52 @@ public class DatabaseHelper { ...@@ -63,65 +55,52 @@ public class DatabaseHelper {
if (exists != null) { if (exists != null) {
return null; return null;
} }
// Account // Account
Account account = new Account(); Account account = new Account();
account.setId(Integer.toString(DatabaseManager.getNextId(account))); account.setId(Integer.toString(DatabaseManager.getNextId(account)));
account.setUsername(username); account.setUsername(username);
account.setPassword(password); account.setPassword(password);
DatabaseHelper.saveAccount(account); DatabaseHelper.saveAccount(account);
return account; return account;
} }
public static void saveAccount(Account account) { public static void saveAccount(Account account) {
DatabaseManager.getDatastore().save(account); DatabaseManager.getDatastore().save(account);
} }
public static Account getAccountByName(String username) { public static Account getAccountByName(String username) {
MorphiaCursor<Account> cursor = DatabaseManager.getDatastore().createQuery(Account.class).field("username").equalIgnoreCase(username).find(FIND_ONE); return DatabaseManager.getDatastore().find(Account.class).filter(Filters.eq("username", username)).first();
if (!cursor.hasNext()) return null;
return cursor.next();
} }
public static Account getAccountByToken(String token) { public static Account getAccountByToken(String token) {
if (token == null) return null; if(token == null) return null;
MorphiaCursor<Account> cursor = DatabaseManager.getDatastore().createQuery(Account.class).field("token").equal(token).find(FIND_ONE); return DatabaseManager.getDatastore().find(Account.class).filter(Filters.eq("token", token)).first();
if (!cursor.hasNext()) return null;
return cursor.next();
} }
public static Account getAccountById(String uid) { public static Account getAccountById(String uid) {
MorphiaCursor<Account> cursor = DatabaseManager.getDatastore().createQuery(Account.class).field("_id").equal(uid).find(FIND_ONE); return DatabaseManager.getDatastore().find(Account.class).filter(Filters.eq("_id", uid)).first();
if (!cursor.hasNext()) return null;
return cursor.next();
} }
public static Account getAccountByPlayerId(int playerId) { public static Account getAccountByPlayerId(int playerId) {
MorphiaCursor<Account> cursor = DatabaseManager.getDatastore().createQuery(Account.class).field("playerId").equal(playerId).find(FIND_ONE); return DatabaseManager.getDatastore().find(Account.class).filter(Filters.eq("playerId", playerId)).first();
if (!cursor.hasNext()) return null;
return cursor.next();
} }
public static boolean deleteAccount(String username) { public static boolean deleteAccount(String username) {
Query<Account> q = DatabaseManager.getDatastore().createQuery(Account.class).field("username").equalIgnoreCase(username); return DatabaseManager.getDatastore().find(Account.class).filter(Filters.eq("username", username)).delete().getDeletedCount() > 0;
return DatabaseManager.getDatastore().findAndDelete(q) != null;
} }
public static GenshinPlayer getPlayerById(int id) { public static GenshinPlayer getPlayerById(int id) {
Query<GenshinPlayer> query = DatabaseManager.getDatastore().createQuery(GenshinPlayer.class).field("_id").equal(id); return DatabaseManager.getDatastore().find(GenshinPlayer.class).filter(Filters.eq("_id", id)).first();
MorphiaCursor<GenshinPlayer> cursor = query.find(FIND_ONE);
if (!cursor.hasNext()) return null;
return cursor.next();
} }
public static boolean checkPlayerExists(int id) { public static boolean checkPlayerExists(int id) {
MorphiaCursor<GenshinPlayer> query = DatabaseManager.getDatastore().createQuery(GenshinPlayer.class).field("_id").equal(id).find(FIND_ONE); return DatabaseManager.getDatastore().find(GenshinPlayer.class).filter(Filters.eq("_id", id)).first() != null;
return query.hasNext();
} }
public static synchronized GenshinPlayer createPlayer(GenshinPlayer character, int reservedId) { public static synchronized GenshinPlayer createPlayer(GenshinPlayer character, int reservedId) {
// Check if reserved id // Check if reserved id
int id = 0; int id;
if (reservedId > 0 && !checkPlayerExists(reservedId)) { if (reservedId > 0 && !checkPlayerExists(reservedId)) {
id = reservedId; id = reservedId;
character.setUid(id); character.setUid(id);
...@@ -136,10 +115,10 @@ public class DatabaseHelper { ...@@ -136,10 +115,10 @@ public class DatabaseHelper {
DatabaseManager.getDatastore().save(character); DatabaseManager.getDatastore().save(character);
return character; return character;
} }
public static synchronized int getNextPlayerId(int reservedId) { public static synchronized int getNextPlayerId(int reservedId) {
// Check if reserved id // Check if reserved id
int id = 0; int id;
if (reservedId > 0 && !checkPlayerExists(reservedId)) { if (reservedId > 0 && !checkPlayerExists(reservedId)) {
id = reservedId; id = reservedId;
} else { } else {
...@@ -150,41 +129,37 @@ public class DatabaseHelper { ...@@ -150,41 +129,37 @@ public class DatabaseHelper {
} }
return id; return id;
} }
public static void savePlayer(GenshinPlayer character) { public static void savePlayer(GenshinPlayer character) {
DatabaseManager.getDatastore().save(character); DatabaseManager.getDatastore().save(character);
} }
public static void saveAvatar(GenshinAvatar avatar) { public static void saveAvatar(GenshinAvatar avatar) {
DatabaseManager.getDatastore().save(avatar); DatabaseManager.getDatastore().save(avatar);
} }
public static List<GenshinAvatar> getAvatars(GenshinPlayer player) { public static List<GenshinAvatar> getAvatars(GenshinPlayer player) {
Query<GenshinAvatar> query = DatabaseManager.getDatastore().createQuery(GenshinAvatar.class).filter("ownerId", player.getUid()); return DatabaseManager.getDatastore().find(GenshinAvatar.class).filter(Filters.eq("playerId", player.getUid())).stream().toList();
return query.find().toList();
} }
public static void saveItem(GenshinItem item) { public static void saveItem(GenshinItem item) {
DatabaseManager.getDatastore().save(item); DatabaseManager.getDatastore().save(item);
} }
public static boolean deleteItem(GenshinItem item) { public static boolean deleteItem(GenshinItem item) {
WriteResult result = DatabaseManager.getDatastore().delete(item); DeleteResult result = DatabaseManager.getDatastore().delete(item);
return result.wasAcknowledged(); return result.wasAcknowledged();
} }
public static List<GenshinItem> getInventoryItems(GenshinPlayer player) { public static List<GenshinItem> getInventoryItems(GenshinPlayer player) {
Query<GenshinItem> query = DatabaseManager.getDatastore().createQuery(GenshinItem.class).filter("ownerId", player.getUid()); return DatabaseManager.getDatastore().find(GenshinItem.class).filter(Filters.eq("ownerId", player.getUid())).stream().toList();
return query.find().toList();
} }
public static List<Friendship> getFriends(GenshinPlayer player) { public static List<Friendship> getFriends(GenshinPlayer player) {
Query<Friendship> query = DatabaseManager.getDatastore().createQuery(Friendship.class).filter("ownerId", player.getUid()); return DatabaseManager.getDatastore().find(Friendship.class).filter(Filters.eq("playerId", player.getUid())).stream().toList();
return query.find().toList();
} }
public static List<Friendship> getReverseFriends(GenshinPlayer player) { public static List<Friendship> getReverseFriends(GenshinPlayer player) {
Query<Friendship> query = DatabaseManager.getDatastore().createQuery(Friendship.class).filter("friendId", player.getUid()); return DatabaseManager.getDatastore().find(Friendship.class).filter(Filters.eq("friendId", player.getUid())).stream().toList();
return query.find().toList();
} }
public static void saveFriendship(Friendship friendship) { public static void saveFriendship(Friendship friendship) {
...@@ -196,13 +171,9 @@ public class DatabaseHelper { ...@@ -196,13 +171,9 @@ public class DatabaseHelper {
} }
public static Friendship getReverseFriendship(Friendship friendship) { public static Friendship getReverseFriendship(Friendship friendship) {
Query<Friendship> query = DatabaseManager.getDatastore().createQuery(Friendship.class); return DatabaseManager.getDatastore().find(Friendship.class).filter(Filters.and(
query.and( Filters.eq("ownerId", friendship.getFriendId()),
query.criteria("ownerId").equal(friendship.getFriendId()), Filters.eq("friendId", friendship.getOwnerId())
query.criteria("friendId").equal(friendship.getOwnerId()) )).first();
);
MorphiaCursor<Friendship> reverseFriendship = query.find(FIND_ONE);
if (!reverseFriendship.hasNext()) return null;
return reverseFriendship.next();
} }
} }
package emu.grasscutter.database; package emu.grasscutter.database;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoCommandException; import com.mongodb.MongoCommandException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable; import com.mongodb.client.MongoIterable;
import dev.morphia.Datastore; import dev.morphia.Datastore;
import dev.morphia.Morphia; import dev.morphia.Morphia;
import dev.morphia.mapping.MapperOptions;
import dev.morphia.query.experimental.filters.Filters;
import emu.grasscutter.Grasscutter; import emu.grasscutter.Grasscutter;
import emu.grasscutter.game.Account; import emu.grasscutter.game.Account;
import emu.grasscutter.game.GenshinPlayer; import emu.grasscutter.game.GenshinPlayer;
...@@ -23,10 +25,6 @@ public final class DatabaseManager { ...@@ -23,10 +25,6 @@ public final class DatabaseManager {
DatabaseCounter.class, Account.class, GenshinPlayer.class, GenshinAvatar.class, GenshinItem.class, Friendship.class DatabaseCounter.class, Account.class, GenshinPlayer.class, GenshinAvatar.class, GenshinItem.class, Friendship.class
}; };
public static MongoClient getMongoClient() {
return mongoClient;
}
public static Datastore getDatastore() { public static Datastore getDatastore() {
return datastore; return datastore;
} }
...@@ -37,27 +35,23 @@ public final class DatabaseManager { ...@@ -37,27 +35,23 @@ public final class DatabaseManager {
public static void initialize() { public static void initialize() {
// Initialize // Initialize
mongoClient = new MongoClient(new MongoClientURI(Grasscutter.getConfig().DatabaseUrl)); mongoClient = MongoClients.create(Grasscutter.getConfig().DatabaseUrl);
Morphia morphia = new Morphia();
// TODO Update when migrating to Morphia 2.0
morphia.getMapper().getOptions().setStoreEmpties(true);
morphia.getMapper().getOptions().setStoreNulls(false);
morphia.getMapper().getOptions().setDisableEmbeddedIndexes(true);
// Map
morphia.map(mappedClasses);
// Build datastore // Set mapper options.
datastore = morphia.createDatastore(mongoClient, Grasscutter.getConfig().DatabaseCollection); MapperOptions mapperOptions = MapperOptions.builder()
.storeEmpties(true).storeNulls(false).build();
// Create data store.
datastore = Morphia.createDatastore(mongoClient, Grasscutter.getConfig().DatabaseCollection, mapperOptions);
// Map classes.
datastore.getMapper().map(mappedClasses);
// Ensure indexes // Ensure indexes
try { try {
datastore.ensureIndexes(); datastore.ensureIndexes();
} catch (MongoCommandException e) { } catch (MongoCommandException exception) {
Grasscutter.getLogger().info("Mongo index error: ", e); Grasscutter.getLogger().info("Mongo index error: ", exception);
// Duplicate index error // Duplicate index error
if (e.getCode() == 85) { if (exception.getCode() == 85) {
// Drop all indexes and re add them // Drop all indexes and re add them
MongoIterable<String> collections = datastore.getDatabase().listCollectionNames(); MongoIterable<String> collections = datastore.getDatabase().listCollectionNames();
for (String name : collections) { for (String name : collections) {
...@@ -68,9 +62,9 @@ public final class DatabaseManager { ...@@ -68,9 +62,9 @@ public final class DatabaseManager {
} }
} }
} }
public static synchronized int getNextId(Class<?> c) { public static synchronized int getNextId(Class<?> c) {
DatabaseCounter counter = getDatastore().createQuery(DatabaseCounter.class).field("_id").equal(c.getSimpleName()).find().tryNext(); DatabaseCounter counter = getDatastore().find(DatabaseCounter.class).filter(Filters.eq("_id", c.getName())).first();
if (counter == null) { if (counter == null) {
counter = new DatabaseCounter(c.getSimpleName()); counter = new DatabaseCounter(c.getSimpleName());
} }
...@@ -80,7 +74,7 @@ public final class DatabaseManager { ...@@ -80,7 +74,7 @@ public final class DatabaseManager {
getDatastore().save(counter); getDatastore().save(counter);
} }
} }
public static synchronized int getNextId(Object o) { public static synchronized int getNextId(Object o) {
return getNextId(o.getClass()); return getNextId(o.getClass());
} }
......
...@@ -15,7 +15,7 @@ import java.util.List; ...@@ -15,7 +15,7 @@ import java.util.List;
import com.mongodb.DBObject; import com.mongodb.DBObject;
@Entity(value = "accounts", noClassnameStored = true) @Entity(value = "accounts", useDiscriminator = false)
public class Account { public class Account {
@Id private String id; @Id private String id;
......
...@@ -58,7 +58,7 @@ import emu.grasscutter.utils.Position; ...@@ -58,7 +58,7 @@ import emu.grasscutter.utils.Position;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
@Entity(value = "players", noClassnameStored = true) @Entity(value = "players", useDiscriminator = false)
public class GenshinPlayer { public class GenshinPlayer {
@Id private int id; @Id private int id;
@Indexed(options = @IndexOptions(unique = true)) private String accountId; @Indexed(options = @IndexOptions(unique = true)) private String accountId;
......
...@@ -50,7 +50,7 @@ import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; ...@@ -50,7 +50,7 @@ import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
@Entity(value = "avatars", noClassnameStored = true) @Entity(value = "avatars", useDiscriminator = false)
public class GenshinAvatar { public class GenshinAvatar {
@Id private ObjectId id; @Id private ObjectId id;
@Indexed private int ownerId; // Id of player that this avatar belongs to @Indexed private int ownerId; // Id of player that this avatar belongs to
......
...@@ -9,7 +9,7 @@ import emu.grasscutter.net.proto.FriendBriefOuterClass.FriendBrief; ...@@ -9,7 +9,7 @@ import emu.grasscutter.net.proto.FriendBriefOuterClass.FriendBrief;
import emu.grasscutter.net.proto.FriendOnlineStateOuterClass.FriendOnlineState; import emu.grasscutter.net.proto.FriendOnlineStateOuterClass.FriendOnlineState;
import emu.grasscutter.net.proto.HeadImageOuterClass.HeadImage; import emu.grasscutter.net.proto.HeadImageOuterClass.HeadImage;
@Entity(value = "friendships", noClassnameStored = true) @Entity(value = "friendships", useDiscriminator = false)
public class Friendship { public class Friendship {
@Id private ObjectId id; @Id private ObjectId id;
......
...@@ -34,7 +34,7 @@ import emu.grasscutter.net.proto.SceneWeaponInfoOuterClass.SceneWeaponInfo; ...@@ -34,7 +34,7 @@ import emu.grasscutter.net.proto.SceneWeaponInfoOuterClass.SceneWeaponInfo;
import emu.grasscutter.net.proto.WeaponOuterClass.Weapon; import emu.grasscutter.net.proto.WeaponOuterClass.Weapon;
import emu.grasscutter.utils.WeightedList; import emu.grasscutter.utils.WeightedList;
@Entity(value = "items", noClassnameStored = true) @Entity(value = "items", useDiscriminator = false)
public class GenshinItem { public class GenshinItem {
@Id private ObjectId id; @Id private ObjectId id;
@Indexed private int ownerId; @Indexed private int ownerId;
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment