using System.Text.Json; using Generated; using Generated.Models; using Microsoft.Data.Sqlite; using TeaQL.Provider.Sqlite; using TeaQL.Sql; using TeaQL.Core; double Number(Value value) => value.TryF64() ?? throw new Exception("Missing numeric result"); string Text(Value value) => value.TryText() ?? throw new Exception("Missing text result"); void Report(string name, object value) => Console.WriteLine("SCHOOL_CASE " + JsonSerializer.Serialize(new { @case = name, value })); var phase = args.Single(); if (!new[] {"bootstrap", "transaction", "worker", "seed", "query", "update", "read-update", "delete", "read-delete"}.Contains(phase)) throw new ArgumentException("Unknown advanced phase"); var module = GeneratedRuntimeModule.Module; var context = module.IntoContext(); await using var connection = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = Environment.GetEnvironmentVariable("SCHOOL_DATABASE") ?? throw new Exception("Missing database") }.ToString()); await connection.OpenAsync(); context.WithDataService(new SqlDataServiceExecutor(new SqliteDialect(), new SqliteTransport(connection), new MetadataSchemaProvider(module.Metadata.GetEntity))); if (phase != "worker") await context.EnsureSchemaAsync(); async Task Load(string name) => await Q.Schools().WithNameIs(name).Limit(2) .Comment("Load complete School state for mutation").Purpose("Preserve optimistic version") .ExecuteForOneAsync(context) ?? throw new Exception("School not found"); if (phase == "seed") { using var fixture = JsonDocument.Parse(File.ReadAllText(Environment.GetEnvironmentVariable("SCHOOL_FIXTURE")!)); foreach (var item in fixture.RootElement.GetProperty("schools").EnumerateArray()) { var school = Q.Schools().Comment("Create an advanced School fixture row") .Purpose("Seed advanced School scenarios").NewEntity(context); school.UpdatePlatformId(1); if (item.GetProperty("type").GetString() == "PRIMARY") school.UpdateSchoolTypeToPrimary(); else school.UpdateSchoolTypeToSecondary(); school.UpdateName(item.GetProperty("name").GetString()!); school.UpdateAddress(fixture.RootElement.GetProperty("address").GetString()!); school.UpdateEstablishedDate(DateTime.Parse(fixture.RootElement.GetProperty("establishedDate").GetString()! + "T00:00:00Z").ToUniversalTime()); school.UpdateStudentCapacity(item.GetProperty("capacity").GetInt32()); school.UpdateActive(item.GetProperty("active").GetBoolean()); await school.AuditAs("Seed the advanced School fixture").SaveAsync(context); } } // scenario: transaction-commit, transaction-rollback if (phase == "transaction") { var rollback = Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") == "transaction-rollback"; var root = await Q.Platforms().SelectSchoolListWith(Q.Schools().WithNameIs("Riverside Primary School").Limit(2)) .Limit(2).Comment("Load the Platform and School transaction graph").Purpose("Verify atomic graph writes").ExecuteForOneAsync(context) ?? throw new Exception("Missing Platform"); var child = root.SchoolList[0]; if (rollback) { var winner = await Load("Riverside Primary School"); winner.UpdateStudentCapacity(801); await winner.AuditAs("Advance School before the stale graph").SaveAsync(context); } root.UpdateName("Transactional Campus"); child.UpdateStudentCapacity(810); Console.WriteLine("SCHOOL_GRAPH_ATTEMPT"); var rejected = false; try { await root.AuditAs("Revise Platform and School atomically").SaveAsync(context); } catch (Exception error) when (rollback && new[] {"version", "optimistic", "conflict", "stale", "authoritative persisted state"}.Any(w => error.ToString().Contains(w, StringComparison.OrdinalIgnoreCase))) { rejected = true; } Report(Environment.GetEnvironmentVariable("SCHOOL_SCENARIO")!, new {rejected}); } // scenario: concurrent-same, concurrent-distinct if (phase == "worker") { var target = Environment.GetEnvironmentVariable("SCHOOL_TARGET")!; var worker = Environment.GetEnvironmentVariable("SCHOOL_WORKER")!; var barrier = Environment.GetEnvironmentVariable("SCHOOL_BARRIER")!; var row = await Load(target); var observedVersion = E.School(row).Version().Eval(); File.WriteAllText(Path.Combine(barrier, worker + ".ready"), JsonSerializer.Serialize(new {observedVersion})); var timeout = System.Diagnostics.Stopwatch.StartNew(); while (!File.Exists(Path.Combine(barrier, "release"))) { if (timeout.Elapsed.TotalSeconds > 30) throw new Exception("Barrier timeout"); await Task.Delay(10); } row.UpdateStudentCapacity(worker == "a" ? 811 : 822); var outcome = "committed"; var conflictReason = ""; try { await row.AuditAs("Concurrent School capacity revision").SaveAsync(context); } catch (Exception error) when (new[] {"version", "optimistic", "conflict", "stale", "authoritative persisted state"}.Any(w => error.ToString().Contains(w, StringComparison.OrdinalIgnoreCase))) { outcome = "conflict"; conflictReason = error.ToString(); } Console.WriteLine("SCHOOL_WORKER " + JsonSerializer.Serialize(new {worker, target, observedVersion, outcome, conflictReason})); } if (phase == "query") { // scenario: continuous-ascending if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "continuous-ascending") { var pages = new List(); var plans = new List(); var totals = new List(); var observedCounts = new List(); foreach (var (offset, threshold) in new[] { (0, 0), (2, 0), (4, 0) }) { var page = await Q.SchoolsWithMinimalFields().SelectName().WithStudentCapacityGreaterThanOrEqualTo(threshold) .OrderByIdAscending().Offset(offset).Limit(2).OptimizeForContinuousPageFetchWith("continuous-ascending", 60) .Comment("Browse School pagination").Purpose("Verify continuous-ascending").ExecuteForListAsync(context); pages.Add(page.Select(s => E.School(s).Name().Eval()).ToArray()); plans.Add(context.ContinuousPagePlan); } Report("continuous-ascending", new {pages, plans}); } // scenario: continuous-descending if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "continuous-descending") { var pages = new List(); var plans = new List(); var totals = new List(); var observedCounts = new List(); foreach (var (offset, threshold) in new[] { (0, 0), (2, 0), (4, 0) }) { var page = await Q.SchoolsWithMinimalFields().SelectName().WithStudentCapacityGreaterThanOrEqualTo(threshold) .OrderByIdDescending().Offset(offset).Limit(2).OptimizeForContinuousPageFetchWith("continuous-descending", 60) .Comment("Browse School pagination").Purpose("Verify continuous-descending").ExecuteForListAsync(context); pages.Add(page.Select(s => E.School(s).Name().Eval()).ToArray()); plans.Add(context.ContinuousPagePlan); } Report("continuous-descending", new {pages, plans}); } // scenario: continuous-cache-miss if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "continuous-cache-miss") { var pages = new List(); var plans = new List(); var totals = new List(); var observedCounts = new List(); foreach (var (offset, threshold) in new[] { (2, 0), (4, 0) }) { var page = await Q.SchoolsWithMinimalFields().SelectName().WithStudentCapacityGreaterThanOrEqualTo(threshold) .OrderByIdAscending().Offset(offset).Limit(2).OptimizeForContinuousPageFetchWith("continuous-cache-miss", 60) .Comment("Browse School pagination").Purpose("Verify continuous-cache-miss").ExecuteForListAsync(context); pages.Add(page.Select(s => E.School(s).Name().Eval()).ToArray()); plans.Add(context.ContinuousPagePlan); } Report("continuous-cache-miss", new {pages, plans}); } // scenario: id-set-jump if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "id-set-jump") { var pages = new List(); var plans = new List(); var totals = new List(); var observedCounts = new List(); foreach (var (offset, threshold) in new[] { (4, 0), (0, 0), (2, 0), (6, 0) }) { var page = await Q.SchoolsWithMinimalFields().SelectName().WithStudentCapacityGreaterThanOrEqualTo(threshold) .OrderByStudentCapacityDescending().OrderByNameAscending().OrderByIdAscending().Offset(offset).Limit(2).OptimizePaginationWithIdSet("id-set-jump", 60, 100).Count() .Comment("Browse School pagination").Purpose("Verify id-set-jump").ExecuteForListAsync(context); pages.Add(page.Select(s => E.School(s).Name().Eval()).ToArray()); plans.Add(context.IdSetPlan); totals.Add(page.TotalCount!); observedCounts.Add(context.IdSetCount!); } Report("id-set-jump", new {pages, plans, totals, observedCounts}); } // scenario: id-set-empty if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "id-set-empty") { var pages = new List(); var plans = new List(); var totals = new List(); var observedCounts = new List(); foreach (var (offset, threshold) in new[] { (0, 100000), (2, 100000) }) { var page = await Q.SchoolsWithMinimalFields().SelectName().WithStudentCapacityGreaterThanOrEqualTo(threshold) .OrderByStudentCapacityDescending().OrderByNameAscending().OrderByIdAscending().Offset(offset).Limit(2).OptimizePaginationWithIdSet("id-set-empty", 60, 100).Count() .Comment("Browse School pagination").Purpose("Verify id-set-empty").ExecuteForListAsync(context); pages.Add(page.Select(s => E.School(s).Name().Eval()).ToArray()); plans.Add(context.IdSetPlan); totals.Add(page.TotalCount!); observedCounts.Add(context.IdSetCount!); } Report("id-set-empty", new {pages, plans, totals, observedCounts}); } // scenario: id-set-overflow if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "id-set-overflow") { var pages = new List(); var plans = new List(); var totals = new List(); var observedCounts = new List(); foreach (var (offset, threshold) in new[] { (2, 0) }) { var page = await Q.SchoolsWithMinimalFields().SelectName().WithStudentCapacityGreaterThanOrEqualTo(threshold) .OrderByStudentCapacityDescending().OrderByNameAscending().OrderByIdAscending().Offset(offset).Limit(2).OptimizePaginationWithIdSet("id-set-overflow", 60, 3).Count() .Comment("Browse School pagination").Purpose("Verify id-set-overflow").ExecuteForListAsync(context); pages.Add(page.Select(s => E.School(s).Name().Eval()).ToArray()); plans.Add(context.IdSetPlan); totals.Add(page.TotalCount!); observedCounts.Add(context.IdSetCount!); } Report("id-set-overflow", new {pages, plans, totals, observedCounts}); } // scenario: id-set-isolation if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "id-set-isolation") { var pages = new List(); var plans = new List(); var totals = new List(); var observedCounts = new List(); foreach (var (offset, threshold) in new[] { (0, 500), (0, 1000), (0, 500) }) { var page = await Q.SchoolsWithMinimalFields().SelectName().WithStudentCapacityGreaterThanOrEqualTo(threshold) .OrderByStudentCapacityDescending().OrderByNameAscending().OrderByIdAscending().Offset(offset).Limit(2).OptimizePaginationWithIdSet("id-set-isolation", 60, 100).Count() .Comment("Browse School pagination").Purpose("Verify id-set-isolation").ExecuteForListAsync(context); pages.Add(page.Select(s => E.School(s).Name().Eval()).ToArray()); plans.Add(context.IdSetPlan); totals.Add(page.TotalCount!); observedCounts.Add(context.IdSetCount!); } Report("id-set-isolation", new {pages, plans, totals, observedCounts}); } // scenario: pagination if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "pagination") { var page = await Q.SchoolsWithMinimalFields().SelectName().WhichAreActive() .WithStudentCapacityGreaterThanOrEqualTo(500) .OrderByStudentCapacityDescending().OrderByIdAscending().Offset(1).Limit(2).Count() .Comment("Page active schools by capacity").Purpose("Review the School directory") .ExecuteForListAsync(context); Report("pagination", new { names = page.Select(s => E.School(s).Name().Eval()), total = page.TotalCount }); } // scenario: relations if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "relations") { var rows = await Q.SchoolsWithMinimalFields().SelectName().WithNameIs("Riverside Primary School") .SelectSchoolTypeWith(Q.SchoolTypesWithMinimalFields().SelectCode()) .SelectPlatformWith(Q.PlatformsWithMinimalFields().SelectName()).Limit(2) .Comment("Load School type and platform").Purpose("Review loaded School relations") .ExecuteForListAsync(context); var one = rows.Single(); Report("relations", new { school = E.School(one).Name().Eval(), type = E.SchoolType(E.School(one).SchoolType().Eval()!).Code().Eval(), platform = E.Platform(E.School(one).Platform().Eval()!).Name().Eval() }); } // scenario: groups if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "groups") { var groups = await Q.Schools().GroupBySchoolType().CountAs("count") .SumStudentCapacityAs("total").AvgStudentCapacityAs("average").Limit(10) .Comment("Group School capacity by type").Purpose("Verify provider aggregation") .ExecuteForRowsAsync(context); Report("groups", groups.Rows.Select(r => new { type = Number(r["school_type"]), count = Number(r["count"]), total = Number(r["total"]), average = Number(r["average"]) })); } // scenario: relation-metrics if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "relation-metrics") { var cards = await Q.SchoolTypesWithMinimalFields().SelectCode().CountSchoolsAs("count") .SumStudentCapacityOfSchoolsAs("total", Q.Schools()).OrderByCodeAscending().Limit(10) .Comment("Calculate SchoolType relation metrics").Purpose("Verify provider relation aggregation") .ExecuteForRowsAsync(context); Report("relation-metrics", cards.Rows.ToDictionary(r => Text(r["code"]), r => new { count = Number(r["count"]), total = Number(r["total"]) })); } // scenario: facets if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "facets") { var allRows = await Q.SchoolsWithMinimalFields().SelectName().WithNameIs("Riverside Primary School") .FacetBySchoolTypeAs("types", Q.SchoolTypesWithMinimalFields().SelectCode().CountSchoolsAs("count"), true) .FacetByPlatformAs("platforms", Q.PlatformsWithMinimalFields().SelectName().CountSchoolsAs("count"), false) .OrderByIdAscending().Limit(2) .Comment("Facet the matching School set").Purpose("Compare zero and matched buckets") .ExecuteForListAsync(context); var matched = await Q.SchoolsWithMinimalFields().SelectName().WithNameIs("Riverside Primary School") .FacetBySchoolTypeAs("types", Q.SchoolTypesWithMinimalFields().SelectCode().CountSchoolsAs("count"), false) .OrderByIdAscending().Limit(2) .Comment("Facet only matched School types").Purpose("Compare zero and matched buckets") .ExecuteForListAsync(context); Report("facets", new { includeAll = allRows.Facet("types")!.ToDictionary(r => Text(r["code"]), r => Number(r["count"])), matchedOnly = matched.Facet("types")!.ToDictionary(r => Text(r["code"]), r => Number(r["count"])), platforms = allRows.Facet("platforms")!.ToDictionary(r => Text(r["name"]), r => Number(r["count"])), rows = allRows.Select(s => E.School(s).Name().Eval()) }); } // scenario: page-boundaries if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "page-boundaries") { var pages = new List(); var totals = new List(); foreach (var offset in new[] {0, 2, 4, 6}) { var page = await Q.SchoolsWithMinimalFields().SelectName() .OrderByStudentCapacityDescending().OrderByNameAscending().OrderByIdAscending().Offset(offset).Limit(2).Count() .Comment("Traverse School pages including an empty tail").Purpose("Verify stable page boundaries") .ExecuteForListAsync(context); pages.Add(page.Select(s => E.School(s).Name().Eval()).ToArray()); totals.Add(page.TotalCount); } Report("page-boundaries", new { pages, totals }); } // scenario: relation-predicates if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "relation-predicates") { var matching = await Q.SchoolsWithMinimalFields().SelectName() .WithSchoolTypeMatching(Q.SchoolTypesWithMinimalFields().WithCodeIs("PRIMARY")) .OrderByNameAscending().Limit(10).Comment("Match School type by child request") .Purpose("Verify relation predicate semantics").ExecuteForListAsync(context); var excluding = await Q.SchoolsWithMinimalFields().SelectName() .WithoutSchoolTypeMatching(Q.SchoolTypesWithMinimalFields().WithCodeIs("PRIMARY")) .OrderByNameAscending().Limit(10).Comment("Exclude School type by child request") .Purpose("Verify negative relation predicates").ExecuteForListAsync(context); var nested = await Q.SchoolsWithMinimalFields().SelectName() .WithSchoolTypeMatching(Q.SchoolTypesWithMinimalFields().WithCodeIs("PRIMARY") .WithPlatformMatching(Q.PlatformsWithMinimalFields().WithNameIs("Campus Learning Platform"))) .OrderByNameAscending().Limit(10).Comment("Match School through type and platform") .Purpose("Verify two-level relation predicates").ExecuteForListAsync(context); Report("relation-predicates", new { matching = matching.Select(s => E.School(s).Name().Eval()), excluding = excluding.Select(s => E.School(s).Name().Eval()), nested = nested.Select(s => E.School(s).Name().Eval()) }); } // scenario: blank-intent if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "blank-intent") { var rejected = new List(); foreach (var (comment, purpose) in new[] {(" ", "Verify blank comment rejection"), ("Check blank purpose rejection", " ")}) { var denied = false; try { await Q.SchoolsWithMinimalFields().Limit(1).Comment(comment).Purpose(purpose).ExecuteForListAsync(context); } catch (Exception error) when (new[] {"comment", "purpose", "intent"}.Any(word => error.ToString().Contains(word, StringComparison.OrdinalIgnoreCase))) { denied = true; } rejected.Add(denied); } Report("blank-intent", new { blankComment = rejected[0], blankPurpose = rejected[1] }); } // scenario: empty-page if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "empty-page") { var page = await Q.SchoolsWithMinimalFields().SelectName().WithNameIs("No such School") .OrderByStudentCapacityDescending().OrderByIdAscending().Offset(1).Limit(2).Count() .Comment("Read a School filter with no matches").Purpose("Verify empty page count") .ExecuteForListAsync(context); Report("empty-page", new { names = page.Select(s => E.School(s).Name().Eval()), total = page.TotalCount }); } // scenario: filtered-groups if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "filtered-groups") { var groups = await Q.Schools().WhichAreActive().WithStudentCapacityGreaterThanOrEqualTo(500).GroupBySchoolType().CountAs("count") .SumStudentCapacityAs("total").AvgStudentCapacityAs("average").Limit(10) .Comment("Aggregate active Schools with capacity at least 500").Purpose("Verify provider aggregation") .ExecuteForRowsAsync(context); Report("filtered-groups", groups.Rows.Select(r => new { type = Number(r["school_type"]), count = Number(r["count"]), total = Number(r["total"]), average = Number(r["average"]) })); } // scenario: filtered-children if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "filtered-children") { var types = await Q.SchoolTypesWithMinimalFields().SelectCode() .SelectSchoolListWith(Q.SchoolsWithMinimalFields().SelectName().WhichAreNotActive() .OrderByStudentCapacityDescending().OrderByIdAscending().Limit(2)) .OrderByCodeAscending().Limit(10) .Comment("Load inactive Schools for each type").Purpose("Preserve parents with empty child lists") .ExecuteForListAsync(context); Report("filtered-children", types.ToDictionary(t => E.SchoolType(t).Code().Eval()!, t => Enumerable.Range(0, E.SchoolType(t).SchoolList().Size().Eval()) .Select(i => E.SchoolType(t).SchoolList().Get(i).Name().Eval()).ToArray())); } // scenario: empty-facets if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "empty-facets") { var allRows = await Q.SchoolsWithMinimalFields().SelectName().WithNameIs("No such School") .FacetBySchoolTypeAs("types", Q.SchoolTypesWithMinimalFields().SelectCode().CountSchoolsAs("count"), true) .FacetByPlatformAs("platforms", Q.PlatformsWithMinimalFields().SelectName().CountSchoolsAs("count"), false) .OrderByIdAscending().Limit(2) .Comment("Facet the matching School set").Purpose("Compare zero and matched buckets") .ExecuteForListAsync(context); var matched = await Q.SchoolsWithMinimalFields().SelectName().WithNameIs("No such School") .FacetBySchoolTypeAs("types", Q.SchoolTypesWithMinimalFields().SelectCode().CountSchoolsAs("count"), false) .OrderByIdAscending().Limit(2) .Comment("Facet only matched School types").Purpose("Compare zero and matched buckets") .ExecuteForListAsync(context); Report("empty-facets", new { includeAll = allRows.Facet("types")!.ToDictionary(r => Text(r["code"]), r => Number(r["count"])), matchedOnly = matched.Facet("types")!.ToDictionary(r => Text(r["code"]), r => Number(r["count"])), platforms = allRows.Facet("platforms")!.ToDictionary(r => Text(r["name"]), r => Number(r["count"])), rows = allRows.Select(s => E.School(s).Name().Eval()) }); } // scenario: top-n if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "top-n") { var types = await Q.SchoolTypesWithMinimalFields().SelectCode() .SelectSchoolListWith(Q.SchoolsWithMinimalFields().SelectName() .OrderByStudentCapacityDescending().OrderByIdAscending().Limit(2)) .OrderByCodeAscending().Limit(10) .Comment("Load the two largest schools for each type").Purpose("Verify Top-N across two parents") .ExecuteForListAsync(context); Report("top-n", types.ToDictionary(t => E.SchoolType(t).Code().Eval()!, t => Enumerable.Range(0, E.SchoolType(t).SchoolList().Size().Eval()) .Select(i => E.SchoolType(t).SchoolList().Get(i).Name().Eval()).ToArray())); } } // scenario: update if (phase == "update") { var school = await Load("Riverside Primary School"); var stale = await Load("Riverside Primary School"); var before = E.School(school).Version().Eval(); school.UpdateStudentCapacity(950); school = await school.AuditAs("Approve School capacity revision").SaveAsync(context); Report("update", new { before, after = E.School(school).Version().Eval(), capacity = E.School(school).StudentCapacity().Eval() }); stale.UpdateStudentCapacity(999); var rejected = false; try { await stale.AuditAs("Reject stale School capacity revision").SaveAsync(context); } catch (Exception error) when (error.Message == "Mutation provider did not return authoritative persisted state for School" || new[] {"version", "optimistic", "conflict", "stale"}.Any(word => error.ToString().Contains(word, StringComparison.OrdinalIgnoreCase))) { rejected = true; } Report("stale-write", new { rejected }); } if (phase == "read-update") { var school = await Load("Riverside Primary School"); Report("read-update", new { capacity = E.School(school).StudentCapacity().Eval(), version = E.School(school).Version().Eval() }); } // scenario: delete if (phase == "delete") { var school = await Load("Hill Secondary School"); school.MarkForDeletion(); await school.AuditAs("Retire inactive School fixture").SaveAsync(context); } if (phase == "delete" || (phase == "read-delete" && Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "read-delete")) { var visible = await Q.SchoolsWithMinimalFields().WithNameIs("Hill Secondary School").Limit(2) .Comment("Check the retired School is hidden").Purpose("Verify soft deletion visibility") .ExecuteForListAsync(context); if (phase == "delete") Report(phase, new { visible = visible.Count }); else { var deleted = await Q.SchoolsWithMinimalFields().DeletedRowsOnly().WithNameIs("Hill Secondary School").Limit(2) .Comment("Read the School tombstone").Purpose("Verify persisted deletion intent") .ExecuteForListAsync(context); Report(phase, new { visible = visible.Count, deleted = deleted.Count }); } } if (phase == "read-delete") { // scenario: deleted-groups if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "deleted-groups") { var groups = await Q.Schools().GroupBySchoolType().CountAs("count") .SumStudentCapacityAs("total").AvgStudentCapacityAs("average").Limit(10) .Comment("Aggregate surviving Schools after deletion").Purpose("Verify provider aggregation") .ExecuteForRowsAsync(context); Report("deleted-groups", groups.Rows.Select(r => new { type = Number(r["school_type"]), count = Number(r["count"]), total = Number(r["total"]), average = Number(r["average"]) })); } // scenario: deleted-metrics if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "deleted-metrics") { var cards = await Q.SchoolTypesWithMinimalFields().SelectCode().CountSchoolsAs("count") .SumStudentCapacityOfSchoolsAs("total", Q.Schools()).OrderByCodeAscending().Limit(10) .Comment("Calculate relation metrics after School deletion").Purpose("Verify provider relation aggregation") .ExecuteForRowsAsync(context); Report("deleted-metrics", cards.Rows.ToDictionary(r => Text(r["code"]), r => new { count = Number(r["count"]), total = Number(r["total"]) })); } // scenario: deleted-facets if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "deleted-facets") { var allRows = await Q.SchoolsWithMinimalFields().SelectName() .FacetBySchoolTypeAs("types", Q.SchoolTypesWithMinimalFields().SelectCode().CountSchoolsAs("count"), true) .FacetByPlatformAs("platforms", Q.PlatformsWithMinimalFields().SelectName().CountSchoolsAs("count"), false) .OrderByStudentCapacityDescending().OrderByIdAscending().Limit(2) .Comment("Facet the matching School set").Purpose("Compare zero and matched buckets") .ExecuteForListAsync(context); var matched = await Q.SchoolsWithMinimalFields().SelectName() .FacetBySchoolTypeAs("types", Q.SchoolTypesWithMinimalFields().SelectCode().CountSchoolsAs("count"), false) .OrderByStudentCapacityDescending().OrderByIdAscending().Limit(2) .Comment("Facet only matched School types").Purpose("Compare zero and matched buckets") .ExecuteForListAsync(context); Report("deleted-facets", new { includeAll = allRows.Facet("types")!.ToDictionary(r => Text(r["code"]), r => Number(r["count"])), matchedOnly = matched.Facet("types")!.ToDictionary(r => Text(r["code"]), r => Number(r["count"])), platforms = allRows.Facet("platforms")!.ToDictionary(r => Text(r["name"]), r => Number(r["count"])), rows = allRows.Select(s => E.School(s).Name().Eval()) }); } // scenario: deleted-children if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "deleted-children") { var types = await Q.SchoolTypesWithMinimalFields().SelectCode() .SelectSchoolListWith(Q.SchoolsWithMinimalFields().SelectName() .OrderByStudentCapacityDescending().OrderByIdAscending().Limit(2)) .OrderByCodeAscending().Limit(10) .Comment("Load surviving Schools for each type").Purpose("Exclude tombstones from ordinary child lists") .ExecuteForListAsync(context); Report("deleted-children", types.ToDictionary(t => E.SchoolType(t).Code().Eval()!, t => Enumerable.Range(0, E.SchoolType(t).SchoolList().Size().Eval()) .Select(i => E.SchoolType(t).SchoolList().Get(i).Name().Eval()).ToArray())); } // scenario: deleted-child-tombstones if (Environment.GetEnvironmentVariable("SCHOOL_SCENARIO") is null or "deleted-child-tombstones") { var types = await Q.SchoolTypesWithMinimalFields().SelectCode() .SelectSchoolListWith(Q.SchoolsWithMinimalFields().SelectName().DeletedRowsOnly() .OrderByStudentCapacityDescending().OrderByIdAscending().Limit(2)) .OrderByCodeAscending().Limit(10) .Comment("Load retired Schools for each live type").Purpose("Keep child deletion scope separate from parent visibility") .ExecuteForListAsync(context); Report("deleted-child-tombstones", types.ToDictionary(t => E.SchoolType(t).Code().Eval()!, t => Enumerable.Range(0, E.SchoolType(t).SchoolList().Size().Eval()) .Select(i => E.SchoolType(t).SchoolList().Get(i).Name().Eval()).ToArray())); } } Console.WriteLine($"SCHOOL_OK phase={phase}");