desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Merge a result into this :class:`.Query` object\'s Session. Given an iterator returned by a :class:`.Query` of the same structure as this one, return an identical iterator of results, with all mapped instances merged into the session using :meth:`.Session.merge`. This is an optimized method which will merge all mapped...
def merge_result(self, iterator, load=True):
return loading.merge_result(self, iterator, load)
'A convenience method that turns a query into an EXISTS subquery of the form EXISTS (SELECT 1 FROM ... WHERE ...). e.g.:: q = session.query(User).filter(User.name == \'fred\') session.query(q.exists()) Producing SQL similar to:: SELECT EXISTS ( SELECT 1 FROM users WHERE users.name = :name_1 ) AS anon_1 .. versionadded:...
def exists(self):
return sql.exists(self.add_columns('1').with_labels().statement.with_only_columns(['1']))
'Return a count of rows this Query would return. This generates the SQL for this Query as follows:: SELECT count(1) AS count_1 FROM ( SELECT <rest of query follows...> ) AS anon_1 .. versionchanged:: 0.7 The above scheme is newly refined as of 0.7b3. For fine grained control over specific columns to count, to skip the ...
def count(self):
col = sql.func.count(sql.literal_column('*')) return self.from_self(col).scalar()
'Perform a bulk delete query. Deletes rows matched by this query from the database. :param synchronize_session: chooses the strategy for the removal of matched objects from the session. Valid values are: ``False`` - don\'t synchronize the session. This option is the most efficient and is reliable once the session is ex...
def delete(self, synchronize_session='evaluate'):
delete_op = persistence.BulkDelete.factory(self, synchronize_session) delete_op.exec_() return delete_op.rowcount
'Perform a bulk update query. Updates rows matched by this query in the database. :param values: a dictionary with attributes names as keys and literal values or sql expressions as values. :param synchronize_session: chooses the strategy to update the attributes on objects in the session. Valid values are: ``False`` - ...
def update(self, values, synchronize_session='evaluate'):
update_op = persistence.BulkUpdate.factory(self, synchronize_session, values) update_op.exec_() return update_op.rowcount
'Apply single-table-inheritance filtering. For all distinct single-table-inheritance mappers represented in the columns clause of this query, add criterion to the WHERE clause of the given QueryContext such that only the appropriate subtypes are selected from the total results.'
def _adjust_for_single_inheritance(self, context):
for (ext_info, adapter) in self._mapper_adapter_map.values(): if (ext_info in self._join_entities): continue single_crit = ext_info.mapper._single_table_criterion if (single_crit is not None): if adapter: single_crit = adapter.traverse(single_crit) ...
'Receive an update from a call to query.with_polymorphic(). Note the newer style of using a free standing with_polymporphic() construct doesn\'t make use of this method.'
def set_with_polymorphic(self, query, cls_or_mappers, selectable, polymorphic_on):
if self.is_aliased_class: raise NotImplementedError("Can't use with_polymorphic() against an Aliased object") if (cls_or_mappers is None): query._reset_polymorphic_adapter(self.mapper) return (mappers, from_obj) = self.mapper._with_polymorphic_args(cls_or_mappers, s...
'Construct a new :class:`.Bundle`. e.g.:: bn = Bundle("mybundle", MyClass.x, MyClass.y) for row in session.query(bn).filter(bn.c.x == 5).filter(bn.c.y == 4): print(row.mybundle.x, row.mybundle.y) :param name: name of the bundle. :param \*exprs: columns or SQL expressions comprising the bundle. :param single_entity=Fals...
def __init__(self, name, *exprs, **kw):
self.name = self._label = name self.exprs = exprs self.c = self.columns = ColumnCollection() self.columns.update(((getattr(col, 'key', col._label), col) for col in exprs)) self.single_entity = kw.pop('single_entity', self.single_entity)
'Provide a copy of this :class:`.Bundle` passing a new label.'
def label(self, name):
cloned = self._clone() cloned.name = name return cloned
'Produce the "row processing" function for this :class:`.Bundle`. May be overridden by subclasses. .. seealso:: :ref:`bundles` - includes an example of subclassing.'
def create_row_processor(self, query, procs, labels):
def proc(row, result): return util.KeyedTuple([proc(row, None) for proc in procs], labels) return proc
'Return a :class:`.MapperOption` that will indicate to the :class:`.Query` that the main table has been aliased. This is a seldom-used option to suit the very rare case that :func:`.contains_eager` is being used in conjunction with a user-defined SELECT statement that aliases the parent table. E.g.:: # define an alias...
def __init__(self, alias):
self.alias = alias
'Provide a relationship between two mapped classes. This corresponds to a parent-child or associative table relationship. The constructed class is an instance of :class:`.RelationshipProperty`. A typical :func:`.relationship`, used in a classical mapping:: mapper(Parent, properties={ \'children\': relationship(Child) ...
def __init__(self, argument, secondary=None, primaryjoin=None, secondaryjoin=None, foreign_keys=None, uselist=None, order_by=False, backref=None, back_populates=None, post_update=False, cascade=False, extension=None, viewonly=False, lazy=True, collection_class=None, passive_deletes=False, passive_updates=True, remote_s...
self.uselist = uselist self.argument = argument self.secondary = secondary self.primaryjoin = primaryjoin self.secondaryjoin = secondaryjoin self.post_update = post_update self.direction = None self.viewonly = viewonly self.lazy = lazy self.single_parent = single_parent self....
'Construction of :class:`.RelationshipProperty.Comparator` is internal to the ORM\'s attribute mechanics.'
def __init__(self, prop, parentmapper, adapt_to_entity=None, of_type=None):
self.prop = prop self._parentmapper = parentmapper self._adapt_to_entity = adapt_to_entity if of_type: self._of_type = of_type
'The target :class:`.Mapper` referred to by this :class:`.RelationshipProperty.Comparator`. This is the "target" or "remote" side of the :func:`.relationship`.'
@util.memoized_property def mapper(self):
return self.property.mapper
'Produce a construct that represents a particular \'subtype\' of attribute for the parent class. Currently this is usable in conjunction with :meth:`.Query.join` and :meth:`.Query.outerjoin`.'
def of_type(self, cls):
return RelationshipProperty.Comparator(self.property, self._parentmapper, adapt_to_entity=self._adapt_to_entity, of_type=cls)
'Produce an IN clause - this is not implemented for :func:`~.orm.relationship`-based attributes at this time.'
def in_(self, other):
raise NotImplementedError('in_() not yet supported for relationships. For a simple many-to-one, use in_() against the set of foreign key values.')
'Implement the ``==`` operator. In a many-to-one context, such as:: MyClass.some_prop == <some object> this will typically produce a clause such as:: mytable.related_id == <some id> Where ``<some id>`` is the primary key of the given object. The ``==`` operator provides partial functionality for non- many-to-one compar...
def __eq__(self, other):
if isinstance(other, (util.NoneType, expression.Null)): if (self.property.direction in [ONETOMANY, MANYTOMANY]): return (~ self._criterion_exists()) else: return _orm_annotate(self.property._optimized_compare(None, adapt_source=self.adapter)) elif self.property.uselist: ...
'Produce an expression that tests a collection against particular criterion, using EXISTS. An expression like:: session.query(MyClass).filter( MyClass.somereference.any(SomeRelated.x==2) Will produce a query like:: SELECT * FROM my_table WHERE EXISTS (SELECT 1 FROM related WHERE related.my_id=my_table.id AND related.x=...
def any(self, criterion=None, **kwargs):
if (not self.property.uselist): raise sa_exc.InvalidRequestError("'any()' not implemented for scalar attributes. Use has().") return self._criterion_exists(criterion, **kwargs)
'Produce an expression that tests a scalar reference against particular criterion, using EXISTS. An expression like:: session.query(MyClass).filter( MyClass.somereference.has(SomeRelated.x==2) Will produce a query like:: SELECT * FROM my_table WHERE EXISTS (SELECT 1 FROM related WHERE related.id==my_table.related_id AN...
def has(self, criterion=None, **kwargs):
if self.property.uselist: raise sa_exc.InvalidRequestError("'has()' not implemented for collections. Use any().") return self._criterion_exists(criterion, **kwargs)
'Return a simple expression that tests a collection for containment of a particular item. :meth:`~.RelationshipProperty.Comparator.contains` is only valid for a collection, i.e. a :func:`~.orm.relationship` that implements one-to-many or many-to-many with ``uselist=True``. When used in a simple one-to-many context, an ...
def contains(self, other, **kwargs):
if (not self.property.uselist): raise sa_exc.InvalidRequestError("'contains' not implemented for scalar attributes. Use ==") clause = self.property._optimized_compare(other, adapt_source=self.adapter) if (self.property.secondaryjoin is not None): clause.negation_clau...
'Implement the ``!=`` operator. In a many-to-one context, such as:: MyClass.some_prop != <some object> This will typically produce a clause such as:: mytable.related_id != <some id> Where ``<some id>`` is the primary key of the given object. The ``!=`` operator provides partial functionality for non- many-to-one compar...
def __ne__(self, other):
if isinstance(other, (util.NoneType, expression.Null)): if (self.property.direction == MANYTOONE): return sql.or_(*[(x != None) for x in self.property._calculated_foreign_keys]) else: return self._criterion_exists() elif self.property.uselist: raise sa_exc.Invalid...
'Return a list of tuples (state, obj) for the given key. returns an empty list if the value is None/empty/PASSIVE_NO_RESULT'
def _value_as_iterable(self, state, dict_, key, passive=attributes.PASSIVE_OFF):
impl = state.manager[key].impl x = impl.get(state, dict_, passive=passive) if ((x is attributes.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(state, dict_, x, passive=passive)] ...
'Return the targeted :class:`.Mapper` for this :class:`.RelationshipProperty`. This is a lazy-initializing static attribute.'
@util.memoized_property def mapper(self):
if (util.callable(self.argument) and (not isinstance(self.argument, (type, mapperlib.Mapper)))): argument = self.argument() else: argument = self.argument if isinstance(argument, type): mapper_ = mapperlib.class_mapper(argument, configure=False) elif isinstance(self.argument, map...
'Return the selectable linked to this :class:`.RelationshipProperty` object\'s target :class:`.Mapper`.'
@util.memoized_property @util.deprecated('0.7', 'Use .target') def table(self):
return self.target
'Convert incoming configuration arguments to their proper form. Callables are resolved, ORM annotations removed.'
def _process_dependent_arguments(self):
for attr in ('order_by', 'primaryjoin', 'secondaryjoin', 'secondary', '_user_defined_foreign_keys', 'remote_side'): attr_value = getattr(self, attr) if util.callable(attr_value): setattr(self, attr, attr_value()) for attr in ('primaryjoin', 'secondaryjoin'): val = getattr(sel...
'Test that this relationship is legal, warn about inheritance conflicts.'
def _check_conflicts(self):
if ((not self.is_primary()) and (not mapperlib.class_mapper(self.parent.class_, configure=False).has_property(self.key))): raise sa_exc.ArgumentError(("Attempting to assign a new relationship '%s' to a non-primary mapper on class '%s'. New relationships ca...
'Return the current cascade setting for this :class:`.RelationshipProperty`.'
def _get_cascade(self):
return self._cascade
'Return True if all columns in the given collection are mapped by the tables referenced by this :class:`.Relationship`.'
def _columns_are_mapped(self, *cols):
for c in cols: if ((self.secondary is not None) and self.secondary.c.contains_column(c)): continue if ((not self.parent.mapped_table.c.contains_column(c)) and (not self.target.c.contains_column(c))): return False return True
'Interpret the \'backref\' instruction to create a :func:`.relationship` complementary to this one.'
def _generate_backref(self):
if (not self.is_primary()): return if ((self.backref is not None) and (not self.back_populates)): if isinstance(self.backref, util.string_types): (backref_key, kwargs) = (self.backref, {}) else: (backref_key, kwargs) = self.backref mapper = self.mapper.pri...
'memoize the \'use_get\' attribute of this RelationshipLoader\'s lazyloader.'
@util.memoized_property def _use_get(self):
strategy = self._lazy_strategy return strategy.use_get
'Determine the \'primaryjoin\' and \'secondaryjoin\' attributes, if not passed to the constructor already. This is based on analysis of the foreign key relationships between the parent and target mapped selectables.'
def _determine_joins(self):
if ((self.secondaryjoin is not None) and (self.secondary is None)): raise sa_exc.ArgumentError(('Property %s specified with secondary join condition but no secondary argument' % self.prop)) try: consider_as_foreign_keys = (self.consider_as_foreign_keys or None) ...
'Return the primaryjoin condition suitable for the "reverse" direction. If the primaryjoin was delivered here with pre-existing "remote" annotations, the local/remote annotations are reversed. Otherwise, the local/remote annotations are removed.'
@util.memoized_property def primaryjoin_reverse_remote(self):
if self._has_remote_annotations: def replace(element): if ('remote' in element._annotations): v = element._annotations.copy() del v['remote'] v['local'] = True return element._with_annotations(v) elif ('local' in element...
'Annotate the primaryjoin and secondaryjoin structures with \'foreign\' annotations marking columns considered as foreign.'
def _annotate_fks(self):
if self._has_foreign_annotations: return if self.consider_as_foreign_keys: self._annotate_from_fk_list() else: self._annotate_present_fks()
'Return True if the join condition contains column comparisons where both columns are in both tables.'
def _refers_to_parent_table(self):
pt = self.parent_selectable mt = self.child_selectable result = [False] def visit_binary(binary): (c, f) = (binary.left, binary.right) if (isinstance(c, expression.ColumnClause) and isinstance(f, expression.ColumnClause) and pt.is_derived_from(c.table) and pt.is_derived_from(f.table) and...
'Return True if parent/child tables have some overlap.'
def _tables_overlap(self):
return selectables_overlap(self.parent_selectable, self.child_selectable)
'Annotate the primaryjoin and secondaryjoin structures with \'remote\' annotations marking columns considered as part of the \'remote\' side.'
def _annotate_remote(self):
if self._has_remote_annotations: return if (self.secondary is not None): self._annotate_remote_secondary() elif (self._local_remote_pairs or self._remote_side): self._annotate_remote_from_args() elif self._refers_to_parent_table(): self._annotate_selfref((lambda col: ('fo...
'annotate \'remote\' in primaryjoin, secondaryjoin when \'secondary\' is present.'
def _annotate_remote_secondary(self):
def repl(element): if self.secondary.c.contains_column(element): return element._annotate({'remote': True}) self.primaryjoin = visitors.replacement_traverse(self.primaryjoin, {}, repl) self.secondaryjoin = visitors.replacement_traverse(self.secondaryjoin, {}, repl)
'annotate \'remote\' in primaryjoin, secondaryjoin when the relationship is detected as self-referential.'
def _annotate_selfref(self, fn):
def visit_binary(binary): equated = binary.left.compare(binary.right) if (isinstance(binary.left, expression.ColumnClause) and isinstance(binary.right, expression.ColumnClause)): if fn(binary.left): binary.left = binary.left._annotate({'remote': True}) if (fn(...
'annotate \'remote\' in primaryjoin, secondaryjoin when the \'remote_side\' or \'_local_remote_pairs\' arguments are used.'
def _annotate_remote_from_args(self):
if self._local_remote_pairs: if self._remote_side: raise sa_exc.ArgumentError('remote_side argument is redundant against more detailed _local_remote_side argument.') remote_side = [r for (l, r) in self._local_remote_pairs] else: remote_side = self._rem...
'annotate \'remote\' in primaryjoin, secondaryjoin when the parent/child tables have some set of tables in common, though is not a fully self-referential relationship.'
def _annotate_remote_with_overlap(self):
def visit_binary(binary): (binary.left, binary.right) = proc_left_right(binary.left, binary.right) (binary.right, binary.left) = proc_left_right(binary.right, binary.left) def proc_left_right(left, right): if (isinstance(left, expression.ColumnClause) and isinstance(right, expression.Col...
'annotate \'remote\' in primaryjoin, secondaryjoin when the parent/child tables are entirely separate.'
def _annotate_remote_distinct_selectables(self):
def repl(element): if (self.child_selectable.c.contains_column(element) and ((not self.parent_local_selectable.c.contains_column(element)) or self.child_local_selectable.c.contains_column(element))): return element._annotate({'remote': True}) self.primaryjoin = visitors.replacement_traverse(...
'Annotate the primaryjoin and secondaryjoin structures with \'local\' annotations. This annotates all column elements found simultaneously in the parent table and the join condition that don\'t have a \'remote\' annotation set up from _annotate_remote() or user-defined.'
def _annotate_local(self):
if self._has_annotation(self.primaryjoin, 'local'): return if self._local_remote_pairs: local_side = util.column_set([l for (l, r) in self._local_remote_pairs]) else: local_side = util.column_set(self.parent_selectable.c) def locals_(elem): if (('remote' not in elem._anno...
'Check the foreign key columns collected and emit error messages.'
def _check_foreign_cols(self, join_condition, primary):
can_sync = False foreign_cols = self._gather_columns_with_annotation(join_condition, 'foreign') has_foreign = bool(foreign_cols) if primary: can_sync = bool(self.synchronize_pairs) else: can_sync = bool(self.secondary_synchronize_pairs) if ((self.support_sync and can_sync) or ((n...
'Determine if this relationship is one to many, many to one, many to many.'
def _determine_direction(self):
if (self.secondaryjoin is not None): self.direction = MANYTOMANY else: parentcols = util.column_set(self.parent_selectable.c) targetcols = util.column_set(self.child_selectable.c) onetomany_fk = targetcols.intersection(self.foreign_key_columns) manytoone_fk = parentcols.i...
'provide deannotation for the various lists of pairs, so that using them in hashes doesn\'t incur high-overhead __eq__() comparisons against original columns mapped.'
def _deannotate_pairs(self, collection):
return [(x._deannotate(), y._deannotate()) for (x, y) in collection]
'Given a source and destination selectable, create a join between them. This takes into account aliasing the join clause to reference the appropriate corresponding columns in the target objects, as well as the extra child criterion, equivalent column sets, etc.'
def join_targets(self, source_selectable, dest_selectable, aliased, single_crit=None):
dest_selectable = _shallow_annotate(dest_selectable, {'no_replacement_traverse': True}) (primaryjoin, secondaryjoin, secondary) = (self.primaryjoin, self.secondaryjoin, self.secondary) if (single_crit is not None): if (secondaryjoin is not None): secondaryjoin = (secondaryjoin & single_c...
'return True if the given object instance has a parent, according to the ``InstrumentedAttribute`` handled by this ``DependencyProcessor``.'
def hasparent(self, state):
return self.parent.class_manager.get_impl(self.key).hasparent(state)
'establish actions and dependencies related to a flush. These actions will operate on all relevant states in the aggregate.'
def per_property_preprocessors(self, uow):
uow.register_preprocessor(self, True)
'establish actions and dependencies related to a flush. These actions will operate on all relevant states individually. This occurs only if there are cycles in the \'aggregated\' version of events.'
def per_state_flush_actions(self, uow, states, isdelete):
parent_base_mapper = self.parent.primary_base_mapper child_base_mapper = self.mapper.primary_base_mapper child_saves = unitofwork.SaveUpdateAll(uow, child_base_mapper) child_deletes = unitofwork.DeleteAll(uow, child_base_mapper) if isdelete: before_delete = unitofwork.ProcessAll(uow, self, T...
'Called by Query for the purposes of constructing a SQL statement. Each MapperProperty associated with the target mapper processes the statement referenced by the query context, adding columns and/or criterion as appropriate.'
def setup(self, context, entity, path, adapter, **kwargs):
pass
'Return a 3-tuple consisting of three row processing functions.'
def create_row_processor(self, context, path, mapper, row, adapter):
return (None, None, None)
'Iterate through instances related to the given instance for a particular \'cascade\', starting with this MapperProperty. Return an iterator3-tuples (instance, mapper, state). Note that the \'cascade\' collection on this MapperProperty is checked first for the given type before cascade_iterator is called. See PropertyL...
def cascade_iterator(self, type_, state, visited_instances=None, halt_on=None):
return iter(())
'Info dictionary associated with the object, allowing user-defined data to be associated with this :class:`.MapperProperty`. The dictionary is generated when first accessed. Alternatively, it can be specified as a constructor argument to the :func:`.column_property`, :func:`.relationship`, or :func:`.composite` functi...
@util.memoized_property def info(self):
return {}
'Called after all mappers are created to assemble relationships between mappers and perform other post-mapper-creation initialization steps.'
def init(self):
self._configure_started = True self.do_init() self._configure_finished = True
'Return the class-bound descriptor corresponding to this :class:`.MapperProperty`. This is basically a ``getattr()`` call:: return getattr(self.parent.class_, self.key) I.e. if this :class:`.MapperProperty` were named ``addresses``, and the class to which it is mapped is ``User``, this sequence is possible:: >>> from s...
@property def class_attribute(self):
return getattr(self.parent.class_, self.key)
'Perform subclass-specific initialization post-mapper-creation steps. This is a template method called by the ``MapperProperty`` object\'s init() method.'
def do_init(self):
pass
'Perform instrumentation adjustments that need to occur after init() has completed.'
def post_instrument_class(self, mapper):
pass
'Return True if this ``MapperProperty``\'s mapper is the primary mapper for its class. This flag is used to indicate that the ``MapperProperty`` can define attribute instrumentation for the class at the class level (as opposed to the individual instance level).'
def is_primary(self):
return (not self.parent.non_primary)
'Merge the attribute represented by this ``MapperProperty`` from source to destination object'
def merge(self, session, source_state, source_dict, dest_state, dest_dict, load, _recursive):
pass
'Return a compare operation for the columns represented by this ``MapperProperty`` to the given value, which may be a column value or an instance. \'operator\' is an operator from the operators module, or from sql.Comparator. By default uses the PropComparator attached to this MapperProperty under the attribute name "...
def compare(self, operator, value, **kw):
return operator(self.comparator, value)
'Return a copy of this PropComparator which will use the given :class:`.AliasedInsp` to produce corresponding expressions.'
def adapt_to_entity(self, adapt_to_entity):
return self.__class__(self.prop, self._parentmapper, adapt_to_entity)
'Produce a callable that adapts column expressions to suit an aliased version of this comparator.'
@property def adapter(self):
if (self._adapt_to_entity is None): return None else: return self._adapt_to_entity._adapt_element
'Redefine this object in terms of a polymorphic subclass. Returns a new PropComparator from which further criterion can be evaluated. e.g.:: query.join(Company.employees.of_type(Engineer)).\ filter(Engineer.name==\'foo\') :param \class_: a class or mapper indicating that criterion will be against this specific subclass...
def of_type(self, class_):
return self.operate(PropComparator.of_type_op, class_)
'Return true if this collection contains any member that meets the given criterion. The usual implementation of ``any()`` is :meth:`.RelationshipProperty.Comparator.any`. :param criterion: an optional ClauseElement formulated against the member class\' table or attributes. :param \**kwargs: key/value pairs correspondin...
def any(self, criterion=None, **kwargs):
return self.operate(PropComparator.any_op, criterion, **kwargs)
'Return true if this element references a member which meets the given criterion. The usual implementation of ``has()`` is :meth:`.RelationshipProperty.Comparator.has`. :param criterion: an optional ClauseElement formulated against the member class\' table or attributes. :param \**kwargs: key/value pairs corresponding ...
def has(self, criterion=None, **kwargs):
return self.operate(PropComparator.has_op, criterion, **kwargs)
'same as process_query(), except that this option may not apply to the given query. Used when secondary loaders resend existing options to a new Query.'
def process_query_conditionally(self, query):
self.process_query(query)
'Return row processing functions which fulfill the contract specified by MapperProperty.create_row_processor. StrategizedProperty delegates its create_row_processor method directly to this method.'
def create_row_processor(self, context, path, loadopt, mapper, row, adapter):
return (None, None, None)
'Return a composite column-based property for use with a Mapper. See the mapping documentation section :ref:`mapper_composite` for a full usage example. The :class:`.MapperProperty` returned by :func:`.composite` is the :class:`.CompositeProperty`. :param class\_: The "composite type" class. :param \*cols: List of Colu...
def __init__(self, class_, *attrs, **kwargs):
self.attrs = attrs self.composite_class = class_ self.active_history = kwargs.get('active_history', False) self.deferred = kwargs.get('deferred', False) self.group = kwargs.get('group', None) self.comparator_factory = kwargs.pop('comparator_factory', self.__class__.Comparator) if ('info' in ...
'Initialization which occurs after the :class:`.CompositeProperty` has been associated with its parent mapper.'
def do_init(self):
self._setup_arguments_on_columns()
'Create the Python descriptor that will serve as the access point on instances of the mapped class.'
def _create_descriptor(self):
def fget(instance): dict_ = attributes.instance_dict(instance) state = attributes.instance_state(instance) if (self.key not in dict_): values = [getattr(instance, key) for key in self._attribute_keys] if ((self.key not in dict_) and ((state.key is not None) or (not _n...
'Propagate configuration arguments made on this composite to the target columns, for those that apply.'
def _setup_arguments_on_columns(self):
for prop in self.props: prop.active_history = self.active_history if self.deferred: prop.deferred = self.deferred prop.strategy_class = prop._strategy_lookup(('deferred', True), ('instrument', True)) prop.group = self.group
'Establish events that populate/expire the composite attribute.'
def _setup_event_handlers(self):
def load_handler(state, *args): dict_ = state.dict if (self.key in dict_): return for k in self._attribute_keys: if (k not in dict_): return dict_[self.key] = self.composite_class(*[state.dict[key] for key in self._attribute_keys]) def expi...
'Provided for userland code that uses attributes.get_history().'
def get_history(self, state, dict_, passive=attributes.PASSIVE_OFF):
added = [] deleted = [] has_history = False for prop in self.props: key = prop.key hist = state.manager[key].impl.get_history(state, dict_) if hist.has_changes(): has_history = True non_deleted = hist.non_deleted() if non_deleted: added.ext...
'Denote an attribute name as a synonym to a mapped property, in that the attribute will mirror the value and expression behavior of another attribute. :param name: the name of the existing mapped property. This can refer to the string name of any :class:`.MapperProperty` configured on the class, including column-bound...
def __init__(self, name, map_column=None, descriptor=None, comparator_factory=None, doc=None):
self.name = name self.map_column = map_column self.descriptor = descriptor self.comparator_factory = comparator_factory self.doc = (doc or (descriptor and descriptor.__doc__) or None) util.set_creation_order(self)
'Provides a method of applying a :class:`.PropComparator` to any Python descriptor attribute. .. versionchanged:: 0.7 :func:`.comparable_property` is superseded by the :mod:`~sqlalchemy.ext.hybrid` extension. See the example at :ref:`hybrid_custom_comparators`. Allows any Python descriptor to behave like a SQL-enabled...
def __init__(self, comparator_factory, descriptor=None, doc=None):
self.descriptor = descriptor self.comparator_factory = comparator_factory self.doc = (doc or (descriptor and descriptor.__doc__) or None) util.set_creation_order(self)
'Close *all* sessions in memory.'
@classmethod def close_all(cls):
for sess in _sessions.values(): sess.close()
'Return an identity key. This is an alias of :func:`.util.identity_key`.'
@classmethod @util.dependencies('sqlalchemy.orm.util') def identity_key(cls, orm_util, *args, **kwargs):
return orm_util.identity_key(*args, **kwargs)
'Return the :class:`.Session` to which an object belongs. This is an alias of :func:`.object_session`.'
@classmethod def object_session(cls, instance):
return object_session(instance)
'Construct a new Session. See also the :class:`.sessionmaker` function which is used to generate a :class:`.Session`-producing callable with a given set of arguments. :param autocommit: .. warning:: The autocommit flag is **not for general use**, and if it is used, queries should only be invoked within the span of a :m...
def __init__(self, bind=None, autoflush=True, expire_on_commit=True, _enable_transaction_accounting=True, autocommit=False, twophase=False, weak_identity_map=True, binds=None, extension=None, info=None, query_cls=query.Query):
if weak_identity_map: self._identity_cls = identity.WeakInstanceDict else: util.warn_deprecated('weak_identity_map=False is deprecated. This feature is not needed.') self._identity_cls = identity.StrongInstanceDict self.identity_map = self._identity_cls() ...
'A user-modifiable dictionary. The initial value of this dictioanry can be populated using the ``info`` argument to the :class:`.Session` constructor or :class:`.sessionmaker` constructor or factory methods. The dictionary here is always local to this :class:`.Session` and can be modified independently of all other :c...
@util.memoized_property def info(self):
return {}
'Begin a transaction on this Session. If this Session is already within a transaction, either a plain transaction or nested transaction, an error is raised, unless ``subtransactions=True`` or ``nested=True`` is specified. The ``subtransactions=True`` flag indicates that this :meth:`~.Session.begin` can create a subtran...
def begin(self, subtransactions=False, nested=False):
if (self.transaction is not None): if (subtransactions or nested): self.transaction = self.transaction._begin(nested=nested) else: raise sa_exc.InvalidRequestError('A transaction is already begun. Use subtransactions=True to allow subtransaction...
'Begin a `nested` transaction on this Session. The target database(s) must support SQL SAVEPOINTs or a SQLAlchemy-supported vendor implementation of the idea. For documentation on SAVEPOINT transactions, please see :ref:`session_begin_nested`.'
def begin_nested(self):
return self.begin(nested=True)
'Rollback the current transaction in progress. If no transaction is in progress, this method is a pass-through. This method rolls back the current transaction or nested transaction regardless of subtransactions being in effect. All subtransactions up to the first real transaction are closed. Subtransactions occur whe...
def rollback(self):
if (self.transaction is None): pass else: self.transaction.rollback()
'Flush pending changes and commit the current transaction. If no transaction is in progress, this method raises an :exc:`~sqlalchemy.exc.InvalidRequestError`. By default, the :class:`.Session` also expires all database loaded state on all ORM-managed attributes after transaction commit. This so that subsequent operatio...
def commit(self):
if (self.transaction is None): if (not self.autocommit): self.begin() else: raise sa_exc.InvalidRequestError('No transaction is begun.') self.transaction.commit()
'Prepare the current transaction in progress for two phase commit. If no transaction is in progress, this method raises an :exc:`~sqlalchemy.exc.InvalidRequestError`. Only root transactions of two phase sessions can be prepared. If the current transaction is not such, an :exc:`~sqlalchemy.exc.InvalidRequestError` is ra...
def prepare(self):
if (self.transaction is None): if (not self.autocommit): self.begin() else: raise sa_exc.InvalidRequestError('No transaction is begun.') self.transaction.prepare()
'Return a :class:`.Connection` object corresponding to this :class:`.Session` object\'s transactional state. If this :class:`.Session` is configured with ``autocommit=False``, either the :class:`.Connection` corresponding to the current transaction is returned, or if no transaction is in progress, a new one is begun an...
def connection(self, mapper=None, clause=None, bind=None, close_with_result=False, **kw):
if (bind is None): bind = self.get_bind(mapper, clause=clause, **kw) return self._connection_for_bind(bind, close_with_result=close_with_result)
'Execute a SQL expression construct or string statement within the current transaction. Returns a :class:`.ResultProxy` representing results of the statement execution, in the same manner as that of an :class:`.Engine` or :class:`.Connection`. E.g.:: result = session.execute( user_table.select().where(user_table.c.id =...
def execute(self, clause, params=None, mapper=None, bind=None, **kw):
clause = expression._literal_as_text(clause) if (bind is None): bind = self.get_bind(mapper, clause=clause, **kw) return self._connection_for_bind(bind, close_with_result=True).execute(clause, (params or {}))
'Like :meth:`~.Session.execute` but return a scalar result.'
def scalar(self, clause, params=None, mapper=None, bind=None, **kw):
return self.execute(clause, params=params, mapper=mapper, bind=bind, **kw).scalar()
'Close this Session. This clears all items and ends any transaction in progress. If this session were created with ``autocommit=False``, a new transaction is immediately begun. Note that this new transaction does not use any connection resources until they are first needed.'
def close(self):
self.expunge_all() if (self.transaction is not None): for transaction in self.transaction._iterate_parents(): transaction.close()
'Remove all object instances from this ``Session``. This is equivalent to calling ``expunge(obj)`` on all objects in this ``Session``.'
def expunge_all(self):
for state in (self.identity_map.all_states() + list(self._new)): state._detach() self.identity_map = self._identity_cls() self._new = {} self._deleted = {}
'Bind operations for a mapper to a Connectable. mapper A mapper instance or mapped class bind Any Connectable: a ``Engine`` or ``Connection``. All subsequent operations involving this mapper will use the given `bind`.'
def bind_mapper(self, mapper, bind):
if isinstance(mapper, type): mapper = class_mapper(mapper) self.__binds[mapper.base_mapper] = bind for t in mapper._all_tables: self.__binds[t] = bind
'Bind operations on a Table to a Connectable. table A ``Table`` instance bind Any Connectable: a ``Engine`` or ``Connection``. All subsequent operations involving this ``Table`` will use the given `bind`.'
def bind_table(self, table, bind):
self.__binds[table] = bind
'Return a "bind" to which this :class:`.Session` is bound. The "bind" is usually an instance of :class:`.Engine`, except in the case where the :class:`.Session` has been explicitly bound directly to a :class:`.Connection`. For a multiply-bound or unbound :class:`.Session`, the ``mapper`` or ``clause`` arguments are use...
def get_bind(self, mapper=None, clause=None):
if (mapper is clause is None): if self.bind: return self.bind else: raise sa_exc.UnboundExecutionError('This session is not bound to a single Engine or Connection, and no context was provided to locate a binding.') ...
'Return a new ``Query`` object corresponding to this ``Session``.'
def query(self, *entities, **kwargs):
return self._query_cls(entities, self, **kwargs)
'Return a context manager that disables autoflush. e.g.:: with session.no_autoflush: some_object = SomeClass() session.add(some_object) # won\'t autoflush some_object.related_thing = session.query(SomeRelated).first() Operations that proceed within the ``with:`` block will not be subject to flushes occurring upon query...
@property @util.contextmanager def no_autoflush(self):
autoflush = self.autoflush self.autoflush = False (yield self) self.autoflush = autoflush
'Expire and refresh the attributes on the given instance. A query will be issued to the database and all attributes will be refreshed with their current database value. Lazy-loaded relational attributes will remain lazily loaded, so that the instance-wide refresh operation will be followed immediately by the lazy load ...
def refresh(self, instance, attribute_names=None, lockmode=None):
try: state = attributes.instance_state(instance) except exc.NO_STATE: raise exc.UnmappedInstanceError(instance) self._expire_state(state, attribute_names) if (loading.load_on_ident(self.query(object_mapper(instance)), state.key, refresh_state=state, lockmode=lockmode, only_load_props=att...
'Expires all persistent instances within this Session. When any attributes on a persistent instance is next accessed, a query will be issued using the :class:`.Session` object\'s current transactional context in order to load all expired attributes for the given instance. Note that a highly isolated transaction will ...
def expire_all(self):
for state in self.identity_map.all_states(): state._expire(state.dict, self.identity_map._modified)
'Expire the attributes on an instance. Marks the attributes of an instance as out of date. When an expired attribute is next accessed, a query will be issued to the :class:`.Session` object\'s current transactional context in order to load all expired attributes for the given instance. Note that a highly isolated tra...
def expire(self, instance, attribute_names=None):
try: state = attributes.instance_state(instance) except exc.NO_STATE: raise exc.UnmappedInstanceError(instance) self._expire_state(state, attribute_names)
'Expire a state if persistent, else expunge if pending'
def _conditional_expire(self, state):
if state.key: state._expire(state.dict, self.identity_map._modified) elif (state in self._new): self._new.pop(state) state._detach()
'Remove unreferenced instances cached in the identity map. Note that this method is only meaningful if "weak_identity_map" is set to False. The default weak identity map is self-pruning. Removes any object in this Session\'s identity map that is not referenced in user code, modified, new or scheduled for deletion. Ret...
@util.deprecated('0.7', 'The non-weak-referencing identity map feature is no longer needed.') def prune(self):
return self.identity_map.prune()