diff --git a/MarkMpn.Sql4Cds.Engine.FetchXml.Tests/FetchXml2SqlTests.cs b/MarkMpn.Sql4Cds.Engine.FetchXml.Tests/FetchXml2SqlTests.cs index 5515d54e..b1e3bd43 100644 --- a/MarkMpn.Sql4Cds.Engine.FetchXml.Tests/FetchXml2SqlTests.cs +++ b/MarkMpn.Sql4Cds.Engine.FetchXml.Tests/FetchXml2SqlTests.cs @@ -116,6 +116,29 @@ public void JoinAlias() Assert.AreEqual("SELECT contact.firstname, contact.lastname, a.name FROM contact INNER JOIN account AS a ON contact.parentcustomerid = a.accountid", NormalizeWhitespace(converted)); } + [TestMethod] + public void JoinAliasFilter() + { + var metadata = new AttributeMetadataCache(_service); + var fetch = @" + + + + + + + + + + + + "; + + var converted = FetchXml2Sql.Convert(_service, metadata, fetch, new FetchXml2SqlOptions(), out _); + + Assert.AreEqual("SELECT contact.firstname, contact.lastname, a.name FROM contact INNER JOIN account AS a ON contact.parentcustomerid = a.accountid WHERE a.name = 'data8'", NormalizeWhitespace(converted)); + } + [TestMethod] public void Order() { diff --git a/MarkMpn.Sql4Cds.Engine/FetchXml2Sql.cs b/MarkMpn.Sql4Cds.Engine/FetchXml2Sql.cs index 067a5369..ae371932 100644 --- a/MarkMpn.Sql4Cds.Engine/FetchXml2Sql.cs +++ b/MarkMpn.Sql4Cds.Engine/FetchXml2Sql.cs @@ -72,7 +72,7 @@ public static string Convert(IOrganizationService org, IAttributeMetadataCache m var aliasToLogicalName = new Dictionary(StringComparer.OrdinalIgnoreCase); // Link entities can also affect the WHERE clause - var filter = GetFilter(org, metadata, entity.Items, entity.name, aliasToLogicalName, options, ctes, parameterValues, ref requiresTimeZone, ref usesToday); + BooleanExpression filter = null; if (entity != null) { @@ -117,6 +117,8 @@ public static string Convert(IOrganizationService org, IAttributeMetadataCache m } // WHERE + filter = CombineExpressions(filter, BooleanBinaryExpressionType.And, GetFilter(org, metadata, entity.Items, entity.name, aliasToLogicalName, options, ctes, parameterValues, ref requiresTimeZone, ref usesToday)); + if (filter != null) { query.WhereClause = new WhereClause @@ -639,12 +641,12 @@ private static TableReference BuildJoins(IOrganizationService org, IAttributeMet private static BooleanExpression CombineExpressions(BooleanExpression expr1, BooleanBinaryExpressionType type, BooleanExpression expr2) { + if (expr1 == null || expr2 == null) + return expr1 ?? expr2; + if (expr2 is BooleanBinaryExpression bbe && bbe.BinaryExpressionType != type) expr2 = new BooleanParenthesisExpression { Expression = expr2 }; - if (expr1 == null) - return expr2; - if (expr1 is BooleanBinaryExpression lhs && lhs.BinaryExpressionType != type) expr2 = new BooleanParenthesisExpression { Expression = expr1 };