4

我想增加(或减少)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}
    )

这比我的第一个解决方案要好一些,但仍然需要过滤当前实体。不幸的是,如果实体分布在多个表中,这将不起作用。

4

1 回答 1

2

我会尝试,但我不确定这是否满足您的需求:

session.query(Posting).\
    .filter(Posting.id==self.id)\
    .update({'score':self.score+1})

您可能想在它之后立即执行 session.commit() 吗?

编辑:[关于问题的更新]

如果 Posting 派生自 Entity 类映射到多个表,上面的解决方案仍然成立,但是 Posting.id 属性的含义发生了变化,即不再映射到某个表的列,而是映射到不同的组合. 在这里: http ://docs.sqlalchemy.org/en/latest/orm/nonstandard_mappings.html#mapping-a-class-against-multiple-tables 你可以看到如何定义它。我建议它会像:

    j = join(entity_table_1, entity_table_2)
    mapper(Entity, j, properties={
        'id': column_property(entity_table_1.c.id, entity_table_2.c.user_id)
        <... some other properties ...>
    })
于 2010-11-12T19:02:41.533 回答