bugfix broken sqla query
code cleanup