Skip to content

Commit

Permalink
SqlServer RevEng: Handle included index columns
Browse files Browse the repository at this point in the history
Fixes #17083
  • Loading branch information
bricelam committed Aug 20, 2020
1 parent e567b4d commit 2edf33f
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -854,7 +854,8 @@ private void GetIndexes(DbConnection connection, IReadOnlyList<DatabaseTable> ta
[i].[has_filter],
[i].[filter_definition],
[i].[fill_factor],
COL_NAME([ic].[object_id], [ic].[column_id]) AS [column_name]
COL_NAME([ic].[object_id], [ic].[column_id]) AS [column_name],
[ic].[is_included_column]
FROM [sys].[indexes] AS [i]
JOIN [sys].[tables] AS [t] ON [i].[object_id] = [t].[object_id]
JOIN [sys].[index_columns] AS [ic] ON [i].[object_id] = [ic].[object_id] AND [i].[index_id] = [ic].[index_id]
Expand Down Expand Up @@ -1004,9 +1005,20 @@ FROM [sys].[indexes] i
index[SqlServerAnnotationNames.FillFactor] = indexGroup.Key.FillFactor;
}

var includedColumns = new List<string>();

foreach (var dataRecord in indexGroup)
{
var columnName = dataRecord.GetValueOrDefault<string>("column_name");

var isIncludedColumn = dataRecord.GetValueOrDefault<bool>("is_included_column");
if (isIncludedColumn)
{
includedColumns.Add(columnName!);

continue;
}

var column = table.Columns.FirstOrDefault(c => c.Name == columnName)
?? table.Columns.FirstOrDefault(
c => c.Name!.Equals(columnName, StringComparison.OrdinalIgnoreCase));
Expand All @@ -1015,6 +1027,11 @@ FROM [sys].[indexes] i
index.Columns.Add(column);
}

if (includedColumns.Count != 0)
{
index[SqlServerAnnotationNames.Include] = includedColumns.ToArray();
}

table.Indexes.Add(index);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1910,6 +1910,29 @@ CREATE TABLE HypotheticalIndexTable (
"DROP TABLE HypotheticalIndexTable;");
}

[ConditionalFact]
public void Set_include_for_index()
{
Test(
@"
CREATE TABLE IncludeIndexTable (
Id int,
IndexProperty int,
IncludeProperty int
);
CREATE INDEX IX_INCLUDE ON IncludeIndexTable(IndexProperty) INCLUDE (IncludeProperty);",
Enumerable.Empty<string>(),
Enumerable.Empty<string>(),
dbModel =>
{
var index = Assert.Single(dbModel.Tables.Single().Indexes);
Assert.Equal(new[] { "IndexProperty" }, index.Columns.Select(ic => ic.Name).ToList());
Assert.Equal(new[] { "IncludeProperty" }, (IReadOnlyList<string>)index[SqlServerAnnotationNames.Include]);
},
"DROP TABLE IncludeIndexTable;");
}

#endregion

#region ForeignKeyFacets
Expand Down

0 comments on commit 2edf33f

Please sign in to comment.