问题
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:
How come autoflush does not prevent from integrity error? Is it that autoflush does not clean the models but
DBSession.flush()
cleans the models?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 callingDBSession.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