Skip to content

Commit

Permalink
Fix default constraint logic in SQL Server migrations (#24274)
Browse files Browse the repository at this point in the history
Fixes #24272
  • Loading branch information
roji authored Mar 1, 2021
1 parent c65e02d commit 2eabf1f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -339,11 +339,14 @@ protected override void Generate(
|| operation.Collation != operation.OldColumn.Collation
|| HasDifferences(operation.GetAnnotations(), operation.OldColumn.GetAnnotations());

var (oldDefaultValue, oldDefaultValueSql) = (operation.OldColumn.DefaultValue, operation.OldColumn.DefaultValueSql);

if (alterStatementNeeded
|| !Equals(operation.DefaultValue, operation.OldColumn.DefaultValue)
|| operation.DefaultValueSql != operation.OldColumn.DefaultValueSql)
|| !Equals(operation.DefaultValue, oldDefaultValue)
|| operation.DefaultValueSql != oldDefaultValueSql)
{
DropDefaultConstraint(operation.Schema, operation.Table, operation.Name, builder);
(oldDefaultValue, oldDefaultValueSql) = (null, null);
}

if (alterStatementNeeded)
Expand Down Expand Up @@ -388,8 +391,7 @@ protected override void Generate(
builder.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator);
}

if (operation.DefaultValue != null
|| operation.DefaultValueSql != null)
if (!Equals(operation.DefaultValue, oldDefaultValue) || operation.DefaultValueSql != oldDefaultValueSql)
{
builder
.Append("ALTER TABLE ")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -964,6 +964,29 @@ FROM [sys].[default_constraints] [d]
ALTER TABLE [People] ADD DEFAULT N'Doe' FOR [Name];");
}

[ConditionalFact]
public virtual async Task Alter_column_change_comment_with_default()
{
await Test(
builder => builder.Entity("People").Property<string>("Name").HasDefaultValue("Doe"),
builder => { },
builder => builder.Entity("People").Property<string>("Name")
.HasComment("Some comment"),
model =>
{
var nameColumn = Assert.Single(Assert.Single(model.Tables).Columns);
Assert.Equal("(N'Doe')", nameColumn.DefaultValueSql);
Assert.Equal("Some comment", nameColumn.Comment);
});

AssertSql(
@"DECLARE @defaultSchema AS sysname;
SET @defaultSchema = SCHEMA_NAME();
DECLARE @description AS sql_variant;
SET @description = N'Some comment';
EXEC sp_addextendedproperty 'MS_Description', @description, 'SCHEMA', @defaultSchema, 'TABLE', N'People', 'COLUMN', N'Name';");
}

[ConditionalFact]
public virtual async Task Alter_column_make_sparse()
{
Expand Down

0 comments on commit 2eabf1f

Please sign in to comment.