Last of the sql refactoring.

I will test this later today and fix things if bugs should appear.