SQLAlchemy 0.3 Documentation - module sqlalchemy.orm.mapper

# SQLAlchemy 0.3 Documentation

Multiple Pages | One Page
Version: 0.3.7 Last Updated: 04/30/07 00:08:52

### module sqlalchemy.orm.mapper

### Module Functions

def class_mapper(class_, entity_name=None, compile=True)

Given a class and optional entity_name, return the primary Mapper associated with the key.

If no mapper can be located, raises `InvalidRequestError`.

def object_mapper(object, entity_name=None, raiseerror=True)

Given an object, return the primary Mapper associated with the object instance.

object
  The object instance.
entity_name
  Entity name of the mapper to retrieve, if the given instance is transient. Otherwise uses the entity name already associated with the instance.
raiseerror
  Defaults to True: raise an `InvalidRequestError` if no mapper can be located. If False, return None.

### class MapperExtension(object)

Base implementation for an object that provides overriding behavior to various Mapper functions. For each method in MapperExtension, a result of EXT_PASS indicates the functionality is not overridden.

def after_delete(self, mapper, connection, instance)

Receive an object instance after that instance is DELETEed.

def after_insert(self, mapper, connection, instance)

Receive an object instance after that instance is INSERTed.

def after_update(self, mapper, connection, instance)

Receive an object instance after that instance is UPDATEed.

def append_result(self, mapper, selectcontext, row, instance, identitykey, result, isnew)

Receive an object instance before that instance is appended to a result list.

If this method returns EXT_PASS, 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.

mapper
  The mapper doing the operation.
selectcontext
  SelectionContext corresponding to the instances() call.
row
  The result row from the database.
instance
  The object instance to be appended to the result.
identitykey
  The identity key of the instance.
result
  List to which results are being appended.
isnew
  Indicates if this is the first time we have seen this object instance in the current result set. if you are selecting from a join, such as an eager load, you might see the same object instance many times in the same result set.

def before_delete(self, mapper, connection, instance)

Receive an object instance before that instance is DELETEed.

def before_insert(self, mapper, connection, instance)

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.

def before_update(self, mapper, connection, instance)

Receive an object instance before that instance is UPDATEed.

def create_instance(self, mapper, selectcontext, row, class_)

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.

mapper
  The mapper doing the operation
selectcontext
  SelectionContext corresponding to the instances() call
row
  The result row from the database
class_
  The class we are mapping.

def get(self, query, *args, **kwargs)

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_PASS.

def get_by(self, query, *args, **kwargs)

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_PASS.

def get_session(self)

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).

def load(self, query, *args, **kwargs)

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_PASS.

def populate_instance(self, mapper, selectcontext, row, instance, identitykey, isnew)

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_PASS, 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.

def select(self, query, *args, **kwargs)

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_PASS.

def select_by(self, query, *args, **kwargs)

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_PASS.

def translate_row(self, mapper, context, row)

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.

back to section top

### class Mapper(object)

Define the correlation of class attributes to database table columns.

Instances of this class should be constructed via the `sqlalchemy.orm.mapper()` function.

def __init__(self, class_, local_table, properties=None, primary_key=None, non_primary=False, inherits=None, inherit_condition=None, extension=None, order_by=False, allow_column_override=False, entity_name=None, always_refresh=False, version_id_col=None, polymorphic_on=None, _polymorphic_map=None, polymorphic_identity=None, concrete=False, select_table=None, allow_null_pks=False, batch=True, column_prefix=None)

Construct a new mapper.

All arguments may be sent to the `sqlalchemy.orm.mapper()` function where they are passed through to here.

class_
  The class to be mapped.
local_table
  The table to which the class is mapped, or None if this mapper inherits from another mapper using concrete table inheritance.
properties
  A dictionary mapping the string names of object attributes to `MapperProperty` instances, which define the persistence behavior of that attribute. Note that the columns in the mapped table are automatically converted into `ColumnProperty` instances based on the key property of each `Column` (although they can be overridden using this dictionary).
primary_key
  A list of `Column` objects which define the primary key to be used against this mapper's selectable unit. This is normally simply the primary key of the local_table, but can be overridden here.
non_primary
  Construct a `Mapper` that will define only the selection of instances, not their persistence.
inherits
  Another `Mapper` for which this `Mapper` will have an inheritance relationship with.
inherit_condition
  For joined table inheritance, a SQL expression (constructed `ClauseElement`) which will define how the two tables are joined; defaults to a natural join between the two tables.
extension
  A `MapperExtension` instance or list of `MapperExtension` instances which will be applied to all operations by this `Mapper`.
order_by
  A single `Column` or list of `Columns` for which selection operations should use as the default ordering for entities. Defaults to the OID/ROWID of the table if any, or the first primary key column of the table.
allow_column_override
  If True, allows the usage of a `relation()` which has the same name as a column in the mapped table. The table column will no longer be mapped.
entity_name
  A name to be associated with the class, to allow alternate mappings for a single class.
always_refresh
  If True, all query operations for this mapped class will overwrite all data within object instances that already exist within the session, erasing any in-memory changes with whatever information was loaded from the database.
version_id_col
  A `Column` which must have an integer type that will be used to keep a running version id of mapped entities in the database. this is used during save operations to ensure that no other thread or process has updated the instance during the lifetime of the entity, else a `ConcurrentModificationError` exception is thrown.
polymorphic_on
  Used with mappers in an inheritance relationship, a `Column` which will identify the class/mapper combination to be used with a particular row. requires the polymorphic_identity value to be set for all mappers in the inheritance hierarchy.
_polymorphic_map
  Used internally to propigate the full map of polymorphic identifiers to surrogate mappers.
polymorphic_identity
  A value which will be stored in the Column denoted by polymorphic_on, corresponding to the class identity of this mapper.
