diff --git a/MarkMpn.Sql4Cds.Engine.Tests/AdoProviderTests.cs b/MarkMpn.Sql4Cds.Engine.Tests/AdoProviderTests.cs index 59a901a2..94ad21d9 100644 --- a/MarkMpn.Sql4Cds.Engine.Tests/AdoProviderTests.cs +++ b/MarkMpn.Sql4Cds.Engine.Tests/AdoProviderTests.cs @@ -2441,5 +2441,30 @@ SELECT CAST(CAST(10.6496 AS float) AS int) AS trunc1, } } } + + [TestMethod] + public void QueryDerivedTableWithContradiction() + { + // https://github.com/MarkMpn/Sql4Cds/issues/546 + using (var con = new Sql4CdsConnection(_localDataSources)) + using (var cmd = con.CreateCommand()) + { + cmd.CommandTimeout = 0; + + cmd.CommandText = @" +SELECT * +FROM (SELECT a.accountid + FROM account AS a + WHERE 1 != 1) AS sub"; + + using (var reader = cmd.ExecuteReader()) + { + var schema = reader.GetSchemaTable(); + + if (reader.Read()) + Assert.Fail(); + } + } + } } } diff --git a/MarkMpn.Sql4Cds.Engine/ExecutionPlan/AliasNode.cs b/MarkMpn.Sql4Cds.Engine/ExecutionPlan/AliasNode.cs index 614b34b8..3784f724 100644 --- a/MarkMpn.Sql4Cds.Engine/ExecutionPlan/AliasNode.cs +++ b/MarkMpn.Sql4Cds.Engine/ExecutionPlan/AliasNode.cs @@ -131,7 +131,7 @@ public override IDataExecutionPlanNodeInternal FoldQuery(NodeCompilationContext { // Remove any unused columns var unusedColumns = constant.Schema.Keys - .Where(sourceCol => !ColumnSet.Any(col => col.SourceColumn.SplitMultiPartIdentifier().Last().EscapeIdentifier() == sourceCol)) + .Where(sourceCol => !ColumnSet.Any(col => (String.IsNullOrEmpty(constant.Alias) && col.SourceColumn == sourceCol) || (!String.IsNullOrEmpty(constant.Alias) && col.SourceColumn == constant.Alias.EscapeIdentifier() + "." + sourceCol))) .ToList(); foreach (var col in unusedColumns) @@ -145,7 +145,7 @@ public override IDataExecutionPlanNodeInternal FoldQuery(NodeCompilationContext // Copy/rename any columns using the new aliases foreach (var col in ColumnSet) { - var sourceColumn = col.SourceColumn.SplitMultiPartIdentifier().Last(); + var sourceColumn = constant.Alias == null ? col.SourceColumn : col.SourceColumn.SplitMultiPartIdentifier().Last(); if (String.IsNullOrEmpty(constant.Alias) && col.OutputColumn != col.SourceColumn || !String.IsNullOrEmpty(constant.Alias) && col.OutputColumn != constant.Alias.EscapeIdentifier() + "." + col.SourceColumn)