首页 > 解决方案 > How does Session tracks changes in sqlalchemy?

问题描述

I studied for a while the sqlalchemy library. Besides its usefulness, I find this library very educational, as it covers pythonic ways of implementing things (like the instrumentation via descriptors) and its overall architecture.

Yet, there are some principles that I would like clarification about.

The concept of InstanceState and its connection to the Session object: I looked in an article that explains the architecture of the library, for understanding the idea of InstanceState and tracking changes of objects, but I would still like an explanation: Each instance of instrumented class has an InstanceState object in it (the _sa_instance_state attribute) as in the chart from the article above: Session overview chart

Yet, how does it really track the changes of the object? When the Session flushes the changes to the db, does it actually implement the changes that are tracked and found inside the InstanceState? (Is it like the Session perform iteration over all of the objects in his identity map and checks which one has changes in his InstanceState, or when chaning objects the InstanceState itself of an object notifies the Session that some changes occured to this object?)

And when does the Mapper actually enter the picture? It saves the correlation between the class attributes and the table columns, so when a change is taking place on an object, does the InstanceState is using the mapper to log what changes are really needed to be performed in the db? Or is it other part of the ORM system that actually uses it? as this answer simulates the Mapper to obesever in the subject-observer pattern:

Think of instrumentation as transparently adding a "Subject" implementation to a mapped class for the "Observer" mapper in a subject-observer pattern.

标签: sqlalchemy

解决方案


推荐阅读