U az@sdZddlmZddlZddlZddlZddlmZddlmZddlm Z ddlm Z dd lm Z dd lm Zdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlmZddlmZddlmZddlmZddlm Z ddZ!Gddde"Z#d1ddZ$Gd d!d!e j%e&Z'Gd"d#d#e'Z(d$d%Z)ddde*d&ede#fd'd(Z+Gd)d*d*e*Z,e,e_-ej.d+d,d-d.Z/e0e#d/d0Z1dS)2z1Public API functions and helpers for declarative.)absolute_importN) attributes) clsregistry)exc)instrumentation) interfacesmapper)_inspect_mapped_class_add_attribute)_as_declarative)_declarative_constructor)_DeferredMapperConfig_del_attribute_mapper)SynonymProperty) inspection)util)MetaData) hybridmethod)hybridpropertycCs.|jddD]}t|dddk rdSqdS)aKGiven a class, return True if any of the classes it inherits from has a mapped table, otherwise return False. This is used in declarative mixins to build attributes that behave differently for the base class vs. a subclass in an inheritance hierarchy. .. seealso:: :ref:`decl_mixin_inheritance` rNZ __table__TF)__mro__getattr)clsclass_r XC:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-nyjtotrf\sqlalchemy\orm\decl_api.pyhas_inherited_table$s r"c@s$eZdZddZddZddZdS)DeclarativeMetacKsjt|dd}|dkr<|dd}t|ts6tdn||_|jddsVt|||t ||||dS)N _sa_registryregistryziDeclarative base class has no 'registry' attribute, or registry is not a sqlalchemy.orm.registry() object __abstract__F) rget isinstancer%rZInvalidRequestErrorr$__dict__rtype__init__)r classnamebasesZdict_kwregr r r!r+8s    zDeclarativeMeta.__init__cCst|||dSNr )rkeyvaluer r r! __setattr__KszDeclarativeMeta.__setattr__cCst||dSr0r)rr1r r r! __delattr__NszDeclarativeMeta.__delattr__N)__name__ __module__ __qualname__r+r3r4r r r r!r#7sr#Fcsfdd}|S)aDecorator that produces an :func:`_orm.synonym` attribute in conjunction with a Python descriptor. The function being decorated is passed to :func:`_orm.synonym` as the :paramref:`.orm.synonym.descriptor` parameter:: class MyClass(Base): __tablename__ = 'my_table' id = Column(Integer, primary_key=True) _job_status = Column("job_status", String(50)) @synonym_for("job_status") @property def job_status(self): return "Status: %s" % self._job_status The :ref:`hybrid properties ` feature of SQLAlchemy is typically preferred instead of synonyms, which is a more legacy feature. .. seealso:: :ref:`synonyms` - Overview of synonyms :func:`_orm.synonym` - the mapper-level function :ref:`mapper_hybrids` - The Hybrid Attribute extension provides an updated approach to augmenting attribute behavior more flexibly than can be achieved with synonyms. cst|dS)N) map_columnZ descriptor) _orm_synonym)fnr8namer r!decoratetszsynonym_for..decorater )r<r8r=r r;r! synonym_forRs"r>csBeZdZdZd fdd ZddZeddZed d Z Z S) declared_attra` Mark a class-level method as representing the definition of a mapped property or special declarative member name. :class:`_orm.declared_attr` is typically applied as a decorator to a class level method, turning the attribute into a scalar-like property that can be invoked from the uninstantiated class. The Declarative mapping process looks for these :class:`_orm.declared_attr` callables as it scans classe, and assumes any attribute marked with :class:`_orm.declared_attr` will be a callable that will produce an object specific to the Declarative mapping or table configuration. :class:`_orm.declared_attr` is usually applicable to mixins, to define relationships that are to be applied to different implementors of the class. It is also used to define :class:`_schema.Column` objects that include the :class:`_schema.ForeignKey` construct, as these cannot be easily reused across different mappings. The example below illustrates both:: class ProvidesUser(object): "A mixin that adds a 'user' relationship to classes." @declared_attr def user_id(self): return Column(ForeignKey("user_account.id")) @declared_attr def user(self): return relationship("User") :class:`_orm.declared_attr` can also be applied to mapped classes, such as to provide a "polymorphic" scheme for inheritance:: class Employee(Base): id = Column(Integer, primary_key=True) type = Column(String(50), nullable=False) @declared_attr def __tablename__(cls): return cls.__name__.lower() @declared_attr def __mapper_args__(cls): if cls.__name__ == 'Employee': return { "polymorphic_on":cls.type, "polymorphic_identity":"Employee" } else: return {"polymorphic_identity":cls.__name__} To use :class:`_orm.declared_attr` inside of a Python dataclass as discussed at :ref:`orm_declarative_dataclasses_declarative_table`, it may be placed directly inside the field metadata using a lambda:: @dataclass class AddressMixin: __sa_dataclass_metadata_key__ = "sa" user_id: int = field( init=False, metadata={"sa": declared_attr(lambda: Column(ForeignKey("user.id")))} ) user: User = field( init=False, metadata={"sa": declared_attr(lambda: relationship(User))} ) :class:`_orm.declared_attr` also may be omitted from this form using a lambda directly, as in:: user: User = field( init=False, metadata={"sa": lambda: relationship(User)} ) .. seealso:: :ref:`orm_mixins_toplevel` - illustrates how to use Declarative Mixins which is the primary use case for :class:`_orm.declared_attr` :ref:`orm_declarative_dataclasses_mixin` - illustrates special forms for use with Python dataclasses Fcs"tt|||j|_||_dSr0)superr?r+__doc__Z _cascading)selffget cascading __class__r r!r+szdeclared_attr.__init__cCst|}|dkrDtd|jjs:td|jj|jf||S|jrT||S|j }|j }||krp||S||||<}|SdS)Nz^__.+__$zEUnmanaged access of declarative attribute %s from non-mapped class %s) rZmanager_of_classrematchrCr5rwarn is_mappeddeclarative_scanZdeclared_attr_reg)descrBrmanagerrKr/objr r r!__get__s"    zdeclared_attr.__get__cKs tf|Sr0)_stateful_declared_attr)rr.r r r! _statefulszdeclared_attr._statefulcCs |jddS)aMark a :class:`.declared_attr` as cascading. This is a special-use modifier which indicates that a column or MapperProperty-based declared attribute should be configured distinctly per mapped subclass, within a mapped-inheritance scenario. .. warning:: The :attr:`.declared_attr.cascading` modifier has several limitations: * The flag **only** applies to the use of :class:`.declared_attr` on declarative mixin classes and ``__abstract__`` classes; it currently has no effect when used on a mapped class directly. * The flag **only** applies to normally-named attributes, e.g. not any special underscore attributes such as ``__tablename__``. On these attributes it has **no** effect. * The flag currently **does not allow further overrides** down the class hierarchy; if a subclass tries to override the attribute, a warning is emitted and the overridden attribute is skipped. This is a limitation that it is hoped will be resolved at some point. Below, both MyClass as well as MySubClass will have a distinct ``id`` Column object established:: class HasIdMixin(object): @declared_attr.cascading def id(cls): if has_inherited_table(cls): return Column( ForeignKey('myclass.id'), primary_key=True ) else: return Column(Integer, primary_key=True) class MyClass(HasIdMixin, Base): __tablename__ = 'myclass' # ... class MySubClass(MyClass): "" # ... The behavior of the above configuration is that ``MySubClass`` will refer to both its own ``id`` column as well as that of ``MyClass`` underneath the attribute named ``some_id``. .. seealso:: :ref:`declarative_inheritance` :ref:`mixin_inheritance_columns` T)rD)rQrr r r!rDs` in being able to identify SQLAlchemy declarative mixin classes when no other context is present. .. versionadded:: 1.4.6 .. seealso:: :ref:`orm_mixins_toplevel` :ref:`mypy_declarative_mixins` - in the :ref:`Mypy plugin documentation ` r rRr r r!declarative_mixin@s'rWBasecCs0|dk rtdt||||dj||||dS)aZ Construct a base class for declarative class definitions. The new base class will be given a metaclass that produces appropriate :class:`~sqlalchemy.schema.Table` objects and makes the appropriate :func:`~sqlalchemy.orm.mapper` calls based on the information provided declaratively in the class and any subclasses of the class. The :func:`_orm.declarative_base` function is a shorthand version of using the :meth:`_orm.registry.generate_base` method. That is, the following:: from sqlalchemy.orm import declarative_base Base = declarative_base() Is equivalent to:: from sqlalchemy.orm import registry mapper_registry = registry() Base = mapper_registry.generate_base() See the docstring for :class:`_orm.registry` and :meth:`_orm.registry.generate_base` for more details. .. versionchanged:: 1.4 The :func:`_orm.declarative_base` function is now a specialization of the more generic :class:`_orm.registry` class. The function also moves to the ``sqlalchemy.orm`` package from the ``declarative.ext`` package. :param bind: An optional :class:`~sqlalchemy.engine.Connectable`, will be assigned the ``bind`` attribute on the :class:`~sqlalchemy.schema.MetaData` instance. .. deprecated:: 1.4 The "bind" argument to declarative_base is deprecated and will be removed in SQLAlchemy 2.0. :param metadata: An optional :class:`~sqlalchemy.schema.MetaData` instance. All :class:`~sqlalchemy.schema.Table` objects implicitly declared by subclasses of the base will share this MetaData. A MetaData instance will be created if none is provided. The :class:`~sqlalchemy.schema.MetaData` instance will be available via the ``metadata`` attribute of the generated declarative base class. :param mapper: An optional callable, defaults to :func:`~sqlalchemy.orm.mapper`. Will be used to map subclasses to their Tables. :param cls: Defaults to :class:`object`. A type to use as the base for the generated declarative base class. May be a class or tuple of classes. :param name: Defaults to ``Base``. The display name for the generated class. Customizing this is not required, but can improve clarity in tracebacks and debugging. :param constructor: Specify the implementation for the ``__init__`` function on a mapped class that has no ``__init__`` of its own. Defaults to an implementation that assigns \**kwargs for declared fields and relationships to an instance. If ``None`` is supplied, no __init__ will be provided and construction will fall back to cls.__init__ by way of the normal Python semantics. :param class_registry: optional dictionary that will serve as the registry of class names-> mapped classes when string names are used to identify classes inside of :func:`_orm.relationship` and others. Allows two or more declarative base classes to share the same registry of class names for simplified inter-base relationships. :param metaclass: Defaults to :class:`.DeclarativeMeta`. A metaclass or __metaclass__ compatible callable to use as the meta type of the generated declarative base class. .. seealso:: :class:`_orm.registry` Nz^The ``bind`` argument to declarative_base is deprecated and will be removed in SQLAlchemy 2.0.)_bindmetadataclass_registry constructor)r rr< metaclass)rZwarn_deprecated_20r% generate_base)bindrZr rr<r\r[r]r r r!declarative_basejsbr`c@seZdZdZddedfddZeddZddZd d Z e d d Z e d dZ ddZ ddZddZddZd)ddZd*ddZddZdedefdd Zd!d"Zd#d$Zd%d&Zd+d'd(ZdS),r%aGeneralized registry for mapping classes. The :class:`_orm.registry` serves as the basis for maintaining a collection of mappings, and provides configurational hooks used to map classes. The three general kinds of mappings supported are Declarative Base, Declarative Decorator, and Imperative Mapping. All of these mapping styles may be used interchangeably: * :meth:`_orm.registry.generate_base` returns a new declarative base class, and is the underlying implementation of the :func:`_orm.declarative_base` function. * :meth:`_orm.registry.mapped` provides a class decorator that will apply declarative mapping to a class without the use of a declarative base class. * :meth:`_orm.registry.map_imperatively` will produce a :class:`_orm.Mapper` for a class without scanning the class for declarative class attributes. This method suits the use case historically provided by the :func:`_orm.mapper` classical mapping function. .. versionadded:: 1.4 .. seealso:: :ref:`orm_mapping_classes_toplevel` - overview of class mapping styles. Nc Cs|pt}|r||_|dkr$t}||_t|_t|_||_||_ t |_ t |_ d|_ tjdtj|<W5QRXdS)aConstruct a new :class:`_orm.registry` :param metadata: An optional :class:`_schema.MetaData` instance. All :class:`_schema.Table` objects generated using declarative table mapping will make use of this :class:`_schema.MetaData` collection. If this argument is left at its default of ``None``, a blank :class:`_schema.MetaData` collection is created. :param constructor: Specify the implementation for the ``__init__`` function on a mapped class that has no ``__init__`` of its own. Defaults to an implementation that assigns \**kwargs for declared fields and relationships to an instance. If ``None`` is supplied, no __init__ will be provided and construction will fall back to cls.__init__ by way of the normal Python semantics. :param class_registry: optional dictionary that will serve as the registry of class names-> mapped classes when string names are used to identify classes inside of :func:`_orm.relationship` and others. Allows two or more declarative base classes to share the same registry of class names for simplified inter-base relationships. NFT)rr_weakrefWeakValueDictionary_class_registryWeakKeyDictionary _managers_non_primary_mappersrZr\set _dependents _dependencies _new_mappers mapperlibZ_CONFIGURE_MUTEXZ_mapper_registries)rBrZr[r\rYZ lcl_metadatar r r!r+s   zregistry.__init__cCstdd|jD|jS)z9read only collection of all :class:`_orm.Mapper` objects.css|] }|jVqdSr0r .0rMr r r! :sz#registry.mappers..) frozensetreunionrfrBr r r!mappers6szregistry.mapperscCs(||kr dS|j||j|dSr0)rhaddri)rBr%r r r!_set_depends_on>s zregistry._set_depends_oncCs,d|_|jrdS||hD] }d|_qdSNT)_ready_for_configurerj_recurse_with_dependents)rBr r/r r r!_flag_new_mapperDs zregistry._flag_new_mapperccsP|}t}|rL|}||||j||V||j|q dSr0)rgpoprsrUrh differencerZ registriestododoner/r r r!rwLs z!registry._recurse_with_dependentsccsP|}t}|rL|}||||j||V||j|q dSr0)rgryrsrUrirzr{r r r!_recurse_with_dependencies]s z#registry._recurse_with_dependenciescCs,tddt|jDddt|jDS)Ncss*|]"}|jr|jjs|jjr|jVqdSr0)rJr configuredrvrlr r r!rnqs z1registry._mappers_to_configure..css|]}|js|jr|VqdSr0)rrv)rmZnpmr r r!rnxs) itertoolschainlistrerfrqr r r!_mappers_to_configureoszregistry._mappers_to_configurecCsd|j|<dSru)rf)rBZ np_mapperr r r!_add_non_primary_mappersz registry._add_non_primary_mappercCst|j||jdSr0)rZ remove_classr5rcrBrr r r! _dispose_clsszregistry._dispose_clscCs"d|j|<|jdkst||_dSru)rer%AssertionError)rBrMr r r! _add_managers zregistry._add_managerFcCstj|h|ddS)a]Configure all as-yet unconfigured mappers in this :class:`_orm.registry`. The configure step is used to reconcile and initialize the :func:`_orm.relationship` linkages between mapped classes, as well as to invoke configuration events such as the :meth:`_orm.MapperEvents.before_configured` and :meth:`_orm.MapperEvents.after_configured`, which may be used by ORM extensions or user-defined extension hooks. If one or more mappers in this registry contain :func:`_orm.relationship` constructs that refer to mapped classes in other registries, this registry is said to be *dependent* on those registries. In order to configure those dependent registries automatically, the :paramref:`_orm.registry.configure.cascade` flag should be set to ``True``. Otherwise, if they are not configured, an exception will be raised. The rationale behind this behavior is to allow an application to programmatically invoke configuration of registries while controlling whether or not the process implicitly reaches other registries. As an alternative to invoking :meth:`_orm.registry.configure`, the ORM function :func:`_orm.configure_mappers` function may be used to ensure configuration is complete for all :class:`_orm.registry` objects in memory. This is generally simpler to use and also predates the usage of :class:`_orm.registry` objects overall. However, this function will impact all mappings throughout the running Python process and may be more memory/time consuming for an application that has many registries in use for different purposes that may not be needed immediately. .. seealso:: :func:`_orm.configure_mappers` .. versionadded:: 1.4.0b2 cascadeN)rkZ_configure_registriesrBrr r r! configures'zregistry.configurecCstj|h|ddS)aDispose of all mappers in this :class:`_orm.registry`. After invocation, all the classes that were mapped within this registry will no longer have class instrumentation associated with them. This method is the per-:class:`_orm.registry` analogue to the application-wide :func:`_orm.clear_mappers` function. If this registry contains mappers that are dependencies of other registries, typically via :func:`_orm.relationship` links, then those registries must be disposed as well. When such registries exist in relation to this one, their :meth:`_orm.registry.dispose` method will also be called, if the :paramref:`_orm.registry.dispose.cascade` flag is set to ``True``; otherwise, an error is raised if those registries were not already disposed. .. versionadded:: 1.4.0b2 .. seealso:: :func:`_orm.clear_mappers` rN)rkZ_dispose_registriesrr r r!disposeszregistry.disposecCs8d|jkr|j}||j}||tj|dS)Nr )r)r Z_set_dispose_flagsrrrZ_instrumentation_factory unregister)rBrMr rr r r!_dispose_manager_and_mappers   z$registry._dispose_manager_and_mapperrXcCsl|j}t|t r|fp|}t||d}t|tr<|j|d<|jrL|j|d<d|d<|r`||d<||||S)a)Generate a declarative base class. Classes that inherit from the returned class object will be automatically mapped using declarative mapping. E.g.:: from sqlalchemy.orm import registry mapper_registry = registry() Base = mapper_registry.generate_base() class MyClass(Base): __tablename__ = "my_table" id = Column(Integer, primary_key=True) The above dynamically generated class is equivalent to the non-dynamic example below:: from sqlalchemy.orm import registry from sqlalchemy.orm.decl_api import DeclarativeMeta mapper_registry = registry() class Base(metaclass=DeclarativeMeta): __abstract__ = True registry = mapper_registry metadata = mapper_registry.metadata The :meth:`_orm.registry.generate_base` method provides the implementation for the :func:`_orm.declarative_base` function, which creates the :class:`_orm.registry` and base class all at once. See the section :ref:`orm_declarative_mapping` for background and examples. :param mapper: An optional callable, defaults to :func:`~sqlalchemy.orm.mapper`. This function is used to generate new :class:`_orm.Mapper` objects. :param cls: Defaults to :class:`object`. A type to use as the base for the generated declarative base class. May be a class or tuple of classes. :param name: Defaults to ``Base``. The display name for the generated class. Customizing this is not required, but can improve clarity in tracebacks and debugging. :param metaclass: Defaults to :class:`.DeclarativeMeta`. A metaclass or __metaclass__ compatible callable to use as the meta type of the generated declarative base class. .. seealso:: :ref:`orm_declarative_mapping` :func:`_orm.declarative_base` )r%rZrAr+Tr&Z__mapper_cls__)rZr(tupledictr*rAr\)rBr rr<r]rZr- class_dictr r r!r^sE    zregistry.generate_basecCst|||j|S)aLClass decorator that will apply the Declarative mapping process to a given class. E.g.:: from sqlalchemy.orm import registry mapper_registry = registry() @mapper_registry.mapped class Foo: __tablename__ = 'some_table' id = Column(Integer, primary_key=True) name = Column(String) See the section :ref:`orm_declarative_mapping` for complete details and examples. :param cls: class to be mapped. :return: the class that was passed. .. seealso:: :ref:`orm_declarative_mapping` :meth:`_orm.registry.generate_base` - generates a base class that will apply Declarative mapping to subclasses automatically using a Python metaclass. rr)rr r r!mapped-s!zregistry.mappedc sfdd}|S)a Class decorator which will invoke :meth:`_orm.registry.generate_base` for a given base class. E.g.:: from sqlalchemy.orm import registry mapper_registry = registry() @mapper_registry.as_declarative_base() class Base(object): @declared_attr def __tablename__(cls): return cls.__name__.lower() id = Column(Integer, primary_key=True) class MyMappedClass(Base): # ... All keyword arguments passed to :meth:`_orm.registry.as_declarative_base` are passed along to :meth:`_orm.registry.generate_base`. cs|d<|jd<jfS)Nrr<)r5r^rRr.rBr r!r=ms z.registry.as_declarative_base..decorater )rBr.r=r rr!as_declarative_baseQszregistry.as_declarative_basecCst|||jS)aMap a class declaratively. In this form of mapping, the class is scanned for mapping information, including for columns to be associated with a table, and/or an actual table object. Returns the :class:`_orm.Mapper` object. E.g.:: from sqlalchemy.orm import registry mapper_registry = registry() class Foo: __tablename__ = 'some_table' id = Column(Integer, primary_key=True) name = Column(String) mapper = mapper_registry.map_declaratively(Foo) This function is more conveniently invoked indirectly via either the :meth:`_orm.registry.mapped` class decorator or by subclassing a declarative metaclass generated from :meth:`_orm.registry.generate_base`. See the section :ref:`orm_declarative_mapping` for complete details and examples. :param cls: class to be mapped. :return: a :class:`_orm.Mapper` object. .. seealso:: :ref:`orm_declarative_mapping` :meth:`_orm.registry.mapped` - more common decorator interface to this function. :meth:`_orm.registry.map_imperatively` rrr r r!map_declarativelyts-zregistry.map_declarativelycKst||||S)aMap a class imperatively. In this form of mapping, the class is not scanned for any mapping information. Instead, all mapping constructs are passed as arguments. This method is intended to be fully equivalent to the classic SQLAlchemy :func:`_orm.mapper` function, except that it's in terms of a particular registry. E.g.:: from sqlalchemy.orm import registry mapper_registry = registry() my_table = Table( "my_table", mapper_registry.metadata, Column('id', Integer, primary_key=True) ) class MyClass: pass mapper_registry.map_imperatively(MyClass, my_table) See the section :ref:`orm_imperative_mapping` for complete background and usage examples. :param class\_: The class to be mapped. Corresponds to the :paramref:`_orm.mapper.class_` parameter. :param local_table: the :class:`_schema.Table` or other :class:`_sql.FromClause` object that is the subject of the mapping. Corresponds to the :paramref:`_orm.mapper.local_table` parameter. :param \**kw: all other keyword arguments are passed to the :func:`_orm.mapper` function directly. .. seealso:: :ref:`orm_imperative_mapping` :ref:`orm_declarative_mapping` r)rBrZ local_tabler.r r r!map_imperativelys1zregistry.map_imperatively)F)F)N)r5r6r7rArr+propertyrrrtrx classmethodrwr~rrrrrrrobjectr#r^rrrrr r r r!r%s<" 5    )   V$#/r%)z2.0z\The ``bind`` argument to as_declarative is deprecated and will be removed in SQLAlchemy 2.0.)r_cKs>|dd|dd|dd}}}t|||djf|S)a Class decorator which will adapt a given class into a :func:`_orm.declarative_base`. This function makes use of the :meth:`_orm.registry.as_declarative_base` method, by first creating a :class:`_orm.registry` automatically and then invoking the decorator. E.g.:: from sqlalchemy.orm import as_declarative @as_declarative() class Base(object): @declared_attr def __tablename__(cls): return cls.__name__.lower() id = Column(Integer, primary_key=True) class MyMappedClass(Base): # ... .. seealso:: :meth:`_orm.registry.as_declarative_base` r_NrZr[)rYrZr[)ryr%r)r.r_rZr[r r r!as_declaratives$   rcCs@t|}|dkrZ_MappedAttributerr?rPrWrr`r%Z_legacy_registryZdeprecated_paramsrZ _inspectsrr r r r!sf                      (: + vz '