add database factory and move query into it