using Khaemhat.Data;
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Application.Seeding;
/// What the removal of the demo data did.
/// Rows removed, by table.
/// Tables whose own rows (not demo) still refer to demo rows: nothing was removed.
public sealed record DemoRemoval(IReadOnlyDictionary Removed, IReadOnlyList Blockers)
{
/// Whether the demo data were removed.
public bool Done => Blockers.Count == 0;
/// All the rows removed.
public int Total => Removed.Values.Sum();
}
///
/// Removes the demo data of a company, and only them (SPEC ยง14, issue #80): the rows marked is_demo and the rows
/// of the tables without the mark that belong to them through a foreign key (the lines of a demo document, the balances
/// of a demo item). The tables and their keys come from the migrations, so a new module is covered without changes.
/// When a row the user entered refers to a demo row (an invoice to a demo customer) nothing is removed and the tables
/// are reported: the user decides what to do. Everything happens in one transaction.
///
/// The units of work.
public sealed class DemoDataRemover(IUnitOfWorkFactory factory)
{
private const string DemoColumn = "is_demo";
/// Removes the demo data of a company.
/// The company.
/// Cancellation.
/// What was removed, or what stopped it.
public async Task RemoveAsync(string companyCode, CancellationToken cancellationToken = default)
{
var model = MigrationCatalog.ForCompany().BuildModel();
var tables = model.Tables.ToDictionary(t => t.Name, StringComparer.Ordinal);
var doomed = new Dictionary(StringComparer.Ordinal);
foreach (var table in tables.Values)
{
Predicate(table, tables, doomed, []);
}
await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
// Rows of the user that point to demo rows through a key that does not follow them.
var blockers = new List();
foreach (var table in tables.Values.Where(t => t.Column(DemoColumn) is not null))
{
foreach (var key in table.ForeignKeys.Where(k => k.OnDelete != ReferentialAction.SetNull && k.ReferencedTable != table.Name && k.Columns.Count == 1))
{
if (doomed.GetValueOrDefault(key.ReferencedTable) is not { } parent)
{
continue;
}
var count = await uow.QuerySingleAsync(
SqlFragment.Literal("SELECT COUNT(*) FROM ") + SqlFragment.Identifier(table.Name) + SqlFragment.Literal(" WHERE ")
+ SqlFragment.Identifier(DemoColumn) + SqlFragment.Literal(" = ") + SqlFragment.Parameter(false) + SqlFragment.Literal(" AND ")
+ SqlFragment.Identifier(key.Columns[0]) + SqlFragment.Literal(" IN (SELECT ") + SqlFragment.Identifier(key.ReferencedColumns[0]) + SqlFragment.Literal(" FROM ") + SqlFragment.Identifier(key.ReferencedTable)
+ SqlFragment.Literal(" WHERE ") + parent + SqlFragment.Literal(")"),
cancellationToken).ConfigureAwait(false);
if (count > 0 && !blockers.Contains(table.Name))
{
blockers.Add(table.Name);
}
}
}
if (blockers.Count > 0)
{
await uow.RollbackAsync(cancellationToken).ConfigureAwait(false);
return new DemoRemoval(new Dictionary(), blockers);
}
var removed = new Dictionary(StringComparer.Ordinal);
foreach (var table in DeleteOrder(tables.Values.Where(t => doomed.GetValueOrDefault(t.Name) is not null).ToList()))
{
var where = doomed[table.Name]!;
// A key to the same table (an item and its parent) is cleared first, so the rows can go in one statement.
foreach (var key in table.ForeignKeys.Where(k => k.ReferencedTable == table.Name && k.Columns.Count == 1))
{
if (table.Column(key.Columns[0]) is { IsNullable: true })
{
await uow.ExecuteAsync(
SqlFragment.Literal("UPDATE ") + SqlFragment.Identifier(table.Name) + SqlFragment.Literal(" SET ") + SqlFragment.Identifier(key.Columns[0])
+ SqlFragment.Literal(" = NULL WHERE ") + where,
cancellationToken).ConfigureAwait(false);
}
}
var rows = await uow.ExecuteAsync(SqlFragment.Literal("DELETE FROM ") + SqlFragment.Identifier(table.Name) + SqlFragment.Literal(" WHERE ") + where, cancellationToken)
.ConfigureAwait(false);
if (rows > 0)
{
removed[table.Name] = rows;
}
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return new DemoRemoval(removed, []);
}
// The rows of a table that go: marked demo, or (for a table without the mark) belonging to a row that goes.
private static SqlFragment? Predicate(TableDefinition table, Dictionary tables, Dictionary doomed, HashSet visiting)
{
if (doomed.TryGetValue(table.Name, out var known))
{
return known;
}
if (table.Column(DemoColumn) is not null)
{
var own = SqlFragment.Identifier(DemoColumn) + SqlFragment.Literal(" = ") + SqlFragment.Parameter(true);
doomed[table.Name] = own;
return own;
}
if (table.ForeignKeys.Count == 0)
{
doomed[table.Name] = null;
return null;
}
if (!visiting.Add(table.Name))
{
return null;
}
var parts = new List();
foreach (var key in table.ForeignKeys.Where(k => k.OnDelete != ReferentialAction.SetNull && k.ReferencedTable != table.Name && k.Columns.Count == 1))
{
if (tables.TryGetValue(key.ReferencedTable, out var parentTable) && Predicate(parentTable, tables, doomed, visiting) is { } parent)
{
parts.Add(SqlFragment.Identifier(key.Columns[0]) + SqlFragment.Literal(" IN (SELECT ") + SqlFragment.Identifier(key.ReferencedColumns[0]) + SqlFragment.Literal(" FROM ") + SqlFragment.Identifier(key.ReferencedTable)
+ SqlFragment.Literal(" WHERE ") + parent + SqlFragment.Literal(")"));
}
}
visiting.Remove(table.Name);
var result = parts.Count == 0 ? null : SqlFragment.Join(" OR ", parts.Select(p => p.Parenthesize())).Parenthesize();
doomed[table.Name] = result;
return result;
}
// Children before their parents.
private static List DeleteOrder(List tables)
{
var names = tables.Select(t => t.Name).ToHashSet(StringComparer.Ordinal);
var result = new List();
var placed = new HashSet(StringComparer.Ordinal);
while (result.Count < tables.Count)
{
var progress = false;
foreach (var table in tables.Where(t => !placed.Contains(t.Name)))
{
// A table goes once no table still to place refers to it.
var referenced = tables.Any(other => !placed.Contains(other.Name) && other.Name != table.Name
&& other.ForeignKeys.Any(k => k.ReferencedTable == table.Name && names.Contains(other.Name)));
if (!referenced)
{
result.Add(table);
placed.Add(table.Name);
progress = true;
}
}
if (!progress)
{
// A cycle between tables: the rest in any order (keys that set null resolve it).
result.AddRange(tables.Where(t => !placed.Contains(t.Name)));
break;
}
}
return result;
}
}