"""PowerShell helpers for recovering a fresh Windows MySQL installation. Embedded as Python text so the helpers ship inside the single-file executable. Only an empty data directory is eligible for automatic initialization. """ MYSQL_RECOVERY_HELPERS = r''' function Read-MySqlOptionFile([string]$Path) { $bytes = [IO.File]::ReadAllBytes($Path) $encoding = New-Object Text.UTF8Encoding($false, $true) if ($bytes.Length -ge 2 -and $bytes[0] -eq 255 -and $bytes[1] -eq 254) { $encoding = [Text.Encoding]::Unicode } elseif ($bytes.Length -ge 2 -and $bytes[0] -eq 254 -and $bytes[1] -eq 255) { $encoding = [Text.Encoding]::BigEndianUnicode } elseif ($bytes.Length -ge 3 -and $bytes[0] -eq 239 -and $bytes[1] -eq 187 -and $bytes[2] -eq 191) { $encoding = New-Object Text.UTF8Encoding($true, $true) } try { $text = $encoding.GetString($bytes).TrimStart([char]0xFEFF) } catch { $encoding = [Text.Encoding]::Default $text = $encoding.GetString($bytes) } return @{ Text = $text; Encoding = $encoding } } function Get-MySqlSettings([string]$Text, [string]$ServiceName) { if ($Text -match '(?m)^\s*!include') { throw 'Automatic recovery does not support included option files. Check my.ini and its includes.' } $settings = @{} $section = '' foreach ($line in ($Text -split '\r?\n')) { if ($line -match '^\s*\[([^]]+)\]') { $section = $Matches[1]; continue } if ($section -notin @('mysqld', 'server', 'mysqld-8.0', $ServiceName)) { continue } if ($line -match '^\s*([\w-]+)\s*=\s*(.*?)\s*$') { $key = $Matches[1].Replace('_', '-').ToLowerInvariant() $value = $Matches[2] if ($value -match '^"([^"]*)"\s*(?:[#;].*)?$' -or $value -match "^'([^']*)'\s*(?:[#;].*)?$") { $value = $Matches[1] } else { $value = ($value -replace '\s+[#;].*$', '').Trim() } $settings[$key] = $value } } return $settings } function Get-MySqlServiceLayout($Service) { $command = $Service.PathName if ($command -notmatch '^\s*"([^"]+\\mysqld\.exe)"|^\s*(\S+\\mysqld\.exe)') { throw 'Cannot resolve mysqld.exe from the Windows service command.' } $serverExe = if ($Matches[1]) { $Matches[1] } else { $Matches[2] } if ($command -notmatch '(?i)--defaults-file(?:=|\s+)(?:"([^"]+)"|(\S+))') { throw 'Cannot resolve --defaults-file from the Windows service command.' } $iniPath = if ($Matches[1]) { $Matches[1] } else { $Matches[2] } if (-not [IO.Path]::IsPathRooted($iniPath) -or -not (Test-Path -LiteralPath $iniPath -PathType Leaf)) { throw ('MySQL option file is missing or not absolute: ' + $iniPath) } $document = Read-MySqlOptionFile $iniPath $settings = Get-MySqlSettings $document.Text $Service.Name $dataPath = $settings['datadir'] if (-not $dataPath -or -not [IO.Path]::IsPathRooted($dataPath)) { throw 'my.ini must contain an absolute datadir for automatic recovery.' } return @{ Server = $serverExe; Ini = $iniPath; Data = [IO.Path]::GetFullPath($dataPath) } } function Repair-MySqlLogNames([string]$Text, [string]$ServiceName) { $names = @{ 'log-bin' = 'mysql-bin'; 'log-bin-index' = 'mysql-bin.index' 'log-error' = 'mysql-error.err'; 'pid-file' = 'mysql.pid' 'general-log-file' = 'mysql-general.log'; 'slow-query-log-file' = 'mysql-slow.log' 'relay-log' = 'mysql-relay-bin'; 'relay-log-index' = 'mysql-relay-bin.index' } $section = '' $newline = if ($Text.Contains("`r`n")) { "`r`n" } else { "`n" } $lines = foreach ($line in ($Text -split '\r?\n')) { if ($line -match '^\s*\[([^]]+)\]') { $section = $Matches[1] } if ($section -in @('mysqld', 'server', 'mysqld-8.0', $ServiceName) -and $line -match '^\s*([\w-]+)(?:\s*=.*|\s*)$') { $key = $Matches[1].Replace('_', '-').ToLowerInvariant() if ($names.ContainsKey($key)) { $key + '=' + $names[$key]; continue } } $line } # Explicit names avoid host-name-derived paths, including on Chinese Windows. return (($lines -join $newline).TrimEnd([char[]]"`r`n") + $newline + '[mysqld]' + $newline + 'log-bin=mysql-bin' + $newline + 'log-bin-index=mysql-bin.index' + $newline + 'log-error=mysql-error.err' + $newline) } function Invoke-MySqlRecoveryCommand([string]$Executable, [string[]]$Arguments) { # Convert native stderr records to plain messages instead of PowerShell stack traces. & $Executable @Arguments 2>&1 | ForEach-Object { Write-Host $_.ToString() } return $LASTEXITCODE } function Initialize-EmptyMySqlData($Service, $Layout) { if ($Service.State -ne 'Stopped' -or [int]$Service.ProcessId -ne 0) { throw 'MySQL must be fully stopped before initialization.' } $dataPath = $Layout.Data if (-not (Test-Path -LiteralPath $dataPath -PathType Container)) { throw ('Data directory does not exist: ' + $dataPath) } if ((Get-Item -LiteralPath $dataPath -ErrorAction Stop).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Automatic initialization is disabled for linked data directories.' } $entries = @(Get-ChildItem -LiteralPath $dataPath -Force -ErrorAction Stop) if ($entries.Count -gt 0) { Write-Host ('Data directory is not empty; initialization and log renaming skipped: ' + $dataPath) Write-Host ('Existing entries: ' + (($entries | Select-Object -First 12 -ExpandProperty Name) -join ', ')) return $false } $document = Read-MySqlOptionFile $Layout.Ini $settings = Get-MySqlSettings $document.Text $Service.Name # Changing an empty default directory must never initialize a different configured directory. if ([IO.Path]::GetFullPath($settings['datadir']) -ne $dataPath) { throw 'datadir changed during recovery.' } $backup = $Layout.Ini + '.autodeploy-' + [Guid]::NewGuid().ToString('N') + '.bak' [IO.File]::Copy($Layout.Ini, $backup, $false) Write-Host ('Configuration backup: ' + $backup) $updated = Repair-MySqlLogNames $document.Text $Service.Name [IO.File]::WriteAllText($Layout.Ini, $updated, $document.Encoding) Write-Host 'Empty data directory: using ASCII log names and initializing MySQL.' # Initialization precedes service startup. Disable binlog for this invocation only. $code = Invoke-MySqlRecoveryCommand $Layout.Server @( ('--defaults-file=' + $Layout.Ini), ('--datadir=' + $dataPath), '--initialize-insecure', '--skip-log-bin', '--console' ) if ($code -ne 0) { throw ('MySQL initialization failed, exit code: ' + $code + '. Existing files were retained.') } if (-not (Test-Path -LiteralPath (Join-Path $dataPath 'mysql.ibd'))) { throw 'Initialization returned success but mysql.ibd is missing. Refusing to start the service.' } Write-Host 'MySQL data directory initialized successfully.' return $true } '''