Fixed SQLAlchemy connection leak.

Also made a few more database optimizations and fixed some additional misc bugs.