Fully implement SQL hooks.

As well as various other cleanup/refactoring.
Signed-off-by: Chris Sanders <zidane@outlook.com>