concrete
  If True, indicates this mapper should use concrete table inheritance with its parent mapper.
select_table
  A `Table` or (more commonly) `Selectable` which will be used to select instances of this mapper's class. usually used to provide polymorphic loading among several classes in an inheritance hierarchy.
allow_null_pks
  Indicates that composite primary keys where one or more (but not all) columns contain NULL is a valid primary key. Primary keys which contain NULL values usually indicate that a result row does not contain an entity and should be skipped.
batch
  Indicates that save operations of multiple entities can be batched together for efficiency. setting to False indicates that an instance will be fully saved before saving the next instance, which includes inserting/updating all table rows corresponding to the entity as well as calling all `MapperExtension` methods corresponding to the save operation.
column_prefix
  A string which will be prepended to the key name of all Columns when creating column-based properties from the given Table. Does not affect explicitly specified column-based properties

def add_properties(self, dict_of_properties)

Add the given dictionary of properties to this mapper, using add_property.

def add_property(self, key, prop)

Add an indiviual MapperProperty to this mapper.

If the mapper has not been compiled yet, just adds the property to the initial properties dictionary sent to the constructor. If this Mapper has already been compiled, then the given MapperProperty is compiled immediately.

def base_mapper(self)

Return the ultimate base mapper in an inheritance chain.

def canload(self, instance)

return true if this mapper is capable of loading the given instance

def cascade_callable(self, type, object, callable_, recursive=None, halt_on=None)

Execute a callable for each element in an object graph, for all relations that meet the given cascade rule.

type
  The name of the cascade rule (i.e. save-update, delete, etc.)
object
  The lead object instance. child items will be processed per the relations defined for this object's mapper.
callable_
  The callable function.
recursive
  Used by the function for internal context during recursive calls, leave as None.

def cascade_iterator(self, type, object, recursive=None, halt_on=None)

Iterate each element in an object graph, for all relations taht meet the given cascade rule.

type
  The name of the cascade rule (i.e. save-update, delete, etc.)
object
  The lead object instance. child items will be processed per the relations defined for this object's mapper.
recursive
  Used by the function for internal context during recursive calls, leave as None.

def common_parent(self, other)

Return true if the given mapper shares a common inherited parent as this mapper.

def compile(self)

Compile this mapper into its final internal format.

This is the external version of the method which is not reentrant.

def delete_obj(self, objects, uowtransaction)

Issue `DELETE` statements for a list of objects.

This is called within the context of a UOWTransaction during a flush operation.

def get_attr_by_column(self, obj, column, raiseerror=True)

Return an instance attribute using a Column as the key.

def get_select_mapper(self)

Return the mapper used for issuing selects.

This mapper is the same mapper as self unless the select_table argument was specified for this mapper.

def get_session(self)

Return the contextual session provided by the mapper extension chain, if any.

Raise `InvalidRequestError` if a session cannot be retrieved from the extension chain.

def has_eager(self)

Return True if one of the properties attached to this Mapper is eager loading.

def identity(self, instance)

Deprecated. A synoynm for primary_key_from_instance.

def identity_key(self, primary_key)

Deprecated. A synonym for identity_key_from_primary_key.

def identity_key_from_instance(self, instance)

Return the identity key for the given instance, based on its primary key attributes.

This value is typically also found on the instance itself under the attribute name _instance_key.

def identity_key_from_primary_key(self, primary_key)

Return an identity-map key for use in storing/retrieving an item from an identity map.

primary_key
  A list of values indicating the identifier.

def identity_key_from_row(self, row)

Return an identity-map key for use in storing/retrieving an item from the identity map.

row
  A `sqlalchemy.engine.base.RowProxy` instance or a dictionary corresponding result-set `ColumnElement` instances to their values within a row.

def instance_key(self, instance)

Deprecated. A synonym for identity_key_from_instance.

def instances(self, cursor, session, *mappers, **kwargs)

Return a list of mapped instances corresponding to the rows in a given ResultProxy.

def is_assigned(self, instance)

Return True if this mapper handles the given instance.

This is dependent not only on class assignment but the optional entity_name parameter as well.

def isa(self, other)

Return True if the given mapper inherits from this mapper.

def iterate_to_root(self)
def polymorphic_iterator(self)

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 populate_instance(self, selectcontext, instance, row, identitykey, isnew)

populate an instance from a result row.

This method iterates through the list of MapperProperty objects attached to this Mapper and calls each properties execute() method.

def primary_key_from_instance(self, instance)

Return the list of primary key values for the given instance.

def primary_mapper(self)

Return the primary mapper corresponding to this mapper's class key (class + entity_name).

props = property()

compiles this mapper if needed, and returns the dictionary of MapperProperty objects associated with this mapper.

def register_dependencies(self, uowcommit, *args, **kwargs)

Register `DependencyProcessor` instances with a `unitofwork.UOWTransaction`.

This call register_dependencies on all attached `MapperProperty` instances.

def save_obj(self, objects, uowtransaction, postupdate=False, post_update_cols=None, single=False)

Issue `INSERT` and/or `UPDATE` statements for a list of objects.

This is called within the context of a UOWTransaction during a flush operation.

save_obj issues SQL statements not just for instances mapped directly by this mapper, but for instances mapped by all inheriting mappers as well. This is to maintain proper insert ordering among a polymorphic chain of instances. Therefore save_obj is typically called only on a base mapper, or a mapper which does not inherit from any other mapper.

def set_attr_by_column(self, obj, column, value)

Set the value of an instance attribute using a Column as the key.

def translate_row(self, tomapper, row)

Translate the column keys of a row into a new or proxied row that can be understood by another mapper.

This can be used in conjunction with populate_instance to populate an instance using an alternate mapper.

back to section top