在代码内调用SQLAlchemy flush()有什么副作用吗? [英] Are there any side effects from calling SQLAlchemy flush() within code?

查看:110
本文介绍了在代码内调用SQLAlchemy flush()有什么副作用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将pyramid框架与SQLAlchemy一起使用.我的数据库会话由pyramid_tm和ZTE处理

I am using pyramid framework with SQLAlchemy. My db session is handled by pyramid_tm and ZTE

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))

我的数据库设计非常复杂,其中包含许多模型类,外键以及模型之间的复杂关系.

I have a very complicated database design with lots of model classes, foreign keys, and complex relationships between my models.

因此,在对模型执行一些非常复杂的逻辑并从不同模型中的关系中删除,更新,插入和移动对象时,我曾经随机获取IntegrityError,而在重新启动pserve之后,该信息将消失.

So while doing some very complicated logic on my Models and deleting, updating , inserting, and moving around objects from relationships in different models I used to get IntegrityError randomly which would go away after restarting pserve.

这很奇怪,因为autoflush处于打开状态,理论上讲,一旦我对模型进行任何更改,都必须刷新该会话.

This is very strange because autoflush is on and in theory session must be flushed as soon as I change anything on models.

所以我对随机IntegrityError的解决方案是,只要事情变得非常复杂,就可以在逻辑内手动刷新会话.

So my solution to the random IntegrityError was to manually flush the session within my logic whenever things get very complicated.

自从我按照自己的逻辑进行了DBSession.flush()操作后,我再也没有收到IntegrityError了.

Since I did the DBSession.flush() within my logic I haven't got the IntegrityError any more.

现在我有2个问题:

  1. 为什么自动刷新不能防止完整性错误?是自动刷新不清除模型而是DBSession.flush()清除模型吗?

在我的代码中调用DBSession.flush()有任何副作用吗?我真的没有想到任何副作用(除了调用DB的少量性能开销外).我真的不喜欢在代码中调用DBSession.flush(),因为它必须由框架真正处理.

Are there any side effects of calling DBSession.flush() within my code? I can't really think of any side effects (apart from little performance overhead of calling DB). I don't really like calling DBSession.flush() within my code as it is something that must really be handled by framework.

另请参见

何时应该在SQLAlchemy上调用flush()?

谢谢.

推荐答案

很难说出为什么以前没有看到任何代码就获取IntegrityError的原因,但是从理论上讲,有些情况下autocommit可能实际上是通过过早刷新会话来引起.例如:

It is very hard to say why you used to get IntegrityError's without seeing any code, but in theory there are a few scenarios where autocommit may actually cause it by flushing the session prematurely. For example:

COURSE_ID = 10
student = Student(name="Bob")
student.course_id = COURSE_ID

course = Course(id=COURSE_ID, name="SQLAlchemy")

上面的代码可能会(未经测试)在打开autocommit时失败,并且如果让SQLAlchemy刷新更改应会成功.

The above code will probably (haven't tested) fail with autocommit turned on and should succeed if you let SQLAlchemy to flush the changes.

如果认为有帮助,定期刷新会话不会有任何危害,但同样,很难说是否可以做一些事情来避免没有任何代码示例的手动刷新.

I don't think there's any harm in flushing the session periodically if it helps, but again, it's hard to tell whether something can be done to avoid the manual flush without any code samples.

这篇关于在代码内调用SQLAlchemy flush()有什么副作用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