# Database Deployment Guide

## Quick Start

### For Development/Testing
```bash
# Windows
deploy_db.bat

# Linux/Mac
chmod +x deploy_db.sh
./deploy_db.sh

# Python (all platforms)
python deploy_database_changes.py
```

### For Production (cPanel/Shared Hosting)
```bash
python deploy_database_changes.py
```

---

## Deployment Scripts Overview

### 1. `deploy_database_changes.py` (Recommended)
**Comprehensive Python script with safety checks**

Features:
- ✅ Database connection verification
- ✅ Backup reminder
- ✅ Migration conflict detection
- ✅ Pending migration check
- ✅ Automatic migration application
- ✅ Critical table verification
- ✅ Foreign key constraint checks
- ✅ Common issue fixes
- ✅ Static file collection
- ✅ System checks
- ✅ Detailed summary report

Usage:
```bash
python deploy_database_changes.py
```

### 2. `deploy_db.sh` (Unix/Linux/Mac)
**Quick shell script for Unix-based systems**

Usage:
```bash
chmod +x deploy_db.sh
./deploy_db.sh
```

### 3. `deploy_db.bat` (Windows)
**Quick batch script for Windows**

Usage:
```bash
deploy_db.bat
```

---

## Manual Deployment Steps

If you prefer manual control:

### Step 1: Backup Database
```bash
# MySQL/MariaDB
mysqldump -u username -p database_name > backup_$(date +%Y%m%d_%H%M%S).sql

# Or use cPanel backup tools
```

### Step 2: Check Pending Migrations
```bash
python manage.py showmigrations
```

### Step 3: Check for Conflicts
```bash
python manage.py makemigrations --dry-run --check
```

### Step 4: Apply Migrations
```bash
python manage.py migrate --noinput
```

### Step 5: Verify Database
```bash
python manage.py check
```

### Step 6: Collect Static Files
```bash
python manage.py collectstatic --noinput
```

---

## Common Issues & Solutions

### Issue 1: Migration Conflicts
**Error:** "Conflicting migrations detected"

**Solution:**
```bash
# Check conflicts
python manage.py makemigrations --merge

# Or reset specific app migrations
python manage.py migrate appname zero
python manage.py migrate appname
```

### Issue 2: Missing Columns
**Error:** "Unknown column in field list"

**Solution:**
```bash
# Run the comprehensive deployment script
python deploy_database_changes.py

# Or manually add columns via SQL
```

### Issue 3: Foreign Key Errors
**Error:** "Cannot add foreign key constraint"

**Solution:**
```sql
-- Check existing constraints
SHOW CREATE TABLE table_name;

-- Drop problematic constraint
ALTER TABLE table_name DROP FOREIGN KEY constraint_name;

-- Re-run migrations
```

### Issue 4: Permission Denied
**Error:** "Access denied for user"

**Solution:**
- Verify database credentials in settings
- Check user has proper permissions
- For cPanel: Use cPanel MySQL user manager

---

## Production Deployment Checklist

- [ ] **Backup database** (critical!)
- [ ] **Test on staging** environment first
- [ ] **Enable maintenance mode** (optional)
- [ ] **Check disk space** (migrations can be large)
- [ ] **Verify database credentials** in settings
- [ ] **Run deployment script**
- [ ] **Test critical functionality**
- [ ] **Monitor error logs**
- [ ] **Disable maintenance mode**

---

## cPanel Specific Instructions

### Via Terminal (if available)
```bash
cd ~/public_html/your_app
source venv/bin/activate
python deploy_database_changes.py
```

### Via Python Script Execution
1. Upload `deploy_database_changes.py` to your app directory
2. In cPanel Terminal or SSH:
```bash
cd ~/public_html/your_app
/usr/bin/python3 deploy_database_changes.py
```

### Via Cron Job (Scheduled)
1. Go to cPanel → Cron Jobs
2. Add command:
```bash
cd ~/public_html/your_app && /usr/bin/python3 deploy_database_changes.py >> deployment.log 2>&1
```

---

## Rollback Procedure

If deployment fails:

### 1. Restore Database Backup
```bash
mysql -u username -p database_name < backup_file.sql
```

### 2. Revert Code Changes
```bash
git checkout previous_commit_hash
```

### 3. Clear Cache
```bash
python manage.py clear_cache
# Or manually delete cache files
```

---

## Environment-Specific Settings

### Development
```python
# settings.py or local_settings.py
DEBUG = True
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
```

### Production
```python
# production_settings.py
DEBUG = False
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'your_db_name',
        'USER': 'your_db_user',
        'PASSWORD': 'your_db_password',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}
```

---

## Monitoring & Verification

### Check Migration Status
```bash
python manage.py showmigrations
```

### Verify Tables Exist
```bash
python manage.py dbshell
> SHOW TABLES;
> DESCRIBE table_name;
```

### Check Application Health
```bash
python manage.py check --deploy
```

### View Recent Logs
```bash
tail -f logs/django.log
# Or check cPanel error logs
```

---

## Best Practices

1. **Always backup before deployment**
2. **Test migrations on staging first**
3. **Run during low-traffic periods**
4. **Keep deployment scripts version controlled**
5. **Document custom SQL changes**
6. **Monitor application after deployment**
7. **Have rollback plan ready**
8. **Use migration squashing for old migrations**

---

## Support & Troubleshooting

### Enable Verbose Output
```bash
python manage.py migrate --verbosity 2
```

### Check Database Connection
```bash
python -c "import django; django.setup(); from django.db import connection; connection.ensure_connection(); print('Connected')"
```

### View SQL Without Executing
```bash
python manage.py sqlmigrate app_name migration_name
```

### Debug Mode
```bash
python manage.py migrate --traceback
```

---

## Quick Reference Commands

```bash
# Show all migrations
python manage.py showmigrations

# Show pending migrations only
python manage.py showmigrations --plan | grep "\[ \]"

# Apply specific app migrations
python manage.py migrate app_name

# Fake a migration (mark as applied without running)
python manage.py migrate app_name migration_name --fake

# Rollback to specific migration
python manage.py migrate app_name migration_name

# Create new migrations
python manage.py makemigrations

# Check for issues
python manage.py check

# Database shell
python manage.py dbshell
```

---

## Contact & Support

For issues or questions:
1. Check error logs first
2. Review this guide
3. Test on local/staging environment
4. Document the error message
5. Check Django documentation

**Remember:** Always backup before making database changes!
