More database optimizations

See individual commits for more information.