module documentation

Undocumented

Class ​Aliased​Class Represents an "aliased" form of a mapped class for usage with Query.
Class ​Aliased​Insp Provide an inspection interface for an .AliasedClass object.
Class ​Bundle A grouping of SQL expressions that are returned by a .Query under one namespace.
Class ​Cascade​Options Keeps track of the options sent to :paramref:`.relationship.cascade`
Function identity​_key Generate "identity key" tuples, as are used as keys in the .Session.identity_map dictionary.
Function was​_deleted Return True if the given object was deleted within a session flush.
Variable all​_cascades Undocumented
Class _​ORMJoin Extend Join to support ORM constructs as input.
Class _​Wrap​User​Entity A wrapper used within the loader_criteria lambda caller so that we can bypass declared_attr descriptors on unmapped mixins, which normally emit a warning for such use.
Class ​Loader​Criteria​Option Add additional WHERE criteria to the load for all occurrences of a particular entity.
Class ​ORMAdapter ColumnAdapter subclass which excludes adaptation of entities from non-matching mappers.
Function ​_entity​_corresponds​_to determine if 'given' corresponds to 'entity', in terms of an entity passed to Query that would match the same entity being referred to elsewhere in the query.
Function ​_entity​_corresponds​_to​_use​_path​_impl determine if 'given' corresponds to 'entity', in terms of a path of loader options where a mapped attribute is taken to be a member of a parent entity.
Function ​_entity​_isa determine if 'given' "is a" mapper, in terms of the given would load rows of type 'mapper'.
Function ​_getitem calculate __getitem__ in terms of an iterable query object that also has a slice() method.
Function ​_orm​_annotate Deep copy the given ClauseElement, annotating each element with the "_orm_adapt" flag.
Function ​_orm​_deannotate Remove annotations that link a column to a particular mapping.
Function ​_orm​_full​_deannotate Undocumented
Function ​_validator​_events Runs a validation method on an attribute value to be set or appended.
Function has​_identity Return True if the given object has a database identity.
Function join Produce an inner join between left and right clauses.
Function outerjoin Produce a left outer join between left and right clauses.
Function polymorphic​_union Create a UNION statement used by a polymorphic mapper.
Function randomize​_unitofwork Use random-ordering sets within the unit of work in order to detect unit of work sorting issues.
Function with​_parent No summary
Function with​_polymorphic Produce an .AliasedClass construct which specifies columns for descendant mappers of the given base.
def identity_key(*args, **kwargs):

Generate "identity key" tuples, as are used as keys in the .Session.identity_map dictionary.

This function has several call styles:

  • identity_key(class, ident, identity_token=token)

    This form receives a mapped class and a primary key scalar or tuple as an argument.

    E.g.:

    >>> identity_key(MyClass, (1, 2))
    (<class '__main__.MyClass'>, (1, 2), None)
    
  • identity_key(instance=instance)

    This form will produce the identity key for a given instance. The instance need not be persistent, only that its primary key attributes are populated (else the key will contain None for those missing values).

    E.g.:

    >>> instance = MyClass(1, 2)
    >>> identity_key(instance=instance)
    (<class '__main__.MyClass'>, (1, 2), None)
    

    In this form, the given instance is ultimately run though _orm.Mapper.identity_key_from_instance, which will have the effect of performing a database check for the corresponding row if the object is expired.

  • identity_key(class, row=row, identity_token=token)

    This form is similar to the class/tuple form, except is passed a database result row as a .Row object.

    E.g.:

    >>> row = engine.execute(\
        text("select * from table where a=1 and b=2")\
        ).first()
    >>> identity_key(MyClass, row=row)
    (<class '__main__.MyClass'>, (1, 2), None)
    
Parameters
*argsUndocumented
**kwargsUndocumented
classmapped class (must be a positional argument)
identprimary key, may be a scalar or tuple argument.
identity​_token

optional identity token

New in version 1.2: added identity_token
instanceobject instance (must be given as a keyword arg)
row.Row row returned by a _engine.CursorResult (must be given as a keyword arg)
def was_deleted(object_):

Return True if the given object was deleted within a session flush.

This is regardless of whether or not the object is persistent or detached.

See Also

.InstanceState.was_deleted

all_cascades =

Undocumented

