我想增加(或减少)Elixir 实体中的分数字段:
class Posting(Entity):
score = Field(Integer, PassiveDefault(text('0')))
def upvote(self):
self.score = self.score + 1
但是,这在并发调用 upvote 时并不可靠。我能想到的最好的就是这个丑陋的混乱(基本上是用 SQLAlchemy 构建一个 SQL UPDATE 语句):
def upvote(self):
# sqlalchemy atomic increment; is there a cleaner way?
update = self.table.update().where(self.table.c.id==self.id)
update = update.values({Posting.score: Posting.score + 1})
update.execute()
你觉得这个解决方案有什么问题吗?有没有更清洁的方法来实现同样的目标?
我想避免在这里使用数据库锁。我正在使用 Elixir、SQLAlchemy、Postgres。
更新
这是一个衍生自 vonPetrushev 解决方案的变体:
def upvote(self):
Posting.query.filter_by(id=self.id).update(
{Posting.score: Posting.score + 1}
)
这比我的第一个解决方案要好一些,但仍然需要过滤当前实体。不幸的是,如果实体分布在多个表中,这将不起作用。