desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Remove the `instance` from this ``Session``. This will free all internal references to the instance. Cascading will be applied according to the *expunge* cascade rule.'
def expunge(self, instance):
try: state = attributes.instance_state(instance) except exc.NO_STATE: raise exc.UnmappedInstanceError(instance) if (state.session_id is not self.hash_key): raise sa_exc.InvalidRequestError(('Instance %s is not present in this Session' % state_str(state))) cas...
'Place an object in the ``Session``. Its state will be persisted to the database on the next flush operation. Repeated calls to ``add()`` will be ignored. The opposite of ``add()`` is ``expunge()``.'
def add(self, instance, _warn=True):
if (_warn and self._warn_on_events): self._flush_warning('Session.add()') try: state = attributes.instance_state(instance) except exc.NO_STATE: raise exc.UnmappedInstanceError(instance) self._save_or_update_state(state)
'Add the given collection of instances to this ``Session``.'
def add_all(self, instances):
if self._warn_on_events: self._flush_warning('Session.add_all()') for instance in instances: self.add(instance, _warn=False)
'Mark an instance as deleted. The database delete operation occurs upon ``flush()``.'
def delete(self, instance):
if self._warn_on_events: self._flush_warning('Session.delete()') try: state = attributes.instance_state(instance) except exc.NO_STATE: raise exc.UnmappedInstanceError(instance) if (state.key is None): raise sa_exc.InvalidRequestError(("Instance '%s' is not per...
'Copy the state of a given instance into a corresponding instance within this :class:`.Session`. :meth:`.Session.merge` examines the primary key attributes of the source instance, and attempts to reconcile it with an instance of the same primary key in the session. If not found locally, it attempts to load the object...
def merge(self, instance, load=True):
if self._warn_on_events: self._flush_warning('Session.merge()') _recursive = {} if load: self._autoflush() object_mapper(instance) autoflush = self.autoflush try: self.autoflush = False return self._merge(attributes.instance_state(instance), attributes.instance_di...
'Associate an object with this :class:`.Session` for related object loading. .. warning:: :meth:`.enable_relationship_loading` exists to serve special use cases and is not recommended for general use. Accesses of attributes mapped with :func:`.relationship` will attempt to load a value from the database using this :cla...
def enable_relationship_loading(self, obj):
state = attributes.instance_state(obj) self._attach(state, include_before=True) state._load_pending = True
'Return True if the instance is associated with this session. The instance may be pending or persistent within the Session for a result of True.'
def __contains__(self, instance):
try: state = attributes.instance_state(instance) except exc.NO_STATE: raise exc.UnmappedInstanceError(instance) return self._contains_state(state)
'Iterate over all pending or persistent instances within this Session.'
def __iter__(self):
return iter((list(self._new.values()) + list(self.identity_map.values())))
'Flush all the object changes to the database. Writes out all pending object creations, deletions and modifications to the database as INSERTs, DELETEs, UPDATEs, etc. Operations are automatically ordered by the Session\'s unit of work dependency solver. Database operations will be issued in the current transactional c...
def flush(self, objects=None):
if self._flushing: raise sa_exc.InvalidRequestError('Session is already flushing') if self._is_clean(): return try: self._flushing = True self._flush(objects) finally: self._flushing = False
'Return ``True`` if the given instance has locally modified attributes. This method retrieves the history for each instrumented attribute on the instance and performs a comparison of the current value to its previously committed value, if any. It is in effect a more expensive and accurate version of checking for the gi...
def is_modified(self, instance, include_collections=True, passive=True):
state = object_state(instance) if (not state.modified): return False dict_ = state.dict for attr in state.manager.attributes: if (((not include_collections) and hasattr(attr.impl, 'get_collection')) or (not hasattr(attr.impl, 'get_history'))): continue (added, unchang...
'True if this :class:`.Session` is in "transaction mode" and is not in "partial rollback" state. The :class:`.Session` in its default mode of ``autocommit=False`` is essentially always in "transaction mode", in that a :class:`.SessionTransaction` is associated with it as soon as it is instantiated. This :class:`.Sessi...
@property def is_active(self):
return (self.transaction and self.transaction.is_active)
'The set of all persistent states considered dirty. This method returns all states that were modified including those that were possibly deleted.'
@property def _dirty_states(self):
return self.identity_map._dirty_states()
'The set of all persistent instances considered dirty. E.g.:: some_mapped_object in session.dirty Instances are considered dirty when they were modified but not deleted. Note that this \'dirty\' calculation is \'optimistic\'; most attribute-setting or collection modification operations will mark an instance as \'dirty\...
@property def dirty(self):
return util.IdentitySet([state.obj() for state in self._dirty_states if (state not in self._deleted)])
'The set of all instances marked as \'deleted\' within this ``Session``'
@property def deleted(self):
return util.IdentitySet(list(self._deleted.values()))
'The set of all instances marked as \'new\' within this ``Session``.'
@property def new(self):
return util.IdentitySet(list(self._new.values()))
'Construct a new :class:`.sessionmaker`. All arguments here except for ``class_`` correspond to arguments accepted by :class:`.Session` directly. See the :meth:`.Session.__init__` docstring for more details on parameters. :param bind: a :class:`.Engine` or other :class:`.Connectable` with which newly created :class:`....
def __init__(self, bind=None, class_=Session, autoflush=True, autocommit=False, expire_on_commit=True, info=None, **kw):
kw['bind'] = bind kw['autoflush'] = autoflush kw['autocommit'] = autocommit kw['expire_on_commit'] = expire_on_commit if (info is not None): kw['info'] = info self.kw = kw self.class_ = type(class_.__name__, (class_,), {})
'Produce a new :class:`.Session` object using the configuration established in this :class:`.sessionmaker`. In Python, the ``__call__`` method is invoked on an object when it is "called" in the same way as a function:: Session = sessionmaker() session = Session() # invokes sessionmaker.__call__()'
def __call__(self, **local_kw):
for (k, v) in self.kw.items(): if ((k == 'info') and ('info' in local_kw)): d = v.copy() d.update(local_kw['info']) local_kw['info'] = d else: local_kw.setdefault(k, v) return self.class_(**local_kw)
'(Re)configure the arguments for this sessionmaker. e.g.:: Session = sessionmaker() Session.configure(bind=create_engine(\'sqlite://\'))'
def configure(self, **new_kw):
self.kw.update(new_kw)
'Construct a new :class:`.scoped_session`. :param session_factory: a factory to create new :class:`.Session` instances. This is usually, but not necessarily, an instance of :class:`.sessionmaker`. :param scopefunc: optional function which defines the current scope. If not passed, the :class:`.scoped_session` object a...
def __init__(self, session_factory, scopefunc=None):
self.session_factory = session_factory if scopefunc: self.registry = ScopedRegistry(session_factory, scopefunc) else: self.registry = ThreadLocalRegistry(session_factory)
'Return the current :class:`.Session`, creating it using the session factory if not present. :param \**kw: Keyword arguments will be passed to the session factory callable, if an existing :class:`.Session` is not present. If the :class:`.Session` is present and keyword arguments have been passed, :exc:`~sqlalchemy.exc...
def __call__(self, **kw):
if kw: scope = kw.pop('scope', False) if (scope is not None): if self.registry.has(): raise sa_exc.InvalidRequestError('Scoped session is already present; no new arguments may be specified.') else: sess = self.sess...
'Dispose of the current :class:`.Session`, if present. This will first call :meth:`.Session.close` method on the current :class:`.Session`, which releases any existing transactional/connection resources still being held; transactions specifically are rolled back. The :class:`.Session` is then discarded. Upon next us...
def remove(self):
if self.registry.has(): self.registry().close() self.registry.clear()
'reconfigure the :class:`.sessionmaker` used by this :class:`.scoped_session`. See :meth:`.sessionmaker.configure`.'
def configure(self, **kwargs):
if self.registry.has(): warn('At least one scoped session is already present. configure() can not affect sessions that have already been created.') self.session_factory.configure(**kwargs)
'return a class property which produces a :class:`.Query` object against the class and the current :class:`.Session` when called. e.g.:: Session = scoped_session(sessionmaker()) class MyClass(object): query = Session.query_property() # after mappers are defined result = MyClass.query.filter(MyClass.name==\'foo\').all()...
def query_property(self, query_cls=None):
class query(object, ): def __get__(s, instance, owner): try: mapper = class_mapper(owner) if mapper: if query_cls: return query_cls(mapper, session=self.registry()) else: retur...
'Return a new :class:`~.Mapper` object. This function is typically used behind the scenes via the Declarative extension. When using Declarative, many of the usual :func:`.mapper` arguments are handled by the Declarative extension itself, including ``class_``, ``local_table``, ``properties``, and ``inherits``. Other ...
def __init__(self, class_, local_table=None, properties=None, primary_key=None, non_primary=False, inherits=None, inherit_condition=None, inherit_foreign_keys=None, extension=None, order_by=False, always_refresh=False, version_id_col=None, version_id_generator=None, polymorphic_on=None, _polymorphic_map=None, polymorph...
self.class_ = util.assert_arg_type(class_, type, 'class_') self.class_manager = None self._primary_key_argument = util.to_list(primary_key) self.non_primary = non_primary if (order_by is not False): self.order_by = util.to_list(order_by) else: self.order_by = order_by self.al...
'Part of the inspection API. Returns self.'
@property def mapper(self):
return self
'Part of the inspection API. Returns self.class\_.'
@property def entity(self):
return self.class_
'Configure settings related to inherting and/or inherited mappers being present.'
def _configure_inheritance(self):
self._inheriting_mappers = util.WeakSequence() if self.inherits: if isinstance(self.inherits, type): self.inherits = class_mapper(self.inherits, configure=False) if (not issubclass(self.class_, self.inherits.class_)): raise sa_exc.ArgumentError(("Class '%s' does ...
'Set the given :class:`.Mapper` as the \'inherits\' for this :class:`.Mapper`, assuming this :class:`.Mapper` is concrete and does not already have an inherits.'
def _set_concrete_base(self, mapper):
assert self.concrete assert (not self.inherits) assert isinstance(mapper, Mapper) self.inherits = mapper self.inherits.polymorphic_map.update(self.polymorphic_map) self.polymorphic_map = self.inherits.polymorphic_map for mapper in self.iterate_to_root(): if (mapper.polymorphic_on is ...
'If this mapper is to be a primary mapper (i.e. the non_primary flag is not set), associate this Mapper with the given class_ and entity name. Subsequent calls to ``class_mapper()`` for the class_/entity name combination will return this mapper. Also decorate the `__init__` method on the mapped class to include option...
def _configure_class_instrumentation(self):
manager = attributes.manager_of_class(self.class_) if self.non_primary: if ((not manager) or (not manager.is_mapped)): raise sa_exc.InvalidRequestError(('Class %s has no primary mapper configured. Configure a primary mapper first before setting u...
'Class-level path to the :func:`.configure_mappers` call.'
@classmethod def _configure_all(cls):
configure_mappers()
'Configure an attribute on the mapper representing the \'polymorphic_on\' column, if applicable, and not already generated by _configure_properties (which is typical). Also create a setter function which will assign this attribute to the value of the \'polymorphic_identity\' upon instance construction, also if applicab...
def _configure_polymorphic_setter(self, init=False):
setter = False if (self.polymorphic_on is not None): setter = True if isinstance(self.polymorphic_on, util.string_types): try: self.polymorphic_on = self._props[self.polymorphic_on] except KeyError: raise sa_exc.ArgumentError(("Can't det...
'generate/update a :class:`.ColumnProprerty` given a :class:`.Column` object.'
def _property_from_column(self, key, prop):
columns = util.to_list(prop) column = columns[0] if (not expression._is_column(column)): raise sa_exc.ArgumentError(('%s=%r is not an instance of MapperProperty or Column' % (key, prop))) prop = self._props.get(key, None) if isinstance(prop, properties.ColumnProperty)...
'Call the ``init()`` method on all ``MapperProperties`` attached to this mapper. This is a deferred configuration step which is intended to execute once all mappers have been constructed.'
def _post_configure_properties(self):
self._log('_post_configure_properties() started') l = [(key, prop) for (key, prop) in self._props.items()] for (key, prop) in l: self._log('initialize prop %s', key) if ((prop.parent is self) and (not prop._configure_started)): prop.init() if prop._configure_fini...
'Add the given dictionary of properties to this mapper, using `add_property`.'
def add_properties(self, dict_of_properties):
for (key, value) in dict_of_properties.items(): self.add_property(key, value)
'Add an individual MapperProperty to this mapper. If the mapper has not been configured yet, just adds the property to the initial properties dictionary sent to the constructor. If this Mapper has already been configured, then the given MapperProperty is configured immediately.'
def add_property(self, key, prop):
self._init_properties[key] = prop self._configure_property(key, prop, init=self.configured)
'return a MapperProperty associated with the given key.'
def get_property(self, key, _configure_mappers=True):
if (_configure_mappers and Mapper._new_mappers): configure_mappers() try: return self._props[key] except KeyError: raise sa_exc.InvalidRequestError(("Mapper '%s' has no property '%s'" % (self, key)))
'Given a :class:`.Column` object, return the :class:`.MapperProperty` which maps this column.'
def get_property_by_column(self, column):
return self._columntoproperty[column]
'return an iterator of all MapperProperty objects.'
@property def iterate_properties(self):
if Mapper._new_mappers: configure_mappers() return iter(self._props.values())
'given a with_polymorphic() argument, return the set of mappers it represents. Trims the list of mappers to just those represented within the given selectable, if present. This helps some more legacy-ish mappings.'
def _mappers_from_spec(self, spec, selectable):
if (spec == '*'): mappers = list(self.self_and_descendants) elif spec: mappers = set() for m in util.to_list(spec): m = _class_to_mapper(m) if (not m.isa(self)): raise sa_exc.InvalidRequestError(('%r does not inherit from %r' % (m, s...
'given a list of mappers (assumed to be within this mapper\'s inheritance hierarchy), construct an outerjoin amongst those mapper\'s mapped tables.'
def _selectable_from_mappers(self, mappers, innerjoin):
from_obj = self.mapped_table for m in mappers: if (m is self): continue if m.concrete: raise sa_exc.InvalidRequestError("'with_polymorphic()' requires 'selectable' argument when concrete-inheriting mappers are used.") elif (not m.single): ...
'The :func:`.select` construct this :class:`.Mapper` selects from by default. Normally, this is equivalent to :attr:`.mapped_table`, unless the ``with_polymorphic`` feature is in use, in which case the full "polymorphic" selectable is returned.'
@property def selectable(self):
return self._with_polymorphic_selectable
'Return an iterator of MapperProperty objects which will render into a SELECT.'
def _iterate_polymorphic_properties(self, mappers=None):
if (mappers is None): mappers = self._with_polymorphic_mappers if (not mappers): for c in self.iterate_properties: (yield c) else: for c in util.unique_list(chain(*[list(mapper.iterate_properties) for mapper in ([self] + mappers)])): if (getattr(c, '_is_polymo...
'A namespace of all :class:`.MapperProperty` objects associated this mapper. This is an object that provides each property based on its key name. For instance, the mapper for a ``User`` class which has ``User.name`` attribute would provide ``mapper.attrs.name``, which would be the :class:`.ColumnProperty` representing...
@util.memoized_property def attrs(self):
if Mapper._new_mappers: configure_mappers() return util.ImmutableProperties(self._props)
'A namespace of all :class:`._InspectionAttr` attributes associated with the mapped class. These attributes are in all cases Python :term:`descriptors` associated with the mapped class or its superclasses. This namespace includes attributes that are mapped to the class as well as attributes declared by extension module...
@util.memoized_property def all_orm_descriptors(self):
return util.ImmutableProperties(dict(self.class_manager._all_sqla_attributes()))
'Return a namespace of all :class:`.SynonymProperty` properties maintained by this :class:`.Mapper`. .. seealso:: :attr:`.Mapper.attrs` - namespace of all :class:`.MapperProperty` objects.'
@_memoized_configured_property def synonyms(self):
return self._filter_properties(properties.SynonymProperty)
'Return a namespace of all :class:`.ColumnProperty` properties maintained by this :class:`.Mapper`. .. seealso:: :attr:`.Mapper.attrs` - namespace of all :class:`.MapperProperty` objects.'
@_memoized_configured_property def column_attrs(self):
return self._filter_properties(properties.ColumnProperty)
'Return a namespace of all :class:`.RelationshipProperty` properties maintained by this :class:`.Mapper`. .. seealso:: :attr:`.Mapper.attrs` - namespace of all :class:`.MapperProperty` objects.'
@_memoized_configured_property def relationships(self):
return self._filter_properties(properties.RelationshipProperty)
'Return a namespace of all :class:`.CompositeProperty` properties maintained by this :class:`.Mapper`. .. seealso:: :attr:`.Mapper.attrs` - namespace of all :class:`.MapperProperty` objects.'
@_memoized_configured_property def composites(self):
return self._filter_properties(properties.CompositeProperty)
'create a "get clause" based on the primary key. this is used by query.get() and many-to-one lazyloads to load this item by primary key.'
@_memoized_configured_property def _get_clause(self):
params = [(primary_key, sql.bindparam(None, type_=primary_key.type)) for primary_key in self.primary_key] return (sql.and_(*[(k == v) for (k, v) in params]), util.column_dict(params))
'Create a map of all *equivalent* columns, based on the determination of column pairs that are equated to one another based on inherit condition. This is designed to work with the queries that util.polymorphic_union comes up with, which often don\'t include the columns from the base table directly (including the subcl...
@_memoized_configured_property def _equivalent_columns(self):
result = util.column_dict() def visit_binary(binary): if (binary.operator == operators.eq): if (binary.left in result): result[binary.left].add(binary.right) else: result[binary.left] = util.column_set((binary.right,)) if (binary.right ...
'determine whether a particular property should be implicitly present on the class. This occurs when properties are propagated from an inherited class, or are applied from the columns present in the mapped table.'
def _should_exclude(self, name, assigned_name, local, column):
if local: if ((self.class_.__dict__.get(assigned_name, None) is not None) and self._is_userland_descriptor(self.class_.__dict__[assigned_name])): return True elif ((getattr(self.class_, assigned_name, None) is not None) and self._is_userland_descriptor(getattr(self.class_, assigned_name))): ...
'Return true if the given mapper shares a common inherited parent as this mapper.'
def common_parent(self, other):
return (self.base_mapper is other.base_mapper)
'Return True if the this mapper inherits from the given mapper.'
def isa(self, other):
m = self while (m and (m is not other)): m = m.inherits return bool(m)
'The collection including this mapper and all descendant mappers. This includes not just the immediately inheriting mappers but all their inheriting mappers as well.'
@_memoized_configured_property def self_and_descendants(self):
descendants = [] stack = deque([self]) while stack: item = stack.popleft() descendants.append(item) stack.extend(item._inheriting_mappers) return util.WeakSequence(descendants)
'Iterate through the collection including this mapper and all descendant mappers. This includes not just the immediately inheriting mappers but all their inheriting mappers as well. To iterate through an entire hierarchy, use ``mapper.base_mapper.polymorphic_iterator()``.'
def polymorphic_iterator(self):
return iter(self.self_and_descendants)
'Return the primary mapper corresponding to this mapper\'s class key (class).'
def primary_mapper(self):
return self.class_manager.mapper
'Return an identity-map key for use in storing/retrieving an item from the identity map. :param row: A :class:`.RowProxy` instance. The columns which are mapped by this :class:`.Mapper` should be locatable in the row, preferably via the :class:`.Column` object directly (as is the case when a :func:`.select` construct ...
def identity_key_from_row(self, row, adapter=None):
pk_cols = self.primary_key if adapter: pk_cols = [adapter.columns[c] for c in pk_cols] return (self._identity_class, tuple((row[column] for column in pk_cols)))
'Return an identity-map key for use in storing/retrieving an item from an identity map. :param primary_key: A list of values indicating the identifier.'
def identity_key_from_primary_key(self, primary_key):
return (self._identity_class, tuple(primary_key))
'Return the identity key for the given instance, based on its primary key attributes. If the instance\'s state is expired, calling this method will result in a database check to see if the object has been deleted. If the row no longer exists, :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised. This value is typi...
def identity_key_from_instance(self, instance):
return self.identity_key_from_primary_key(self.primary_key_from_instance(instance))
'Return the list of primary key values for the given instance. If the instance\'s state is expired, calling this method will result in a database check to see if the object has been deleted. If the row no longer exists, :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised.'
def primary_key_from_instance(self, instance):
state = attributes.instance_state(instance) return self._primary_key_from_state(state)
'assemble a WHERE clause which retrieves a given state by primary key, using a minimized set of tables. Applies to a joined-table inheritance mapper where the requested attribute names are only present on joined tables, not the base table. The WHERE clause attempts to include only those tables to minimize joins.'
def _optimized_get_statement(self, state, attribute_names):
props = self._props tables = set(chain(*[sql_util.find_tables(c, check_columns=True) for key in attribute_names for c in props[key].columns])) if (self.base_mapper.local_table in tables): return None class ColumnsNotAvailable(Exception, ): pass def visit_binary(binary): leftc...
'Iterate each element and its mapper in an object graph, for all relationships that meet the given cascade rule. :param type_: The name of the cascade rule (i.e. save-update, delete, etc.) :param state: The lead InstanceState. child items will be processed per the relationships defined for this object\'s mapper. the r...
def cascade_iterator(self, type_, state, halt_on=None):
visited_states = set() (prp, mpp) = (object(), object()) visitables = deque([(deque(self._props.values()), prp, state, state.dict)]) while visitables: (iterator, item_type, parent_state, parent_dict) = visitables[(-1)] if (not iterator): visitables.pop() continue ...
'memoized map of tables to collections of columns to be synchronized upwards to the base mapper.'
@util.memoized_property def _table_to_equated(self):
result = util.defaultdict(list) for table in self._sorted_tables: cols = set(table.c) for m in self.iterate_to_root(): if (m._inherits_equated_pairs and cols.intersection(util.reduce(set.union, [l.proxy_set for (l, r) in m._inherits_equated_pairs]))): result[table].ap...
'Return a namespace representing each attribute on the mapped object, including its current value and history. The returned object is an instance of :class:`.AttributeState`.'
@util.memoized_property def attrs(self):
return util.ImmutableProperties(dict(((key, AttributeState(self, key)) for key in self.manager)))
'Return true if the object is transient.'
@property def transient(self):
return ((self.key is None) and (not self._attached))
'Return true if the object is pending.'
@property def pending(self):
return ((self.key is None) and self._attached)
'Return true if the object is persistent.'
@property def persistent(self):
return ((self.key is not None) and self._attached)
'Return true if the object is detached.'
@property def detached(self):
return ((self.key is not None) and (not self._attached))
'Return the owning :class:`.Session` for this instance, or ``None`` if none available.'
@property @util.dependencies('sqlalchemy.orm.session') def session(self, sessionlib):
return sessionlib._state_session(self)
'Return the mapped object represented by this :class:`.InstanceState`.'
@property def object(self):
return self.obj()
'Return the mapped identity of the mapped object. This is the primary key identity as persisted by the ORM which can always be passed directly to :meth:`.Query.get`. Returns ``None`` if the object has no primary key identity. .. note:: An object which is transient or pending does **not** have a mapped identity until it...
@property def identity(self):
if (self.key is None): return None else: return self.key[1]
'Return the identity key for the mapped object. This is the key used to locate the object within the :attr:`.Session.identity_map` mapping. It contains the identity as returned by :attr:`.identity` within it.'
@property def identity_key(self):
return self.key
'Return the :class:`.Mapper` used for this mapepd object.'
@util.memoized_property def mapper(self):
return self.manager.mapper
'Return ``True`` if this object has an identity key. This should always have the same value as the expression ``state.persistent or state.detached``.'
@property def has_identity(self):
return bool(self.key)
'Set this attribute to an empty value or collection, based on the AttributeImpl in use.'
def _initialize(self, key):
self.manager.get_impl(key).initialize(self, self.dict)
'Remove the given attribute and any callables associated with it.'
def _reset(self, dict_, key):
old = dict_.pop(key, None) if ((old is not None) and self.manager[key].impl.collection): self.manager[key].impl._invalidate_collection(old) self.callables.pop(key, None)
'a fast expire that can be called by column loaders during a load. The additional bookkeeping is finished up in commit_all(). Should only be called for scalar attributes. This method is actually called a lot with joined-table loading, when the second table isn\'t present in the result.'
def _expire_attribute_pre_commit(self, dict_, key):
dict_.pop(key, None) self.callables[key] = self
'__call__ allows the InstanceState to act as a deferred callable for loading expired attributes, which is also serializable (picklable).'
def __call__(self, state, passive):
if (not (passive & SQL_OK)): return PASSIVE_NO_RESULT toload = self.expired_attributes.intersection(self.unmodified) self.manager.deferred_scalar_loader(self, toload) for k in toload.intersection(self.callables): del self.callables[k] return ATTR_WAS_SET
'Return the set of keys which have no uncommitted changes'
@property def unmodified(self):
return set(self.manager).difference(self.committed_state)
'Return self.unmodified.intersection(keys).'
def unmodified_intersection(self, keys):
return set(keys).intersection(self.manager).difference(self.committed_state)
'Return the set of keys which do not have a loaded value. This includes expired attributes and any other attribute that was never populated or modified.'
@property def unloaded(self):
return set(self.manager).difference(self.committed_state).difference(self.dict)
'Return the set of keys which are \'expired\' to be loaded by the manager\'s deferred scalar loader, assuming no pending changes. see also the ``unmodified`` collection which is intersected against this set when a refresh operation occurs.'
@property def expired_attributes(self):
return set([k for (k, v) in self.callables.items() if (v is self)])
'Commit attributes. This is used by a partial-attribute load operation to mark committed those attributes which were refreshed from the database. Attributes marked as "expired" can potentially remain "expired" after this step if a value was not populated in state.dict.'
def _commit(self, dict_, keys):
for key in keys: self.committed_state.pop(key, None) self.expired = False for key in set(self.callables).intersection(keys).intersection(dict_): del self.callables[key]
'commit all attributes unconditionally. This is used after a flush() or a full load/refresh to remove all pending state from the instance. - all attributes are marked as "committed" - the "strong dirty reference" is removed - the "modified" flag is set to False - any "expired" markers/callables for attributes loaded ar...
def _commit_all(self, dict_, instance_dict=None):
self._commit_all_states([(self, dict_)], instance_dict)
'Mass version of commit_all().'
@classmethod def _commit_all_states(self, iter, instance_dict=None):
for (state, dict_) in iter: state.committed_state.clear() InstanceState._pending_mutations._reset(state) callables = state.callables for key in list(callables): if ((key in dict_) and (callables[key] is state)): del callables[key] if (instance_dict...
'The current value of this attribute as loaded from the database. If the value has not been loaded, or is otherwise not present in the object\'s dictionary, returns NO_VALUE.'
@property def loaded_value(self):
return self.state.dict.get(self.key, NO_VALUE)
'Return the value of this attribute. This operation is equivalent to accessing the object\'s attribute directly or via ``getattr()``, and will fire off any pending loader callables if needed.'
@property def value(self):
return self.state.manager[self.key].__get__(self.state.obj(), self.state.class_)
'Return the current pre-flush change history for this attribute, via the :class:`.History` interface. This method will **not** emit loader callables if the value of the attribute is unloaded. .. seealso:: :meth:`.AttributeState.load_history` - retrieve history using loader callables if the value is not locally present....
@property def history(self):
return self.state.get_history(self.key, PASSIVE_NO_INITIALIZE)
'Return the current pre-flush change history for this attribute, via the :class:`.History` interface. This method **will** emit loader callables if the value of the attribute is unloaded. .. seealso:: :attr:`.AttributeState.history` :func:`.attributes.get_history` - underlying function .. versionadded:: 0.9.0'
def load_history(self):
return self.state.get_history(self.key, (PASSIVE_OFF ^ INIT_OK))
'return True if any InstanceStates present have been marked as \'modified\'.'
def check_modified(self):
return bool(self._modified)
'prune unreferenced, non-dirty states.'
def prune(self):
ref_count = len(self) dirty = [s.obj() for s in self.all_states() if s.modified] keepers = weakref.WeakValueDictionary() keepers.update(self) dict.clear(self) dict.update(self, keepers) self.modified = bool(dirty) return (ref_count - len(self))
'Add a left outer join to the statement thats being constructed.'
def setup_query(self, context, entity, path, loadopt, adapter, column_collection=None, parentmapper=None, **kwargs):
if (not context.query._enable_eagerloads): return path = path[self.parent_property] with_polymorphic = None user_defined_adapter = (self._init_user_defined_eager_proc(loadopt, context) if loadopt else False) if (user_defined_adapter is not False): (clauses, adapter, add_to_collection...
'Given a path (mapper A, prop X), replace the prop with the wildcard, e.g. (mapper A, \'relationship:.*\') or (mapper A, \'column:.*\'), then return within the ("loader", path) structure.'
@util.memoized_property def _wildcard_path_loader_key(self):
return ('loader', self.parent.token(('%s:%s' % (self.prop.strategy_wildcard_key, _WILDCARD_TOKEN))).path)
'Tag the method as the collection appender. The appender method is called with one positional argument: the value to append. The method will be automatically decorated with \'adds(1)\' if not already decorated:: @collection.appender def add(self, append): ... # or, equivalently @collection.appender @collection.adds(1) ...
@staticmethod def appender(fn):
fn._sa_instrument_role = 'appender' return fn
'Tag the method as the collection remover. The remover method is called with one positional argument: the value to remove. The method will be automatically decorated with :meth:`removes_return` if not already decorated:: @collection.remover def zap(self, entity): ... # or, equivalently @collection.remover @collection.r...
@staticmethod def remover(fn):
fn._sa_instrument_role = 'remover' return fn
'Tag the method as the collection remover. The iterator method is called with no arguments. It is expected to return an iterator over all collection members:: @collection.iterator def __iter__(self): ...'
@staticmethod def iterator(fn):
fn._sa_instrument_role = 'iterator' return fn
'Tag the method as instrumented. This tag will prevent any decoration from being applied to the method. Use this if you are orchestrating your own calls to :func:`.collection_adapter` in one of the basic SQLAlchemy interface methods, or to prevent an automatic ABC method decoration from wrapping your implementation:: #...
@staticmethod def internally_instrumented(fn):
fn._sa_instrumented = True return fn
'Tag the method as a "linked to attribute" event handler. This optional event handler will be called when the collection class is linked to or unlinked from the InstrumentedAttribute. It is invoked immediately after the \'_sa_adapter\' property is set on the instance. A single argument is passed: the collection adapt...
@staticmethod def linker(fn):
fn._sa_instrument_role = 'linker' return fn
'Tag the method as the collection converter. This optional method will be called when a collection is being replaced entirely, as in:: myobj.acollection = [newvalue1, newvalue2] The converter method will receive the object being assigned and should return an iterable of values suitable for use by the ``appender`` metho...
@staticmethod def converter(fn):
fn._sa_instrument_role = 'converter' return fn
'Mark the method as adding an entity to the collection. Adds "add to collection" handling to the method. The decorator argument indicates which method argument holds the SQLAlchemy-relevant value. Arguments can be specified positionally (i.e. integer) or by name:: @collection.adds(1) def push(self, item): ... @collec...
@staticmethod def adds(arg):
def decorator(fn): fn._sa_instrument_before = ('fire_append_event', arg) return fn return decorator