Optimized the upgrade script

- We're not triggering event handlers so there's no need to deregister them
- Removed DB queries from foreach loops
- Uses correct coding style