Add StaleDataCleaner and related changes

This commit is contained in:
Noi 2020-04-10 00:20:47 -07:00
parent 6195e1ed60
commit 0b6f2c45a4
3 changed files with 51 additions and 3 deletions

View file

@ -0,0 +1,47 @@
using BirthdayBot.Data;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace BirthdayBot.BackgroundServices
{
/// <summary>
/// Automatically removes database information for guilds that have not been accessed in a long time.
/// </summary>
class StaleDataCleaner : BackgroundService
{
public StaleDataCleaner(BirthdayBot instance) : base(instance) { }
public override async Task OnTick()
{
using var db = await BotInstance.Config.DatabaseSettings.OpenConnectionAsync();
// Update only for all guilds the bot has cached
using (var c = db.CreateCommand())
{
c.CommandText = $"update {GuildStateInformation.BackingTable} set last_seen = now() "
+ "where guild_id = @Gid";
var updateGuild = c.Parameters.Add("@Gid", NpgsqlTypes.NpgsqlDbType.Bigint);
c.Prepare();
var list = new List<ulong>(BotInstance.GuildCache.Keys);
foreach (var id in list)
{
updateGuild.Value = (long)id;
c.ExecuteNonQuery();
}
}
// Delete all old values - expecte referencing tables to have 'on delete cascade'
using (var t = db.BeginTransaction())
{
using (var c = db.CreateCommand())
{
// Delete data for guilds not seen in 2 weeks
c.CommandText = $"delete from {GuildUserSettings.BackingTable} where (now() - interval '14 days') > last_seen";
var r = c.ExecuteNonQuery();
if (r != 0) Log($"Removed {r} stale guild(s).");
}
}
}
}
}

View file

@ -316,14 +316,15 @@ namespace BirthdayBot.Data
+ "moderator_role bigint null, "
+ "announce_message text null, "
+ "announce_message_pl text null, "
+ "announce_ping boolean not null default FALSE"
+ "announce_ping boolean not null default FALSE, "
+ "last_seen timestamptz not null default NOW()"
+ ")";
c.ExecuteNonQuery();
}
using (var c = db.CreateCommand())
{
c.CommandText = $"create table if not exists {BackingTableBans} ("
+ $"guild_id bigint not null references {BackingTable}, "
+ $"guild_id bigint not null references {BackingTable} ON DELETE CASCADE, "
+ "user_id bigint not null, "
+ "PRIMARY KEY (guild_id, user_id)"
+ ")";

View file

@ -126,7 +126,7 @@ namespace BirthdayBot.Data
using (var c = db.CreateCommand())
{
c.CommandText = $"create table if not exists {BackingTable} ("
+ $"guild_id bigint not null references {GuildStateInformation.BackingTable}, "
+ $"guild_id bigint not null references {GuildStateInformation.BackingTable} ON DELETE CASCADE, "
+ "user_id bigint not null, "
+ "birth_month integer not null, "
+ "birth_day integer not null, "