88 lines
3.0 KiB
PowerShell
88 lines
3.0 KiB
PowerShell
#!/usr/bin/env pwsh
|
||
<#
|
||
.SYNOPSIS
|
||
远程数据库查询工具 - 彻底解决引号转义问题
|
||
.DESCRIPTION
|
||
使用 Base64 编码传递 SQL 查询,避免 PowerShell 引号转义问题
|
||
.PARAMETER Target
|
||
目标系统:production(正式)或 shadow(影子),默认 shadow
|
||
.EXAMPLE
|
||
# 方式1:从管道读取 SQL
|
||
"SELECT * FROM Material LIMIT 5;" | .\scripts\query-db.ps1
|
||
|
||
.EXAMPLE
|
||
# 方式2:从文件读取 SQL
|
||
Get-Content query.sql | .\scripts\query-db.ps1
|
||
|
||
.EXAMPLE
|
||
# 方式3:指定目标系统
|
||
"SELECT * FROM Material LIMIT 5;" | .\scripts\query-db.ps1 -Target production
|
||
#>
|
||
|
||
param(
|
||
[Parameter(Mandatory=$false)]
|
||
[ValidateSet('production', 'shadow')]
|
||
[string]$Target = 'shadow',
|
||
|
||
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
|
||
[string]$SqlQuery
|
||
)
|
||
|
||
$ErrorActionPreference = 'Stop'
|
||
|
||
# 配置
|
||
$ServerIP = "192.168.58.20"
|
||
$ServerPassword = $env:PRODUCTION_SERVER_PASSWORD
|
||
$PlinkPath = "C:\Program Files\PuTTY\plink.exe"
|
||
|
||
if ([string]::IsNullOrWhiteSpace($ServerPassword)) {
|
||
throw '缺少生产服务器密码,请先设置 PRODUCTION_SERVER_PASSWORD 环境变量'
|
||
}
|
||
|
||
# 根据目标选择容器和数据库
|
||
if ($Target -eq 'production') {
|
||
$ContainerName = "youyidian-3d-material"
|
||
$DatabaseName = "lobechat"
|
||
} else {
|
||
$ContainerName = "youyidian-3d-shadow"
|
||
$DatabaseName = "lobechat_stage"
|
||
}
|
||
|
||
Write-Host "========================================" -ForegroundColor Cyan
|
||
Write-Host "远程数据库查询工具" -ForegroundColor Cyan
|
||
Write-Host "========================================" -ForegroundColor Cyan
|
||
Write-Host "目标系统: $Target" -ForegroundColor Yellow
|
||
Write-Host "容器名称: $ContainerName" -ForegroundColor Yellow
|
||
Write-Host "数据库名: $DatabaseName" -ForegroundColor Yellow
|
||
Write-Host "查询语句: $SqlQuery" -ForegroundColor Yellow
|
||
Write-Host "========================================`n" -ForegroundColor Cyan
|
||
|
||
try {
|
||
# 使用 Base64 编码(最可靠的方式)
|
||
# 将 SQL 查询编码为 Base64,避免所有引号问题
|
||
$QueryBytes = [System.Text.Encoding]::UTF8.GetBytes($SqlQuery)
|
||
$QueryBase64 = [Convert]::ToBase64String($QueryBytes)
|
||
|
||
# 构建远程命令:先解码 Base64,再执行 SQL
|
||
$RemoteCommand = "echo '$QueryBase64' | base64 -d | docker exec -i $ContainerName psql -U gongxiangpan -d $DatabaseName"
|
||
|
||
Write-Host "执行查询..." -ForegroundColor Green
|
||
|
||
# 执行远程命令
|
||
$Result = & $PlinkPath -batch -pw $ServerPassword root@$ServerIP $RemoteCommand
|
||
|
||
if ($LASTEXITCODE -eq 0) {
|
||
Write-Host "`n查询成功!" -ForegroundColor Green
|
||
Write-Host "========================================" -ForegroundColor Cyan
|
||
Write-Host $Result
|
||
Write-Host "========================================" -ForegroundColor Cyan
|
||
} else {
|
||
Write-Host "`n查询失败!退出码: $LASTEXITCODE" -ForegroundColor Red
|
||
Write-Host $Result -ForegroundColor Red
|
||
exit 1
|
||
}
|
||
} catch {
|
||
Write-Host "`n错误: $_" -ForegroundColor Red
|
||
exit 1
|
||
}
|