run-clean-us-business-data.ps1 2.97 KB
#Requires -Version 5.1
<#
.SYNOPSIS
  执行美国版业务数据清理 SQL(标签 / 日志 / 门店等)

.DESCRIPTION
  调用同目录 clean-us-business-data.sql。
  默认不保留 user / role / menu;会清空 userlocation,登录用户需重新绑定门店。

.PARAMETER Host
  MySQL 主机,默认 127.0.0.1

.PARAMETER Port
  MySQL 端口,默认 3306

.PARAMETER User
  MySQL 用户,默认 root

.PARAMETER Database
  数据库名(必填)

.PARAMETER Password
  密码;未传则提示输入

.PARAMETER DryRun
  仅打印将执行的命令,不真正执行

.EXAMPLE
  .\run-clean-us-business-data.ps1 -Database food_labeling_us

.EXAMPLE
  .\run-clean-us-business-data.ps1 -Host 127.0.0.1 -Port 3306 -User root -Database food_labeling_us
#>

[CmdletBinding(SupportsShouldProcess = $true)]
param(
  [string] $Host = '127.0.0.1',
  [int] $Port = 3306,
  [string] $User = 'root',
  [Parameter(Mandatory = $true)]
  [string] $Database,
  [string] $Password,
  [switch] $DryRun
)

$ErrorActionPreference = 'Stop'
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$sqlFile = Join-Path $scriptDir 'clean-us-business-data.sql'

if (-not (Test-Path $sqlFile)) {
  throw "SQL file not found: $sqlFile"
}

$mysql = Get-Command mysql -ErrorAction SilentlyContinue
if (-not $mysql) {
  throw "mysql CLI not found in PATH. Install MySQL client or add mysql.exe to PATH."
}

Write-Host ''
Write-Host '========================================' -ForegroundColor Yellow
Write-Host ' US business data cleanup (DESTRUCTIVE) ' -ForegroundColor Yellow
Write-Host '========================================' -ForegroundColor Yellow
Write-Host "Target : $User@${Host}:$Port / $Database"
Write-Host 'Clears : print logs, labels, templates, products, locations, partner/region, userlocation'
Write-Host 'Keeps  : user, role, userrole, userpost, menu, rolemenu'
Write-Host ''

if (-not $PSCmdlet.ShouldProcess($Database, 'Run clean-us-business-data.sql')) {
  return
}

$confirm = Read-Host "Type YES to continue"
if ($confirm -ne 'YES') {
  Write-Host 'Cancelled.' -ForegroundColor Cyan
  return
}

if (-not $Password) {
  $secure = Read-Host 'MySQL password' -AsSecureString
  $bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
  try {
    $Password = [Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)
  } finally {
    [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
  }
}

$args = @(
  "-h$Host",
  "-P$Port",
  "-u$User",
  "-p$Password",
  '--default-character-set=utf8mb4',
  $Database
)

$cmdDisplay = "mysql -h$Host -P$Port -u$User -p*** $Database < clean-us-business-data.sql"
Write-Host "Executing: $cmdDisplay" -ForegroundColor Gray

if ($DryRun) {
  Write-Host '[DryRun] Skipped execution.' -ForegroundColor Cyan
  return
}

Get-Content -LiteralPath $sqlFile -Encoding UTF8 | & $mysql.Source @args
if ($LASTEXITCODE -ne 0) {
  throw "mysql exited with code $LASTEXITCODE"
}

Write-Host ''
Write-Host 'Cleanup finished. Check BEFORE/AFTER counts in output above.' -ForegroundColor Green