# The standalone check is canonical; the upgrade stays self-contained for mysql SOURCE. # Run from any directory. Use -Check in verification to reject an outdated embed. [CmdletBinding()] param( [string]$SourcePath, [string]$MigrationPath, [switch]$Check ) if (-not $SourcePath) { $SourcePath = Join-Path $PSScriptRoot 'checks/company-master-data-integrity.sql' } if (-not $MigrationPath) { $MigrationPath = Join-Path $PSScriptRoot 'upgrades/2026-10-08-company-master-data-isolation.sql' } $ErrorActionPreference = 'Stop' function Get-MarkedContent { param([string]$Text, [string]$BeginMarker, [string]$EndMarker) $begin = $Text.IndexOf($BeginMarker, [System.StringComparison]::Ordinal) $end = $Text.IndexOf($EndMarker, [System.StringComparison]::Ordinal) if ($begin -lt 0 -or $end -le $begin -or $Text.IndexOf($BeginMarker, $begin + $BeginMarker.Length, [System.StringComparison]::Ordinal) -ge 0 -or $Text.IndexOf($EndMarker, $end + $EndMarker.Length, [System.StringComparison]::Ordinal) -ge 0) { throw "Expected one ordered marker pair: $BeginMarker / $EndMarker" } $contentStart = $begin + $BeginMarker.Length return @{ Start = $contentStart End = $end Content = $Text.Substring($contentStart, $end - $contentStart) } } try { $source = (Resolve-Path -LiteralPath $SourcePath).Path $migration = (Resolve-Path -LiteralPath $MigrationPath).Path if ($source -eq $migration) { throw 'Source and migration must be different files' } # Normalize only line endings: content, statement order and whitespace in the # canonical block otherwise remain exact. Output is deterministic UTF-8/LF. $sourceText = [System.IO.File]::ReadAllText($source).Replace("`r`n", "`n").Replace("`r", "`n") $migrationText = [System.IO.File]::ReadAllText($migration).Replace("`r`n", "`n").Replace("`r", "`n") $core = Get-MarkedContent $sourceText '-- BEGIN COMPANY INTEGRITY CORE' '-- END COMPANY INTEGRITY CORE' $embedded = Get-MarkedContent $migrationText '-- BEGIN GENERATED COMPANY INTEGRITY CHECKS' '-- END GENERATED COMPANY INTEGRITY CHECKS' $expected = $migrationText.Substring(0, $embedded.Start) + $core.Content + $migrationText.Substring($embedded.End) if ($Check) { if ($migrationText -cne $expected) { Write-Error 'Integrity SQL embed is stale. Run scripts/sync-company-integrity.ps1 to regenerate it.' -ErrorAction Continue exit 1 } Write-Output 'Integrity SQL embed is current.' exit 0 } [System.IO.File]::WriteAllText($migration, $expected, [System.Text.UTF8Encoding]::new($false)) Write-Output 'Integrity SQL embed regenerated from the canonical check.' exit 0 } catch { Write-Error $_ -ErrorAction Continue exit 1 }