Files
caliverse_server/BrokerApiCore/MetaverseBrokerDb_AutoMigrationGen.ps1
2025-05-01 07:20:41 +09:00

109 lines
6.0 KiB
PowerShell

#========================================================================
# 자동으로 마이그레이션을 생성하고 마이그레이션할 내용이 없으면 생성된 마이그레이션을 삭제하는 스크립트
# PowerShell 스크립트
#========================================================================
# 설정 (프로젝트 경로, DbContext 타입 등 - 필요에 따라 변수로 설정)
$projectDir = $PSScriptRoot # 스크립트 파일이 있는 디렉토리를 프로젝트 경로로 설정
Write-Host "프로젝트 경로: $projectDir"
$dbContextTypeName = "MetaverseBrokerDbContext"
$migrationsOutputDir = "$projectDir/Migrations" # 마이그레이션 파일 출력 디렉토리
Write-Host "마이그레이션 시작..."
# dotnet ef migrations script 명령어 실행 및 결과 캡처
$scriptOutput = dotnet ef migrations script `
--idempotent `
--project $projectDir `
--context $dbContextTypeName
#Write-Host "마이그레이션 필요 여부 확인 결과:"
# 결과에서 "No pending migrations" 메시지 또는 빈 스크립트 여부 확인
if ($scriptOutput -like "-- *No pending migrations*" -or ([string]::IsNullOrEmpty($scriptOutput)) ) {
Write-Host "스키마 변경 없음: 새로운 마이그레이션 불필요"
Write-Host "데이터베이스 업데이트 불필요 (스키마 변경 없음)"
} else {
# Write-Host "스키마 변경 감지: 새로운 마이그레이션 필요"
# 마이그레이션 이름 생성 (예: 날짜_시간 기반)
$migrationName = "SchemaChanges_" + (Get-Date -Format "HHmmss")
Write-Host "마이그레이션 생성 시작: $migrationName"
# dotnet ef migrations add 명령어 실행 (자동 마이그레이션 생성)
$scriptOutput = dotnet ef migrations add $migrationName `
--project $projectDir `
--context $dbContextTypeName `
--output-dir $migrationsOutputDir `
--verbose
Write-Host "마이그레이션 생성 결과: $scriptOutput"
if ($LASTEXITCODE -eq 0) {
Write-Host "마이그레이션 생성 성공: $migrationName"
# $migrationFileName = "$migrationsOutputDir/$migrationName.cs" # 마이그레이션 파일 경로
# $migrationsOutputDir에서 $migrationName로 끝나는 cs 파일 찾기
# $migrationFileName = Get-ChildItem -Path $migrationsOutputDir -Filter "$migrationName.cs" -Recurse | Select-Object -First 1 -ExpandProperty FullName
$migrationFileName = Get-ChildItem -Path $migrationsOutputDir -Filter "*$migrationName.cs" -Recurse | Select-Object -First 1 -ExpandProperty Name
$migrationFileName = "$migrationsOutputDir/$migrationFileName" # 마이그레이션 파일 경로
if ($migrationFileName -eq $null) {
Write-Error "마이그레이션 파일을 찾을 수 없습니다."
exit
}
# 생성된 마이그레이션 파일 내용 확인 (Up 및 Down 메소드 검사)
Write-Host "마이그레이션 파일 내용 분석 시작: $migrationFileName"
$migrationFileContent = Get-Content $migrationFileName -Raw
# Up 메소드와 Down 메소드 내용 정규식으로 추출 (공백 및 주석 허용)
$upMethodContentMatch = [regex]::Match($migrationFileContent, 'protected override void Up\(MigrationBuilder migrationBuilder\)\s*{(.*?)}', [System.Text.RegularExpressions.RegexOptions]::Singleline)
$downMethodContentMatch = [regex]::Match($migrationFileContent, 'protected override void Down\(MigrationBuilder migrationBuilder\)\s*{(.*?)}', [System.Text.RegularExpressions.RegexOptions]::Singleline)
$upMethodContent = $upMethodContentMatch.Groups[1].Value.Trim()
$downMethodContent = $downMethodContentMatch.Groups[1].Value.Trim()
# Up 및 Down 메소드가 비어 있는지 확인 (공백 및 주석 제거 후)
$isEmptyMigration = ($upMethodContent -notmatch '\S') -and ($downMethodContent -notmatch '\S') # \S: 공백 문자 제외한 문자
if ($isEmptyMigration) {
Write-Host "마이그레이션 클래스 (Up, Down 메소드) 내용 없음 감지"
Write-Host "생성된 마이그레이션 삭제 시작: $migrationName"
# 마이그레이션 삭제 명령어 실행
dotnet ef migrations remove `
--project $projectDir `
--context $dbContextTypeName --force
if ($LASTEXITCODE -eq 0) {
Write-Host "마이그레이션 삭제 성공: $migrationName"
Write-Host "스키마 변경 내용이 없어 데이터베이스 업데이트를 생략합니다."
} else {
Write-Error "마이그레이션 삭제 실패 (Exit Code: $LASTEXITCODE)"
Write-Error "마이그레이션 파일은 남아있을 수 있습니다: $migrationFileName"
Write-Error "수동으로 마이그레이션 삭제를 확인해주세요."
}
} else {
Write-Host "마이그레이션 클래스 내용 확인: 스키마 변경 내용 있음"
Write-Host "데이터베이스 업데이트 시작..."
# dotnet ef database update 명령어 실행 (데이터베이스 업데이트)
dotnet ef database update `
--project $projectDir `
--context $dbContextTypeName
if ($LASTEXITCODE -eq 0) {
Write-Host "데이터베이스 업데이트 성공"
} else {
Write-Error "데이터베이스 업데이트 실패 (Exit Code: $LASTEXITCODE)"
Write-Error "마이그레이션은 생성되었지만, 데이터베이스 업데이트에 실패했습니다. 수동으로 데이터베이스 업데이트를 수행해야 할 수 있습니다."
}
}
} else {
Write-Error "마이그레이션 생성 실패 (Exit Code: $LASTEXITCODE)"
Write-Error "데이터베이스 업데이트를 진행할 수 없습니다."
}
}
Write-Host "마이그레이션 및 데이터베이스 업데이트 자동화 스크립트 완료."