📄 __init__.py
字号:
# mapper/__init__.py# Copyright (C) 2005, 2006, 2007, 2008 Michael Bayer mike_mp@zzzcomputing.com## This module is part of SQLAlchemy and is released under# the MIT License: http://www.opensource.org/licenses/mit-license.php"""Functional constructs for ORM configuration.See the SQLAlchemy object relational tutorial and mapper configurationdocumentation for an overview of how this module is used."""from sqlalchemy import util as sautilfrom sqlalchemy.orm.mapper import Mapper, object_mapper, class_mapper, _mapper_registryfrom sqlalchemy.orm.interfaces import MapperExtension, EXT_CONTINUE, EXT_STOP, EXT_PASS, ExtensionOption, PropComparatorfrom sqlalchemy.orm.properties import SynonymProperty, PropertyLoader, ColumnProperty, CompositeProperty, BackReffrom sqlalchemy.orm import mapper as mapperlibfrom sqlalchemy.orm import strategiesfrom sqlalchemy.orm.query import Queryfrom sqlalchemy.orm.util import polymorphic_union, create_row_adapterfrom sqlalchemy.orm.session import Session as _Sessionfrom sqlalchemy.orm.session import object_session, sessionmakerfrom sqlalchemy.orm.scoping import ScopedSessionfrom itertools import chain__all__ = [ 'relation', 'column_property', 'composite', 'backref', 'eagerload', 'eagerload_all', 'lazyload', 'noload', 'deferred', 'defer', 'undefer', 'undefer_group', 'extension', 'mapper', 'clear_mappers', 'compile_mappers', 'class_mapper', 'object_mapper', 'sessionmaker', 'scoped_session', 'dynamic_loader', 'MapperExtension', 'polymorphic_union', 'create_session', 'synonym', 'contains_alias', 'Query', 'contains_eager', 'EXT_CONTINUE', 'EXT_STOP', 'EXT_PASS', 'object_session', 'PropComparator' ]def scoped_session(session_factory, scopefunc=None): """Provides thread-local management of Sessions. This is a front-end function to the [sqlalchemy.orm.scoping#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, ...) """ return ScopedSession(session_factory, scopefunc=scopefunc)def create_session(bind=None, **kwargs): """create a new [sqlalchemy.orm.session#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 [sqlalchemy.orm#sessionmaker()] function instead of create_session(). """ kwargs.setdefault('autoflush', False) kwargs.setdefault('transactional', False) return _Session(bind=bind, **kwargs)def relation(argument, secondary=None, **kwargs): """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 [sqlalchemy.orm.properties#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 synonymous 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" attributes, 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 loading behavior during 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. passive_updates=True Indicates loading and INSERT/UPDATE/DELETE behavior when the source of a foreign key value changes (i.e. an "on update" cascade), which are typically the primary key columns of the source row. When True, it is assumed that ON UPDATE CASCADE is configured on the foreign key in the database, and that the database will handle propagation of an UPDATE from a source column to dependent rows. Note that with databases which enforce referential integrity (i.e. Postgres, MySQL with InnoDB tables), ON UPDATE CASCADE is required for this operation. The relation() will update the value of the attribute on related items which are locally present in the session during a flush. When False, it is assumed that the database does not enforce referential integrity and will not be issuing its own CASCADE operation for an update. The relation() will issue the appropriate UPDATE statements to the database in response to the change of a referenced key, and items locally present in the session during a flush will also be refreshed. This flag should probably be set to False if primary key changes are expected and the database in use doesn't support CASCADE (i.e. SQLite, MySQL MyISAM tables). 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.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -