refactor: add SqlKata for SQL generation, move connection handling into ModelRepository

This commit is contained in:
spiral
2021-09-29 21:51:38 -04:00
parent 6251d29abb
commit 92e45a07ff
60 changed files with 806 additions and 640 deletions

View File

@@ -42,16 +42,14 @@ namespace PluralKit.Bot
if (groupName.Length > Limits.MaxGroupNameLength)
throw new PKError($"Group name too long ({groupName.Length}/{Limits.MaxGroupNameLength} characters).");
await using var conn = await _db.Obtain();
// Check group cap
var existingGroupCount = await _repo.GetSystemGroupCount(conn, ctx.System.Id);
var existingGroupCount = await _repo.GetSystemGroupCount(ctx.System.Id);
var groupLimit = ctx.System.GroupLimitOverride ?? Limits.MaxGroupCount;
if (existingGroupCount >= groupLimit)
throw new PKError($"System has reached the maximum number of groups ({groupLimit}). Please delete unused groups first in order to create new ones.");
// Warn if there's already a group by this name
var existingGroup = await _repo.GetGroupByName(conn, ctx.System.Id, groupName);
var existingGroup = await _repo.GetGroupByName(ctx.System.Id, groupName);
if (existingGroup != null)
{
var msg = $"{Emojis.Warn} You already have a group in your system with the name \"{existingGroup.Name}\" (with ID `{existingGroup.Hid}`). Do you want to create another group with the same name?";
@@ -59,7 +57,7 @@ namespace PluralKit.Bot
throw new PKError("Group creation cancelled.");
}
var newGroup = await _repo.CreateGroup(conn, ctx.System.Id, groupName);
var newGroup = await _repo.CreateGroup(ctx.System.Id, groupName);
var eb = new EmbedBuilder()
.Description($"Your new group, **{groupName}**, has been created, with the group ID **`{newGroup.Hid}`**.\nBelow are a couple of useful commands:")
@@ -82,10 +80,8 @@ namespace PluralKit.Bot
if (newName.Length > Limits.MaxGroupNameLength)
throw new PKError($"New group name too long ({newName.Length}/{Limits.MaxMemberNameLength} characters).");
await using var conn = await _db.Obtain();
// Warn if there's already a group by this name
var existingGroup = await _repo.GetGroupByName(conn, ctx.System.Id, newName);
var existingGroup = await _repo.GetGroupByName(ctx.System.Id, newName);
if (existingGroup != null && existingGroup.Id != target.Id)
{
var msg = $"{Emojis.Warn} You already have a group in your system with the name \"{existingGroup.Name}\" (with ID `{existingGroup.Hid}`). Do you want to rename this group to that name too?";
@@ -93,7 +89,7 @@ namespace PluralKit.Bot
throw new PKError("Group rename cancelled.");
}
await _repo.UpdateGroup(conn, target.Id, new GroupPatch { Name = newName });
await _repo.UpdateGroup(target.Id, new() { Name = newName });
await ctx.Reply($"{Emojis.Success} Group name changed from **{target.Name}** to **{newName}**.");
}
@@ -139,7 +135,7 @@ namespace PluralKit.Bot
if (await ctx.MatchClear("this group's display name"))
{
var patch = new GroupPatch { DisplayName = Partial<string>.Null() };
await _db.Execute(conn => _repo.UpdateGroup(conn, target.Id, patch));
await _repo.UpdateGroup(target.Id, patch);
await ctx.Reply($"{Emojis.Success} Group display name cleared.");
}
@@ -148,7 +144,7 @@ namespace PluralKit.Bot
var newDisplayName = ctx.RemainderOrNull(skipFlags: false).NormalizeLineEndSpacing();
var patch = new GroupPatch { DisplayName = Partial<string>.Present(newDisplayName) };
await _db.Execute(conn => _repo.UpdateGroup(conn, target.Id, patch));
await _repo.UpdateGroup(target.Id, patch);
await ctx.Reply($"{Emojis.Success} Group display name changed.");
}
@@ -190,7 +186,7 @@ namespace PluralKit.Bot
if (await ctx.MatchClear("this group's description"))
{
var patch = new GroupPatch { Description = Partial<string>.Null() };
await _db.Execute(conn => _repo.UpdateGroup(conn, target.Id, patch));
await _repo.UpdateGroup(target.Id, patch);
await ctx.Reply($"{Emojis.Success} Group description cleared.");
}
else
@@ -200,7 +196,7 @@ namespace PluralKit.Bot
throw Errors.StringTooLongError("Description", description.Length, Limits.MaxDescriptionLength);
var patch = new GroupPatch { Description = Partial<string>.Present(description) };
await _db.Execute(conn => _repo.UpdateGroup(conn, target.Id, patch));
await _repo.UpdateGroup(target.Id, patch);
await ctx.Reply($"{Emojis.Success} Group description changed.");
}
@@ -212,7 +208,7 @@ namespace PluralKit.Bot
{
ctx.CheckOwnGroup(target);
await _db.Execute(c => _repo.UpdateGroup(c, target.Id, new GroupPatch { Icon = null }));
await _repo.UpdateGroup(target.Id, new() { Icon = null });
await ctx.Reply($"{Emojis.Success} Group icon cleared.");
}
@@ -222,7 +218,7 @@ namespace PluralKit.Bot
await AvatarUtils.VerifyAvatarOrThrow(_client, img.Url);
await _db.Execute(c => _repo.UpdateGroup(c, target.Id, new GroupPatch { Icon = img.Url }));
await _repo.UpdateGroup(target.Id, new() { Icon = img.Url });
var msg = img.Source switch
{
@@ -274,7 +270,7 @@ namespace PluralKit.Bot
{
ctx.CheckOwnGroup(target);
await _db.Execute(c => _repo.UpdateGroup(c, target.Id, new GroupPatch { BannerImage = null }));
await _repo.UpdateGroup(target.Id, new() { BannerImage = null });
await ctx.Reply($"{Emojis.Success} Group banner image cleared.");
}
@@ -284,7 +280,7 @@ namespace PluralKit.Bot
await AvatarUtils.VerifyAvatarOrThrow(_client, img.Url, isFullSizeImage: true);
await _db.Execute(c => _repo.UpdateGroup(c, target.Id, new GroupPatch { BannerImage = img.Url }));
await _repo.UpdateGroup(target.Id, new() { BannerImage = img.Url });
var msg = img.Source switch
{
@@ -338,7 +334,7 @@ namespace PluralKit.Bot
ctx.CheckOwnGroup(target);
var patch = new GroupPatch { Color = Partial<string>.Null() };
await _db.Execute(conn => _repo.UpdateGroup(conn, target.Id, patch));
await _repo.UpdateGroup(target.Id, patch);
await ctx.Reply($"{Emojis.Success} Group color cleared.");
}
@@ -368,7 +364,7 @@ namespace PluralKit.Bot
if (!Regex.IsMatch(color, "^[0-9a-fA-F]{6}$")) throw Errors.InvalidColorError(color);
var patch = new GroupPatch { Color = Partial<string>.Present(color.ToLowerInvariant()) };
await _db.Execute(conn => _repo.UpdateGroup(conn, target.Id, patch));
await _repo.UpdateGroup(target.Id, patch);
await ctx.Reply(embed: new EmbedBuilder()
.Title($"{Emojis.Success} Group color changed.")
@@ -389,7 +385,6 @@ namespace PluralKit.Bot
ctx.CheckSystemPrivacy(system, system.GroupListPrivacy);
// TODO: integrate with the normal "search" system
await using var conn = await _db.Obtain();
var pctx = LookupContext.ByNonOwner;
if (ctx.MatchFlag("a", "all"))
@@ -400,7 +395,7 @@ namespace PluralKit.Bot
throw new PKError("You do not have permission to access this information.");
}
var groups = (await conn.QueryGroupList(system.Id))
var groups = (await _db.Execute(conn => conn.QueryGroupList(system.Id)))
.Where(g => g.Visibility.CanAccess(pctx))
.OrderBy(g => g.Name, StringComparer.InvariantCultureIgnoreCase)
.ToList();
@@ -434,8 +429,7 @@ namespace PluralKit.Bot
public async Task ShowGroupCard(Context ctx, PKGroup target)
{
await using var conn = await _db.Obtain();
var system = await GetGroupSystem(ctx, target, conn);
var system = await GetGroupSystem(ctx, target);
await ctx.Reply(embed: await _embeds.CreateGroupEmbed(ctx, system, target));
}
@@ -448,10 +442,8 @@ namespace PluralKit.Bot
.Distinct()
.ToList();
await using var conn = await _db.Obtain();
var existingMembersInGroup = (await conn.QueryMemberList(target.System,
new DatabaseViewsExt.MemberListQueryOptions { GroupFilter = target.Id }))
var existingMembersInGroup = (await _db.Execute(conn => conn.QueryMemberList(target.System,
new DatabaseViewsExt.MemberListQueryOptions { GroupFilter = target.Id })))
.Select(m => m.Id.Value)
.Distinct()
.ToHashSet();
@@ -463,14 +455,14 @@ namespace PluralKit.Bot
toAction = members
.Where(m => !existingMembersInGroup.Contains(m.Value))
.ToList();
await _repo.AddMembersToGroup(conn, target.Id, toAction);
await _repo.AddMembersToGroup(target.Id, toAction);
}
else if (op == AddRemoveOperation.Remove)
{
toAction = members
.Where(m => existingMembersInGroup.Contains(m.Value))
.ToList();
await _repo.RemoveMembersFromGroup(conn, target.Id, toAction);
await _repo.RemoveMembersFromGroup(target.Id, toAction);
}
else return; // otherwise toAction "may be undefined"
@@ -479,9 +471,7 @@ namespace PluralKit.Bot
public async Task ListGroupMembers(Context ctx, PKGroup target)
{
await using var conn = await _db.Obtain();
var targetSystem = await GetGroupSystem(ctx, target, conn);
var targetSystem = await GetGroupSystem(ctx, target);
ctx.CheckSystemPrivacy(targetSystem, target.ListPrivacy);
var opts = ctx.ParseMemberListOptions(ctx.LookupContextFor(target.System));
@@ -523,7 +513,7 @@ namespace PluralKit.Bot
async Task SetAll(PrivacyLevel level)
{
await _db.Execute(c => _repo.UpdateGroup(c, target.Id, new GroupPatch().WithAllPrivacy(level)));
await _repo.UpdateGroup(target.Id, new GroupPatch().WithAllPrivacy(level));
if (level == PrivacyLevel.Private)
await ctx.Reply($"{Emojis.Success} All {target.Name}'s privacy settings have been set to **{level.LevelName()}**. Other accounts will now see nothing on the group card.");
@@ -533,7 +523,7 @@ namespace PluralKit.Bot
async Task SetLevel(GroupPrivacySubject subject, PrivacyLevel level)
{
await _db.Execute(c => _repo.UpdateGroup(c, target.Id, new GroupPatch().WithPrivacy(subject, level)));
await _repo.UpdateGroup(target.Id, new GroupPatch().WithPrivacy(subject, level));
var subjectName = subject switch
{
@@ -576,19 +566,17 @@ namespace PluralKit.Bot
if (!await ctx.ConfirmWithReply(target.Hid))
throw new PKError($"Group deletion cancelled. Note that you must reply with your group ID (`{target.Hid}`) *verbatim*.");
await _db.Execute(conn => _repo.DeleteGroup(conn, target.Id));
await _repo.DeleteGroup(target.Id);
await ctx.Reply($"{Emojis.Success} Group deleted.");
}
public async Task GroupFrontPercent(Context ctx, PKGroup target)
{
await using var conn = await _db.Obtain();
var targetSystem = await GetGroupSystem(ctx, target, conn);
var targetSystem = await GetGroupSystem(ctx, target);
ctx.CheckSystemPrivacy(targetSystem, targetSystem.FrontHistoryPrivacy);
var totalSwitches = await _db.Execute(conn => _repo.GetSwitchCount(conn, targetSystem.Id));
var totalSwitches = await _repo.GetSwitchCount(targetSystem.Id);
if (totalSwitches == 0) throw Errors.NoRegisteredSwitches;
string durationStr = ctx.RemainderOrNull() ?? "30d";
@@ -611,12 +599,12 @@ namespace PluralKit.Bot
await ctx.Reply(embed: await _embeds.CreateFrontPercentEmbed(frontpercent, targetSystem, target, targetSystem.Zone, ctx.LookupContextFor(targetSystem), title.ToString(), ignoreNoFronters, showFlat));
}
private async Task<PKSystem> GetGroupSystem(Context ctx, PKGroup target, IPKConnection conn)
private async Task<PKSystem> GetGroupSystem(Context ctx, PKGroup target)
{
var system = ctx.System;
if (system?.Id == target.System)
return system;
return await _repo.GetSystem(conn, target.System)!;
return await _repo.GetSystem(target.System)!;
}
}
}