re #1 to use sqlalchemy and do some optimizations