The demo company now has its electronic invoices: a paused PEC channel and an intermediary, routing rules, the files of the demo invoices with the notifications the SDI would send (delivered, one rejected, one not delivered, some waiting) read by the fiscal pack as real ones, and three supplier invoices in the inbox with their metadata. Every demo seeder now marks as demo also the rows the services write for it (entries, open items, payments, mandates, statements), so the new DemoDataRemover, driven by the schema of the migrations, removes the demo data and only them; it stops and names the tables when rows entered by users still refer to demo rows. `scripts/seed.sh --remove-demo` exposes it and the seed prints its time. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
182 lines
8.4 KiB
C#
182 lines
8.4 KiB
C#
using Khaemhat.Data;
|
|
using Khaemhat.Data.Migrations;
|
|
using Khaemhat.Data.Schema;
|
|
|
|
namespace Khaemhat.Application.Seeding;
|
|
|
|
/// <summary>What the removal of the demo data did.</summary>
|
|
/// <param name="Removed">Rows removed, by table.</param>
|
|
/// <param name="Blockers">Tables whose own rows (not demo) still refer to demo rows: nothing was removed.</param>
|
|
public sealed record DemoRemoval(IReadOnlyDictionary<string, int> Removed, IReadOnlyList<string> Blockers)
|
|
{
|
|
/// <summary>Whether the demo data were removed.</summary>
|
|
public bool Done => Blockers.Count == 0;
|
|
|
|
/// <summary>All the rows removed.</summary>
|
|
public int Total => Removed.Values.Sum();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Removes the demo data of a company, and only them (SPEC §14, issue #80): the rows marked <c>is_demo</c> 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.
|
|
/// </summary>
|
|
/// <param name="factory">The units of work.</param>
|
|
public sealed class DemoDataRemover(IUnitOfWorkFactory factory)
|
|
{
|
|
private const string DemoColumn = "is_demo";
|
|
|
|
/// <summary>Removes the demo data of a company.</summary>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>What was removed, or what stopped it.</returns>
|
|
public async Task<DemoRemoval> 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<string, SqlFragment?>(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<string>();
|
|
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<long>(
|
|
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<string, int>(), blockers);
|
|
}
|
|
|
|
var removed = new Dictionary<string, int>(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<string, TableDefinition> tables, Dictionary<string, SqlFragment?> doomed, HashSet<string> 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<SqlFragment>();
|
|
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<TableDefinition> DeleteOrder(List<TableDefinition> tables)
|
|
{
|
|
var names = tables.Select(t => t.Name).ToHashSet(StringComparer.Ordinal);
|
|
var result = new List<TableDefinition>();
|
|
var placed = new HashSet<string>(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;
|
|
}
|
|
}
|