using System.Diagnostics; using System.Globalization; using Khaemhat.Data.Querying; using Khaemhat.Data.Tests.Support; namespace Khaemhat.Data.Tests; /// /// Reference numbers for the data layer (issue M1 #13): insert and read rows through the repository. With /// KHAEMHAT_PERF=1 it uses 100,000 rows and prints the timings; otherwise 2,000 rows as a smoke test. No /// threshold is asserted: the numbers are recorded in docs/DATA-MODEL.md. /// [TestClass] public sealed class PerformanceBaselineTests { public TestContext TestContext { get; set; } = null!; [TestMethod] [TestCategory("Performance")] [DataRow(TestDatabase.Sqlite)] [DataRow(TestDatabase.Postgres)] public async Task InsertAndQuery_Baseline(string engine) { var rows = Environment.GetEnvironmentVariable("KHAEMHAT_PERF") == "1" ? 100_000 : 2_000; await using var db = await TestDatabase.CreateAsync(engine); await db.CreateTestTableAsync(); await using var unitOfWork = await db.OpenAsync(); var items = unitOfWork.Repository(); var insert = Stopwatch.StartNew(); await unitOfWork.InTransactionAsync(async ct => { for (var i = 0; i < rows; i++) { await items.InsertAsync( new TestItem { Code = "K" + i.ToString(CultureInfo.InvariantCulture), Name = "Item " + i.ToString(CultureInfo.InvariantCulture), Quantity = i % 100, Amount = i * 1.5m, At = DateTime.UtcNow, }, ct); } }); insert.Stop(); var query = Stopwatch.StartNew(); var all = await items.ListAsync(Query.For()); query.Stop(); var page = Stopwatch.StartNew(); var filtered = await items.ListAsync(Query.For().Where(x => x.Quantity == 42).OrderBy(x => x.Code).Page(0, 50)); page.Stop(); Assert.HasCount(rows, all.Items); Assert.AreEqual(rows / 100, filtered.TotalCount); TestContext.WriteLine(string.Create( CultureInfo.InvariantCulture, $"[perf] {engine}: {rows} inserts in one transaction {insert.ElapsedMilliseconds} ms ({rows * 1000.0 / Math.Max(1, insert.ElapsedMilliseconds):F0}/s); " + $"read all {query.ElapsedMilliseconds} ms; filtered page+count {page.ElapsedMilliseconds} ms")); } }