The mapper package provides object-relational functionality, building upon the schema and sql packages and tying operations to class properties and constructors.
Create a BackRef object with explicit arguments, which are the same arguments one can send to relation().
Used with the backref keyword argument to relation() in place of a string argument.
Given a class and optional entity_name, return the primary Mapper associated with the key.
If no mapper can be located, raises InvalidRequestError.
Remove all mappers that have been created thus far.
The mapped classes will return to their initial "unmapped" state and can be re-mapped with new mappers.
Provide a column-level property for use with a Mapper.
Column-based properties can normally be applied to the mapper's properties dictionary using the schema.Column element directly. Use this function when the given column is not directly present within the mapper's selectable; examples include SQL expressions, functions, and scalar SELECT queries.
Columns that arent present in the mapper's selectable won't be persisted by the mapper and are effectively "read-only" attributes.
- *cols
- list of Column objects to be mapped.
- group
- a group name for this property when marked as deferred.
- deferred
- when True, the column property is "deferred", meaning that it does not load immediately, and is instead loaded when the attribute is first accessed on an instance. See also deferred().
Compile all mappers that have been defined.
This is equivalent to calling compile() on any individual mapper.
Return a composite column-based property for use with a Mapper.
This is very much like a column-based property except the given class is used to represent "composite" values composed of one or more columns.
The class must implement a constructor with positional arguments matching the order of columns supplied here, as well as a __composite_values__() method which returns values in the same order.
A simple example is representing separate two columns in a table as a single, first-class "Point" object:
class Point(object): def __init__(self, x, y): self.x = x self.y = y def __composite_values__(self): return (self.x, self.y) # and then in the mapping: ... composite(Point, mytable.c.x, mytable.c.y) ...
Arguments are:
Return a MapperOption that will indicate to the query that the main table has been aliased.
alias is the string name or Alias object representing the alias.
Return a MapperOption that will indicate to the query that the given attribute will be eagerly loaded.
Used when feeding SQL result sets directly into query.instances(). Also bundles an EagerLazyOption to turn on eager loading in case it isnt already.
alias is the string name of an alias, or an sql.Alias object, which represents the aliased columns in the query. This argument is optional.
decorator is mutually exclusive of alias and is a row-processing function which will be applied to the incoming row before sending to the eager load handler. use this for more sophisticated row adjustments beyond a straight alias.
create a new Session.
The session by default does not begin a transaction, and requires that flush() be called explicitly in order to persist results to the database.
It is recommended to use the sessionmaker() function instead of create_session().
Return a MapperOption that will convert the column property of the given name into a deferred load.
Used with query.options()
Return a DeferredColumnProperty, which indicates this object attributes should only be loaded from its corresponding table column when first accessed.
Used with the properties dictionary sent to mapper().
construct a dynamically-loading mapper property.
This property is similar to relation(), except read operations return an active Query object, which reads from the database in all cases. Items may be appended to the attribute via append(), or removed via remove(); changes will be persisted to the database during a flush(). However, no other list mutation operations are available.
A subset of arguments available to relation() are available here.
Return a MapperOption that will convert the property of the given name into an eager load.
Used with query.options().
Return a MapperOption that will convert all properties along the given dot-separated path into an eager load.
For example, this:
query.options(eagerload_all('orders.items.keywords'))...
will set all of 'orders', 'orders.items', and 'orders.items.keywords' to load in one eager load.
Used with query.options().
Return a MapperOption that will insert the given MapperExtension to the beginning of the list of extensions that will be called in the context of the Query.
Used with query.options().
Return a MapperOption that will convert the property of the given name into a lazy load.
Used with query.options().
Return a new Mapper object.
Return a MapperOption that will convert the property of the given name into a non-load.
Used with query.options().
Given an object, return the primary Mapper associated with the object instance.
Create a UNION statement used by a polymorphic mapper.
See the SQLAlchemy advanced mapping docs for an example of how this is used.
Provide a relationship of a primary Mapper to a secondary Mapper.
This corresponds to a parent-child or associative table relationship. The constructed class is an instance of PropertyLoader.
- argument
- a class or Mapper instance, representing the target of the relation.
- secondary
- for a many-to-many relationship, specifies the intermediary table. The secondary keyword argument should generally only be used for a table that is not otherwise expressed in any class mapping. In particular, using the Association Object Pattern is generally mutually exclusive against using the secondary keyword argument.
**kwargs follow:
- association
- Deprecated; as of version 0.3.0 the association keyword is synonomous with applying the "all, delete-orphan" cascade to a "one-to-many" relationship. SA can now automatically reconcile a "delete" and "insert" operation of two objects with the same "identity" in a flush() operation into a single "update" statement, which is the pattern that "association" used to indicate.
- backref
- indicates the name of a property to be placed on the related mapper's class that will handle this relationship in the other direction, including synchronizing the object attributes on both sides of the relation. Can also point to a backref() construct for more configurability.
- cascade
- a string list of cascade rules which determines how persistence operations should be "cascaded" from parent to child.
- collection_class
- a class or function that returns a new list-holding object. will be used in place of a plain list for storing elements.
- foreign_keys
- a list of columns which are to be used as "foreign key" columns. this parameter should be used in conjunction with explicit primaryjoin and secondaryjoin (if needed) arguments, and the columns within the foreign_keys list should be present within those join conditions. Normally, relation() will inspect the columns within the join conditions to determine which columns are the "foreign key" columns, based on information in the Table metadata. Use this argument when no ForeignKey's are present in the join condition, or to override the table-defined foreign keys.
- foreignkey
- deprecated. use the foreign_keys argument for foreign key specification, or remote_side for "directional" logic.
- join_depth=None
- when non-None, an integer value indicating how many levels deep eagerload joins should be constructed on a self-referring or cyclical relationship. The number counts how many times the same Mapper shall be present in the loading condition along a particular join branch. When left at its default of None, eager loads will automatically stop chaining joins when they encounter a mapper which is already higher up in the chain.
- lazy=(True|False|None|'dynamic')
specifies how the related items should be loaded. Values include:
- True - items should be loaded lazily when the property is first
- accessed.
- False - items should be loaded "eagerly" in the same query as that
- of the parent, using a JOIN or LEFT OUTER JOIN.
- None - no loading should occur at any time. This is to support
- "write-only" attrbitutes, or attributes which are populated in some manner specific to the application.
- 'dynamic' - a DynaLoader will be attached, which returns a
- Query object for all read operations. The dynamic- collection supports only append() and remove() for write operations; changes to the dynamic property will not be visible until the data is flushed to the database.
- order_by
- indicates the ordering that should be applied when loading these items.
- passive_deletes=False
Indicates the behavior of delete operations. A value of True indicates that unloaded child items should not be loaded during a delete operation on the parent. Normally, when a parent item is deleted, all child items are loaded so that they can either be marked as deleted, or have their foreign key to the parent set to NULL. Marking this flag as True usually implies an ON DELETE <CASCADE|SET NULL> rule is in place which will handle updating/deleting child rows on the database side.
Additionally, setting the flag to the string value 'all' will disable the "nulling out" of the child foreign keys, when there is no delete or delete-orphan cascade enabled. This is typically used when a triggering or error raise scenario is in place on the database side. Note that the foreign key attributes on in-session child objects will not be changed after a flush occurs so this is a very special use-case setting.
- post_update
- this indicates that the relationship should be handled by a second UPDATE statement after an INSERT or before a DELETE. Currently, it also will issue an UPDATE after the instance was UPDATEd as well, although this technically should be improved. This flag is used to handle saving bi-directional dependencies between two individual rows (i.e. each row references the other), where it would otherwise be impossible to INSERT or DELETE both rows fully since one row exists before the other. Use this flag when a particular mapping arrangement will incur two rows that are dependent on each other, such as a table that has a one-to-many relationship to a set of child rows, and also has a column that references a single child row within that list (i.e. both tables contain a foreign key to each other). If a flush() operation returns an error that a "cyclical dependency" was detected, this is a cue that you might want to use post_update to "break" the cycle.
- primaryjoin
- a ClauseElement that will be used as the primary join of this child object against the parent object, or in a many-to-many relationship the join of the primary object to the association table. By default, this value is computed based on the foreign key relationships of the parent and child tables (or association table).
- private=False
- deprecated. setting private=True is the equivalent of setting cascade="all, delete-orphan", and indicates the lifecycle of child objects should be contained within that of the parent.
- remote_side
- used for self-referential relationships, indicates the column or list of columns that form the "remote side" of the relationship.
- secondaryjoin
- a ClauseElement that will be used as the join of an association table to the child object. By default, this value is computed based on the foreign key relationships of the association and child tables.
- uselist=(True|False)
- a boolean that indicates if this property should be loaded as a list or a scalar. In most cases, this value is determined automatically by relation(), based on the type and direction of the relationship - one to many forms a list, many to one forms a scalar, many to many is a list. If a scalar is desired where normally a list would be present, such as a bi-directional one-to-one relationship, set uselist to False.
- viewonly=False
- when set to True, the relation is used only for loading objects within the relationship, and has no effect on the unit-of-work flush process. Relations with viewonly can specify any kind of join conditions to provide additional views of related objects onto a parent object. Note that the functionality of a viewonly relationship has its limits - complicated join conditions may not compile into eager or lazy loaders properly. If this is the case, use an alternative method.
Provides thread-local management of Sessions.
This is a front-end function to the ScopedSession class.
Usage:
Session = scoped_session(sessionmaker(autoflush=True))
To instantiate a Session object which is part of the scoped context, instantiate normally:
session = Session()
Most session methods are available as classmethods from the scoped session:
Session.commit() Session.close()
To map classes so that new instances are saved in the current Session automatically, as well as to provide session-aware class attributes such as "query", use the mapper classmethod from the scoped session:
mapper = Session.mapper mapper(Class, table, ...)
Generate a custom-configured Session class.
The returned object is a subclass of Session, which, when instantiated with no arguments, uses the keyword arguments configured here as its constructor arguments. It is intended that the sessionmaker() function be called within the global scope of an application, and the returned class be made available to the rest of the application as the single class used to instantiate sessions.
e.g.:
# global scope Session = sessionmaker(autoflush=False) # later, in a local scope, create and use a session: sess = Session()
Any keyword arguments sent to the constructor itself will override the "configured" keywords:
Session = sessionmaker() # bind an individual session to a connection sess = Session(bind=connection)
The class also includes a special classmethod configure(), which allows additional configurational options to take place after the custom Session class has been generated. This is useful particularly for defining the specific Engine (or engines) to which new instances of Session should be bound:
Session = sessionmaker() Session.configure(bind=create_engine('sqlite:///foo.db')) sess = Session()
The function features a single keyword argument of its own, class_, which may be used to specify an alternate class other than sqlalchemy.orm.session.Session which should be used by the returned class. All other keyword arguments sent to sessionmaker() are passed through to the instantiated Session() object.
Set up name as a synonym to another MapperProperty.
Used with the properties dictionary sent to mapper().
Base implementation for customizing Mapper behavior.
For each method in MapperExtension, returning a result of EXT_CONTINUE will allow processing to continue to the next MapperExtension in line or use the default functionality if there are no other extensions.
Returning EXT_STOP will halt processing of further extensions handling that method. Some methods such as load have other return requirements, see the individual documentation for details. Other than these exception cases, any return value other than EXT_CONTINUE or EXT_STOP will be interpreted as equivalent to EXT_STOP.
EXT_PASS is a synonym for EXT_CONTINUE and is provided for backward compatibility.
Receive an object instance after that instance is DELETEed.
Receive an object instance after that instance is INSERTed.
Receive an object instance after that instance is UPDATEed.
Receive an object instance before that instance is appended to a result list.
If this method returns EXT_CONTINUE, result appending will proceed normally. if this method returns any other value or None, result appending will not proceed for this instance, giving this extension an opportunity to do the appending itself, if desired.
Receive an object instance before that instance is DELETEed.
Note that no changes to the overall flush plan can be made here; this means any collection modification, save() or delete() operations which occur within this method will not take effect until the next flush call.
Receive an object instance before that instance is INSERTed into its table.
This is a good place to set up primary key values and such that aren't handled otherwise.
Column-based attributes can be modified within this method which will result in the new value being inserted. However no changes to the overall flush plan can be made; this means any collection modification or save() operations which occur within this method will not take effect until the next flush call.
Receive an object instance before that instance is UPDATEed.
Note that this method is called for all instances that are marked as "dirty", even those which have no net changes to their column-based attributes. An object is marked as dirty when any of its column-based attributes have a "set attribute" operation called or when any of its collections are modified. If, at update time, no column-based attributes have any net changes, no UPDATE statement will be issued. This means that an instance being sent to before_update is not a guarantee that an UPDATE statement will be issued (although you can affect the outcome here).
To detect if the column-based attributes on the object have net changes, and will therefore generate an UPDATE statement, use object_session(instance).is_modified(instance, include_collections=False).
Column-based attributes can be modified within this method which will result in their being updated. However no changes to the overall flush plan can be made; this means any collection modification or save() operations which occur within this method will not take effect until the next flush call.
Receive a row when a new object instance is about to be created from that row.
The method can choose to create the instance itself, or it can return None to indicate normal object creation should take place.
Override the get method of the Query object.
The return value of this method is used as the result of query.get() if the value is anything other than EXT_CONTINUE.
Override the get_by method of the Query object.
The return value of this method is used as the result of query.get_by() if the value is anything other than EXT_CONTINUE.
DEPRECATED.
Retrieve a contextual Session instance with which to register a new object.
Note: this is not called if a session is provided with the __init__ params (i.e. _sa_session).
Override the load method of the Query object.
The return value of this method is used as the result of query.load() if the value is anything other than EXT_CONTINUE.
Receive a newly-created instance before that instance has its attributes populated.
The normal population of attributes is according to each attribute's corresponding MapperProperty (which includes column-based attributes as well as relationships to other classes). If this method returns EXT_CONTINUE, instance population will proceed normally. If any other value or None is returned, instance population will not proceed, giving this extension an opportunity to populate the instance itself, if desired.
Override the select method of the Query object.
The return value of this method is used as the result of query.select() if the value is anything other than EXT_CONTINUE.
DEPRECATED.
Override the select_by method of the Query object.
The return value of this method is used as the result of query.select_by() if the value is anything other than EXT_CONTINUE.
DEPRECATED.
Perform pre-processing on the given result row and return a new row instance.
This is called as the very first step in the _instance() method.
defines comparison operations for MapperProperty objects
return true if this collection contains any member that meets the given criterion.
return true if this element references a member which meets the given criterion.
Encapsulates the object-fetching operations provided by Mappers.
add a SQL ColumnElement to the list of result columns to be returned.
This will have the effect of all result-returning methods returning a tuple of results, the first element being an instance of the primary class for this Query, and subsequent elements matching columns or entities which were specified via add_column or add_entity.
When adding columns to the result, its generally desireable to add limiting criterion to the query which can associate the primary entity of this Query along with the additional columns, if the column is based on a table or selectable that is not the primary mapped selectable. The Query selects from all tables with no joining criterion by default.
- column
- a string column name or sql.ColumnElement to be added to the results.
add a mapped entity to the list of result columns to be returned.
This will have the effect of all result-returning methods returning a tuple of results, the first element being an instance of the primary class for this Query, and subsequent elements matching columns or entities which were specified via add_column or add_entity.
When adding entities to the result, its generally desireable to add limiting criterion to the query which can associate the primary entity of this Query along with the additional entities. The Query selects from all tables with no joining criterion by default.
- entity
- a class or mapper which will be added to the results.
- alias
- a sqlalchemy.sql.Alias object which will be used to select rows. this will match the usage of the given Alias in filter(), order_by(), etc. expressions
- id
- a string ID matching that given to query.join() or query.outerjoin(); rows will be selected from the aliased join created via those methods.
Return the results represented by this Query as a list.
This results in an execution of the underlying query.
apply the SQL avg() function against the given column to the query and return the newly resulting Query.
apply the SQL max() function against the given column to the query and return the newly resulting Query.
apply the SQL min() function against the given column to the query and return the newly resulting Query.
apply the SQL sum() function against the given column to the query and return the newly resulting Query.
compiles and returns a SQL statement based on the criterion and conditions within this Query.
Apply this query's criterion to a SELECT COUNT statement.
the whereclause, params and **kwargs arguments are deprecated. use filter() and other generative methods to establish modifiers.
apply the given filtering criterion to the query and return the newly resulting Query
the criterion is any sql.ClauseElement applicable to the WHERE clause of a select.
apply the given filtering criterion to the query and return the newly resulting Query.
Return the first result of this Query or None if the result doesn't contain any row.
This results in an execution of the underlying query.
Return an instance of the object based on the given identifier, or None if not found.
The ident argument is a scalar or tuple of primary key column values in the order of the table def's primary key columns.
apply one or more GROUP BY criterion to the query and return the newly resulting Query
apply a HAVING criterion to the quer and return the newly resulting Query.
Return a list of mapped instances corresponding to the rows in a given cursor (i.e. ResultProxy).
The *mappers_or_columns and **kwargs arguments are deprecated. To add instances or columns to the results, use add_entity() and add_column().
create a join of this Query object's criterion to a relationship and return the newly resulting Query.
'prop' may be a string property name or a list of string property names.
Return an instance of the object based on the given identifier.
If not found, raises an exception. The method will remove all pending changes to the object already existing in the Session. The ident argument is a scalar or tuple of primary key column values in the order of the table def's primary key columns.
Return the first result of this Query, raising an exception if more than one row exists.
This results in an execution of the underlying query.
apply one or more ORDER BY criterion to the query and return the newly resulting Query
create a left outer join of this Query object's criterion to a relationship and return the newly resulting Query.
'prop' may be a string property name or a list of string property names.
add values for bind parameters which may have been specified in filter().
parameters may be specified using **kwargs, or optionally a single dictionary as the first positional argument. The reason for both is that **kwargs is convenient, however some parameter dictionaries contain unicode keys in which case **kwargs cannot be used.
return a Query that will refresh all instances loaded.
this includes all entities accessed from the database, including secondary entities, eagerly-loaded collection items.
All changes present on entities which are already present in the session will be reset and the entities will all be marked "clean".
This is essentially the en-masse version of load().
return a newly constructed Query object, with criterion corresponding to a relationship to the given parent instance.
- instance
- a persistent or detached instance which is related to class represented by this query.
- property
- string name of the property which relates this query's class to the instance.
- **kwargs
- all extra keyword arguments are propigated to the constructor of Query.
return a new Query reset the 'joinpoint' of this Query reset back to the starting mapper. Subsequent generative calls will be constructed from the new joinpoint.
Note that each call to join() or outerjoin() also starts from the root.
DEPRECATED. use query.filter(whereclause).all(), or query.from_statement(statement).all()
Set the from_obj parameter of the query and return the newly resulting Query.
from_obj is a list of one or more tables.
add a join criterion corresponding to a relationship to the given parent instance.
- instance
- a persistent or detached instance which is related to class represented by this query.
- property
- string name of the property which relates this query's class to the instance. if None, the method will attempt to find a suitable property.
currently, this method only works with immediate parent relationships, but in the future may be enhanced to work across a chain of parent mappers.