|
| 1 | +using System.Data.Common; |
| 2 | +using static Microsoft.VisualStudio.TestTools.UnitTesting.Assert; |
| 3 | + |
| 4 | +namespace SqlServerSimulator; |
| 5 | + |
| 6 | +/// <summary> |
| 7 | +/// Tests for derived tables in FROM that reference outer-scope columns — |
| 8 | +/// SQL Server's "any FROM derived table can correlate" rule, not just the |
| 9 | +/// CROSS APPLY / OUTER APPLY shape. The simulator threads the outer-type |
| 10 | +/// resolver into the inner Parse and defers execution per Selection |
| 11 | +/// instance so the inner plan re-runs with each call's outer resolver. |
| 12 | +/// </summary> |
| 13 | +[TestClass] |
| 14 | +public sealed class CorrelatedDerivedTableTests |
| 15 | +{ |
| 16 | + private static DbConnection SeededSales() |
| 17 | + { |
| 18 | + var connection = new Simulation().CreateOpenConnection(); |
| 19 | + _ = connection.CreateCommand( |
| 20 | + "create table sales (region varchar(10), salesperson varchar(20), amount decimal(10,2))").ExecuteNonQuery(); |
| 21 | + _ = connection.CreateCommand( |
| 22 | + "insert into sales values " + |
| 23 | + "('east', 'alice', 100), " + |
| 24 | + "('east', 'alice', 200), " + |
| 25 | + "('east', 'bob', 150), " + |
| 26 | + "('west', 'carol', 300), " + |
| 27 | + "('west', 'carol', 500), " + |
| 28 | + "('west', 'dan', 50)").ExecuteNonQuery(); |
| 29 | + return connection; |
| 30 | + } |
| 31 | + |
| 32 | + [TestMethod] |
| 33 | + public void DistinctCorrelatedCount_TheEFShape_Works() |
| 34 | + { |
| 35 | + // The exact shape EF Core 10 emits for `db.X.Select(s => new { |
| 36 | + // DistinctCount = db.Y.Where(...).Distinct().Count() })`. Before |
| 37 | + // this fix, the simulator threw "Invalid column name 's.Region'" |
| 38 | + // because the inner derived table couldn't see the outer scope. |
| 39 | + using var connection = SeededSales(); |
| 40 | + using var reader = connection.CreateCommand( |
| 41 | + "select s.region, (select count(*) from (select distinct s0.salesperson from sales as s0 where s0.region = s.region) as s1) from sales as s").ExecuteReader(); |
| 42 | + var counts = new Dictionary<string, int>(); |
| 43 | + while (reader.Read()) |
| 44 | + counts[reader.GetString(0)] = reader.GetInt32(1); |
| 45 | + AreEqual(2, counts["east"]); // alice, bob |
| 46 | + AreEqual(2, counts["west"]); // carol, dan |
| 47 | + } |
| 48 | + |
| 49 | + [TestMethod] |
| 50 | + public void CorrelatedDerivedTableInWhereExists() |
| 51 | + { |
| 52 | + // `where exists (select 1 from (correlated derived) as sub where ...)` |
| 53 | + using var connection = SeededSales(); |
| 54 | + using var reader = connection.CreateCommand( |
| 55 | + "select distinct s.region from sales as s where exists (" + |
| 56 | + " select 1 from (select distinct x.salesperson from sales as x where x.region = s.region) as sub" + |
| 57 | + " where sub.salesperson = 'alice')").ExecuteReader(); |
| 58 | + var regions = new List<string>(); |
| 59 | + while (reader.Read()) |
| 60 | + regions.Add(reader.GetString(0)); |
| 61 | + // Only east has 'alice'; west doesn't. |
| 62 | + HasCount(1, regions); |
| 63 | + AreEqual("east", regions[0]); |
| 64 | + } |
| 65 | + |
| 66 | + [TestMethod] |
| 67 | + public void NonCorrelatedDerivedTable_StillWorks() |
| 68 | + { |
| 69 | + // Regression — an uncorrelated derived table (no outer reference) |
| 70 | + // should still produce its own row stream. Always-defer changes |
| 71 | + // the runtime path but the result must be identical. |
| 72 | + using var connection = SeededSales(); |
| 73 | + using var reader = connection.CreateCommand( |
| 74 | + "select region, total from (select region, sum(amount) as total from sales group by region) as g order by region").ExecuteReader(); |
| 75 | + var pairs = new List<(string Region, decimal Total)>(); |
| 76 | + while (reader.Read()) |
| 77 | + pairs.Add((reader.GetString(0), reader.GetDecimal(1))); |
| 78 | + HasCount(2, pairs); |
| 79 | + AreEqual(("east", 450.00m), pairs[0]); |
| 80 | + AreEqual(("west", 850.00m), pairs[1]); |
| 81 | + } |
| 82 | + |
| 83 | + [TestMethod] |
| 84 | + public void NonCorrelatedDerivedTable_JoinedToHeapTable() |
| 85 | + { |
| 86 | + // Pre-existing JOIN-with-derived-table shape. After the always-defer |
| 87 | + // change the JoinDriver lateral branch handles the ON predicate |
| 88 | + // and INNER semantics for these too. |
| 89 | + using var connection = SeededSales(); |
| 90 | + using var reader = connection.CreateCommand( |
| 91 | + "select s.region, s.salesperson, t.total " + |
| 92 | + "from sales as s inner join (select region, sum(amount) as total from sales group by region) as t " + |
| 93 | + " on s.region = t.region " + |
| 94 | + "order by s.region, s.salesperson, s.amount").ExecuteReader(); |
| 95 | + var rows = new List<(string Region, string Person, decimal Total)>(); |
| 96 | + while (reader.Read()) |
| 97 | + rows.Add((reader.GetString(0), reader.GetString(1), reader.GetDecimal(2))); |
| 98 | + HasCount(6, rows); |
| 99 | + // Each detail row carries its region's broadcast total. |
| 100 | + IsTrue(rows.Where(r => r.Region == "east").All(r => r.Total == 450.00m)); |
| 101 | + IsTrue(rows.Where(r => r.Region == "west").All(r => r.Total == 850.00m)); |
| 102 | + } |
| 103 | + |
| 104 | + [TestMethod] |
| 105 | + public void LeftJoin_DerivedTable_NullFillsNoMatch() |
| 106 | + { |
| 107 | + // LEFT JOIN to a derived table with an ON predicate that fails |
| 108 | + // for some outer rows must null-fill, matching real SQL Server. |
| 109 | + using var connection = SeededSales(); |
| 110 | + _ = connection.CreateCommand( |
| 111 | + "create table regions (region varchar(10), label varchar(20))").ExecuteNonQuery(); |
| 112 | + _ = connection.CreateCommand( |
| 113 | + "insert into regions values ('east', 'East'), ('north', 'North')").ExecuteNonQuery(); |
| 114 | + using var reader = connection.CreateCommand( |
| 115 | + "select r.region, r.label, t.total " + |
| 116 | + "from regions as r left join (select region, sum(amount) as total from sales group by region) as t " + |
| 117 | + " on r.region = t.region " + |
| 118 | + "order by r.region").ExecuteReader(); |
| 119 | + var rows = new List<(string Region, string Label, decimal? Total)>(); |
| 120 | + while (reader.Read()) |
| 121 | + rows.Add((reader.GetString(0), reader.GetString(1), reader.IsDBNull(2) ? null : reader.GetDecimal(2))); |
| 122 | + HasCount(2, rows); |
| 123 | + AreEqual("east", rows[0].Region); |
| 124 | + AreEqual(450.00m, rows[0].Total); |
| 125 | + // 'north' has no matching sales rows → null-filled total. |
| 126 | + AreEqual("north", rows[1].Region); |
| 127 | + IsNull(rows[1].Total); |
| 128 | + } |
| 129 | + |
| 130 | + [TestMethod] |
| 131 | + public void CorrelatedDerivedTable_AsScalarSubqueryFromSource() |
| 132 | + { |
| 133 | + // Scalar subquery whose own FROM is a correlated derived table — |
| 134 | + // the EF distinct-count shape with TOP rather than COUNT. |
| 135 | + using var connection = SeededSales(); |
| 136 | + using var reader = connection.CreateCommand( |
| 137 | + "select s.region, (select top 1 sub.salesperson from (select distinct x.salesperson from sales as x where x.region = s.region) as sub order by sub.salesperson) " + |
| 138 | + "from sales as s where s.salesperson = 'alice'").ExecuteReader(); |
| 139 | + // Both alice rows are in 'east'; the inner returns the first |
| 140 | + // distinct salesperson alphabetically in 'east' = 'alice'. |
| 141 | + var rows = new List<(string Region, string FirstSp)>(); |
| 142 | + while (reader.Read()) |
| 143 | + rows.Add((reader.GetString(0), reader.GetString(1))); |
| 144 | + HasCount(2, rows); |
| 145 | + IsTrue(rows.All(r => r.Region == "east" && r.FirstSp == "alice")); |
| 146 | + } |
| 147 | +} |
0 commit comments