2017-10-08 20:07:54 +00:00
|
|
|
using System.Collections.Generic;
|
2020-08-18 20:11:44 +00:00
|
|
|
using System.Data;
|
2016-09-22 17:57:12 +00:00
|
|
|
using System.Linq;
|
2020-08-18 20:11:44 +00:00
|
|
|
using Dapper;
|
2022-01-26 00:08:27 +00:00
|
|
|
using NzbDrone.Common.Extensions;
|
2016-09-22 17:57:12 +00:00
|
|
|
using NzbDrone.Core.Datastore;
|
|
|
|
|
|
|
|
namespace NzbDrone.Core.Housekeeping.Housekeepers
|
|
|
|
{
|
|
|
|
public class CleanupUnusedTags : IHousekeepingTask
|
|
|
|
{
|
|
|
|
private readonly IMainDatabase _database;
|
|
|
|
|
|
|
|
public CleanupUnusedTags(IMainDatabase database)
|
|
|
|
{
|
|
|
|
_database = database;
|
|
|
|
}
|
|
|
|
|
|
|
|
public void Clean()
|
|
|
|
{
|
2020-08-18 20:11:44 +00:00
|
|
|
using (var mapper = _database.OpenConnection())
|
|
|
|
{
|
2022-09-26 19:54:35 +00:00
|
|
|
var usedTags = new[] { "Artists", "Notifications", "DelayProfiles", "ReleaseProfiles", "ImportLists", "Indexers" }
|
2016-09-22 17:57:12 +00:00
|
|
|
.SelectMany(v => GetUsedTags(v, mapper))
|
2020-08-18 20:11:44 +00:00
|
|
|
.Distinct()
|
|
|
|
.ToArray();
|
2016-09-22 17:57:12 +00:00
|
|
|
|
2022-01-26 00:08:27 +00:00
|
|
|
if (usedTags.Any())
|
|
|
|
{
|
|
|
|
var usedTagsList = usedTags.Select(d => d.ToString()).Join(",");
|
2016-09-22 17:57:12 +00:00
|
|
|
|
2022-01-26 00:08:27 +00:00
|
|
|
if (_database.DatabaseType == DatabaseType.PostgreSQL)
|
|
|
|
{
|
|
|
|
mapper.Execute($"DELETE FROM \"Tags\" WHERE NOT \"Id\" = ANY (\'{{{usedTagsList}}}\'::int[])");
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
mapper.Execute($"DELETE FROM \"Tags\" WHERE NOT \"Id\" IN ({usedTagsList})");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
mapper.Execute("DELETE FROM \"Tags\"");
|
|
|
|
}
|
2020-08-18 20:11:44 +00:00
|
|
|
}
|
2016-09-22 17:57:12 +00:00
|
|
|
}
|
|
|
|
|
2020-08-18 20:11:44 +00:00
|
|
|
private int[] GetUsedTags(string table, IDbConnection mapper)
|
2016-09-22 17:57:12 +00:00
|
|
|
{
|
2022-01-26 00:08:27 +00:00
|
|
|
return mapper.Query<List<int>>($"SELECT DISTINCT \"Tags\" FROM \"{table}\" WHERE NOT \"Tags\" = '[]' AND NOT \"Tags\" IS NULL")
|
2020-08-18 20:11:44 +00:00
|
|
|
.SelectMany(x => x)
|
|
|
|
.Distinct()
|
|
|
|
.ToArray();
|
2016-09-22 17:57:12 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|