def _entity_corresponds_to(given, entity):
determine if 'given' corresponds to 'entity', in terms of an entity passed to Query that would match the same entity being referred to elsewhere in the query.
def _entity_corresponds_to_use_path_impl(given, entity):

determine if 'given' corresponds to 'entity', in terms of a path of loader options where a mapped attribute is taken to be a member of a parent entity.

e.g.:

someoption(A).someoption(A.b)  # -> fn(A, A) -> True
someoption(A).someoption(C.d)  # -> fn(A, C) -> False

a1 = aliased(A)
someoption(a1).someoption(A.b) # -> fn(a1, A) -> False
someoption(a1).someoption(a1.b) # -> fn(a1, a1) -> True

wp = with_polymorphic(A, [A1, A2])
someoption(wp).someoption(A1.foo)  # -> fn(wp, A1) -> False
someoption(wp).someoption(wp.A1.foo)  # -> fn(wp, wp.A1) -> True
def _entity_isa(given, mapper):
determine if 'given' "is a" mapper, in terms of the given would load rows of type 'mapper'.
def _getitem(iterable_query, item, allow_negative):
calculate __getitem__ in terms of an iterable query object that also has a slice() method.
def _orm_annotate(element, exclude=None):

Deep copy the given ClauseElement, annotating each element with the "_orm_adapt" flag.

Elements within the exclude collection will be cloned but not annotated.

def _orm_deannotate(element):

Remove annotations that link a column to a particular mapping.

Note this doesn't affect "remote" and "foreign" annotations passed by the _orm.foreign and _orm.remote annotators.

def _orm_full_deannotate(element):

Undocumented

def _validator_events(desc, key, validator, include_removes, include_backrefs):
Runs a validation method on an attribute value to be set or appended.
def has_identity(object_):

Return True if the given object has a database identity.

This typically corresponds to the object being in either the persistent or detached state.

See Also

.was_deleted

def join(left, right, onclause=None, isouter=False, full=False, join_to_left=None):

Produce an inner join between left and right clauses.

_orm.join is an extension to the core join interface provided by _expression.join(), where the left and right selectables may be not only core selectable objects such as _schema.Table, but also mapped classes or .AliasedClass instances. The "on" clause can be a SQL expression, or an attribute or string name referencing a configured _orm.relationship.

_orm.join is not commonly needed in modern usage, as its functionality is encapsulated within that of the _query.Query.join method, which features a significant amount of automation beyond _orm.join by itself. Explicit usage of _orm.join with _query.Query involves usage of the _query.Query.select_from method, as in:

from sqlalchemy.orm import join
session.query(User).\
    select_from(join(User, Address, User.addresses)).\
    filter(Address.email_address=='foo@bar.com')

In modern SQLAlchemy the above join can be written more succinctly as:

session.query(User).\
        join(User.addresses).\
        filter(Address.email_address=='foo@bar.com')

See _query.Query.join for information on modern usage of ORM level joins.

Deprecated since version 0.8: the join_to_left parameter is deprecated, and will be removed in a future release. The parameter has no effect.
def outerjoin(left, right, onclause=None, full=False, join_to_left=None):

Produce a left outer join between left and right clauses.

This is the "outer join" version of the _orm.join function, featuring the same behavior except that an OUTER JOIN is generated. See that function's documentation for other usage details.

def polymorphic_union(table_map, typecolname, aliasname='p_union', cast_nulls=True):

Create a UNION statement used by a polymorphic mapper.

See :ref:`concrete_inheritance` for an example of how this is used.

Parameters
table​_mapmapping of polymorphic identities to _schema.Table objects.
typecolnamestring name of a "discriminator" column, which will be derived from the query, producing the polymorphic identity for each row. If None, no polymorphic discriminator is generated.
aliasnamename of the ~sqlalchemy.sql.expression.alias() construct generated.
cast​_nullsif True, non-existent columns, which are represented as labeled NULLs, will be passed into CAST. This is a legacy behavior that is problematic on some backends such as Oracle - in which case it can be set to False.
def randomize_unitofwork():

Use random-ordering sets within the unit of work in order to detect unit of work sorting issues.

