Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Query: Add identifier appropriately when generating joins #20599

Merged
merged 1 commit into from
Apr 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ private static void PopulateCollection<TCollection, TElement, TRelatedEntity>(
}

var innerKey = selfIdentifier(queryContext, dbDataReader);
if (innerKey.Any(e => e == null))
if (innerKey.Length > 0 && innerKey.All(e => e == null))
{
// No correlated element
return;
Expand Down Expand Up @@ -236,7 +236,7 @@ private static void PopulateIncludeCollection<TIncludingEntity, TIncludedEntity>
}

var innerKey = selfIdentifier(queryContext, dbDataReader);
if (innerKey.Any(e => e == null))
if (innerKey.All(e => e == null))
{
// No correlated element
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ private static bool IsNullableProjection(ProjectionExpression projectionExpressi
};

private ColumnExpression(string name, TableExpressionBase table, Type type, RelationalTypeMapping typeMapping, bool nullable)
: base(type, typeMapping)
: base(nullable ? type.MakeNullable() : type, typeMapping)
{
Check.NotEmpty(name, nameof(name));
Check.NotNull(table, nameof(table));
Expand Down
19 changes: 12 additions & 7 deletions src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ private readonly IDictionary<EntityProjectionExpression, IDictionary<IProperty,
private readonly List<TableExpressionBase> _tables = new List<TableExpressionBase>();
private readonly List<SqlExpression> _groupBy = new List<SqlExpression>();
private readonly List<OrderingExpression> _orderings = new List<OrderingExpression>();
private readonly List<(SqlExpression Column, ValueComparer Comparer)> _identifier
= new List<(SqlExpression Column, ValueComparer Comparer)>();
private readonly List<(SqlExpression Column, ValueComparer Comparer)> _childIdentifiers
= new List<(SqlExpression Column, ValueComparer Comparer)>();
private readonly List<(ColumnExpression Column, ValueComparer Comparer)> _identifier
= new List<(ColumnExpression Column, ValueComparer Comparer)>();
private readonly List<(ColumnExpression Column, ValueComparer Comparer)> _childIdentifiers
= new List<(ColumnExpression Column, ValueComparer Comparer)>();
private readonly List<SelectExpression> _pendingCollections = new List<SelectExpression>();

private IDictionary<ProjectionMember, Expression> _projectionMapping = new Dictionary<ProjectionMember, Expression>();
Expand Down Expand Up @@ -979,7 +979,7 @@ public Expression ApplyCollectionJoin(

foreach (var identifier in innerSelectExpression._identifier.Concat(innerSelectExpression._childIdentifiers))
{
var updatedColumn = MakeNullable(identifier.Column);
var updatedColumn = identifier.Column.MakeNullable();
_childIdentifiers.Add((updatedColumn, identifier.Comparer));
AppendOrdering(new OrderingExpression(updatedColumn, ascending: true));
}
Expand All @@ -1000,7 +1000,7 @@ private static SqlExpression MakeNullable(SqlExpression sqlExpression)
=> sqlExpression is ColumnExpression column ? column.MakeNullable() : sqlExpression;

private (Expression, IReadOnlyList<ValueComparer>) GetIdentifierAccessor(
IEnumerable<(SqlExpression Column, ValueComparer Comparer)> identifyingProjection)
IEnumerable<(ColumnExpression Column, ValueComparer Comparer)> identifyingProjection)
{
var updatedExpressions = new List<Expression>();
var comparers = new List<ValueComparer>();
Expand Down Expand Up @@ -1383,7 +1383,12 @@ private void AddJoin(
.Remap(joinPredicate);
}

if (joinType != JoinType.LeftJoin)
if (joinType == JoinType.LeftJoin
|| joinType == JoinType.OuterApply)
{
_identifier.AddRange(innerSelectExpression._identifier.Select(e => (e.Column.MakeNullable(), e.Comparer)));
}
else
{
_identifier.AddRange(innerSelectExpression._identifier);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,40 +51,76 @@ public void AssertBaseline(string[] expected)
}
catch
{
var writeToLog = true;
var methodCallLine = Environment.StackTrace.Split(
new[] { _eol },
StringSplitOptions.RemoveEmptyEntries)[3].Substring(6);

var testName = methodCallLine.Substring(0, methodCallLine.IndexOf(')') + 1);
var lineIndex = methodCallLine.LastIndexOf("line", StringComparison.Ordinal);
var lineNumber = lineIndex > 0 ? methodCallLine.Substring(lineIndex) : "";
var indexMethodEnding = methodCallLine.IndexOf(')') + 1;
var testName = methodCallLine.Substring(0, indexMethodEnding);
var parts = methodCallLine[indexMethodEnding..].Split(" ", StringSplitOptions.RemoveEmptyEntries);
var fileName = parts[1][..^5];
var lineNumber = int.Parse(parts[2]);

const string indent = FileNewLine + " ";

var currentDirectory = Directory.GetCurrentDirectory();
var logFile = currentDirectory.Substring(
0,
currentDirectory.LastIndexOf("\\artifacts\\", StringComparison.Ordinal) + 1)
+ "QueryBaseline.txt";
if (writeToLog || SqlStatements.Count > 9)
{
var currentDirectory = Directory.GetCurrentDirectory();
var logFile = currentDirectory.Substring(
0,
currentDirectory.LastIndexOf("\\artifacts\\", StringComparison.Ordinal) + 1)
+ "QueryBaseline.txt";

var testInfo = testName + " : " + lineNumber + FileNewLine;
var testInfo = testName + " : " + lineNumber + FileNewLine;
const string indent = FileNewLine + " ";

var newBaseLine = $@" AssertSql(
var newBaseLine = $@" AssertSql(
{string.Join("," + indent + "//" + indent, SqlStatements.Take(9).Select(sql => "@\"" + sql.Replace("\"", "\"\"") + "\""))});

";

if (SqlStatements.Count > 9)
{
newBaseLine += "Output truncated.";
}
if (SqlStatements.Count > 9)
{
newBaseLine += "Output truncated.";
}

Logger.TestOutputHelper?.WriteLine("---- New Baseline -------------------------------------------------------------------");
Logger.TestOutputHelper?.WriteLine(newBaseLine);
Logger.TestOutputHelper?.WriteLine("---- New Baseline -------------------------------------------------------------------");
Logger.TestOutputHelper?.WriteLine(newBaseLine);

var contents = testInfo + newBaseLine + FileNewLine + FileNewLine;
var contents = testInfo + newBaseLine + FileNewLine + FileNewLine;

File.AppendAllText(logFile, contents);
File.AppendAllText(logFile, contents);
}
else
{
var indentCount = 3;
var initialIndent = string.Join("", Enumerable.Repeat(" ", indentCount));
var additionalIndent = initialIndent + " ";
var existingLines = File.ReadAllLines(fileName);
var newBaseLine = $@"{initialIndent}AssertSql(
{additionalIndent}{string.Join("," + FileNewLine + additionalIndent + "//" + FileNewLine + additionalIndent, SqlStatements.Take(9).Select(sql => "@\"" + sql.Replace("\"", "\"\"") + "\""))});";
var newLines = newBaseLine.Split(Environment.NewLine);
using (var fileStream = File.Open(fileName, FileMode.Open))
{
using (var streamWriter = new StreamWriter(fileStream))
{
for (var i = 1; i <= existingLines.Length; i++)
{
if (i == lineNumber)
{
for (var j = 0; j < newLines.Length; i++, j++)
{
streamWriter.WriteLine(newLines[j]);
}
}

streamWriter.WriteLine(existingLines[i - 1]);
}
}
}

Logger.TestOutputHelper?.WriteLine("---- New Baseline -------------------------------------------------------------------");
Logger.TestOutputHelper?.WriteLine(newBaseLine);
}

throw;
}
Expand Down
156 changes: 150 additions & 6 deletions test/EFCore.Specification.Tests/Query/NorthwindIncludeQueryTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -827,26 +827,170 @@ var orders
[ConditionalTheory]
[InlineData(false)]
[InlineData(true)]
public virtual void Include_collection_on_join_clause_with_filter(bool useString)
public virtual void Include_collection_with_join_clause_with_filter(bool useString)
{
using var context = CreateContext();
var customers
= useString
? (from c in context.Set<Customer>().Include("Orders")
join o in context.Set<Order>() on c.CustomerID equals o.CustomerID
where c.CustomerID == "ALFKI"
where c.CustomerID.StartsWith("F")
select c)
.ToList()
: (from c in context.Set<Customer>().Include(c => c.Orders)
join o in context.Set<Order>() on c.CustomerID equals o.CustomerID
where c.CustomerID == "ALFKI"
where c.CustomerID.StartsWith("F")
select c)
.ToList();

Assert.Equal(6, customers.Count);
Assert.Equal(36, customers.SelectMany(c => c.Orders).Count());
Assert.Equal(63, customers.Count);
Assert.Equal(769, customers.SelectMany(c => c.Orders).Count());
Assert.True(customers.SelectMany(c => c.Orders).All(o => o.Customer != null));
Assert.Equal(1 + 6, context.ChangeTracker.Entries().Count());
Assert.Equal(7 + 63, context.ChangeTracker.Entries().Count());

foreach (var customer in customers)
{
CheckIsLoaded(
context,
customer,
ordersLoaded: true,
orderDetailsLoaded: false,
productLoaded: false);
}
}

[ConditionalTheory]
[InlineData(false)]
[InlineData(true)]
public virtual void Include_collection_with_left_join_clause_with_filter(bool useString)
{
using var context = CreateContext();
var customers
= useString
? (from c in context.Set<Customer>().Include("Orders")
join o in context.Set<Order>() on c.CustomerID equals o.CustomerID into grouping
from o in grouping.DefaultIfEmpty()
where c.CustomerID.StartsWith("F")
select c)
.ToList()
: (from c in context.Set<Customer>().Include(c => c.Orders)
join o in context.Set<Order>() on c.CustomerID equals o.CustomerID into grouping
from o in grouping.DefaultIfEmpty()
where c.CustomerID.StartsWith("F")
select c)
.ToList();

Assert.Equal(64, customers.Count);
Assert.Equal(769, customers.SelectMany(c => c.Orders).Count());
Assert.True(customers.SelectMany(c => c.Orders).All(o => o.Customer != null));
Assert.Equal(8 + 63, context.ChangeTracker.Entries().Count());

foreach (var customer in customers)
{
CheckIsLoaded(
context,
customer,
ordersLoaded: true,
orderDetailsLoaded: false,
productLoaded: false);
}
}

[ConditionalTheory]
[InlineData(false)]
[InlineData(true)]
public virtual void Include_collection_with_cross_join_clause_with_filter(bool useString)
{
using var context = CreateContext();
var customers
= useString
? (from c in context.Set<Customer>().Include("Orders")
from o in context.Set<Order>().OrderBy(o => o.OrderID).Take(5)
where c.CustomerID.StartsWith("F")
select c)
.ToList()
: (from c in context.Set<Customer>().Include(c => c.Orders)
from o in context.Set<Order>().OrderBy(o => o.OrderID).Take(5)
where c.CustomerID.StartsWith("F")
select c)
.ToList();

Assert.Equal(40, customers.Count);
Assert.Equal(315, customers.SelectMany(c => c.Orders).Count());
Assert.True(customers.SelectMany(c => c.Orders).All(o => o.Customer != null));
Assert.Equal(8 + 63, context.ChangeTracker.Entries().Count());

foreach (var customer in customers)
{
CheckIsLoaded(
context,
customer,
ordersLoaded: true,
orderDetailsLoaded: false,
productLoaded: false);
}
}

[ConditionalTheory]
[InlineData(false)]
[InlineData(true)]
public virtual void Include_collection_with_cross_apply_with_filter(bool useString)
{
using var context = CreateContext();
var customers
= useString
? (from c in context.Set<Customer>().Include("Orders")
from o in context.Set<Order>().Where(o => o.CustomerID == c.CustomerID).OrderBy(o => c.CustomerID).Take(5)
where c.CustomerID.StartsWith("F")
select c)
.ToList()
: (from c in context.Set<Customer>().Include(c => c.Orders)
from o in context.Set<Order>().Where(o => o.CustomerID == c.CustomerID).OrderBy(o => c.CustomerID).Take(5)
where c.CustomerID.StartsWith("F")
select c)
.ToList();

Assert.Equal(33, customers.Count);
Assert.Equal(309, customers.SelectMany(c => c.Orders).Count());
Assert.True(customers.SelectMany(c => c.Orders).All(o => o.Customer != null));
Assert.Equal(7 + 63, context.ChangeTracker.Entries().Count());

foreach (var customer in customers)
{
CheckIsLoaded(
context,
customer,
ordersLoaded: true,
orderDetailsLoaded: false,
productLoaded: false);
}
}

[ConditionalTheory]
[InlineData(false)]
[InlineData(true)]
public virtual void Include_collection_with_outer_apply_with_filter(bool useString)
{
using var context = CreateContext();
var customers
= useString
? (from c in context.Set<Customer>().Include("Orders")
from o in context.Set<Order>().Where(o => o.CustomerID == c.CustomerID)
.OrderBy(o => c.CustomerID).Take(5).DefaultIfEmpty()
where c.CustomerID.StartsWith("F")
select c)
.ToList()
: (from c in context.Set<Customer>().Include(c => c.Orders)
from o in context.Set<Order>().Where(o => o.CustomerID == c.CustomerID)
.OrderBy(o => c.CustomerID).Take(5).DefaultIfEmpty()
where c.CustomerID.StartsWith("F")
select c)
.ToList();

Assert.Equal(34, customers.Count);
Assert.Equal(309, customers.SelectMany(c => c.Orders).Count());
Assert.True(customers.SelectMany(c => c.Orders).All(o => o.Customer != null));
Assert.Equal(8 + 63, context.ChangeTracker.Entries().Count());

foreach (var customer in customers)
{
Expand Down
Loading