rewrite queries to use db abstraction layer and chaining
rewrite lastrun function