# Migration Cleanup Tools

These scripts help clean up and verify Django migration state when you encounter issues with inconsistent migrations.

## Available Scripts

### 1. clean_migration_history.py

Cleans up migration history by:
- Removing duplicate migration records
- Fixing migration dependencies
- Re-applying migrations in the correct order

Usage:
```bash
python scripts/clean_migration_history.py
```

### 2. verify_migration_state.py

Verifies that migration state is consistent by checking:
- All disk migrations are applied
- All applied migrations exist on disk
- Dependencies are correctly ordered

Usage:
```bash
python scripts/verify_migration_state.py
```

## Recommended Process

1. **Backup First**
   The cleanup script will automatically create backups, but it's recommended to also:
   ```bash
   python manage.py dumpdata > data_backup.json
   ```

2. **Clean Migrations**
   ```bash
   python scripts/clean_migration_history.py
   ```

3. **Verify State**
   ```bash
   python scripts/verify_migration_state.py
   ```

4. **If Issues Found**
   - Check the error messages from verify_migration_state.py
   - Run clean_migration_history.py again if needed
   - If problems persist, restore from backup:
     ```bash
     python manage.py flush
     python manage.py loaddata data_backup.json
     ```

## Common Issues

1. **Dependency Ordering**
   - If you see dependency errors, check the order in INSTALLED_APPS
   - Ensure migrations reference the correct dependencies

2. **Duplicate Migrations**
   - The cleanup script will handle most cases
   - For persistent issues, you may need to manually resolve conflicts

3. **Missing Migrations**
   - If verify_migration_state.py shows missing migrations:
     1. Check if they exist in the correct directories
     2. Run makemigrations to create any missing ones
     3. Run the cleanup script again

## Troubleshooting

If you encounter issues:

1. Check the Django migration table:
   ```sql
   SELECT * FROM django_migrations ORDER BY id;
   ```

2. Look for duplicate entries:
   ```sql
   SELECT app, name, COUNT(*) 
   FROM django_migrations 
   GROUP BY app, name 
   HAVING COUNT(*) > 1;
   ```

3. Verify migration files match the database state:
   ```bash
   python manage.py showmigrations
   ```
