using Microsoft.EntityFrameworkCore.Migrations; #nullable disable namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations { /// /// Moves composition-derived templates to AVEVA-style contained names: a /// derived template stores only its slot name (e.g. Pump), not the /// dotted qualified path (Motor Controller.Pump). The qualified name /// is computed on read by walking the OwnerComposition chain. The unique /// index on Template.Name becomes filtered to base templates only — /// derived templates' uniqueness is the (TemplateId, InstanceName) index on /// TemplateComposition. /// public partial class ContainedDerivedTemplateNames : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) { // Drop the global unique index first: derived rows are about to be // renamed to contained names that may duplicate one another or a // base template. migrationBuilder.DropIndex( name: "IX_Templates_Name", table: "Templates"); // Collapse every derived template's dotted name to its contained // name — the owning composition slot's InstanceName. migrationBuilder.Sql(@" UPDATE t SET t.Name = c.InstanceName FROM Templates t INNER JOIN TemplateCompositions c ON c.Id = t.OwnerCompositionId WHERE t.IsDerived = 1;"); // Recreate the uniqueness guarantee for base templates only. migrationBuilder.CreateIndex( name: "IX_Templates_Name", table: "Templates", column: "Name", unique: true, filter: "[IsDerived] = 0"); } /// protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropIndex( name: "IX_Templates_Name", table: "Templates"); // Rebuild the dotted qualified names so the global unique index can // be restored — derived templates' contained names are not globally // unique. The recursive CTE walks the OwnerComposition chain down // from each base template. migrationBuilder.Sql(@" WITH q AS ( SELECT t.Id, CAST(t.Name AS NVARCHAR(MAX)) AS Qualified FROM Templates t WHERE t.IsDerived = 0 UNION ALL SELECT t.Id, CAST(q.Qualified + N'.' + c.InstanceName AS NVARCHAR(MAX)) FROM Templates t INNER JOIN TemplateCompositions c ON c.Id = t.OwnerCompositionId INNER JOIN q ON q.Id = c.TemplateId ) UPDATE t SET t.Name = q.Qualified FROM Templates t INNER JOIN q ON q.Id = t.Id WHERE t.IsDerived = 1;"); migrationBuilder.CreateIndex( name: "IX_Templates_Name", table: "Templates", column: "Name", unique: true); } } }