AFSQL refactors & bugfixes from PE

This is a set of patches to refactor some very ugly parts of the afsql driver, and also correct some errors (memory leaks and lost messages on transaction failure, for example).