Optimize to avoid unnecessary database connections

Helps to avoid excessive time being spent connecting to the database to
check things that have already been checked.  This change is especially
important for codebases that test excessively for upgrades.
Cleanup of debugging after optimizations.