line-gestao-api/Migrations/20260226130300_BackfillMobi...

48 lines
1.6 KiB
C#

using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using line_gestao_api.Data;
#nullable disable
namespace line_gestao_api.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260226130300_BackfillMobileLinesTenantIdFromTenantSourceKey")]
public partial class BackfillMobileLinesTenantIdFromTenantSourceKey : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("""
UPDATE "MobileLines" m
SET "TenantId" = t."Id"
FROM "Tenants" t
WHERE t."SourceType" = 'MobileLines.Cliente'
AND t."SourceKey" = m."Cliente"
AND (m."TenantId" IS NULL OR m."TenantId" <> t."Id");
""");
migrationBuilder.Sql("""
DO $$
BEGIN
IF EXISTS (
SELECT 1
FROM "MobileLines" m
LEFT JOIN "Tenants" t
ON t."SourceType" = 'MobileLines.Cliente'
AND t."SourceKey" = m."Cliente"
WHERE t."Id" IS NULL
) THEN
RAISE EXCEPTION 'Backfill abortado: existem MobileLines sem tenant correspondente por SourceKey exato.';
END IF;
END
$$;
""");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
// No-op intencional.
}
}
}