您真的需要针对重负载对其进行优化吗?可能不是,让您使用 SQLite。在这种情况下,简单的解决方案要好得多:
class Like(Base):
__tablename__ = 'Like'
id = Column(Integer, primary_key=True)
counter = Column(Integer, nullable=False, default=0)
o = session.merge(Like(id=1))
session.flush() # Required when it's new record
o.counter = Like.counter+1
session.commit()
检查和插入之间存在竞争条件,但我相信它不会在实践中击败你。
当你真的需要稍微优化或修复这个竞争条件时,SQLite 中有一个INSERT OR IGNORE 以避免检查(目前执行了 2 个单独的语句):
clause = Like.__table__.insert(prefixes=['OR IGNORE'],
values=dict(id=1, counter=0))
session.execute(clause)
o = session.merge(Like(id=1, counter=Like.counter+1))
session.commit()
最后有一种方法可以在单个语句中使用INSERT OR REPLACE 和 subselect(在大多数其他数据库中还有其他方法可以做到这一点,例如 MySQL 中的ON DUPLICATE KEY),但我怀疑它会给你显着的性能提升:
old = session.query(Like.counter).filter_by(id=1).statement.as_scalar()
new = func.ifnull(old, 0) + 1
clause = Like.__table__.insert(prefixes=['OR REPLACE'],
values=dict(id=1, counter=new))
session.execute(clause)