# Database Operations

## Common Validation Checks

### Check Required Variables

```bash
# Validate required variables from step-00-init
for VAR_NAME in DBCONTEXT DBCONTEXT_TYPE INFRA_PROJECT STARTUP_PROJECT SELECTED_ENV; do
  if [ -z "${!VAR_NAME}" ]; then
    echo "ERROR: Required variable $VAR_NAME is not set"
    echo "Run step-00-init first"
    exit 1
  fi
done
```

## Backup Command

```bash
BACKUP_DIR=".claude/gitflow/backup/database"
mkdir -p "$BACKUP_DIR"

BACKUP_FILE="$BACKUP_DIR/${DATABASE_NAME}_$(date +%Y%m%d_%H%M%S).bak"

echo "Creating backup: $BACKUP_FILE"

sqlcmd -S "$SERVER_NAME" -E -Q "BACKUP DATABASE [$DATABASE_NAME] TO DISK='$BACKUP_FILE'"

if [ $? -eq 0 ]; then
  echo "Backup created: $BACKUP_FILE"
else
  echo "WARNING: Backup failed. Continue anyway?"
fi
```

## Connection Test

```bash
CONNECTION_TEST=$(dotnet ef migrations list \
  --context "$DBCONTEXT" \
  --project "$INFRA_PROJECT" \
  --startup-project "$STARTUP_PROJECT" 2>&1)

if [ $? -eq 0 ]; then
  echo "Connection:  OK"
else
  echo "Connection:  FAILED"
  echo ""
  echo "$CONNECTION_TEST"
fi
```

## Migration Count Utilities

```bash
# Count applied and pending
MIGRATION_OUTPUT=$(dotnet ef migrations list \
  --context "$DBCONTEXT" \
  --project "$INFRA_PROJECT" \
  --startup-project "$STARTUP_PROJECT" 2>/dev/null)

APPLIED=$(echo "$MIGRATION_OUTPUT" | grep -v "(Pending)" | grep -c "^[0-9]" || echo "0")
PENDING=$(echo "$MIGRATION_OUTPUT" | grep -c "(Pending)" || echo "0")
TOTAL=$((APPLIED + PENDING))
```
