WIP - somewhat crazy sql rewrite