将索引缩短为 IX_CE_Offering_Status_WaitlistedAt。

将候补迁移改为可重入:先检查列和索引是否存在,再执行 DDL。
附件中已经成功添加 WaitlistedAt、但索引创建失败的数据库可直接重试,不会报重复列。
运行时和 dotnet ef 连接统一开启 AllowUserVariables;Connector/NET 默认关闭该选项。Connector/NET 官方说明
增加所有 MySQL 索引名不得超过 64 字符的回归测试。
This commit is contained in:
2026-07-26 16:24:52 +08:00 Unverified
parent f62cd21319
commit ec28eb6c16
9 changed files with 148 additions and 30 deletions
@@ -518,7 +518,7 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
x.CourseSelectionOfferingId, x.CourseSelectionOfferingId,
x.Status, x.Status,
x.WaitlistedAt x.WaitlistedAt
}); }).HasDatabaseName("IX_CE_Offering_Status_WaitlistedAt");
entity.HasOne(x => x.CourseSelectionOffering) entity.HasOne(x => x.CourseSelectionOffering)
.WithMany(x => x.Enrollments) .WithMany(x => x.Enrollments)
.HasForeignKey(x => x.CourseSelectionOfferingId) .HasForeignKey(x => x.CourseSelectionOfferingId)
@@ -12,7 +12,7 @@ public sealed class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbConte
?? "Server=localhost;Port=3306;Database=jiaowu;User=__design_time__;Password=__not_used__;"; ?? "Server=localhost;Port=3306;Database=jiaowu;User=__design_time__;Password=__not_used__;";
var options = new DbContextOptionsBuilder<AppDbContext>() var options = new DbContextOptionsBuilder<AppDbContext>()
.UseMySQL(connectionString) .UseMySQL(MySqlConnectionStringPolicy.ForApplication(connectionString))
.Options; .Options;
return new AppDbContext(options); return new AppDbContext(options);
@@ -1611,7 +1611,7 @@ public sealed class DevelopmentSqliteMigrator(
ADD COLUMN "WaitlistedAt" TEXT NULL; ADD COLUMN "WaitlistedAt" TEXT NULL;
""", """,
""" """
CREATE INDEX IF NOT EXISTS "IX_CourseEnrollments_CourseSelectionOfferingId_Status_WaitlistedAt" CREATE INDEX IF NOT EXISTS "IX_CE_Offering_Status_WaitlistedAt"
ON "CourseEnrollments" ("CourseSelectionOfferingId", "Status", "WaitlistedAt"); ON "CourseEnrollments" ("CourseSelectionOfferingId", "Status", "WaitlistedAt");
""" """
]; ];
@@ -12,26 +12,91 @@ public partial class CourseSelectionWaitlist : Migration
{ {
protected override void Up(MigrationBuilder migrationBuilder) protected override void Up(MigrationBuilder migrationBuilder)
{ {
migrationBuilder.AddColumn<DateTime>( migrationBuilder.Sql("""
name: "WaitlistedAt", SET @waitlisted_column_exists = (
table: "CourseEnrollments", SELECT COUNT(*)
type: "datetime(6)", FROM `INFORMATION_SCHEMA`.`COLUMNS`
nullable: true); WHERE `TABLE_SCHEMA` = DATABASE()
AND `TABLE_NAME` = 'CourseEnrollments'
AND `COLUMN_NAME` = 'WaitlistedAt'
);
""");
migrationBuilder.Sql("""
SET @add_waitlisted_column_sql = IF(
@waitlisted_column_exists = 0,
'ALTER TABLE `CourseEnrollments` ADD COLUMN `WaitlistedAt` datetime(6) NULL',
'SELECT 1'
);
""");
migrationBuilder.Sql(
"PREPARE add_waitlisted_column_stmt FROM @add_waitlisted_column_sql;");
migrationBuilder.Sql("EXECUTE add_waitlisted_column_stmt;");
migrationBuilder.Sql("DEALLOCATE PREPARE add_waitlisted_column_stmt;");
migrationBuilder.CreateIndex( migrationBuilder.Sql("""
name: "IX_CourseEnrollments_CourseSelectionOfferingId_Status_WaitlistedAt", SET @waitlist_index_exists = (
table: "CourseEnrollments", SELECT COUNT(*)
columns: new[] { "CourseSelectionOfferingId", "Status", "WaitlistedAt" }); FROM `INFORMATION_SCHEMA`.`STATISTICS`
WHERE `TABLE_SCHEMA` = DATABASE()
AND `TABLE_NAME` = 'CourseEnrollments'
AND `INDEX_NAME` = 'IX_CE_Offering_Status_WaitlistedAt'
);
""");
migrationBuilder.Sql("""
SET @add_waitlist_index_sql = IF(
@waitlist_index_exists = 0,
'CREATE INDEX `IX_CE_Offering_Status_WaitlistedAt` ON `CourseEnrollments` (`CourseSelectionOfferingId`, `Status`, `WaitlistedAt`)',
'SELECT 1'
);
""");
migrationBuilder.Sql(
"PREPARE add_waitlist_index_stmt FROM @add_waitlist_index_sql;");
migrationBuilder.Sql("EXECUTE add_waitlist_index_stmt;");
migrationBuilder.Sql("DEALLOCATE PREPARE add_waitlist_index_stmt;");
} }
protected override void Down(MigrationBuilder migrationBuilder) protected override void Down(MigrationBuilder migrationBuilder)
{ {
migrationBuilder.DropIndex( migrationBuilder.Sql("""
name: "IX_CourseEnrollments_CourseSelectionOfferingId_Status_WaitlistedAt", SET @waitlist_index_exists = (
table: "CourseEnrollments"); SELECT COUNT(*)
FROM `INFORMATION_SCHEMA`.`STATISTICS`
WHERE `TABLE_SCHEMA` = DATABASE()
AND `TABLE_NAME` = 'CourseEnrollments'
AND `INDEX_NAME` = 'IX_CE_Offering_Status_WaitlistedAt'
);
""");
migrationBuilder.Sql("""
SET @drop_waitlist_index_sql = IF(
@waitlist_index_exists > 0,
'DROP INDEX `IX_CE_Offering_Status_WaitlistedAt` ON `CourseEnrollments`',
'SELECT 1'
);
""");
migrationBuilder.Sql(
"PREPARE drop_waitlist_index_stmt FROM @drop_waitlist_index_sql;");
migrationBuilder.Sql("EXECUTE drop_waitlist_index_stmt;");
migrationBuilder.Sql("DEALLOCATE PREPARE drop_waitlist_index_stmt;");
migrationBuilder.DropColumn( migrationBuilder.Sql("""
name: "WaitlistedAt", SET @waitlisted_column_exists = (
table: "CourseEnrollments"); SELECT COUNT(*)
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA` = DATABASE()
AND `TABLE_NAME` = 'CourseEnrollments'
AND `COLUMN_NAME` = 'WaitlistedAt'
);
""");
migrationBuilder.Sql("""
SET @drop_waitlisted_column_sql = IF(
@waitlisted_column_exists > 0,
'ALTER TABLE `CourseEnrollments` DROP COLUMN `WaitlistedAt`',
'SELECT 1'
);
""");
migrationBuilder.Sql(
"PREPARE drop_waitlisted_column_stmt FROM @drop_waitlisted_column_sql;");
migrationBuilder.Sql("EXECUTE drop_waitlisted_column_stmt;");
migrationBuilder.Sql("DEALLOCATE PREPARE drop_waitlisted_column_stmt;");
} }
} }
@@ -748,7 +748,8 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.HasIndex("StudentId", "Status"); b.HasIndex("StudentId", "Status");
b.HasIndex("CourseSelectionOfferingId", "Status", "WaitlistedAt"); b.HasIndex("CourseSelectionOfferingId", "Status", "WaitlistedAt")
.HasDatabaseName("IX_CE_Offering_Status_WaitlistedAt");
b.ToTable("CourseEnrollments"); b.ToTable("CourseEnrollments");
}); });
@@ -745,7 +745,8 @@ namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
b.HasIndex("StudentId", "Status"); b.HasIndex("StudentId", "Status");
b.HasIndex("CourseSelectionOfferingId", "Status", "WaitlistedAt"); b.HasIndex("CourseSelectionOfferingId", "Status", "WaitlistedAt")
.HasDatabaseName("IX_CE_Offering_Status_WaitlistedAt");
b.ToTable("CourseEnrollments"); b.ToTable("CourseEnrollments");
}); });
@@ -0,0 +1,15 @@
using MySql.Data.MySqlClient;
namespace Jiaowu.Api.Infrastructure.Persistence;
public static class MySqlConnectionStringPolicy
{
public static string ForApplication(string connectionString)
{
var builder = new MySqlConnectionStringBuilder(connectionString)
{
AllowUserVariables = true
};
return builder.ConnectionString;
}
}
+3 -1
View File
@@ -141,7 +141,9 @@ builder.Services.AddDbContextPool<AppDbContext>(options =>
throw new InvalidOperationException( throw new InvalidOperationException(
"缺少 MySQL 连接串。请通过 ConnectionStrings__MySql 环境变量配置。"); "缺少 MySQL 连接串。请通过 ConnectionStrings__MySql 环境变量配置。");
} }
options.UseMySQL(connectionString, mySqlOptions => options.UseMySQL(
MySqlConnectionStringPolicy.ForApplication(connectionString),
mySqlOptions =>
{ {
mySqlOptions.CommandTimeout(databaseOptions.CommandTimeoutSeconds); mySqlOptions.CommandTimeout(databaseOptions.CommandTimeoutSeconds);
mySqlOptions.EnableRetryOnFailure( mySqlOptions.EnableRetryOnFailure(
+36 -2
View File
@@ -2,6 +2,7 @@ using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Migrations;
using MySql.Data.MySqlClient;
namespace Jiaowu.Api.Tests; namespace Jiaowu.Api.Tests;
@@ -27,9 +28,14 @@ public sealed class MySqlMigrationTests
Assert.Contains("CREATE TABLE `WarningRules`", script); Assert.Contains("CREATE TABLE `WarningRules`", script);
Assert.Contains("ADD `CheckInMethod` int NOT NULL DEFAULT 1", script); Assert.Contains("ADD `CheckInMethod` int NOT NULL DEFAULT 1", script);
Assert.Contains("CREATE UNIQUE INDEX `IX_AttendanceSheets_CheckInToken`", script); Assert.Contains("CREATE UNIQUE INDEX `IX_AttendanceSheets_CheckInToken`", script);
Assert.Contains("ADD `WaitlistedAt` datetime(6) NULL", script); Assert.Contains("ADD COLUMN `WaitlistedAt` datetime(6) NULL", script);
Assert.Contains( Assert.Contains(
"CREATE INDEX `IX_CourseEnrollments_CourseSelectionOfferingId_Status_WaitlistedAt`", "CREATE INDEX `IX_CE_Offering_Status_WaitlistedAt`",
script);
Assert.Contains("@waitlisted_column_exists", script);
Assert.Contains("@waitlist_index_exists", script);
Assert.DoesNotContain(
"IX_CourseEnrollments_CourseSelectionOfferingId_Status_WaitlistedAt",
script); script);
Assert.Contains( Assert.Contains(
"ADD `MaxCourseCount` int NULL", "ADD `MaxCourseCount` int NULL",
@@ -86,6 +92,34 @@ public sealed class MySqlMigrationTests
Assert.Contains(ids[1].ToString(), sql, StringComparison.OrdinalIgnoreCase); Assert.Contains(ids[1].ToString(), sql, StringComparison.OrdinalIgnoreCase);
} }
[Fact]
public void MySql_index_names_fit_the_server_identifier_limit()
{
using var db = new AppDbContext(CreateMySqlOptions());
var indexNames = db.Model.GetEntityTypes()
.SelectMany(x => x.GetIndexes())
.Select(x => x.GetDatabaseName())
.Where(x => !string.IsNullOrEmpty(x))
.ToList();
Assert.NotEmpty(indexNames);
Assert.All(indexNames, name => Assert.True(
name!.Length <= 64,
$"MySQL index name '{name}' has {name.Length} characters."));
}
[Fact]
public void Application_mysql_connections_allow_migration_user_variables()
{
var normalized = MySqlConnectionStringPolicy.ForApplication(
"Server=localhost;Database=jiaowu;User=test;Password=test;");
var builder = new MySqlConnectionStringBuilder(normalized);
Assert.True(builder.AllowUserVariables);
}
private static DbContextOptions<AppDbContext> CreateMySqlOptions() => private static DbContextOptions<AppDbContext> CreateMySqlOptions() =>
new DbContextOptionsBuilder<AppDbContext>() new DbContextOptionsBuilder<AppDbContext>()
.UseMySQL( .UseMySQL(