python - (Flask-)SQLAlchemy 主键问题可能是由于隐式事务
问题描述
在使用 Flask-SQLAlchemy 的项目中,我遇到了一些间歇性错误,我认为这可能是由于未明确使用事务。
我有这两个模型类,一个用于位置,另一个用于闭包:
class Location(db.Model):
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.String)
code = sa.Column(sa.String, unique=True)
class LocationPath(db.Model):
ancestor_id = sa.Column(sa.Integer, sa.ForeignKey('location.id'), nullable=False, primary_key=True)
descendant_id = sa.Column(sa.Integer, sa.ForeignKey('location.id'), nullable=False, primary_key=True)
depth = sa.Column(sa.Integer, default=0, nullable=False)
在后台进程中,我做了很多插入,所以我绕过 ORM 来使用 Core:
location_table = Location.__table__
location_path_table = LocationPath.__table__
statement = select([location_table.c.id]).where(code == code)
result = db.session.get_bind().execute(statement)
location_id = result.first()
if location_id is None:
statement = location_table.insert().values(**kwargs)
result = db.session.get_bind().execute(statement)
new_id = result.inserted_primary_key[0]
result.close()
else:
new_id = location_id
# save new_id as an ancestor_id or a descendant_id
path = LocationPath.query.filter_by(
ancestor_id=ancestor_id,
descendant_id=descendant_id
).first()
if path is None:
statement = location_path_table.insert().values(
ancestor_id=ancestor_id,
descendant_id=descendant_id,
depth=depth)
# the line below intermittently generates either of two errors:
# - the inserted primary key (ancestor/descendant) does not exist
# - a duplicate key error where the path already exists
result = db.session.get_bind().execute(statement)
这导致我相当头疼,因为我从 a或 an获取ancestor_id
or ,并且我还在尝试插入路径之前查询数据库以查看路径是否存在。descendant_id
select
insert
编辑:上面的代码循环运行。
解决方案
推荐阅读
- git - 工作流程推荐以及如何查看 git fetch 更改
- objective-c - 如何将数据从 collectionView 发送到另一个视图(Objective-C)
- visual-studio-code - Visual Studio Code Intellisense for C
- c# - c# winform程序连接sql数据库
- swift - 从 SwiftUI 推送到 UIKit 后的导航栏项目
- python - 加载 JSON 时出错(额外数据:第 1 行第 2108737 列)
- android - 反应原生 | 安装应用程序失败。请使用 SDK 管理器接受所有必要的 SDK 许可证
- mongodb - 如何创建具有属性的空集合
- android - 如何在 kotlin 中使用 retrofit2 处理动态 JSON 响应?
- odata - 从本地运行的 SAPUI5 应用程序访问 OData 服务