【问题标题】:Lock a table or rows to check a condition and insert a row锁定表或行以检查条件并插入行
【发布时间】:2021-10-19 03:01:02
【问题描述】:

我需要按顺序执行:

  1. 锁定表或特定行(带有条件)以进行写入;
  2. 检查某些具有特定条件的行;
  3. 如果没有符合条件的行,则添加新行
  4. 解锁

如何在 SQLAlchemy、Flask、PostgreSQL 中做到这一点?哪些方法是正确的?

【问题讨论】:

  • 在事务中完成所有操作。这涉及访问数据库的代码。然后将transaction isolation 级别设置为所需的级别。

标签: postgresql flask sqlalchemy flask-sqlalchemy


【解决方案1】:

如果您希望它免受竞争条件的影响,您需要使用具有SERIALIZABLE 隔离级别的事务。在该事务中执行整个操作。

【讨论】:

    【解决方案2】:

    我正在使用 Flask-Sqlalchemy,所以请尝试进行调整。

    您可以在此处使用 with_for_update()docs

    一个例子是。

    class TestTable(db.Model):
        __tablename__ = "test_table"
        id = Column(db.Integer(), primary_key=True)
        filename = Column(db.String(1024))
        is_complete = Column(db.Boolean(), default=False, server_default="f")
    

    您可以通过以下方式锁定它们:

    for table in TestTable.query.with_for_update().filter_by(is_complete=False).all():
        # Example Check condition
        if table.filename != 'bar' and table.id >= 10:
           # Add a new row
           newtable = TestTable(filename='foo')
           db.session.add(newtable)
    
    # Save and release lock
    db.session.commit()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-02
      • 2023-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多