From 86e728b7533e38d34fd56f7c76b9ba7c75c9434e Mon Sep 17 00:00:00 2001 From: Kwoth Date: Sun, 20 Mar 2022 19:31:04 +0100 Subject: [PATCH] Converted many raw sql queries to their linq2db equivalents --- .../Db/Extensions/DiscordUserExtensions.cs | 71 ------------------- .../Db/Extensions/WaifuExtensions.cs | 21 ++++-- .../Modules/Gambling/GamblingService.cs | 21 +++--- .../Gambling/Waifus/WaifuClaimCommands.cs | 6 +- .../Modules/Gambling/Waifus/WaifuService.cs | 12 ++-- .../Modules/Utility/Remind/RemindService.cs | 2 - 6 files changed, 36 insertions(+), 97 deletions(-) diff --git a/src/NadekoBot/Db/Extensions/DiscordUserExtensions.cs b/src/NadekoBot/Db/Extensions/DiscordUserExtensions.cs index a130e26ea..cff06edab 100644 --- a/src/NadekoBot/Db/Extensions/DiscordUserExtensions.cs +++ b/src/NadekoBot/Db/Extensions/DiscordUserExtensions.cs @@ -84,77 +84,6 @@ public static class DiscordUserExtensions item.CurrencyAmount = 0; } - public static bool TryUpdateCurrencyState( - this NadekoContext ctx, - ulong userId, - string name, - string discrim, - string avatarId, - long amount, - bool allowNegative = false) - { - if (amount == 0) - return true; - - // if remove - try to remove if he has more or equal than the amount - // and return number of rows > 0 (was there a change) - if (amount < 0 && !allowNegative) - { - var rows = ctx.Database.ExecuteSqlInterpolated($@" -UPDATE DiscordUser -SET CurrencyAmount=CurrencyAmount+{amount} -WHERE UserId={userId} AND CurrencyAmount>={-amount};"); - return rows > 0; - } - - // if remove and negative is allowed, just remove without any condition - if (amount < 0 && allowNegative) - { - var rows = ctx.Database.ExecuteSqlInterpolated($@" -UPDATE DiscordUser -SET CurrencyAmount=CurrencyAmount+{amount} -WHERE UserId={userId};"); - return rows > 0; - } - - // if add - create a new user with default values if it doesn't exist - // if it exists, sum current amount with the new one, if it doesn't - // he just has the new amount - var updatedUserData = !string.IsNullOrWhiteSpace(name); - name ??= "Unknown"; - discrim ??= "????"; - avatarId ??= ""; - - // just update the amount, there is no new user data - if (!updatedUserData) - { - ctx.Database.ExecuteSqlInterpolated($@" -UPDATE OR IGNORE DiscordUser -SET CurrencyAmount=CurrencyAmount+{amount} -WHERE UserId={userId}; - -INSERT OR IGNORE INTO DiscordUser (UserId, Username, Discriminator, AvatarId, CurrencyAmount, TotalXp) -VALUES ({userId}, {name}, {discrim}, {avatarId}, {amount}, 0); -"); - } - else - { - ctx.Database.ExecuteSqlInterpolated($@" -UPDATE OR IGNORE DiscordUser -SET CurrencyAmount=CurrencyAmount+{amount}, - Username={name}, - Discriminator={discrim}, - AvatarId={avatarId} -WHERE UserId={userId}; - -INSERT OR IGNORE INTO DiscordUser (UserId, Username, Discriminator, AvatarId, CurrencyAmount, TotalXp) -VALUES ({userId}, {name}, {discrim}, {avatarId}, {amount}, 0); -"); - } - - return true; - } - public static decimal GetTotalCurrency(this DbSet users) => users.Sum((Func)(x => x.CurrencyAmount)); diff --git a/src/NadekoBot/Db/Extensions/WaifuExtensions.cs b/src/NadekoBot/Db/Extensions/WaifuExtensions.cs index 42d2482f1..266708768 100644 --- a/src/NadekoBot/Db/Extensions/WaifuExtensions.cs +++ b/src/NadekoBot/Db/Extensions/WaifuExtensions.cs @@ -1,4 +1,6 @@ #nullable disable +using LinqToDB; +using LinqToDB.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using NadekoBot.Db.Models; using NadekoBot.Services.Database; @@ -75,11 +77,22 @@ public static class WaifuExtensions .Select(x => x.Waifu.UserId) .FirstOrDefault(); - public static WaifuInfoStats GetWaifuInfo(this NadekoContext ctx, ulong userId) + public static async Task GetWaifuInfoAsync(this NadekoContext ctx, ulong userId) { - ctx.Database.ExecuteSqlInterpolated($@" -INSERT OR IGNORE INTO WaifuInfo (AffinityId, ClaimerId, Price, WaifuId) -VALUES ({null}, {null}, {1}, (SELECT Id FROM DiscordUser WHERE UserId={userId}));"); + await ctx.WaifuInfo + .ToLinqToDBTable() + .InsertOrUpdateAsync(() => new() + { + AffinityId = null, + ClaimerId = null, + Price = 1, + WaifuId = ctx.DiscordUser.Where(x => x.UserId == userId).Select(x => x.Id).First() + }, + _ => new(), + () => new() + { + WaifuId = ctx.DiscordUser.Where(x => x.UserId == userId).Select(x => x.Id).First() + }); var toReturn = ctx.WaifuInfo.AsQueryable() .Where(w => w.WaifuId diff --git a/src/NadekoBot/Modules/Gambling/GamblingService.cs b/src/NadekoBot/Modules/Gambling/GamblingService.cs index 5b28a52af..477f01177 100644 --- a/src/NadekoBot/Modules/Gambling/GamblingService.cs +++ b/src/NadekoBot/Modules/Gambling/GamblingService.cs @@ -102,17 +102,16 @@ public class GamblingService : INService, IReadyExecutor if (maxDecay == 0) maxDecay = int.MaxValue; - await uow.Database.ExecuteSqlInterpolatedAsync($@" -UPDATE DiscordUser -SET CurrencyAmount= - CASE WHEN - {maxDecay} > ROUND(CurrencyAmount * {config.Decay.Percent} - 0.5) - THEN - CurrencyAmount - ROUND(CurrencyAmount * {config.Decay.Percent} - 0.5) - ELSE - CurrencyAmount - {maxDecay} - END -WHERE CurrencyAmount > {config.Decay.MinThreshold} AND UserId!={_client.CurrentUser.Id};"); + var decay = (double)config.Decay.Percent; + await uow.DiscordUser + .Where(x => x.CurrencyAmount > config.Decay.MinThreshold && x.UserId != _client.CurrentUser.Id) + .UpdateAsync(old => new() + { + CurrencyAmount = + maxDecay > Sql.Round((old.CurrencyAmount * decay) - 0.5) + ? (long)(old.CurrencyAmount - Sql.Round((old.CurrencyAmount * decay) - 0.5)) + : old.CurrencyAmount - maxDecay + }); _cache.SetLastCurrencyDecay(); await uow.SaveChangesAsync(); diff --git a/src/NadekoBot/Modules/Gambling/Waifus/WaifuClaimCommands.cs b/src/NadekoBot/Modules/Gambling/Waifus/WaifuClaimCommands.cs index 5b350a7d2..bdee7d11a 100644 --- a/src/NadekoBot/Modules/Gambling/Waifus/WaifuClaimCommands.cs +++ b/src/NadekoBot/Modules/Gambling/Waifus/WaifuClaimCommands.cs @@ -236,9 +236,9 @@ public partial class Gambling public partial Task WaifuInfo(ulong targetId) => InternalWaifuInfo(targetId); - private Task InternalWaifuInfo(ulong targetId, string name = null) + private async Task InternalWaifuInfo(ulong targetId, string name = null) { - var wi = _service.GetFullWaifuInfoAsync(targetId); + var wi = await _service.GetFullWaifuInfoAsync(targetId); var affInfo = _service.GetAffinityTitle(wi.AffinityCount); var waifuItems = _service.GetWaifuItems().ToDictionary(x => x.ItemEmoji, x => x); @@ -280,7 +280,7 @@ public partial class Gambling true) .AddField(GetText(strs.gifts), itemsStr, true); - return ctx.Channel.EmbedAsync(embed); + await ctx.Channel.EmbedAsync(embed); } [Cmd] diff --git a/src/NadekoBot/Modules/Gambling/Waifus/WaifuService.cs b/src/NadekoBot/Modules/Gambling/Waifus/WaifuService.cs index 703e4fc3a..952633b81 100644 --- a/src/NadekoBot/Modules/Gambling/Waifus/WaifuService.cs +++ b/src/NadekoBot/Modules/Gambling/Waifus/WaifuService.cs @@ -385,10 +385,10 @@ public class WaifuService : INService, IReadyExecutor return true; } - public WaifuInfoStats GetFullWaifuInfoAsync(ulong targetId) + public async Task GetFullWaifuInfoAsync(ulong targetId) { - using var uow = _db.GetDbContext(); - var wi = uow.GetWaifuInfo(targetId); + await using var uow = _db.GetDbContext(); + var wi = await uow.GetWaifuInfoAsync(targetId); if (wi is null) { wi = new() @@ -409,12 +409,12 @@ public class WaifuService : INService, IReadyExecutor return wi; } - public WaifuInfoStats GetFullWaifuInfoAsync(IGuildUser target) + public async Task GetFullWaifuInfoAsync(IGuildUser target) { - using var uow = _db.GetDbContext(); + await using var uow = _db.GetDbContext(); _ = uow.GetOrCreateUser(target); - return GetFullWaifuInfoAsync(target.Id); + return await GetFullWaifuInfoAsync(target.Id); } public string GetClaimTitle(int count) diff --git a/src/NadekoBot/Modules/Utility/Remind/RemindService.cs b/src/NadekoBot/Modules/Utility/Remind/RemindService.cs index d60ef9ca5..d214fa83b 100644 --- a/src/NadekoBot/Modules/Utility/Remind/RemindService.cs +++ b/src/NadekoBot/Modules/Utility/Remind/RemindService.cs @@ -78,8 +78,6 @@ public class RemindService : INService .ToLinqToDBTable() .Where(x => x.ServerId / 4194304 % (ulong)_creds.TotalShards == (ulong)_client.ShardId && x.When < now) - // .FromSqlInterpolated( - // $"select * from reminders where ((serverid >> 22) % {_creds.TotalShards}) == {_client.ShardId} and \"when\" < {now};") .ToListAsyncLinqToDB(); }