PlotDirector/PlotLine.Tests/LocationsWorkspaceDatabaseTests.cs

99 lines
11 KiB
C#

using System.Data;
using System.Diagnostics;
using System.Text.Json;
using Dapper;
using Microsoft.Data.SqlClient;
using PlotLine.Controllers;
using PlotLine.Models;
using PlotLine.Data;
internal static class LocationsWorkspaceDatabaseTests
{
public static async Task ExportTaxonomy(string configPath, string outputPath)
{
using var config=JsonDocument.Parse(await File.ReadAllTextAsync(configPath));
var builder=new SqlConnectionStringBuilder(config.RootElement.GetProperty("connection").GetString());
if(builder.DataSource!="192.168.10.10,1433"||!builder.InitialCatalog.StartsWith("PlotDirector_Qualification_Locations",StringComparison.Ordinal))throw new InvalidOperationException("Disposable Locations clone required.");
using var db=new SqlConnection(builder.ConnectionString);
var taxonomy=await db.QueryAsync<LocationTypeTaxonomyEntry>("dbo.LocationTypeTaxonomy_Read",commandType:CommandType.StoredProcedure);
await File.WriteAllTextAsync(outputPath,JsonSerializer.Serialize(taxonomy.Select(PlotLine.Services.LocationWorkspaceIcons.Presentation),new JsonSerializerOptions(JsonSerializerDefaults.Web)));
Console.WriteLine("PASS exported canonical taxonomy presentation from disposable clone; no manuscript data.");
}
public static async Task Run(string configPath)
{
using var config=JsonDocument.Parse(await File.ReadAllTextAsync(configPath));
var builder=new SqlConnectionStringBuilder(config.RootElement.GetProperty("connection").GetString());
if(builder.DataSource!="192.168.10.10,1433"||!builder.InitialCatalog.StartsWith("PlotDirector_Qualification_Locations",StringComparison.Ordinal))throw new InvalidOperationException("Disposable Locations clone required.");
using var db=new SqlConnection(builder.ConnectionString);await db.OpenAsync();
if(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()")!=builder.InitialCatalog)throw new InvalidOperationException("Wrong database.");
var identity=await db.QueryFirstAsync<(int ProjectID,int UserID)>("SELECT TOP(1) p.ProjectID,a.UserID FROM dbo.Projects p JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID WHERE p.IsArchived=0 AND a.IsActive=1 AND a.AccessRole=N'Owner' ORDER BY p.ProjectID");
using var transaction=db.BeginTransaction();
try
{
var created=await db.QuerySingleAsync<int>("dbo.Location_WorkspaceCreate",new{identity.ProjectID,identity.UserID,Name="Dapper workspace contract",ParentID=(int?)null},transaction,commandType:CommandType.StoredProcedure);
if(!await db.ExecuteScalarAsync<bool>("SELECT CONVERT(bit,COUNT(*)) FROM dbo.Locations WHERE LocationID=@created AND LocationName=N'Dapper workspace contract'",new{created},transaction))throw new Exception("Create returned an audit identifier instead of the location identifier.");
var row=await db.QuerySingleAsync<LocationWorkspaceRecord>("SELECT * FROM dbo.Locations WHERE LocationID=@created",new{created},transaction);
var changes=new[]{new LocationWorkspaceController.Change(created,"Fictionalised",row.UpdatedDate.ToString("O"))};
var before=(await db.QueryAsync<LocationWorkspaceController.Change>("dbo.Location_WorkspaceAssign",new{identity.ProjectID,identity.UserID,Attribute="classification",Changes=JsonSerializer.Serialize(changes)},transaction,commandType:CommandType.StoredProcedure)).ToArray();
if(before.Length!=1||before[0].Id!=created||before[0].Value!=""||!DateTime.TryParse(before[0].Version,out var version))throw new Exception("Invalid assignment result/undo receipt.");
await db.QueryAsync<LocationWorkspaceController.Change>("dbo.Location_WorkspaceAssign",new{identity.ProjectID,identity.UserID,Attribute="classification",Changes=JsonSerializer.Serialize(before),Restore=true},transaction,commandType:CommandType.StoredProcedure);
if(await db.ExecuteScalarAsync<string?>("SELECT Classification FROM dbo.Locations WHERE LocationID=@created",new{created},transaction)!=null)throw new Exception("Exact timestamp Undo failed.");
var presence=await db.QueryFirstOrDefaultAsync<int?>("SELECT TOP(1) sc.SceneCharacterID FROM dbo.SceneCharacters sc JOIN dbo.Scenes s ON s.SceneID=sc.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID AND b.IsArchived=0 AND c.IsArchived=0 AND s.IsArchived=0",new{identity.ProjectID},transaction);
if(presence is null)throw new Exception("Clone character presence fixture required.");
await db.ExecuteAsync("UPDATE dbo.SceneCharacters SET LocationID=NULL,EntryLocationID=@created,ExitLocationID=@created WHERE SceneCharacterID=@presence",new{created,presence},transaction);
foreach(var count in new[]{50,200,500,1000})
{
await db.ExecuteAsync("DELETE FROM dbo.Locations WHERE ProjectID=@ProjectID AND LocationName LIKE N'Dapper performance fixture %'; WITH n AS (SELECT TOP(@count) ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS ID FROM sys.all_objects) INSERT dbo.Locations(ProjectID,LocationName,Description) SELECT @ProjectID,CONCAT(N'Dapper performance fixture ',ID),REPLICATE(N'Complete synthetic description. ',20) FROM n",new{identity.ProjectID,count},transaction);
var baseline=Stopwatch.StartNew();
var previousRows=(await db.QueryAsync<LocationItem>("dbo.Location_ListByProject",new{identity.ProjectID},transaction,commandType:CommandType.StoredProcedure)).ToArray();
var baselineMs=baseline.Elapsed.TotalMilliseconds;
var watch=Stopwatch.StartNew();
using var result=await db.QueryMultipleAsync("dbo.Location_WorkspaceRead",new{identity.ProjectID,identity.UserID},transaction,commandType:CommandType.StoredProcedure);
var rows=(await result.ReadAsync<LocationWorkspaceRecord>()).ToArray();
await result.ReadAsync<LocationAlias>();await result.ReadAsync<LocationWorkspaceController.Link>();await result.ReadAsync<LocationWorkspaceController.Link>();var usage=(await result.ReadAsync<LocationWorkspaceController.Usage>()).ToArray();await result.ReadAsync<LocationWorkspaceController.Option>();
if(!usage.Any(u=>u.LocationID==created&&u.SceneCount==1))throw new Exception("Entry/exit-only assignments were missed or double counted.");
if(rows.Count(r=>r.LocationName.StartsWith("Dapper performance fixture "))!=count)throw new Exception("Directory lost fixture rows.");
Console.WriteLine($"PASS Dapper read: {count} synthetic + {rows.Length-count} existing clone records, old list {baselineMs:F1} ms ({previousRows.Length} rows), new six-result directory {watch.Elapsed.TotalMilliseconds:F1} ms");
}
var mergeSource=await db.QuerySingleAsync<int>("dbo.Location_WorkspaceCreate",new{identity.ProjectID,identity.UserID,Name="Dapper exact merge source",ParentID=(int?)null},transaction,commandType:CommandType.StoredProcedure);
// A fractional timestamp that SQL datetime cannot represent exposes accidental default binding.
await db.ExecuteAsync("UPDATE dbo.Locations SET UpdatedDate=CONVERT(datetime2(7),'2026-11-27T10:11:12.1234567') WHERE LocationID IN(@created,@mergeSource)",new{created,mergeSource},transaction);
var mergeVersion=new DateTime(2026,11,27,10,11,12).AddTicks(1234567);
var mergeParameters=new DynamicParameters(new{identity.ProjectID,identity.UserID,SourceID=mergeSource,TargetID=created});
mergeParameters.Add("SourceVersion",mergeVersion,DbType.DateTime2);mergeParameters.Add("TargetVersion",mergeVersion,DbType.DateTime2);
var merged=await db.QuerySingleAsync<EntityMergeResult>("dbo.Location_WorkspaceMerge",mergeParameters,transaction,commandType:CommandType.StoredProcedure);
if(!await db.ExecuteScalarAsync<bool>("SELECT IsArchived FROM dbo.Locations WHERE LocationID=@mergeSource",new{mergeSource},transaction))throw new Exception("Dapper merge did not archive its reviewed source.");
Console.WriteLine("PASS Dapper reviewed merge preserves exact datetime2(7) versions.");
transaction.Rollback();
Console.WriteLine("PASS Dapper create result, exact-version assignment/Undo, directory projections including entry/exit-only usage, and rollback; no live data changed.");
}
catch{try{transaction.Rollback();}catch{}throw;}
// Verify the typed export and the existing generic location restore on committed clone-only data.
var fixture=await db.QuerySingleAsync<int>("dbo.Location_WorkspaceCreate",new{identity.ProjectID,identity.UserID,Name="Classification round-trip fixture",ParentID=(int?)null},commandType:CommandType.StoredProcedure);
try
{
var original=await db.QuerySingleAsync<LocationWorkspaceRecord>("SELECT * FROM dbo.Locations WHERE LocationID=@fixture",new{fixture});
await db.QueryAsync<LocationWorkspaceController.Change>("dbo.Location_WorkspaceAssign",new{identity.ProjectID,identity.UserID,Attribute="classification",Changes=JsonSerializer.Serialize(new[]{new LocationWorkspaceController.Change(fixture,"Fictionalised",original.UpdatedDate.ToString("O"))})},commandType:CommandType.StoredProcedure);
var export=await new ProjectBackupRepository(new Connections(builder.ConnectionString)).GetProjectBackupAsync(identity.ProjectID,identity.UserID)??throw new Exception("Export failed.");
var exported=export.Data.Locations.Single(l=>l.LocationID==fixture);
if(exported.Classification!="Fictionalised")throw new Exception("Typed project export lost classification.");
using var restore=db.BeginTransaction();
try
{
await db.ExecuteAsync("DELETE dbo.Locations WHERE LocationID=@fixture",new{fixture},restore);
await db.ExecuteAsync("dbo.ProjectRestore_InsertJsonTable",new{TableName="Locations",JsonPath="$.Data.Locations",JsonData=JsonSerializer.Serialize(new{Data=new{Locations=new[]{exported}}}),identity.ProjectID,ProjectScopedOnly=false},restore,commandType:CommandType.StoredProcedure);
if(await db.ExecuteScalarAsync<string>("SELECT Classification FROM dbo.Locations WHERE LocationID=@fixture",new{fixture},restore)!="Fictionalised")throw new Exception("Location restore lost classification.");
restore.Rollback();
}
catch{try{restore.Rollback();}catch{}throw;}
Console.WriteLine("PASS actual typed ProjectBackup export and generic location JSON restore retain classification; restore rolled back.");
}
finally
{
await db.ExecuteAsync("DELETE dbo.ProjectActivity WHERE ProjectID=@ProjectID AND EntityType=N'Location' AND EntityID=@fixture; DELETE dbo.Locations WHERE LocationID=@fixture AND ProjectID=@ProjectID",new{identity.ProjectID,fixture});
}
}
private sealed class Connections(string value):ISqlConnectionFactory { public IDbConnection CreateConnection()=>new SqlConnection(value); }
}