PluralKit/PluralKit.Core/Database/Repository/ModelRepository.Message.cs

70 lines
2.6 KiB
C#
Raw Normal View History

2020-08-29 11:46:27 +00:00
using Dapper;
using SqlKata;
namespace PluralKit.Core;
public partial class ModelRepository
2020-08-29 11:46:27 +00:00
{
public Task AddMessage(PKMessage msg)
2020-08-29 11:46:27 +00:00
{
var query = new Query("messages").AsInsert(new
2021-08-27 15:03:47 +00:00
{
mid = msg.Mid,
guild = msg.Guild,
channel = msg.Channel,
member = msg.Member,
sender = msg.Sender,
original_mid = msg.OriginalMid
});
_logger.Debug("Stored message {@StoredMessage} in channel {Channel}", msg, msg.Channel);
// "on conflict do nothing" in the (pretty rare) case of duplicate events coming in from Discord, which would lead to a DB error before
return _db.ExecuteQuery(query, "on conflict do nothing", messages: true);
}
2021-08-27 15:03:47 +00:00
public Task<PKMessage?> GetMessage(ulong id)
=> _db.QueryFirst<PKMessage?>(new Query("messages").Where("mid", id), messages: true);
public async Task<FullMessage?> GetFullMessage(ulong id)
{
var rawMessage = await GetMessage(id);
if (rawMessage == null) return null;
2020-08-29 11:46:27 +00:00
var member = rawMessage.Member == null ? null : await GetMember(rawMessage.Member.Value);
var system = member == null ? null : await GetSystem(member.System);
return new FullMessage
{
Message = rawMessage,
Member = member,
System = system,
};
}
2020-08-29 11:46:27 +00:00
public async Task DeleteMessage(ulong id)
{
if ((await GetMessage(id)) == null)
return;
var query = new Query("messages").AsDelete().Where("mid", id);
var rowCount = await _db.ExecuteQuery(query, messages: true);
if (rowCount > 0)
_logger.Information("Deleted message {MessageId} from database", id);
}
2020-08-29 11:46:27 +00:00
public async Task DeleteMessagesBulk(IReadOnlyCollection<ulong> ids)
{
var q = new Query("messages").Select("mid").WhereIn("mid", ids.Select(id => (long)id).ToArray());
var realIds = await _db.Query<long>(q);
if (realIds.Count() == 0) return;
// Npgsql doesn't support ulongs in general - we hacked around it for plain ulongs but tbh not worth it for collections of ulong
// Hence we map them to single longs, which *are* supported (this is ok since they're Technically (tm) stored as signed longs in the db anyway)
var query = new Query("messages").AsDelete().WhereIn("mid", realIds);
var rowCount = await _db.ExecuteQuery(query, messages: true);
if (rowCount > 0)
_logger.Information("Bulk deleted messages ({FoundCount} found) from database: {MessageIds}", rowCount,
ids);
}
2020-08-29 11:46:27 +00:00
}