Here are the examples of the python api sqlalchemy.orm.attributes.instance_state taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
57 Examples
3
Example 1
Project: CouchPotatoV1 Source File: util.py
def object_mapper(instance):
"""Given an object, return the primary Mapper associated with the object
instance.
Raises UnmappedInstanceError if no mapping is configured.
"""
try:
state = attributes.instance_state(instance)
return state.manager.mapper
except exc.UnmappedClassError:
raise exc.UnmappedInstanceError(instance)
except exc.NO_STATE:
raise exc.UnmappedInstanceError(instance)
3
Example 2
def count(self):
sess = self.__session()
if sess is None:
return len(self.attr._get_collection_history(
attributes.instance_state(self.instance),
attributes.PASSIVE_NO_INITIALIZE).added_items)
else:
return self._clone(sess).count()
3
Example 3
def __getitem__(self, index):
sess = self.__session()
if sess is None:
return self.attr._get_collection_history(
attributes.instance_state(self.instance),
attributes.PASSIVE_NO_INITIALIZE).added_items.\
__getitem__(index)
else:
return self._clone(sess).__getitem__(index)
3
Example 4
def replace(self, state):
if dict.__contains__(self, state.key):
existing = dict.__getitem__(self, state.key)
existing = attributes.instance_state(existing)
if existing is not state:
self._manage_removed_state(existing)
else:
return
dict.__setitem__(self, state.key, state.obj())
self._manage_incoming_state(state)
3
Example 5
def fire_remove_event(self, state, dict_, value, initiator):
collection_history = self._modified_event(state, dict_)
collection_history.deleted_items.append(value)
if self.trackparent and value is not None:
self.sethasparent(attributes.instance_state(value), False)
for ext in self.extensions:
ext.remove(state, value, initiator or self)
3
Example 6
Project: sqlalchemy Source File: test_lazy_relations.py
def test_history_empty_passive_return_never_set(self):
User, Address, sess, a1 = self._u_ad_fixture(False)
eq_(
Address.user.impl.get_history(
attributes.instance_state(a1),
attributes.instance_dict(a1),
passive=attributes.PASSIVE_RETURN_NEVER_SET),
((), (), ())
)
assert 'user_id' not in a1.__dict__
assert 'user' not in a1.__dict__
3
Example 7
def fire_remove_event(self, state, dict_, value, initiator):
collection_history = self._modified_event(state, dict_)
collection_history.deleted_items.append(value)
if self.trackparent and value is not None:
self.sethasparent(attributes.instance_state(value), state, False)
for fn in self.dispatch.remove:
fn(state, value, initiator or self)
3
Example 8
Project: sqlalchemy Source File: test_lazy_relations.py
def test_get_empty_passive_no_initialize(self):
User, Address, sess, a1 = self._u_ad_fixture(False)
eq_(
Address.user.impl.get(
attributes.instance_state(a1),
attributes.instance_dict(a1),
passive=attributes.PASSIVE_NO_INITIALIZE),
attributes.PASSIVE_NO_RESULT
)
assert 'user_id' not in a1.__dict__
assert 'user' not in a1.__dict__
3
Example 9
Project: maraschino Source File: state.py
def value_as_iterable(self, dict_, key, passive=PASSIVE_OFF):
"""Return a list of tuples (state, obj) for the given
key.
returns an empty list if the value is None/empty/PASSIVE_NO_RESULT
"""
impl = self.manager[key].impl
x = impl.get(self, dict_, passive=passive)
if x is PASSIVE_NO_RESULT or x is None:
return []
elif hasattr(impl, 'get_collection'):
return [
(attributes.instance_state(o), o) for o in
impl.get_collection(self, dict_, x, passive=passive)
]
else:
return [(attributes.instance_state(x), x)]
3
Example 10
Project: sqlalchemy Source File: test_lazy_relations.py
def test_history_populated_passive_no_initialize(self):
User, Address, sess, a1 = self._u_ad_fixture(True)
eq_(
Address.user.impl.get_history(
attributes.instance_state(a1),
attributes.instance_dict(a1),
passive=attributes.PASSIVE_NO_INITIALIZE),
attributes.HISTORY_BLANK
)
assert 'user_id' not in a1.__dict__
assert 'user' not in a1.__dict__
3
Example 11
Project: CouchPotatoV1 Source File: util.py
def identity_equal(a, b):
if a is b:
return True
if a is None or b is None:
return False
try:
state_a = attributes.instance_state(a)
state_b = attributes.instance_state(b)
except exc.NO_STATE:
return False
if state_a.key is None or state_b.key is None:
return False
return state_a.key == state_b.key
3
Example 12
def __getitem__(self, index):
sess = self.__session()
if sess is None:
return self.attr._get_collection_history(
attributes.instance_state(self.instance),
passive=True).added_items.__getitem__(index)
else:
return self._clone(sess).__getitem__(index)
3
Example 13
Project: sqlalchemy Source File: test_lazy_relations.py
def test_get_empty_passive_return_never_set(self):
User, Address, sess, a1 = self._u_ad_fixture(False)
eq_(
Address.user.impl.get(
attributes.instance_state(a1),
attributes.instance_dict(a1),
passive=attributes.PASSIVE_RETURN_NEVER_SET),
attributes.NEVER_SET
)
assert 'user_id' not in a1.__dict__
assert 'user' not in a1.__dict__
3
Example 14
Project: CouchPotatoV1 Source File: unitofwork.py
def remove(self, state, item, initiator):
sess = _state_session(state)
if sess:
prop = _state_mapper(state).get_property(self.key)
# expunge pending orphans
if prop.cascade.delete_orphan and \
item in sess.new and \
prop.mapper._is_orphan(attributes.instance_state(item)):
sess.expunge(item)
3
Example 15
def add(self, state):
if state.key in self:
if attributes.instance_state(dict.__getitem__(self, state.key)) is not state:
raise AssertionError("A conflicting state is already present in the identity map for key %r" % (state.key, ))
else:
dict.__setitem__(self, state.key, state.obj())
self._manage_incoming_state(state)
3
Example 16
@model_function
def is_deleted(self, obj):
"""
:return: True if the object has been deleted from the persistent
state, False otherwise"""
from sqlalchemy.orm.attributes import instance_state
state = instance_state( obj )
if state != None and state.deleted:
return True
return False
3
Example 17
def fire_append_event(self, state, dict_, value, initiator):
collection_history = self._modified_event(state, dict_)
collection_history.added_items.append(value)
for fn in self.dispatch.append:
value = fn(state, value, initiator or self)
if self.trackparent and value is not None:
self.sethasparent(attributes.instance_state(value), state, True)
3
Example 18
def __iter__(self):
sess = self.__session()
if sess is None:
return iter(self.attr._get_collection_history(
attributes.instance_state(self.instance),
attributes.PASSIVE_NO_INITIALIZE).added_items)
else:
return iter(self._clone(sess))
3
Example 19
Project: sqlalchemy Source File: test_sync.py
def _fixture(self):
A, B = self.classes.A, self.classes.B
session = create_session()
uowcommit = self._get_test_uow(session)
a_mapper = class_mapper(A)
b_mapper= class_mapper(B)
self.a1 = a1 = A()
self.b1 = b1 = B()
uowcommit = self._get_test_uow(session)
return uowcommit,\
attributes.instance_state(a1),\
attributes.instance_state(b1),\
a_mapper, b_mapper
3
Example 20
def discard(self, state):
obj = dict.get(self, state.key, None)
if obj is not None:
st = attributes.instance_state(obj)
if st is state:
dict.pop(self, state.key, None)
self._manage_removed_state(state)
3
Example 21
def presort_saves(self, uowcommit, states):
for state in states:
uowcommit.register_object(state)
if self.cascade.delete_orphan:
history = uowcommit.get_attribute_history(
state,
self.key,
passive=self.passive_deletes)
if history:
ret = True
for child in history.deleted:
if self.hasparent(child) is False:
uowcommit.register_object(child, isdelete=True)
for c, m in self.mapper.cascade_iterator(
'delete', child):
uowcommit.register_object(
attributes.instance_state(c),
isdelete=True)
3
Example 22
def fire_append_event(self, state, dict_, value, initiator):
collection_history = self._modified_event(state, dict_)
collection_history.added_items.append(value)
for ext in self.extensions:
ext.append(state, value, initiator or self)
if self.trackparent and value is not None:
self.sethasparent(attributes.instance_state(value), True)
3
Example 23
def add(self, state):
if state.key in self:
if attributes.instance_state(dict.__getitem__(self,
state.key)) is not state:
raise AssertionError('A conflicting state is already '
'present in the identity map for key %r'
% (state.key, ))
else:
dict.__setitem__(self, state.key, state.obj())
self._manage_incoming_state(state)
3
Example 24
def __iter__(self):
sess = self.__session()
if sess is None:
return iter(self.attr._get_collection_history(
attributes.instance_state(self.instance),
passive=True).added_items)
else:
return iter(self._clone(sess))
3
Example 25
Project: sqlalchemy Source File: test_lazy_relations.py
def test_get_populated_passive_return_never_set(self):
User, Address, sess, a1 = self._u_ad_fixture(True)
eq_(
Address.user.impl.get(
attributes.instance_state(a1),
attributes.instance_dict(a1),
passive=attributes.PASSIVE_RETURN_NEVER_SET),
User(name='ed')
)
3
Example 26
Project: maraschino Source File: dynamic.py
def get_all_pending(self, state, dict_):
c = self._get_collection_history(state, True)
return [
(attributes.instance_state(x), x)
for x in
c.added_items + c.unchanged_items + c.deleted_items
]
3
Example 27
def count(self):
sess = self.__session()
if sess is None:
return len(self.attr._get_collection_history(
attributes.instance_state(self.instance),
passive=True).added_items)
else:
return self._clone(sess).count()
3
Example 28
Project: CouchPotatoV1 Source File: unitofwork.py
def set(self, state, newvalue, oldvalue, initiator):
# process "save_update" cascade rules for when an instance
# is attached to another instance
if oldvalue is newvalue:
return newvalue
sess = _state_session(state)
if sess:
prop = _state_mapper(state).get_property(self.key)
if newvalue is not None and \
prop.cascade.save_update and \
(prop.cascade_backrefs or self.key == initiator.key) and \
newvalue not in sess:
sess.add(newvalue)
if prop.cascade.delete_orphan and \
oldvalue in sess.new and \
prop.mapper._is_orphan(attributes.instance_state(oldvalue)):
sess.expunge(oldvalue)
return newvalue
3
Example 29
Project: sqlalchemy Source File: test_pickled.py
def test_exceptions(self):
class Foo(object):
pass
users = self.tables.users
mapper(User, users)
for sa_exc in (
orm_exc.UnmappedInstanceError(Foo()),
orm_exc.UnmappedClassError(Foo),
orm_exc.ObjectDeletedError(attributes.instance_state(User())),
):
for loads, dumps in picklers():
repickled = loads(dumps(sa_exc))
eq_(repickled.args[0], sa_exc.args[0])
3
Example 30
Project: sqlalchemy Source File: test_lazy_relations.py
def test_history_empty_passive_no_initialize(self):
User, Address, sess, a1 = self._u_ad_fixture(False)
eq_(
Address.user.impl.get_history(
attributes.instance_state(a1),
attributes.instance_dict(a1),
passive=attributes.PASSIVE_NO_INITIALIZE),
attributes.HISTORY_BLANK
)
assert 'user_id' not in a1.__dict__
assert 'user' not in a1.__dict__
3
Example 31
Project: sqlalchemy Source File: test_lazy_relations.py
def test_get_populated_passive_no_initialize(self):
User, Address, sess, a1 = self._u_ad_fixture(True)
eq_(
Address.user.impl.get(
attributes.instance_state(a1),
attributes.instance_dict(a1),
passive=attributes.PASSIVE_NO_INITIALIZE),
attributes.PASSIVE_NO_RESULT
)
assert 'user_id' not in a1.__dict__
assert 'user' not in a1.__dict__
3
Example 32
Project: deblaze Source File: test_sqlalchemy.py
def test_lazy_load_attributes(self):
user = self._build_obj()
self._save(user)
self.session.commit()
self._clear()
user = self.session.query(User).first()
encoder = pyamf.get_encoder(pyamf.AMF3)
encoder.writeElement(user)
encoded = encoder.stream.getvalue()
decoded = pyamf.get_decoder(pyamf.AMF3, encoded).readElement()
self.assertFalse(decoded.__dict__.has_key('lazy_loaded'))
if hasattr(attributes, 'instance_state'):
obj_state = attributes.instance_state(decoded)
self.assertFalse(obj_state.committed_state.has_key('lazy_loaded'))
self.assertFalse(obj_state.dict.has_key('lazy_loaded'))
3
Example 33
Project: sqlalchemy Source File: test_lazy_relations.py
def test_history_populated_passive_return_never_set(self):
User, Address, sess, a1 = self._u_ad_fixture(True)
eq_(
Address.user.impl.get_history(
attributes.instance_state(a1),
attributes.instance_dict(a1),
passive=attributes.PASSIVE_RETURN_NEVER_SET),
((), [User(name='ed'), ], ())
)
0
Example 34
def remove(self, item):
self.attr.remove(
attributes.instance_state(self.instance),
attributes.instance_dict(self.instance), item, None)
0
Example 35
Project: sqlalchemy Source File: test_load_on_fks.py
def test_m2o_lazy_loader_on_transient(self):
for loadonpending in (False, True):
for attach in (False, True):
for autoflush in (False, True):
for manualflush in (False, True):
for enable_relationship_rel in (False, True):
Child.parent.property.load_on_pending = loadonpending
sess.autoflush = autoflush
c2 = Child()
if attach:
state = instance_state(c2)
state.session_id = sess.hash_key
if enable_relationship_rel:
sess.enable_relationship_loading(c2)
c2.parent_id = p2.id
if manualflush:
sess.flush()
if (loadonpending and attach) or enable_relationship_rel:
assert c2.parent is p2
else:
assert c2.parent is None
sess.rollback()
0
Example 36
def all_states(self):
return [attributes.instance_state(o) for o in self.itervalues()]
0
Example 37
Project: CouchPotatoV1 Source File: identity.py
def contains_state(self, state):
return state.key in self and attributes.instance_state(self[state.key]) is state
0
Example 38
Project: sqlalchemy Source File: test_hasparent.py
@testing.requires.predictable_gc
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
)
# unfortunately, u1.addresses was impacted
# here
assert u1.addresses == []
# expire all and we can continue
s.expire_all()
u1.addresses.remove(a1)
self._assert_not_hasparent(a1)
0
Example 39
Project: sqlalchemy Source File: test_transaction.py
@testing.requires.savepoints
def test_dirty_state_transferred_deep_nesting(self):
User, users = self.classes.User, self.tables.users
mapper(User, users)
s = Session(testing.db)
u1 = User(name='u1')
s.add(u1)
s.commit()
nt1 = s.begin_nested()
nt2 = s.begin_nested()
u1.name = 'u2'
assert attributes.instance_state(u1) not in nt2._dirty
assert attributes.instance_state(u1) not in nt1._dirty
s.flush()
assert attributes.instance_state(u1) in nt2._dirty
assert attributes.instance_state(u1) not in nt1._dirty
s.commit()
assert attributes.instance_state(u1) in nt2._dirty
assert attributes.instance_state(u1) in nt1._dirty
s.rollback()
assert attributes.instance_state(u1).expired
eq_(u1.name, 'u1')
0
Example 40
Project: sqlalchemy Source File: test_transaction.py
@testing.requires.predictable_gc
def test_gced_delete_on_rollback(self):
User, users = self.classes.User, self.tables.users
s = self.session()
u1 = User(name='ed')
s.add(u1)
s.commit()
s.delete(u1)
u1_state = attributes.instance_state(u1)
assert u1_state in s.identity_map.all_states()
assert u1_state in s._deleted
s.flush()
assert u1_state not in s.identity_map.all_states()
assert u1_state not in s._deleted
del u1
gc_collect()
assert u1_state.obj() is None
s.rollback()
# new in 1.1, not in identity map if the object was
# gc'ed and we restore snapshot; we've changed update_impl
# to just skip this object
assert u1_state not in s.identity_map.all_states()
# in any version, the state is replaced by the query
# because the identity map would switch it
u1 = s.query(User).filter_by(name='ed').one()
assert u1_state not in s.identity_map.all_states()
eq_(s.scalar(select([func.count('*')]).select_from(users)), 1)
s.delete(u1)
s.flush()
eq_(s.scalar(select([func.count('*')]).select_from(users)), 0)
s.commit()
0
Example 41
Project: cruzdb Source File: sqlsoup.py
def init_instance(self, mapper, class_, oldinit, instance, args, kwargs):
session = self.scoped_session()
state = attributes.instance_state(instance)
session._save_impl(state)
return EXT_CONTINUE
0
Example 42
def create_version(obj, session, deleted=False):
obj_mapper = object_mapper(obj)
history_mapper = obj.__history_mapper__
history_cls = history_mapper.class_
obj_state = attributes.instance_state(obj)
attr = {}
obj_changed = False
for om, hm in zip(
obj_mapper.iterate_to_root(),
history_mapper.iterate_to_root()
):
if hm.single:
continue
for hist_col in hm.local_table.c:
if _is_versioning_col(hist_col):
continue
obj_col = om.local_table.c[hist_col.key]
# get the value of the
# attribute based on the MapperProperty related to the
# mapped column. this will allow usage of MapperProperties
# that have a different keyname than that of the mapped column.
try:
prop = obj_mapper.get_property_by_column(obj_col)
except UnmappedColumnError:
# in the case of single table inheritance, there may be
# columns on the mapped table intended for the subclass only.
# the "unmapped" status of the subclass column on the
# base class is a feature of the declarative module.
continue
# expired object attributes and also deferred cols might not
# be in the dict. force it to load no matter what by
# using getattr().
if prop.key not in obj_state.dict:
getattr(obj, prop.key)
a, u, d = attributes.get_history(obj, prop.key)
if d:
attr[prop.key] = d[0]
obj_changed = True
elif u:
attr[prop.key] = u[0]
elif a:
# if the attribute had no value.
attr[prop.key] = a[0]
obj_changed = True
if not obj_changed:
# not changed, but we have relationships. OK
# check those too
for prop in obj_mapper.iterate_properties:
if isinstance(prop, RelationshipProperty) and \
attributes.get_history(
obj, prop.key,
passive=attributes.PASSIVE_NO_INITIALIZE).has_changes():
for p in prop.local_columns:
if p.foreign_keys:
obj_changed = True
break
if obj_changed is True:
break
if not obj_changed and not deleted:
return
attr['version'] = obj.version
hist = history_cls()
for key, value in attr.items():
setattr(hist, key, value)
session.add(hist)
obj.version += 1
0
Example 43
Project: sqlalchemy Source File: test_hasparent.py
@testing.requires.predictable_gc
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)
0
Example 44
def presort_saves(self, uowcommit, states):
children_added = uowcommit.memo(('children_added', self), set)
for state in states:
pks_changed = self._pks_changed(uowcommit, state)
history = uowcommit.get_attribute_history(
state,
self.key,
passive=not pks_changed
or self.passive_updates)
if history:
for child in history.added:
if child is not None:
uowcommit.register_object(child, cancel_delete=True)
children_added.update(history.added)
for child in history.deleted:
if not self.cascade.delete_orphan:
uowcommit.register_object(child, isdelete=False)
elif self.hasparent(child) is False:
uowcommit.register_object(child, isdelete=True)
for c, m in self.mapper.cascade_iterator(
'delete', child):
uowcommit.register_object(
attributes.instance_state(c),
isdelete=True)
if pks_changed:
if history:
for child in history.unchanged:
if child is not None:
uowcommit.register_object(
child,
False,
self.passive_updates)
0
Example 45
Project: CouchPotatoV1 Source File: dependency.py
def presort_deletes(self, uowcommit, states):
if self.cascade.delete or self.cascade.delete_orphan:
for state in states:
history = uowcommit.get_attribute_history(
state,
self.key,
passive=self.passive_deletes)
if history:
if self.cascade.delete_orphan:
todelete = history.sum()
else:
todelete = history.non_deleted()
for child in todelete:
if child is None:
continue
uowcommit.register_object(child, isdelete=True)
for c, m in self.mapper.cascade_iterator(
'delete', child):
uowcommit.register_object(
attributes.instance_state(c), isdelete=True)
0
Example 46
def test_instance_state(self):
User = self.classes.User
u1 = User()
insp = inspect(u1)
is_(insp, instance_state(u1))
0
Example 47
def presort_saves(self, uowcommit, states):
if not self.passive_updates:
# if no passive updates, load history on
# each collection where parent has changed PK,
# so that prop_has_changes() returns True
for state in states:
if self._pks_changed(uowcommit, state):
history = uowcommit.get_attribute_history(
state,
self.key,
False)
if not self.cascade.delete_orphan:
return
# check for child items removed from the collection
# if delete_orphan check is turned on.
for state in states:
history = uowcommit.get_attribute_history(
state,
self.key,
passive=True)
if history:
for child in history.deleted:
if self.hasparent(child) is False:
uowcommit.register_object(child, isdelete=True)
for c, m in self.mapper.cascade_iterator(
'delete',
child):
uowcommit.register_object(
attributes.instance_state(c), isdelete=True)
0
Example 48
Project: sqlalchemy Source File: test_extendedattr.py
def test_alternate_finders(self):
"""Ensure the generic finder front-end deals with edge cases."""
class Unknown(object):
pass
class Known(MyBaseClass):
pass
register_class(Known)
k, u = Known(), Unknown()
assert instrumentation.manager_of_class(Unknown) is None
assert instrumentation.manager_of_class(Known) is not None
assert instrumentation.manager_of_class(None) is None
assert attributes.instance_state(k) is not None
assert_raises((AttributeError, KeyError),
attributes.instance_state, u)
assert_raises((AttributeError, KeyError),
attributes.instance_state, None)
0
Example 49
Project: sqlalchemy Source File: test_lazy_relations.py
def test_no_orphan(self):
"""test that a lazily loaded child object is not marked as an orphan"""
users, Address, addresses, User = (
self.tables.users,
self.classes.Address,
self.tables.addresses,
self.classes.User)
mapper(User, users, properties={
'addresses': relationship(
Address, cascade="all,delete-orphan", lazy='select')
})
mapper(Address, addresses)
sess = create_session()
user = sess.query(User).get(7)
assert getattr(User, 'addresses').hasparent(
attributes.instance_state(user.addresses[0]), optimistic=True)
assert not sa.orm.class_mapper(Address)._is_orphan(
attributes.instance_state(user.addresses[0]))
0
Example 50
def append(self, item):
self.attr.append(
attributes.instance_state(self.instance),
attributes.instance_dict(self.instance), item, None)