Are there any side effects from calling SQLAlchemy flush() within code?

耗尽温柔 提交于 2019-12-11 01:55:36

问题


A bit of background:

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.

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.

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

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

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

The question

Now I have 2 questions:

  1. How come autoflush does not prevent from integrity error? Is it that autoflush does not clean the models but DBSession.flush() cleans the models?

  2. 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.

See also

When should I be calling flush() on SQLAlchemy?

Thank you.


回答1:


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")

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.



来源:https://stackoverflow.com/questions/29338419/are-there-any-side-effects-from-calling-sqlalchemy-flush-within-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!