From: Mike Bayer Date: Sat, 17 Jun 2006 00:45:45 +0000 (+0000) Subject: if an object fails construction, doesnt get added to the session X-Git-Tag: rel_0_2_3~1 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=3736b3ddff65f6d4b7e273b040b48b19dbac9b66;p=thirdparty%2Fsqlalchemy%2Fsqlalchemy.git if an object fails construction, doesnt get added to the session --- diff --git a/CHANGES b/CHANGES index 9161965fd3..9b80778efa 100644 --- a/CHANGES +++ b/CHANGES @@ -38,7 +38,8 @@ __doc__ from the original class function at the moment - some fixes to between(), column.between() to propigate typing information better [ticket:202] - +- if an object fails to be constructed, is not added to the +session [ticket:203] 0.2.2 - big improvements to polymorphic inheritance behavior, enabling it diff --git a/lib/sqlalchemy/orm/mapper.py b/lib/sqlalchemy/orm/mapper.py index 90db7f83e5..ac8d6f330f 100644 --- a/lib/sqlalchemy/orm/mapper.py +++ b/lib/sqlalchemy/orm/mapper.py @@ -468,7 +468,12 @@ class Mapper(object): session._register_new(self) if oldinit is not None: - oldinit(self, *args, **kwargs) + try: + oldinit(self, *args, **kwargs) + except: + if session is not None: + session.expunge(self) + raise # override oldinit, insuring that its not already a Mapper-decorated init method if oldinit is None or not hasattr(oldinit, '_sa_mapper_init'): init._sa_mapper_init = True diff --git a/test/orm/mapper.py b/test/orm/mapper.py index 96b092d89d..b73f20b150 100644 --- a/test/orm/mapper.py +++ b/test/orm/mapper.py @@ -135,6 +135,24 @@ class MapperTest(MapperSuperTest): self.assert_(u.user_name == 'jack') self.assert_(a not in u.addresses) + def testbadconstructor(self): + """tests that if the construction of a mapped class fails, the instnace does not get placed in the session""" + class Foo(object): + def __init__(self, one, two): + pass + mapper(Foo, users) + sess = create_session() + try: + Foo('one', _sa_session=sess) + assert False + except: + assert len(list(sess)) == 0 + try: + Foo('one') + assert False + except TypeError, e: + pass + def testrefresh_lazy(self): """tests that when a lazy loader is set as a trigger on an object's attribute (at the attribute level, not the class level), a refresh() operation doesnt fire the lazy loader or create any problems""" s = create_session()