[backend/database] Add database maintenance service with functions to recompute note & user counters (ISH-21)

This commit is contained in:
Laura Hausmann 2024-02-09 14:20:32 +01:00
parent 78b69c180c
commit d566875f54
No known key found for this signature in database
GPG key ID: D044E84C5BE01605
3 changed files with 28 additions and 1 deletions

View file

@ -230,6 +230,9 @@ public class Note : IEntity {
[InverseProperty(nameof(InverseReply))]
public virtual Note? Reply { get; set; }
[NotMapped] [Projectable] public bool IsPureRenote => RenoteId != null && !IsQuote;
[NotMapped] [Projectable] public bool IsQuote => RenoteId != null && (Text != null || HasPoll || FileIds.Count > 0);
[ForeignKey("UserId")]
[InverseProperty(nameof(Tables.User.Notes))]
public virtual User User { get; set; } = null!;

View file

@ -32,9 +32,10 @@ public static class ServiceExtensions {
.AddScoped<ActivityPub.ActivityHandlerService>()
.AddScoped<ActivityPub.ActivityFetcherService>()
.AddScoped<UserService>()
.AddScoped<SystemUserService>()
.AddScoped<NoteService>()
.AddScoped<WebFingerService>()
.AddScoped<SystemUserService>()
.AddScoped<DatabaseMaintenanceService>()
.AddScoped<AuthorizedFetchMiddleware>()
.AddScoped<AuthenticationMiddleware>()
.AddScoped<UserRenderer>()

View file

@ -0,0 +1,23 @@
using Iceshrimp.Backend.Core.Database;
using Microsoft.EntityFrameworkCore;
namespace Iceshrimp.Backend.Core.Services;
public class DatabaseMaintenanceService(DatabaseContext db) {
public async Task RecomputeNoteCountersAsync() {
await db.Notes.ExecuteUpdateAsync(p => p.SetProperty(n => n.RenoteCount,
n => db.Notes.Count(r => r.IsPureRenote))
.SetProperty(n => n.RepliesCount,
n => db.Notes.Count(r => r.Reply == n)));
//TODO: update reaction counts as well? (can likely not be done database-side :/)
}
public async Task RecomputeUserCountersAsync() {
await db.Users.ExecuteUpdateAsync(p => p.SetProperty(u => u.FollowersCount,
u => db.Followings.Count(f => f.Followee == u))
.SetProperty(u => u.FollowingCount,
u => db.Followings.Count(f => f.Follower == u))
.SetProperty(u => u.NotesCount,
u => db.Notes.Count(n => n.User == u && !n.IsPureRenote)));
}
}