Faster database queries and some refactoring of untidy code



Change-Id: I8806596ba5ceadd4dd813f0f12dd57cf37f4ddc6
Signed-off-by: Mike Kelly <m.f.kelly@arts.ac.uk>