Improve logging and break query execution into more modular parts