- .cursor/rules + AGENTS.md:供应商二次开发的隔离硬规则落库(库/端口/上传目录/对象前缀) - 部署与本地配置:docker-compose*.yml、.env.*.example(仅占位值)、start-split-native / sync-prod-db-to-local 脚本 - 小程序:入库归档识别(stockInboundArchive + 识别与入库面板改动) - tools:设计门禁脚本(check-migrations / run-all / verify-facts)与架构图脚本更新 - docs:跨系统改价改量审核、第三方订单退货跟随、免入库推进、500+ 分公司规模改造、 拍照入库识别与档案回写等设计文档;对接清单新增 §4.5.4 我方回执(第六批端到端) - server:存量修数脚本(legacy CS / 供应商应付 / 结算口径)、采购耳标核对脚本; 新增测试:入库归档回写、租户优选顺序、规模并发
169 lines
7.3 KiB
PowerShell
169 lines
7.3 KiB
PowerShell
# 从生产环境 PostgreSQL 同步数据到本机(读取 server/.env 中的 DATABASE_URL)
|
||
# 依赖:OpenSSH、本机 PostgreSQL(psql)、deploy\id_rsa_tencent
|
||
param(
|
||
[string]$KeyFile = '',
|
||
[string]$ApiHost = 'ubuntu@146.56.223.139',
|
||
[switch]$SkipDevStop,
|
||
[switch]$SkipPasswordReset
|
||
)
|
||
|
||
$ErrorActionPreference = 'Stop'
|
||
$root = Split-Path -Parent $PSScriptRoot
|
||
Set-Location $root
|
||
|
||
if (-not $KeyFile) { $KeyFile = Join-Path $root 'deploy\id_rsa_tencent' }
|
||
if (-not (Test-Path $KeyFile)) { Write-Error "SSH key not found: $KeyFile" }
|
||
|
||
function Read-DatabaseUrlFromEnv {
|
||
param([string]$EnvFile)
|
||
if (-not (Test-Path $EnvFile)) {
|
||
return 'postgresql://supplier@127.0.0.1:5432/supplier_delivery'
|
||
}
|
||
$line = Get-Content $EnvFile | Where-Object { $_ -match '^\s*DATABASE_URL=' } | Select-Object -First 1
|
||
if (-not $line) {
|
||
return 'postgresql://supplier@127.0.0.1:5432/supplier_delivery'
|
||
}
|
||
return ($line -replace '^\s*DATABASE_URL=', '').Trim()
|
||
}
|
||
|
||
function Parse-PostgresUrl {
|
||
param([string]$Url)
|
||
$uri = [Uri]$Url
|
||
$user = [Uri]::UnescapeDataString($uri.UserInfo.Split(':')[0])
|
||
$pass = if ($uri.UserInfo.Contains(':')) { [Uri]::UnescapeDataString($uri.UserInfo.Split(':', 2)[1]) } else { '' }
|
||
$db = $uri.AbsolutePath.TrimStart('/')
|
||
if (-not $db) { = 'supplier_delivery' }
|
||
return @{
|
||
Host = if ($uri.Host) { $uri.Host } else { '127.0.0.1' }
|
||
Port = if ($uri.Port -gt 0) { $uri.Port } else { 5432 }
|
||
User = $user
|
||
Password = $pass
|
||
Database = $db
|
||
}
|
||
}
|
||
|
||
$dbConfig = Parse-PostgresUrl (Read-DatabaseUrlFromEnv (Join-Path $root 'server\.env'))
|
||
$pgBinCandidates = @(
|
||
'C:\Program Files\PostgreSQL\18\bin',
|
||
'C:\Program Files\PostgreSQL\16\bin',
|
||
'C:\Program Files\PostgreSQL\17\bin'
|
||
)
|
||
$psql = $null
|
||
foreach ($bin in $pgBinCandidates) {
|
||
$candidate = Join-Path $bin 'psql.exe'
|
||
if (Test-Path $candidate) { $psql = $candidate; break }
|
||
}
|
||
if (-not $psql) {
|
||
$cmd = Get-Command psql -ErrorAction SilentlyContinue
|
||
if ($cmd) { $psql = $cmd.Source }
|
||
}
|
||
if (-not $psql) { Write-Error 'psql not found. Install PostgreSQL client tools or add psql to PATH.' }
|
||
|
||
$env:PGPASSWORD = $dbConfig.Password
|
||
$pgHost = $dbConfig.Host
|
||
$pgPort = $dbConfig.Port
|
||
$pgUser = $dbConfig.User
|
||
$pgDb = $dbConfig.Database
|
||
|
||
Write-Host "Local target: ${pgUser}@${pgHost}:${pgPort}/${pgDb}" -ForegroundColor DarkGray
|
||
|
||
$tmpDir = Join-Path $root 'tmp'
|
||
New-Item -ItemType Directory -Force -Path $tmpDir | Out-Null
|
||
$localSql = Join-Path $tmpDir 'prod-db.sql'
|
||
$stamp = Get-Date -Format 'yyyyMMdd_HHmmss'
|
||
$remoteSql = "/tmp/supplier_prod_$stamp.sql"
|
||
$sshOpts = @('-i', $KeyFile, '-o', 'StrictHostKeyChecking=accept-new', '-o', 'ConnectTimeout=60')
|
||
|
||
if (-not $SkipDevStop) {
|
||
Write-Host 'Stopping local dev servers (ports 3001/3015)...' -ForegroundColor Yellow
|
||
foreach ($p in 3001, 3015) {
|
||
Get-NetTCPConnection -LocalPort $p -ErrorAction SilentlyContinue |
|
||
ForEach-Object { Stop-Process -Id $_.OwningProcess -Force -ErrorAction SilentlyContinue }
|
||
}
|
||
Start-Sleep -Seconds 2
|
||
}
|
||
|
||
Write-Host 'Dumping production database (postgres:18 docker on API server)...' -ForegroundColor Cyan
|
||
$dumpCmd = @(
|
||
'set -e'
|
||
"DB=`$(grep -m1 '^DATABASE_URL=' /opt/ai-fresh-delivery/server/.env | cut -d= -f2- | tr -d '\r')"
|
||
"sudo docker run --rm --network host -e DATABASE_URL=`"`$DB`" postgres:18-alpine sh -c 'pg_dump `"`$DATABASE_URL`" --no-owner --no-acl --clean --if-exists' > $remoteSql"
|
||
"ls -lh $remoteSql"
|
||
) -join "`n"
|
||
& ssh @sshOpts $ApiHost $dumpCmd
|
||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||
|
||
Write-Host "Downloading $remoteSql -> $localSql" -ForegroundColor Cyan
|
||
& scp @sshOpts "${ApiHost}:$remoteSql" $localSql
|
||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||
|
||
# PG 18 pg_dump 会写入 \restrict/\unrestrict;本机 psql 17 无法识别,导入前剔除。
|
||
# 必须用 UTF-8 无 BOM 读写:PowerShell Get-Content/Set-Content 默认编码会损坏中文 COMMENT。
|
||
$localSqlClean = Join-Path $tmpDir 'prod-db-clean.sql'
|
||
Write-Host 'Stripping PG18-only psql meta commands for local client compatibility...' -ForegroundColor DarkGray
|
||
$utf8NoBom = New-Object System.Text.UTF8Encoding $false
|
||
$sqlText = [System.IO.File]::ReadAllText($localSql, $utf8NoBom)
|
||
$sqlFiltered = ($sqlText -split "`r?`n" | Where-Object {
|
||
$_ -notmatch '^\\restrict\b' -and $_ -notmatch '^\\unrestrict\b'
|
||
}) -join "`n"
|
||
[System.IO.File]::WriteAllText($localSqlClean, $sqlFiltered + "`n", $utf8NoBom)
|
||
$localSql = $localSqlClean
|
||
|
||
Write-Host "Recreating local database $pgDb ..." -ForegroundColor Cyan
|
||
& $psql -U $pgUser -h $pgHost -p $pgPort -d postgres -v ON_ERROR_STOP=1 -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '$pgDb' AND pid <> pg_backend_pid();" | Out-Null
|
||
& $psql -U $pgUser -h $pgHost -p $pgPort -d postgres -v ON_ERROR_STOP=1 -c "DROP DATABASE IF EXISTS `"$pgDb`";" | Out-Null
|
||
& $psql -U $pgUser -h $pgHost -p $pgPort -d postgres -v ON_ERROR_STOP=1 -c "CREATE DATABASE `"$pgDb`" OWNER `"$pgUser`";" | Out-Null
|
||
|
||
Write-Host 'Importing SQL dump (may take a minute)...' -ForegroundColor Cyan
|
||
& $psql -U $pgUser -h $pgHost -p $pgPort -d $pgDb -v ON_ERROR_STOP=0 -f $localSql 2>&1 | Out-Null
|
||
|
||
Write-Host 'Applying pending local migrations...' -ForegroundColor Cyan
|
||
$env:NODE_ENV = 'development'
|
||
$env:SKIP_LOCAL_DB_SETUP = '1'
|
||
$env:SKIP_DEMO_SEED = '1'
|
||
Push-Location (Join-Path $root 'server')
|
||
npx tsx --env-file=.env src/migrate.ts 2>&1 | Select-Object -Last 12
|
||
Pop-Location
|
||
Remove-Item Env:SKIP_LOCAL_DB_SETUP -ErrorAction SilentlyContinue
|
||
Remove-Item Env:SKIP_DEMO_SEED -ErrorAction SilentlyContinue
|
||
|
||
# pg_dump --no-acl 会丢掉 ACL;生产 dump 已带 schema_migrations,migrate 会跳过 GRANT 类迁移。
|
||
# 强制重跑,否则 SET LOCAL ROLE canteen_app_rls 后 tenant_* 表表现为「关系不存在」。
|
||
Write-Host 'Re-applying RLS grants for canteen_app_rls (tenant schema USAGE)...' -ForegroundColor Cyan
|
||
$grantFiles = @(
|
||
(Join-Path $root 'migrations\20260790_grant_tenant_schema_registry.sql'),
|
||
(Join-Path $root 'migrations\20260793_rls_schema_usage_grants.sql')
|
||
)
|
||
foreach ($gf in $grantFiles) {
|
||
if (Test-Path $gf) {
|
||
& $psql -U $pgUser -h $pgHost -p $pgPort -d $pgDb -v ON_ERROR_STOP=1 -f $gf | Out-Null
|
||
Write-Host " applied $(Split-Path -Leaf $gf)" -ForegroundColor DarkGray
|
||
}
|
||
}
|
||
|
||
Write-Host 'Data summary (active tenant schemas):' -ForegroundColor Green
|
||
& $psql -U $pgUser -h $pgHost -p $pgPort -d $pgDb -c @"
|
||
SELECT r.branch_code, r.schema_name, r.status,
|
||
(SELECT count(*)::int FROM information_schema.tables t
|
||
WHERE t.table_schema = r.schema_name AND t.table_name = 'orders') AS has_orders_tbl
|
||
FROM public.tenant_schema_registry r
|
||
ORDER BY r.branch_code;
|
||
"@
|
||
& $psql -U $pgUser -h $pgHost -p $pgPort -d $pgDb -c @"
|
||
SELECT schema_name,
|
||
(xpath('/row/c/text()', query_to_xml(format('SELECT count(*)::int AS c FROM %I.orders', schema_name), false, true, '')))[1]::text::int AS orders
|
||
FROM public.tenant_schema_registry
|
||
WHERE status = 'active'
|
||
ORDER BY schema_name;
|
||
"@
|
||
& $psql -U $pgUser -h $pgHost -p $pgPort -d $pgDb -c "SELECT count(*)::int AS auth_users FROM auth.users;"
|
||
|
||
if (-not $SkipPasswordReset) {
|
||
Write-Host 'Resetting local dev passwords to 123456...' -ForegroundColor Cyan
|
||
Push-Location (Join-Path $root 'server')
|
||
npm run seed:dev-passwords 2>&1 | Select-Object -Last 20
|
||
Pop-Location
|
||
}
|
||
|
||
Write-Host "`nDone. Start local app: powershell -ExecutionPolicy Bypass -File scripts/start-local.ps1" -ForegroundColor Green
|