This is a utility function that can be used to help reproduce inconsistent unit of work sorting issues. For example, if two kinds of objects A and B are being inserted, and B has a foreign key reference to A - the A must be inserted first. However, if there is no relationship between A and B, the unit of work won't know to perform this sorting, and an operation may or may not fail, depending on how the ordering works out. Since Python sets and dictionaries have non-deterministic ordering, such an issue may occur on some runs and not on others, and in practice it tends to have a great dependence on the state of the interpreter. This leads to so-called "heisenbugs" where changing entirely irrelevant aspects of the test program still cause the failure behavior to change.

By calling randomize_unitofwork() when a script first runs, the ordering of a key series of sets within the unit of work implementation are randomized, so that the script can be minimized down to the fundamental mapping and operation that's failing, while still reproducing the issue on at least some runs.

This utility is also available when running the test suite via the --reversetop flag.

def with_parent(instance, prop, from_entity=None):

Create filtering criterion that relates this query's primary entity to the given related instance, using established _orm.relationship() configuration.

E.g.:

stmt = select(Address).where(with_parent(some_user, User.addresses))

The SQL rendered is the same as that rendered when a lazy loader would fire off from the given parent on that attribute, meaning that the appropriate state is taken from the parent object in Python without the need to render joins to the parent table in the rendered statement.

The given property may also make use of _orm.PropComparator.of_type to indicate the left side of the criteria:

a1 = aliased(Address)
a2 = aliased(Address)
stmt = select(a1, a2).where(
    with_parent(u1, User.addresses.of_type(a2))
)

The above use is equivalent to using the _orm.with_parent.from_entity argument:

a1 = aliased(Address)
a2 = aliased(Address)
stmt = select(a1, a2).where(
    with_parent(u1, User.addresses, from_entity=a2)
)
Parameters
instanceAn instance which has some _orm.relationship.
propUndocumented
from​_entity

Entity in which to consider as the left side. This defaults to the "zero" entity of the _query.Query itself.

New in version 1.2.
property

String property name, or class-bound attribute, which indicates what relationship from the instance should be used to reconcile the parent/child relationship.

Deprecated since version 1.4: Using strings is deprecated and will be removed in SQLAlchemy 2.0. Please use the class-bound attribute directly.
def with_polymorphic(base, classes, selectable=False, flat=False, polymorphic_on=None, aliased=False, innerjoin=False, _use_mapper_path=False, _existing_alias=None):

Produce an .AliasedClass construct which specifies columns for descendant mappers of the given base.

Using this method will ensure that each descendant mapper's tables are included in the FROM clause, and will allow filter() criterion to be used against those tables. The resulting instances will also have those columns already loaded so that no "post fetch" of those columns will be required.

See Also

:ref:`with_polymorphic` - full discussion of _orm.with_polymorphic.

Parameters
baseBase class to be aliased.
classesa single class or mapper, or list of class/mappers, which inherit from the base class. Alternatively, it may also be the string '*', in which case all descending mapped classes will be added to the FROM clause.
selectable

a table or subquery that will be used in place of the generated FROM clause. This argument is required if any of the desired classes use concrete table inheritance, since SQLAlchemy currently cannot generate UNIONs among tables automatically. If used, the selectable argument must represent the full set of tables and columns mapped by every mapped class. Otherwise, the unaccounted mapped columns will result in their table being appended directly to the FROM clause which will usually lead to incorrect results.

When left at its default value of False, the polymorphic selectable assigned to the base mapper is used for selecting rows. However, it may also be passed as None, which will bypass the configured polymorphic selectable and instead construct an ad-hoc selectable for the target classes given; for joined table inheritance this will be a join that includes all target mappers and their subclasses.

flatBoolean, will be passed through to the _expression.FromClause.alias call so that aliases of _expression.Join objects will alias the individual tables inside the join, rather than creating a subquery. This is generally supported by all modern databases with regards to right-nested joins and generally produces more efficient queries. Setting this flag is recommended as long as the resulting SQL is functional.
polymorphic​_ona column to be used as the "discriminator" column for the given selectable. If not given, the polymorphic_on attribute of the base classes' mapper will be used, if any. This is useful for mappings that don't have polymorphic loading behavior by default.
aliasedwhen True, the selectable will be aliased. For a JOIN, this means the JOIN will be SELECTed from inside of a subquery unless the :paramref:`_orm.with_polymorphic.flat` flag is set to True, which is recommended for simpler use cases.
innerjoinif True, an INNER JOIN will be used. This should only be specified if querying for one specific subtype only
​_use​_mapper​_pathUndocumented
​_existing​_aliasUndocumented