66 lines
2.3 KiB
PowerShell
66 lines
2.3 KiB
PowerShell
|
|
param(
|
||
|
|
[string]$Name,
|
||
|
|
[string]$Context = "AppDataContext",
|
||
|
|
[string]$Project = "Avalonia-EFCore/Avalonia-EFCore.csproj",
|
||
|
|
[string]$StartupProject = "Avalonia-API/Avalonia-API.csproj",
|
||
|
|
[string]$OutputDir = "Migrations"
|
||
|
|
)
|
||
|
|
|
||
|
|
$ErrorActionPreference = "Stop"
|
||
|
|
|
||
|
|
$repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..")
|
||
|
|
Set-Location $repoRoot
|
||
|
|
|
||
|
|
if ([string]::IsNullOrWhiteSpace($Name)) {
|
||
|
|
$Name = "AutoMigration_{0}" -f (Get-Date -Format "yyyyMMddHHmmss")
|
||
|
|
}
|
||
|
|
|
||
|
|
Write-Host "Restoring local dotnet tools..."
|
||
|
|
dotnet tool restore
|
||
|
|
if ($LASTEXITCODE -ne 0) {
|
||
|
|
throw "dotnet tool restore failed."
|
||
|
|
}
|
||
|
|
|
||
|
|
Write-Host "Generating migration '$Name'..."
|
||
|
|
dotnet tool run dotnet-ef migrations add $Name `
|
||
|
|
--project $Project `
|
||
|
|
--startup-project $StartupProject `
|
||
|
|
--context $Context `
|
||
|
|
--output-dir $OutputDir
|
||
|
|
if ($LASTEXITCODE -ne 0) {
|
||
|
|
throw "dotnet ef migrations add failed."
|
||
|
|
}
|
||
|
|
|
||
|
|
$migrationDir = Join-Path (Split-Path $Project -Parent) $OutputDir
|
||
|
|
$migrationFile = Get-ChildItem $migrationDir -Filter "*_$Name.cs" |
|
||
|
|
Where-Object { $_.Name -notlike "*.Designer.cs" } |
|
||
|
|
Sort-Object LastWriteTime -Descending |
|
||
|
|
Select-Object -First 1
|
||
|
|
|
||
|
|
if ($null -eq $migrationFile) {
|
||
|
|
throw "Migration file was not found for '$Name'."
|
||
|
|
}
|
||
|
|
|
||
|
|
$content = Get-Content $migrationFile.FullName -Raw
|
||
|
|
$upMatch = [regex]::Match($content, "protected override void Up\(MigrationBuilder migrationBuilder\)\s*\{(?<body>.*?)\n\s*\}", "Singleline")
|
||
|
|
$downMatch = [regex]::Match($content, "protected override void Down\(MigrationBuilder migrationBuilder\)\s*\{(?<body>.*?)\n\s*\}", "Singleline")
|
||
|
|
|
||
|
|
$upBody = if ($upMatch.Success) { $upMatch.Groups["body"].Value.Trim() } else { "" }
|
||
|
|
$downBody = if ($downMatch.Success) { $downMatch.Groups["body"].Value.Trim() } else { "" }
|
||
|
|
|
||
|
|
if ([string]::IsNullOrWhiteSpace($upBody) -and [string]::IsNullOrWhiteSpace($downBody)) {
|
||
|
|
Write-Host "No model changes were detected. Removing empty migration '$Name'..."
|
||
|
|
dotnet tool run dotnet-ef migrations remove --force `
|
||
|
|
--project $Project `
|
||
|
|
--startup-project $StartupProject `
|
||
|
|
--context $Context
|
||
|
|
if ($LASTEXITCODE -ne 0) {
|
||
|
|
throw "dotnet ef migrations remove failed."
|
||
|
|
}
|
||
|
|
exit 0
|
||
|
|
}
|
||
|
|
|
||
|
|
Write-Host "Migration generated:"
|
||
|
|
Write-Host " $($migrationFile.FullName)"
|
||
|
|
Write-Host "Review the migration, then start the app. Startup will automatically apply pending migrations."
|