using System.Globalization; using System.Reflection; using System.Text.Json; using Dapper; using Microsoft.Data.SqlClient; using PlotLine.Models; internal static class ProjectTransferOwnedRowCensus { private sealed class Column { public string TableName { get; init; }=""; public string ColumnName { get; init; }=""; public bool IsNullable { get; init; } } private sealed class ForeignPart { public int ConstraintID { get; init; } public string ChildTable { get; init; }=""; public string ParentTable { get; init; }=""; public string ChildColumn { get; init; }=""; public string ParentColumn { get; init; }=""; } private sealed class PrimaryPart { public string TableName { get; init; }=""; public string ColumnName { get; init; }=""; public int KeyOrdinal { get; init; } } private sealed record Link(string Parent,(string Child,string Parent)[] Columns); private static void Check(bool condition,string message){if(!condition)throw new InvalidOperationException(message);} private static string Quote(string name)=>"["+name.Replace("]","]]")+ "]"; private static object? Read(object row,string column)=>row.GetType().GetProperty(column,BindingFlags.Public|BindingFlags.Instance|BindingFlags.IgnoreCase)!.GetValue(row); private static string Key(IEnumerable values)=>JsonSerializer.Serialize(values.ToArray()); internal static async Task VerifyAsync(SqlConnection db,ProjectBackupExport backup,bool emit=true) { Check(await db.ExecuteScalarAsync("SELECT DB_NAME()") == "PlotDirector_Phase2_20261103_2305" && await db.ExecuteScalarAsync("SELECT COUNT(*) FROM sys.extended_properties WHERE class=0 AND name=N'PlotDirector.Phase2.SyntheticOnly' AND CONVERT(nvarchar(20),value)=N'true'")==1,"Owned-row census requires the verified synthetic database."); var columns=(await db.QueryAsync("SELECT t.name AS TableName,c.name AS ColumnName,c.is_nullable AS IsNullable FROM sys.tables t JOIN sys.schemas s ON s.schema_id=t.schema_id JOIN sys.columns c ON c.object_id=t.object_id WHERE s.name=N'dbo'")).GroupBy(row=>row.TableName).ToDictionary(group=>group.Key,group=>group.ToArray()); var foreign=(await db.QueryAsync("SELECT fk.object_id AS ConstraintID,t.name AS ChildTable,rt.name AS ParentTable,c.name AS ChildColumn,rc.name AS ParentColumn FROM sys.foreign_keys fk JOIN sys.foreign_key_columns f ON f.constraint_object_id=fk.object_id JOIN sys.tables t ON t.object_id=f.parent_object_id JOIN sys.tables rt ON rt.object_id=f.referenced_object_id JOIN sys.columns c ON c.object_id=t.object_id AND c.column_id=f.parent_column_id JOIN sys.columns rc ON rc.object_id=rt.object_id AND rc.column_id=f.referenced_column_id WHERE SCHEMA_NAME(t.schema_id)=N'dbo' AND SCHEMA_NAME(rt.schema_id)=N'dbo'")).GroupBy(row=>row.ChildTable).ToDictionary(group=>group.Key,group=>group.GroupBy(row=>row.ConstraintID).Select(parts=>new Link(parts.First().ParentTable,parts.Select(part=>(part.ChildColumn,part.ParentColumn)).ToArray())).ToList()); var primary=(await db.QueryAsync("SELECT t.name AS TableName,c.name AS ColumnName,ic.key_ordinal AS KeyOrdinal FROM sys.tables t JOIN sys.indexes i ON i.object_id=t.object_id AND i.is_primary_key=1 JOIN sys.index_columns ic ON ic.object_id=i.object_id AND ic.index_id=i.index_id JOIN sys.columns c ON c.object_id=t.object_id AND c.column_id=ic.column_id WHERE SCHEMA_NAME(t.schema_id)=N'dbo'")).GroupBy(row=>row.TableName).ToDictionary(group=>group.Key,group=>group.OrderBy(row=>row.KeyOrdinal).Select(row=>row.ColumnName).ToArray()); var aliasNumber=0; string? Scope(string table,string alias,HashSet path) { if(!path.Add(table))return null; var fields=columns[table];var project=fields.FirstOrDefault(field=>field.ColumnName=="ProjectID"); if(project is {IsNullable:false})return alias+".[ProjectID]=@OwnedProject"; var choices=new List(); if(project is not null)choices.Add(alias+".[ProjectID]=@OwnedProject"); var links=foreign.GetValueOrDefault(table)?.ToList() ?? []; // Legacy analysis rows can identify their book without a declared database FK. if(fields.Any(field=>field.ColumnName=="BookID") && !links.Any(link=>link.Columns.Any(part=>part.Child=="BookID")))links.Add(new("Books",[("BookID","BookID")])); foreach(var link in links) { var parentAlias="owned"+(++aliasNumber).ToString(CultureInfo.InvariantCulture); var parent=Scope(link.Parent,parentAlias,new HashSet(path)); if(parent is null)continue; var join=string.Join(" AND ",link.Columns.Select(part=>alias+"."+Quote(part.Child)+"="+parentAlias+"."+Quote(part.Parent))); choices.Add("EXISTS(SELECT 1 FROM dbo."+Quote(link.Parent)+" "+parentAlias+" WHERE "+join+" AND ("+parent+"))"); } return choices.Count==0 ? null : "("+string.Join(" OR ",choices)+")"; } var aliases=new Dictionary{["TimelineSettings"]="ProjectTimelineSettings",["TimelineMetricSettings"]="ProjectTimelineMetricSettings",["AssetCustodyCharacters"]="AssetCustodyEventCharacters",["ProjectAccess"]="ProjectUserAccess",["UserFiles"]="UserFile"}; var collections=typeof(ProjectBackupData).GetProperties().Where(property=>property.Name is not ("GenreMetricPresets" or "GenreMetricPresetMetrics")) .Select(property=>(Name:property.Name,Table:aliases.GetValueOrDefault(property.Name,property.Name),Rows:((System.Collections.IEnumerable)property.GetValue(backup.Data)!).Cast().ToArray())).ToList(); collections.Add(("Project","Projects",[backup.Project!])); var ownedRows=0; var coverage=new List{"Table,Collection,OwnedDatabaseRows,ExportedRows,ExtraSharedRows,MissingOwnedRows"}; foreach(var collection in collections) { var scope=Scope(collection.Table,"ownedRoot",[]); Check(scope is not null,"Unclassified ownership path for backup table "+collection.Table); var keys=primary[collection.Table]; var actual=(await db.QueryAsync("SELECT "+string.Join(',',keys.Select(key=>"ownedRoot."+Quote(key)))+" FROM dbo."+Quote(collection.Table)+" ownedRoot WHERE "+scope,new{OwnedProject=backup.Project!.ProjectID})) .Cast>().Select(row=>Key(keys.Select(key=>row[key]))).ToHashSet(); var exported=collection.Rows.Select(row=>Key(keys.Select(key=>Read(row,key)))).ToHashSet(); Check(exported.Count==collection.Rows.Length,"Backup repeats primary-key rows in "+collection.Table); Check(actual.IsSubsetOf(exported),"Backup omits owned rows from "+collection.Table+": "+actual.Except(exported).Count()); foreach(var row in collection.Rows) { var shared=collection.Table is "AssetStates" or "CharacterAttributeTypes" or "SceneMetricTypes" && Read(row,"ProjectID") is null; Check(shared || actual.Contains(Key(keys.Select(key=>Read(row,key)))),"Backup contains a foreign owned row from "+collection.Table); } ownedRows+=actual.Count; coverage.Add($"{collection.Table},{collection.Name},{actual.Count},{collection.Rows.Length},{exported.Except(actual).Count()},0"); } if(emit) { await File.WriteAllLinesAsync("Docs/Sprints/2026-11-03-phase2-row-coverage.csv",coverage); Console.WriteLine($"PASS independent ownership row census: {collections.Count} scoped entities / {ownedRows} owned rows present; shared vocabulary checked separately."); } } }