The synchronize_session is used for query synchronization policy for the session when the delete or update operation is performed.
- False-Do not synchronize the session with the delete or update operation directly.
- ' Fetch '
Before the delete or update operation, send a SQL to the database to get the records that match the criteria.
1 def_do_pre_synchronize (self):2query =Self.query3Session =query.session4Context =Query._compile_context ()5SELECT_STMT =Context.statement.with_only_columns (6 Self.primary_table.primary_key)7Self.matched_rows =Session.execute (8 select_stmt,9Mapper=Self.mapper,TenParams=query._params). Fetchall ()
After the delete or update operation, match the Identity_map of the session with the record obtained in the previous step, and the qualifying entries are deleted or updated from the session.
1 def_do_post_synchronize (self):2Session =self.query.session3Target_mapper =Self.query._mapper_zero ()4 forPrimary_keyinchself.matched_rows:5 #Todo:inline This and the call remove_newly_deleted6 #once7Identity_key =Target_mapper.identity_key_from_primary_key (8 list (primary_key))9 ifIdentity_keyinchSession.identity_map:Ten session._remove_newly_deleted ( One [Attributes.instance_state ( A Session.identity_map[identity_key] - )] -)
Before the delete or update operation, the objects in the session's Identity_map is directly eval with the conditions in query, and the qualifying record is recorded.
1 def_do_pre_synchronize (self):2query =Self.query3Target_cls =Query._mapper_zero (). Class_4 5 Try:6Evaluator_compiler =evaluator. Evaluatorcompiler (TARGET_CLS)7 ifQuery.whereclause is notNone:8Eval_condition =evaluator_compiler.process (9 query.whereclause)Ten Else: One defeval_condition (obj): A returnTrue - - self._additional_evaluators (Evaluator_compiler) the - exceptevaluator. Unevaluatableerror: - RaiseSa_exc. Invalidrequesterror ( - "Could not evaluate current criteria in Python." + "specify ' fetch ' or False for the" - "synchronize_session parameter.") + A #Todo:detect when the WHERE clause is a trivial primary key match atSelf.matched_objects = [ -Obj for(CLS, PK), objinch - Query.session.identity_map.items () - ifIssubclass (CLS, TARGET_CLS) and -Eval_condition (obj)]
After the delete or update operation, the eligible records are deleted or updated.
1 def _do_post_synchronize (self): 2 self.query.session._remove_newly_deleted (3 [Attributes.instance_state (obj) 4for in self.matched_objects])
[SQLAlchemy] Synchronize_session parameter detailed