# migration-sandbox

## When to Use

Run database migrations for SandboxRemote environment, apply pending EF Core migrations, create backups, and verify connectivity.

## Prerequisites

- .NET SDK installed (`dotnet --version`)
- PostgreSQL accessible for SandboxRemote
- Connection string in `appsettings.SandboxRemote.json`
- `scripts/safe-migrate.sh` available and executable

## Execution Steps

### Step 1: Verify Script Exists and is Executable

Check: `test -f scripts/safe-migrate.sh`

**If missing:** Error and **STOP**

**If not executable:** `chmod +x scripts/safe-migrate.sh`

### Step 2: Verify Environment Configuration

Check: `test -f src/Managing.Api/appsettings.SandboxRemote.json`

**If missing:** Check `appsettings.Sandbox.json`, else **STOP**

### Step 3: Run Migration Script

Run: `./scripts/safe-migrate.sh SandboxRemote`

**Script performs:** Build projects → Check connectivity → Create DB if needed → Prompt backup → Check pending changes → Generate script → Apply migrations → Verify status

**On success:** Show success message, backup location, log file location

**On failure:** Show error output, diagnose (connectivity, connection string, server status, permissions), provide guidance or **STOP** if unresolvable

## Error Handling

**Script not found:** Check `ls -la scripts/safe-migrate.sh`, **STOP** if missing

**Not executable:** `chmod +x scripts/safe-migrate.sh`, retry

**Database connection fails:** Verify PostgreSQL running, check connection string in `appsettings.SandboxRemote.json`, verify network/firewall/credentials

**Build fails:** Show errors (C# compilation, missing dependencies, config errors), try auto-fix (compilation errors, imports, config), if fixed re-run else **STOP**

**Migration conflicts:** Review migration history, script handles idempotent migrations, schema conflicts may need manual intervention

**Backup fails:** Script warns, recommend fixing before proceeding, warn if proceeding without backup

## Example Execution

**Success flow:**
1. Verify script → ✅
2. Check executable → ✅
3. Verify config → ✅
4. Run: `./scripts/safe-migrate.sh SandboxRemote`
5. Script: Build → Connect → Backup → Generate → Apply → Verify → ✅
6. Show backup/log locations

**Connection fails:** Diagnose connection string/server, provide guidance, **STOP**

**Build fails:** Show errors, try auto-fix, if fixed re-run else **STOP**

## Important Notes

- ✅ Backup recommended, script prompts for it
- ✅ Review migration script before applying
- ✅ Idempotent migrations - safe to run multiple times
- ⚠️ Environment: `SandboxRemote`, Config: `appsettings.SandboxRemote.json`
- ⚠️ Backups: `scripts/backups/SandboxRemote/`, Logs: `scripts/logs/`
- 📦 Keeps last 5 backups automatically

