Commits

Mike Bayer committed 246a567

- Fixed potential memory leak whereby previously pickled objects
placed back in a session would not be fully garbage collected
unless the Session were explicitly closed out.

Comments (0)

Files changed (3)

 
     - Fixed bug whereby session.is_modified() would raise an exception
       if any synonyms were in use.
+    
+    - Fixed potential memory leak whereby previously pickled objects
+      placed back in a session would not be fully garbage collected
+      unless the Session were explicitly closed out.
       
     - Fixed Query being able to join() from individual columns of
       a joined-table subclass entity, i.e.

lib/sqlalchemy/orm/state.py

     load_path = ()
     insert_order = None
     mutable_dict = None
+    _strong_obj = None
     
     def __init__(self, obj, manager):
         self.class_ = obj.__class__
         return d
         
     def __setstate__(self, state):
-        self.obj = weakref.ref(state['instance'])
+        self.obj = weakref.ref(state['instance'], self._cleanup)
         self.class_ = state['instance'].__class__
         self.manager = manager_of_class(self.class_)
 
         self.expired = state.get('expired', False)
         self.callables = state.get('callables', {})
         
+        if self.modified:
+            self._strong_obj = state['instance']
+            
         self.__dict__.update(
             (k, state[k]) for k in (
                 'key', 'load_options', 'expired_attributes', 'mutable_dict'
                 instance_dict._modified.add(self)
 
         self.modified = True
-        self._strong_obj = self.obj()
+        if not self._strong_obj:
+            self._strong_obj = self.obj()
 
     def commit(self, dict_, keys):
         """Commit attributes.

test/orm/test_session.py

         user = s.query(User).one()
         assert user.name == 'fred'
         assert s.identity_map
+
+    @testing.resolve_artifact_names
+    def test_weak_ref_pickled(self):
+        s = create_session()
+        mapper(User, users)
+
+        s.add(User(name='ed'))
+        s.flush()
+        assert not s.dirty
+
+        user = s.query(User).one()
+        user.name = 'fred'
+        s.expunge(user)
+
+        u2 = pickle.loads(pickle.dumps(user))
+
+        del user
+        s.add(u2)
+        
+        del u2
+        gc.collect()
+        
+        assert len(s.identity_map) == 1
+        assert len(s.dirty) == 1
+        assert None not in s.dirty
+        s.flush()
+        gc.collect()
+        assert not s.dirty
+        
+        assert not s.identity_map
     
     @testing.resolve_artifact_names
     def test_weakref_with_cycles_o2m(self):