# ==================================== # HR Portal - 資料庫設定腳本 (PowerShell) # ==================================== Write-Host "=== HR Portal 資料庫設定 ===" -ForegroundColor Cyan Write-Host "" # 設定變數 $DB_HOST = "10.1.0.254" $DB_NAME = "hr_portal" $DB_USER = "hr_user" $DB_PASSWORD = "hr_password_change_me" # 請修改為強密碼 Write-Host "連接到 PostgreSQL..." -ForegroundColor Yellow Write-Host "" # 檢查 psql 是否可用 $psqlAvailable = Get-Command psql -ErrorAction SilentlyContinue if (-not $psqlAvailable) { Write-Host "錯誤: 找不到 psql 命令" -ForegroundColor Red Write-Host "請確認 PostgreSQL 客戶端已安裝" -ForegroundColor Red Write-Host "或使用 Docker 方式執行" -ForegroundColor Yellow exit 1 } try { # 1. 創建資料庫用戶 Write-Host "1. 創建資料庫用戶: $DB_USER" -ForegroundColor Green $createUserSQL = @" DO `$`$ BEGIN IF NOT EXISTS (SELECT FROM pg_user WHERE usename = '$DB_USER') THEN CREATE USER $DB_USER WITH PASSWORD '$DB_PASSWORD'; RAISE NOTICE 'User $DB_USER created'; ELSE RAISE NOTICE 'User $DB_USER already exists'; END IF; END `$`$; "@ $createUserSQL | psql -h $DB_HOST -U postgres -w Write-Host "" # 2. 創建資料庫 Write-Host "2. 創建資料庫: $DB_NAME" -ForegroundColor Green $createDbSQL = @" SELECT 'CREATE DATABASE $DB_NAME OWNER $DB_USER' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '$DB_NAME')\gexec "@ $createDbSQL | psql -h $DB_HOST -U postgres -w Write-Host "" # 3. 授予權限 Write-Host "3. 授予權限" -ForegroundColor Green $grantSQL = @" GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER; GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO $DB_USER; GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO $DB_USER; ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO $DB_USER; ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO $DB_USER; "@ $grantSQL | psql -h $DB_HOST -U postgres -d $DB_NAME -w Write-Host "" # 4. 執行 Schema 初始化 Write-Host "4. 執行 Schema 初始化" -ForegroundColor Green $schemaFile = Join-Path $PSScriptRoot "init-db.sql" if (Test-Path $schemaFile) { Get-Content $schemaFile | psql -h $DB_HOST -U $DB_USER -d $DB_NAME } else { Write-Host "警告: 找不到 init-db.sql" -ForegroundColor Yellow } Write-Host "" Write-Host "✅ 資料庫設定完成!" -ForegroundColor Green Write-Host "" Write-Host "資料庫連接資訊:" -ForegroundColor Cyan Write-Host " Host: $DB_HOST" Write-Host " Database: $DB_NAME" Write-Host " User: $DB_USER" Write-Host " Password: $DB_PASSWORD" Write-Host "" Write-Host "DATABASE_URL: postgresql://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:5432/${DB_NAME}" -ForegroundColor Yellow Write-Host "" Write-Host "請將上述 DATABASE_URL 複製到 backend/.env 檔案中" -ForegroundColor Cyan } catch { Write-Host "錯誤: $_" -ForegroundColor Red exit 1 }