Python sqlalchemy.orm.attributes.instance_state() Examples
The following are 30
code examples of sqlalchemy.orm.attributes.instance_state().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
sqlalchemy.orm.attributes
, or try the search function
.
Example #1
Source File: test_attributes.py From sqlalchemy with MIT License | 6 votes |
def test_object_del_expired(self): Foo, Bar = self._two_obj_fixture(uselist=False) f = Foo() b1 = Bar() f.someattr = b1 self._commit_someattr(f) # the "delete" handler checks if the object # is db-loaded when testing if an empty "del" is valid, # because there's nothing else to look at for a related # object, there's no "expired" status attributes.instance_state(f).key = ("foo",) attributes.instance_state(f)._expire_attributes( attributes.instance_dict(f), ["someattr"] ) del f.someattr eq_(self._someattr_history(f), ([None], (), ()))
Example #2
Source File: test_attributes.py From sqlalchemy with MIT License | 6 votes |
def test_collection_obj_remove_invalid(self): A, B = self._collection_obj_fixture() a1 = A() b1 = B() b2 = B() A.b.impl.append( attributes.instance_state(a1), attributes.instance_dict(a1), b1, None, ) assert a1.b == [b1] assert_raises_message( ValueError, r"list.remove\(.*?\): .* not in list", A.b.impl.remove, attributes.instance_state(a1), attributes.instance_dict(a1), b2, None, )
Example #3
Source File: test_attributes.py From sqlalchemy with MIT License | 6 votes |
def test_scalar_obj_pop_valid(self): A, B = self._scalar_obj_fixture() a1 = A() b1 = B() A.b.impl.append( attributes.instance_state(a1), attributes.instance_dict(a1), b1, None, ) assert a1.b is b1 A.b.impl.pop( attributes.instance_state(a1), attributes.instance_dict(a1), b1, None, ) assert a1.b is None
Example #4
Source File: test_attributes.py From sqlalchemy with MIT License | 6 votes |
def test_scalar_obj_pop_invalid(self): A, B = self._scalar_obj_fixture() a1 = A() b1 = B() b2 = B() A.b.impl.append( attributes.instance_state(a1), attributes.instance_dict(a1), b1, None, ) assert a1.b is b1 A.b.impl.pop( attributes.instance_state(a1), attributes.instance_dict(a1), b2, None, ) assert a1.b is b1
Example #5
Source File: test_attributes.py From sqlalchemy with MIT License | 6 votes |
def test_collection_obj_pop_invalid(self): A, B = self._collection_obj_fixture() a1 = A() b1 = B() b2 = B() A.b.impl.append( attributes.instance_state(a1), attributes.instance_dict(a1), b1, None, ) assert a1.b == [b1] A.b.impl.pop( attributes.instance_state(a1), attributes.instance_dict(a1), b2, None, ) assert a1.b == [b1]
Example #6
Source File: test_attributes.py From sqlalchemy with MIT License | 6 votes |
def test_collection_obj_pop_valid(self): A, B = self._collection_obj_fixture() a1 = A() b1 = B() A.b.impl.append( attributes.instance_state(a1), attributes.instance_dict(a1), b1, None, ) assert a1.b == [b1] A.b.impl.pop( attributes.instance_state(a1), attributes.instance_dict(a1), b1, None, ) assert a1.b == []
Example #7
Source File: test_attributes.py From sqlalchemy with MIT License | 6 votes |
def test_state_gc(self): """test that InstanceState always has a dict, even after host object gc'ed.""" class Foo(object): pass instrumentation.register_class(Foo) f = Foo() state = attributes.instance_state(f) f.bar = "foo" eq_(state.dict, {"bar": "foo", state.manager.STATE_ATTR: state}) del f gc_collect() assert state.obj() is None assert state.dict == {}
Example #8
Source File: test_expire.py From sqlalchemy with MIT License | 6 votes |
def test_expire_committed(self): """test that the committed state of the attribute receives the most recent DB data""" orders, Order = self.tables.orders, self.classes.Order mapper(Order, orders) sess = create_session() o = sess.query(Order).get(3) sess.expire(o) orders.update().execute(description="order 3 modified") assert o.isopen == 1 assert ( attributes.instance_state(o).dict["description"] == "order 3 modified" ) def go(): sess.flush() self.assert_sql_count(testing.db, go, 0)
Example #9
Source File: test_expire.py From sqlalchemy with MIT License | 6 votes |
def test_no_instance_key(self): User, users = self.classes.User, self.tables.users # this tests an artificial condition such that # an instance is pending, but has expired attributes. this # is actually part of a larger behavior when postfetch needs to # occur during a flush() on an instance that was just inserted mapper(User, users) sess = create_session() u = sess.query(User).get(7) sess.expire(u, attribute_names=["name"]) sess.expunge(u) attributes.instance_state(u).key = None assert "name" not in u.__dict__ sess.add(u) assert u.name == "jack"
Example #10
Source File: test_attributes.py From sqlalchemy with MIT License | 6 votes |
def test_no_double_state(self): states = set() class Foo(object): def __init__(self): states.add(attributes.instance_state(self)) class Bar(Foo): def __init__(self): states.add(attributes.instance_state(self)) Foo.__init__(self) instrumentation.register_class(Foo) instrumentation.register_class(Bar) b = Bar() eq_(len(states), 1) eq_(list(states)[0].obj(), b)
Example #11
Source File: test_attributes.py From sqlalchemy with MIT License | 6 votes |
def test_mark_dirty_no_attr(self): Foo = self._fixture( uselist=False, useobject=False, active_history=False ) f = Foo() f.someattr = "foo" attributes.instance_state(f)._commit_all(f.__dict__) eq_(self._someattr_history(f), ((), ["foo"], ())) attributes.instance_state(f)._expire_attributes( attributes.instance_dict(f), ["someattr"] ) is_false(attributes.instance_state(f).modified) attributes.flag_dirty(f) is_true(attributes.instance_state(f).modified)
Example #12
Source File: test_attributes.py From sqlalchemy with MIT License | 6 votes |
def test_flag_modified_but_no_value_raises(self): Foo = self._fixture( uselist=False, useobject=False, active_history=False ) f = Foo() f.someattr = "foo" self._commit_someattr(f) eq_(self._someattr_history(f), ((), ["foo"], ())) attributes.instance_state(f)._expire_attributes( attributes.instance_dict(f), ["someattr"] ) assert_raises_message( sa_exc.InvalidRequestError, "Can't flag attribute 'someattr' modified; it's " "not present in the object state", attributes.flag_modified, f, "someattr", )
Example #13
Source File: test_attributes.py From sqlalchemy with MIT License | 6 votes |
def test_lazy_history_collection(self): Post, Blog, lazy_posts = self._fixture() p1, p2, p3 = Post("post 1"), Post("post 2"), Post("post 3") lazy_posts.return_value = [p1, p2, p3] b = Blog("blog 1") p = Post("post 4") p.blog = b p4 = Post("post 5") p4.blog = b eq_(lazy_posts.call_count, 1) eq_( attributes.instance_state(b).get_history( "posts", attributes.PASSIVE_OFF ), ([p, p4], [p1, p2, p3], []), ) eq_(lazy_posts.call_count, 1)
Example #14
Source File: test_attributes.py From sqlalchemy with MIT License | 6 votes |
def test_scalar_passive_flag(self): Foo = self._fixture( uselist=False, useobject=False, active_history=True ) f = Foo() f.someattr = "one" eq_(self._someattr_history(f), (["one"], (), ())) self._commit_someattr(f) state = attributes.instance_state(f) # do the same thing that # populators.expire.append((self.key, True)) # does in loading.py state.dict.pop("someattr", None) state.expired_attributes.add("someattr") def scalar_loader(state, toload, passive): state.dict["someattr"] = "one" state.manager.expired_attribute_loader = scalar_loader eq_(self._someattr_history(f), ((), ["one"], ()))
Example #15
Source File: test_events.py From sqlalchemy with MIT License | 6 votes |
def test_state_after_attach(self): User, users = self.classes.User, self.tables.users sess = Session() @event.listens_for(sess, "after_attach") def listener(session, inst): state = attributes.instance_state(inst) if state.key: assert session.identity_map[state.key] is inst else: assert inst in session.new mapper(User, users) u = User(name="u1") sess.add(u) sess.flush() sess.expunge(u) sess.add(u)
Example #16
Source File: test_attributes.py From sqlalchemy with MIT License | 6 votes |
def test_scalar_del_expired(self): # note - compare: # test_scalar_set_None, # test_scalar_get_first_set_None, # test_use_object_set_None, # test_use_object_get_first_set_None Foo = self._fixture( uselist=False, useobject=False, active_history=False ) f = Foo() f.someattr = 5 self._commit_someattr(f) attributes.instance_state(f)._expire_attributes( attributes.instance_dict(f), ["someattr"] ) del f.someattr eq_(self._someattr_history(f), ([None], (), ()))
Example #17
Source File: test_hasparent.py From sqlalchemy with MIT License | 6 votes |
def test_stale_state_negative(self): User = self.classes.User s, u1, a1 = self._fixture() u2 = User(addresses=[a1]) s.add(u2) s.flush() s._expunge_states([attributes.instance_state(u2)]) del u2 gc_collect() assert_raises_message( orm_exc.StaleDataError, "can't be sure this is the most recent parent.", u1.addresses.remove, a1, ) s.flush() self._assert_hasparent(a1)
Example #18
Source File: test_attributes.py From sqlalchemy with MIT License | 6 votes |
def test_commit_removes_pending(self): Post, Blog, lazy_posts = self._fixture() p1 = Post("post 1") lazy_posts.return_value = attributes.PASSIVE_NO_RESULT b = Blog("blog 1") p1.blog = b b_state = attributes.instance_state(b) p1_state = attributes.instance_state(p1) b_state._commit_all(attributes.instance_dict(b)) p1_state._commit_all(attributes.instance_dict(p1)) lazy_posts.return_value = [p1] eq_(b.posts, [Post("post 1")]) eq_( lazy_posts.mock_calls, [ call(b_state, attributes.PASSIVE_NO_FETCH), call(b_state, attributes.PASSIVE_OFF), ], )
Example #19
Source File: test_attributes.py From sqlalchemy with MIT License | 6 votes |
def test_scalar_del(self): # note - compare: # test_scalar_set_None, # test_scalar_get_first_set_None, # test_use_object_set_None, # test_use_object_get_first_set_None Foo = self._fixture( uselist=False, useobject=False, active_history=False ) f = Foo() f.someattr = 5 attributes.instance_state(f).key = ("foo",) self._commit_someattr(f) del f.someattr eq_(self._someattr_history(f), ((), (), [5]))
Example #20
Source File: test_query.py From sqlalchemy with MIT License | 5 votes |
def test_m2o_compare_instance(self): User, Address = self.classes.User, self.classes.Address u7 = User(id=5) attributes.instance_state(u7)._commit_all(attributes.instance_dict(u7)) u7.id = 7 self._test(Address.user == u7, ":param_1 = addresses.user_id")
Example #21
Source File: test_events.py From sqlalchemy with MIT License | 5 votes |
def test_changes_reset(self): """test the contract of load/refresh such that history is reset. This has never been an official contract but we are testing it here to ensure it is maintained given the loading performance enhancements. """ User = self.classes.User @event.listens_for(User, "load") def canary1(obj, context): obj.name = "new name!" @event.listens_for(User, "refresh") def canary2(obj, context, props): obj.name = "refreshed name!" sess = Session() u1 = User(name="u1") sess.add(u1) sess.commit() sess.close() u1 = sess.query(User).first() eq_(attributes.get_history(u1, "name"), ((), ["new name!"], ())) assert "name" not in attributes.instance_state(u1).committed_state assert u1 not in sess.dirty sess.expire(u1) u1.id eq_(attributes.get_history(u1, "name"), ((), ["refreshed name!"], ())) assert "name" not in attributes.instance_state(u1).committed_state assert u1 in sess.dirty
Example #22
Source File: test_hasparent.py From sqlalchemy with MIT License | 5 votes |
def test_stale_state_positive_pk_change(self): """Illustrate that we can't easily link a stale state to a fresh one if the fresh one has a PK change (unless we a. tracked all the previous PKs, wasteful, or b. recycled states - time consuming, breaks lots of edge cases, destabilizes the code) """ User = self.classes.User s, u1, a1 = self._fixture() s._expunge_states([attributes.instance_state(u1)]) del u1 gc_collect() u1 = s.query(User).first() # primary key change. now we # can't rely on state.key as the # identifier. u1.id = 5 a1.user_id = 5 s.flush() assert_raises_message( orm_exc.StaleDataError, "can't be sure this is the most recent parent.", u1.addresses.remove, a1, ) # u1.addresses wasn't actually impacted, because the event was # caught before collection mutation eq_(u1.addresses, [a1]) # expire all and we can continue s.expire_all() u1.addresses.remove(a1) self._assert_not_hasparent(a1)
Example #23
Source File: test_events.py From sqlalchemy with MIT License | 5 votes |
def test_unmapped_listen(self): users = self.tables.users class Foo(object): pass fn = Mock() event.listen(Foo, "before_insert", fn, propagate=True) class User(Foo): pass m = mapper(User, users) u1 = User() m.dispatch.before_insert(m, None, attributes.instance_state(u1)) eq_(fn.call_count, 1) event.remove(Foo, "before_insert", fn) # existing event is removed m.dispatch.before_insert(m, None, attributes.instance_state(u1)) eq_(fn.call_count, 1) # the _HoldEvents is also cleaned out class Bar(Foo): pass m = mapper(Bar, users) b1 = Bar() m.dispatch.before_insert(m, None, attributes.instance_state(b1)) eq_(fn.call_count, 1)
Example #24
Source File: test_attributes.py From sqlalchemy with MIT License | 5 votes |
def test_pop_existing(self): A, B = self.A, self.B a1 = A() coll = a1.bs a1.bs.append(B()) state = attributes.instance_state(a1) state._reset(state.dict, "bs") assert_raises(Warning, coll.append, B())
Example #25
Source File: test_attributes.py From sqlalchemy with MIT License | 5 votes |
def test_scalar_no_init_side_effect(self): Foo = self._fixture( uselist=False, useobject=False, active_history=False ) f = Foo() self._someattr_history(f) # no side effects assert "someattr" not in f.__dict__ assert "someattr" not in attributes.instance_state(f).committed_state
Example #26
Source File: test_attributes.py From sqlalchemy with MIT License | 5 votes |
def test_expired(self): A, B = self.A, self.B a1 = A() coll = a1.bs a1.bs.append(B()) state = attributes.instance_state(a1) state._expire(state.dict, set()) assert_raises(Warning, coll.append, B())
Example #27
Source File: test_attributes.py From sqlalchemy with MIT License | 5 votes |
def test_assert_false_on_default_value(self): A = self.A a1 = A() state = attributes.instance_state(a1) attributes.init_state_collection(state, state.dict, "bs") assert_raises( AssertionError, A.bs.impl._default_value, state, state.dict )
Example #28
Source File: test_attributes.py From sqlalchemy with MIT License | 5 votes |
def test_bulk_replace_resets_empty(self): A = self.A a1 = A() state = attributes.instance_state(a1) existing = a1.bs is_(state._empty_collections["bs"], existing) is_not_(existing._sa_adapter, None) a1.bs = [] # replaces previous "empty" collection not_in_("bs", state._empty_collections) # empty is replaced is_(existing._sa_adapter, None)
Example #29
Source File: test_attributes.py From sqlalchemy with MIT License | 5 votes |
def test_none_init_collection(self): canary = Mock() class Foo(object): pass class Bar(object): pass instrumentation.register_class(Foo) instrumentation.register_class(Bar) attributes.register_attribute(Foo, "bar", useobject=True, uselist=True) event.listen(Foo.bar, "set", canary) f1 = Foo() eq_(f1.bar, []) assert "bar" not in f1.__dict__ adapter = Foo.bar.impl.get_collection( attributes.instance_state(f1), attributes.instance_dict(f1) ) assert adapter.empty # reversal of approach in #3061 eq_(canary.mock_calls, []) f1.bar.append(Bar()) assert "bar" in f1.__dict__ assert not adapter.empty
Example #30
Source File: test_attributes.py From sqlalchemy with MIT License | 5 votes |
def test_use_object_no_init_side_effect(self): Foo, Bar = self._two_obj_fixture(uselist=False) f = Foo() self._someattr_history(f) assert "someattr" not in f.__dict__ assert "someattr" not in attributes.instance_state(f).committed_state