reimplement 76aa5ed54e272fb4ee6d6949bb1df1caf18b124d in a sqlalchemy-compatible way