Skip to content

Commit 4bf3248

Browse files
committed
Preserve collation when changing column type (#3479)
Fixes #3476 (cherry picked from commit e327d6b)
1 parent 0fdf784 commit 4bf3248

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

src/EFCore.PG/Migrations/NpgsqlMigrationsSqlGenerator.cs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -456,9 +456,15 @@ protected override void Generate(AlterColumnOperation operation, IModel? model,
456456
.Append("TYPE ")
457457
.Append(type);
458458

459-
if (newCollation != oldCollation)
459+
if (newCollation is not null)
460460
{
461-
builder.Append(" COLLATE ").Append(DelimitIdentifier(newCollation ?? "default"));
461+
builder.Append(" COLLATE ").Append(DelimitIdentifier(newCollation));
462+
}
463+
else if (type == oldType)
464+
{
465+
// If the type is the same, make it more explicit that we're just resetting the collation to the default
466+
// (this isn't really required)
467+
builder.Append(" COLLATE ").Append(DelimitIdentifier("default"));
462468
}
463469

464470
builder.AppendLine(";");

test/EFCore.PG.FunctionalTests/Migrations/MigrationsNpgsqlTest.cs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -972,6 +972,30 @@ public override async Task Alter_column_change_type()
972972
AssertSql("""ALTER TABLE "People" ALTER COLUMN "SomeColumn" TYPE bigint;""");
973973
}
974974

975+
[Fact]
976+
public virtual async Task Alter_column_change_type_preserves_collation()
977+
{
978+
await Test(
979+
builder => builder.Entity("People").Property<int>("Id"),
980+
builder => builder.Entity("People").Property<string>("SomeColumn")
981+
.HasColumnType("varchar")
982+
.UseCollation(NonDefaultCollation),
983+
builder => builder.Entity("People").Property<string>("SomeColumn")
984+
.HasColumnType("text")
985+
.UseCollation(NonDefaultCollation),
986+
model =>
987+
{
988+
var table = Assert.Single(model.Tables);
989+
var column = Assert.Single(table.Columns, c => c.Name == "SomeColumn");
990+
Assert.Equal(NonDefaultCollation, column.Collation);
991+
});
992+
993+
AssertSql(
994+
"""
995+
ALTER TABLE "People" ALTER COLUMN "SomeColumn" TYPE text COLLATE "POSIX";
996+
""");
997+
}
998+
975999
public override async Task Alter_column_make_required()
9761000
{
9771001
await base.Alter_column_make_required();

0 commit comments

Comments
 (0)