U kf @sdZddlmZddlZddlZddlZddlmZddlmZddlmZddlm Z ddlm Z dd lm Z dd lm Z dd lm Z dd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#dd lm$Z$dd!lm%Z%dd"l&m'Z'dd#l&m(Z(dd$l&m)Z)dd%l&m*Z*dd&l+m,Z,dd'l+m-Z-dd(l+m.Z.dd)l+m/Z/dd*l+m0Z0dd+l+m1Z1dd,l+m2Z2dd-l3m4Z4dd.l3m5Z5dd.l3m5Z6dd/l7m8Z8dd0l9m:Z:dd1l;mZ>d3d4lm?Z?d3d5lm@Z@d3d6lmAZAd3d7lBmCZCd3d8lDmEZEd3d9lFmGZGd3d:lHmIZId3d;lJmKZKd3dlAmZNd3d?lOmPZPd3d@lOmQZQd3dAlOmRZRd3dBlOmSZSd3dClOmTZTd3dDlOmUZUd3dElOmVZVd3dFlOmWZWerddGlXmYZYddHlXmZZZddIl+m[Z[ddJlm\Z\ddKlm]Z]dd2l=m>Z>d3dLl^m_Z_d3dMl`maZaedNedOZbedPedOZceedQfZde edQfZeedRee)ebe*ebeGebffZfdSdTdUdVdWZgGdXdYdYehZiGdZd[d[eie@jje8eZkeNjle:eeekdxZxdrdrdsd{d|d}ZyGd~dde@jje>eZzdSdbddsdddZ{dde|ddde/enddddrdbddddrdd ddZ}GdddZ~e~Zese~ZZdddddZe@enexekdrddUddZdS)z1Public API functions and helpers for declarative.) annotationsN)Any)Callable)cast)ClassVar)Dict) FrozenSet)Generic)Iterable)Iterator)Mapping)Optional)overload)Set)Tuple)Type) TYPE_CHECKING)TypeVar)Union) attributes) clsregistry)instrumentation) interfaces) mapperlib) composite)deferred) mapped_column) relationship)synonym)InstrumentedAttribute)_inspect_mapped_class)_is_mapped_class)Mapped) ORMDescriptor_add_attribute)_as_declarative)_ClassScanMapperConfig)_declarative_constructor)_DeferredMapperConfig)_del_attribute_mapper) Composite)Synonym)Mapper) MappedColumn)RelationshipProperty) InstanceState)exc) inspection)util)sqltypes)_NoArg)SQLCoreOperations)MetaData) FromClause) hybridmethod)hybridproperty)typing)CallableReference)flatten_newtype) is_generic) is_literal) is_newtype) is_pep695)Literal)Self)_O) _RegistryType)_DataclassArguments) ClassManager)MapperProperty)_TypeEngineArgument)_MatchedOnType_T)bound_TTz_TypeEngineArgument[Any].Type[_O]boolclsreturncCs.|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` rN __table__TF)__mro__getattr)rUclass_r[G/opt/hc_python/lib64/python3.8/site-packages/sqlalchemy/orm/decl_api.pyhas_inherited_tablels r]c@s.eZdZddddddZddddd Zd S) _DynamicAttributesTypestrrNone)keyvaluerVcCs*d|jkrt|||nt|||dSN __mapper__)__dict__r&type __setattr__)rUrarbr[r[r\rgs z"_DynamicAttributesType.__setattr__)rarVcCs&d|jkrt||n t||dSrc)rer+rf __delattr__rUrar[r[r\rhs  z"_DynamicAttributesType.__delattr__N)__name__ __module__ __qualname__rgrhr[r[r[r\r^sr^c@seZdZdZdS)DeclarativeAttributeInterceptzMetaclass that may be used in conjunction with the :class:`_orm.DeclarativeBase` class to support addition of class attributes dynamically. Nrjrkrl__doc__r[r[r[r\rmsrmfield_specifiersc@seZdZdZdS)DCTransformDeclarativez-metaclass that includes @dataclass_transformsNrnr[r[r[r\rrsrrc@s4eZdZUded<ded<dddddddd Zd S) DeclarativeMetar;metadata RegistryTyperegistryrr`) classnamebasesdict_kwrVcKsp|j}t|dd}|dkrB|dd}t|ts` 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. Callable[..., Any]z Synonym[Any]fnrVcst|dS)N)rZ descriptor) _orm_synonym)rrrr[r\decorateszsynonym_for..decorater[)rrrr[rr\ synonym_fors$rc@s@eZdZdddddddZddd d Zd d d d ddZdS)_declared_attr_commonFrrS)r cascadingquietcCs.t|tr|j}||_||_||_|j|_dSN)r~ classmethod__func__fgetZ _cascadingZ_quietro)selfrrrr[r[r\rs z_declared_attr_common.__init__zOptional[Type[Any]]rVcCst|jdS)NrV)r7Zget_annotationsrr}rr[r[r\_collect_return_annotationsz0_declared_attr_common._collect_return_annotationOptional[object]rinstanceownerrVcCs|}t|}|dkrHtd|jjs>td|jj|jf||S|jrX||S| }|dk slt |j }||kr||S||||<}|SdS)Nz^__.+__$zEUnmanaged access of declarative attribute %s from non-mapped class %s) rZopt_manager_of_classrematchrrjr7warn is_mappeddeclarative_scanAssertionErrorZdeclared_attr_reg)rrrrUmanagerrrobjr[r[r\__get__ s&     z_declared_attr_common.__get__N)FF)rjrkrlrrrr[r[r[r\rs rc@sheZdZejrdddddddZddd d d d Zddd dddZdd dddZdddddZ dS)_declared_directiveFzCallable[..., _T]rSrrcCsdSrr[rrrr[r[r\r8sz_declared_directive.__init__rrrOrcCsdSrr[rrrr[r[r\r>z_declared_directive.__get__r`rrbrVcCsdSrr[rrrbr[r[r\__set__@rz_declared_directive.__set__rrVcCsdSrr[rrr[r[r\ __delete__Brz_declared_directive.__delete__zCallable[..., _TT]z_declared_directive[_TT]rcCsdSrr[rrr[r[r\__call__Dsz_declared_directive.__call__N)F) rjrkrlr?rrrrrrr[r[r[r\r3src@seZdZdZejrd%dddddZddd d d d Zdd d ddZe d dddddZ e ddddddZ ddddddZ e dddddZ e ddd d!Ze ddd"d#Zd$S)& declared_attraMark a class-level method as representing the definition of a mapped property or Declarative directive. :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 classes, 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 :ref:`mixins `, to define relationships that are to be applied to different implementors of the class. It may also be used to define dynamically generated column expressions and other Declarative attributes. Example:: class ProvidesUserMixin: "A mixin that adds a 'user' relationship to classes." user_id: Mapped[int] = mapped_column(ForeignKey("user_table.id")) @declared_attr def user(cls) -> Mapped["User"]: return relationship("User") When used with Declarative directives such as ``__tablename__``, the :meth:`_orm.declared_attr.directive` modifier may be used which indicates to :pep:`484` typing tools that the given method is not dealing with :class:`_orm.Mapped` attributes:: class CreateTableName: @declared_attr.directive def __tablename__(cls) -> str: return cls.__name__.lower() :class:`_orm.declared_attr` can also be applied directly to mapped classes, to allow for attributes that dynamically configure themselves on subclasses when using mapped inheritance schemes. Below illustrates :class:`_orm.declared_attr` to create a dynamic scheme for generating the :paramref:`_orm.Mapper.polymorphic_identity` parameter for subclasses:: class Employee(Base): __tablename__ = 'employee' id: Mapped[int] = mapped_column(primary_key=True) type: Mapped[str] = mapped_column(String(50)) @declared_attr.directive def __mapper_args__(cls) -> Dict[str, Any]: if cls.__name__ == 'Employee': return { "polymorphic_on":cls.type, "polymorphic_identity":"Employee" } else: return {"polymorphic_identity":cls.__name__} class Engineer(Employee): pass :class:`_orm.declared_attr` supports decorating functions that are explicitly decorated with ``@classmethod``. This is never necessary from a runtime perspective, however may be needed in order to support :pep:`484` typing tools that don't otherwise recognize the decorated function as having class-level behaviors for the ``cls`` parameter:: class SomethingMixin: x: Mapped[int] y: Mapped[int] @declared_attr @classmethod def x_plus_y(cls) -> Mapped[int]: return column_property(cls.x + cls.y) .. versionadded:: 2.0 - :class:`_orm.declared_attr` can accommodate a function decorated with ``@classmethod`` to help with :pep:`484` integration where needed. .. seealso:: :ref:`orm_mixins_toplevel` - Declarative Mixin documentation with background on use patterns for :class:`_orm.declared_attr`. F_DeclaredAttrDecorated[_T]rSrcCsdSrr[rr[r[r\rszdeclared_attr.__init__rr`rcCsdSrr[rr[r[r\rrzdeclared_attr.__set__rcCsdSrr[rr[r[r\rrzdeclared_attr.__delete__zInstrumentedAttribute[_T]rcCsdSrr[rr[r[r\rszdeclared_attr.__get__objectrOcCsdSrr[rr[r[r\rsrz$Union[InstrumentedAttribute[_T], _T]cCsdSrr[rr[r[r\rs_stateful_declared_attr[_T]rzrVcKs tf|Sr)_stateful_declared_attrrUrzr[r[r\ _statefulszdeclared_attr._statefulz_declared_directive[Any]rcCstSr)rrUr[r[r\ directiveszdeclared_attr.directivecCs |jddS)NT)r)rrr[r[r\rszdeclared_attr.cascadingN)F)rjrkrlror?rrrrrrr=rr>rrr[r[r[r\rIs"[rc@sHeZdZUded<ddddZedddd d Zd d d ddZdS)rzDict[str, Any]rzrrzcKs ||_dSrrrrzr[r[r\rsz _stateful_declared_attr.__init__rrcKs|j}||tf|Sr)rzcopyupdater)rrzZnew_kwr[r[r\rs  z!_stateful_declared_attr._statefulrzdeclared_attr[_T]rcCst|f|jSr)rrzrr[r[r\rsz _stateful_declared_attr.__call__N)rjrkrlrrr=rrr[r[r[r\rs rType[_T]cCs|S)a,Mark a class as providing the feature of "declarative mixin". E.g.:: from sqlalchemy.orm import declared_attr from sqlalchemy.orm import declarative_mixin @declarative_mixin class MyMixin: @declared_attr def __tablename__(cls): return cls.__name__.lower() __table_args__ = {'mysql_engine': 'InnoDB'} __mapper_args__= {'always_refresh': True} id = Column(Integer, primary_key=True) class MyModel(MyMixin, Base): name = Column(String(1000)) The :func:`_orm.declarative_mixin` decorator currently does not modify the given class in any way; it's current purpose is strictly to assist the :ref:`Mypy plugin ` 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[rr[r[r\declarative_mixins'r Type[Any]r`cCsd|jkr|jd}nd}d|jkr0|jd}nd}|jdd}|dk rtt|ts`tdq|dk rtdnt||d}||_||_d|jkr|jj|_t|dt j t j kr|jj |_ dS)Nrttype_annotation_maprvzfDeclarative base class has a 'registry' attribute that is not an instance of sqlalchemy.orm.registry()zDeclarative base class has both a 'registry' attribute and a type_annotation_map entry. Per-base type_annotation_maps are not supported. Please apply the type_annotation_map to this registry directly.)rtrr) rer}r~rvr5rr{rtrYrr constructor)rUrtrrr[r[r\_setup_declarative_base s4       rc sZeZdZdZejejejejejejejejfddddddddddd fdd ZZS) MappedAsDataclassaMixin class to indicate when mapping this class, also convert it to be a dataclass. .. seealso:: :ref:`orm_declarative_native_dataclasses` - complete background on SQLAlchemy native dataclass mapping .. versionadded:: 2.0 Union[_NoArg, bool]'Union[_NoArg, Callable[..., Type[Any]]]rr`) initrepreqorder unsafe_hash match_argskw_onlydataclass_callablerzrVc s||||||||d} t|drN|jtfdd| D|_} n | |_} tjf| t|st|} t | || dS)Nrrrrrrrr_sa_apply_dc_transformscs.i|]&\}}||tjkr&|tjn|qSr[)r9NO_ARGr}).0kvcurrentr[r\ `sz7MappedAsDataclass.__init_subclass__..) hasattrrr(Z_assert_dc_argumentsitemssuper__init_subclass__r"Z(_update_annotations_for_non_mapped_classZ_apply_dataclasses_to_any_class) rUrrrrrrrrrzZapply_dc_transformsZcurrent_transformsZnew_anno __class__rr\r@s8   z#MappedAsDataclass.__init_subclass__)rjrkrlror9rr __classcell__r[r[rr\r3sr) metaclasscseZdZUdZejrddddZddddZd ed <d ed <d ed <ded<ded<ded<ded<ded<ded<ddddZ dddfdd Z Z S)DeclarativeBaseaBase class used for declarative class definitions. The :class:`_orm.DeclarativeBase` allows for the creation of new declarative bases in such a way that is compatible with type checkers:: from sqlalchemy.orm import DeclarativeBase class Base(DeclarativeBase): pass The above ``Base`` class is now usable as the base for new declarative mappings. The superclass makes use of the ``__init_subclass__()`` method to set up new classes and metaclasses aren't used. When first used, the :class:`_orm.DeclarativeBase` class instantiates a new :class:`_orm.registry` to be used with the base, assuming one was not provided explicitly. The :class:`_orm.DeclarativeBase` class supports class-level attributes which act as parameters for the construction of this registry; such as to indicate a specific :class:`_schema.MetaData` collection as well as a specific value for :paramref:`_orm.registry.type_annotation_map`:: from typing_extensions import Annotated from sqlalchemy import BigInteger from sqlalchemy import MetaData from sqlalchemy import String from sqlalchemy.orm import DeclarativeBase bigint = Annotated[int, "bigint"] my_metadata = MetaData() class Base(DeclarativeBase): metadata = my_metadata type_annotation_map = { str: String().with_variant(String(255), "mysql", "mariadb"), bigint: BigInteger() } Class-level attributes which may be specified include: :param metadata: optional :class:`_schema.MetaData` collection. If a :class:`_orm.registry` is constructed automatically, this :class:`_schema.MetaData` collection will be used to construct it. Otherwise, the local :class:`_schema.MetaData` collection will supercede that used by an existing :class:`_orm.registry` passed using the :paramref:`_orm.DeclarativeBase.registry` parameter. :param type_annotation_map: optional type annotation map that will be passed to the :class:`_orm.registry` as :paramref:`_orm.registry.type_annotation_map`. :param registry: supply a pre-existing :class:`_orm.registry` directly. .. versionadded:: 2.0 Added :class:`.DeclarativeBase`, so that declarative base classes may be constructed in such a way that is also recognized by :pep:`484` type checkers. As a result, :class:`.DeclarativeBase` and other subclassing-oriented APIs should be seen as superseding previous "class returned by a function" APIs, namely :func:`_orm.declarative_base` and :meth:`_orm.registry.generate_base`, where the base class returned cannot be recognized by type checkers without using plugins. **__init__ behavior** In a plain Python class, the base-most ``__init__()`` method in the class hierarchy is ``object.__init__()``, which accepts no arguments. However, when the :class:`_orm.DeclarativeBase` subclass is first declared, the class is given an ``__init__()`` method that links to the :paramref:`_orm.registry.constructor` constructor function, if no ``__init__()`` method is already present; this is the usual declarative constructor that will assign keyword arguments as attributes on the instance, assuming those attributes are established at the class level (i.e. are mapped, or are linked to a descriptor). This constructor is **never accessed by a mapped class without being called explicitly via super()**, as mapped classes are themselves given an ``__init__()`` method directly which calls :paramref:`_orm.registry.constructor`, so in the default case works independently of what the base-most ``__init__()`` method does. .. versionchanged:: 2.0.1 :class:`_orm.DeclarativeBase` has a default constructor that links to :paramref:`_orm.registry.constructor` by default, so that calls to ``super().__init__()`` can access this constructor. Previously, due to an implementation mistake, this default constructor was missing, and calling ``super().__init__()`` would invoke ``object.__init__()``. The :class:`_orm.DeclarativeBase` subclass may also declare an explicit ``__init__()`` method which will replace the use of the :paramref:`_orm.registry.constructor` function at this level:: class Base(DeclarativeBase): def __init__(self, id=None): self.id = id Mapped classes still will not invoke this constructor implicitly; it remains only accessible by calling ``super().__init__()``:: class MyClass(Base): def __init__(self, id=None, name=None): self.name = name super().__init__(id=id) Note that this is a different behavior from what functions like the legacy :func:`_orm.declarative_base` would do; the base created by those functions would always install :paramref:`_orm.registry.constructor` for ``__init__()``. Mapper[Self]rcCsdSrr[rr[r[r\_sa_inspect_typerz DeclarativeBase._sa_inspect_typeInstanceState[Self]cCsdSrr[rr[r[r\_sa_inspect_instancerz$DeclarativeBase._sa_inspect_instanceClassVar[_RegistryType]r{rvClassVar[MetaData]rtz ClassVar[str]rjClassVar[Mapper[Any]]rdzClassVar[FromClause]rWr __tablename____mapper_args____table_args__rcKsdSrr[rr[r[r\r=rzDeclarativeBase.__init__r`rc s@t|jkrt|tt|nt|j||jtjf|dSr) r __bases___check_not_declarativerr'r{rerrrrr[r\r?s    z!DeclarativeBase.__init_subclass__) rjrkrlror?rrrrrrrr[r[rr\rts o     r)rUbaserVcCsR|j}d|kr(t|ds(t|ddr:t|ddtrNtd|jddS)NrWrrz Cannot use zR directly as a declarative base class. Create a Base by creating a subclass of it.) recallablerr~r}r_r5rrj)rUrcls_dictr[r[r\rHs   rcseZdZUdZded<ded<ded<ded<d ed <ejr~d d d dZdd ddZded<ded<ded<ddddZ dddfdd Z Z S)DeclarativeBaseNoMetazSame as :class:`_orm.DeclarativeBase`, but does not use a metaclass to intercept new attributes. The :class:`_orm.DeclarativeBaseNoMeta` base may be used when use of custom metaclasses is desirable. .. versionadded:: 2.0 rr{rvrrtrrdOptional[FromClause]rWrrcCsdSrr[rr[r[r\rrz&DeclarativeBaseNoMeta._sa_inspect_typercCsdSrr[rr[r[r\rrz*DeclarativeBaseNoMeta._sa_inspect_instancerrrrrcKsdSrr[rr[r[r\rrzDeclarativeBaseNoMeta.__init__r`rc s@t|jkrt|tt|nt|j||jtjf|dSr) rrrrr'r{rerrrrr[r\rs    z'DeclarativeBaseNoMeta.__init_subclass__) rjrkrlrorr?rrrrrrr[r[rr\rWs       rzMapperProperty[Any])targetraattrrVcCst|||dS)a'Add a new mapped attribute to an ORM mapped class. E.g.:: add_mapped_attribute(User, "addresses", relationship(Address)) This may be used for ORM mappings that aren't using a declarative metaclass that intercepts attribute set operations. .. versionadded:: 2.0 Nr%)rrarr[r[r\add_mapped_attributesrBasertmapperrUrclass_registryrrrOptional[MetaData]$Optional[Callable[..., Mapper[Any]]]&Optional[clsregistry._ClsRegistryType] Optional[_TypeAnnotationMapType]Callable[(Ellipsis, None)]r) rtrrUrrrrrrVcCst||||dj||||dS)aConstruct 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 :class:`_orm.Mapper` calls based on the information provided declaratively in the class and any subclasses of the class. .. versionchanged:: 2.0 Note that the :func:`_orm.declarative_base` function is superseded by the new :class:`_orm.DeclarativeBase` class, which generates a new "base" class using subclassing, rather than return value of a function. This allows an approach that is compatible with :pep:`484` typing tools. 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 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 :class:`_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 type_annotation_map: optional dictionary of Python types to SQLAlchemy :class:`_types.TypeEngine` classes or instances. This is used exclusively by the :class:`_orm.MappedColumn` construct to produce column types based on annotations within the :class:`_orm.Mapped` type. .. versionadded:: 2.0 .. seealso:: :ref:`orm_declarative_mapped_column_type_map` :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` )rtrrr)rrUrr)rv generate_baserr[r[r\declarative_basesnrc@s~eZdZUdZded<ded<ded<ded <d ed <d ed <ded<ded<ded<dddeddddddddZdddddZd d!d"d#d$Ze d%d&d'd(Z d)dd*d+d,Z d-dd.d/d0Z e d1d2d3d4d5Ze d1d2d3d6d7Zd8d&d9d:Zd-dd;ddd?d@dAZdBddCdDdEZdrdddGdHdIZdsdddGdJdKZdBddCdLdMZdedNefdOdPdQdPdRdSdTdUZejeeeee e!e"e#e$f dVe%d>d>dWdXdYZ&e%dtdZdZdZdZdZdZdZdZd[d\d]d]d]d]d]d]d]d^d_d` dadYZ&due'j(e'j(e'j(e'j(e'j(e'j(e'j(e'j(d[dbd]d]d]d]d]d]d]d^dcd` dddYZ&d>d>d?dedfZ)dRdgdhdidjZ*d>dkd?dldmZ+dvd>dndRdkdodpdqZ,dS)wrvaGeneralized 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 ``sqlalchemy.orm.mapper()`` classical mapping function, which is removed as of SQLAlchemy 2.0. .. versionadded:: 1.4 .. seealso:: :ref:`orm_mapping_classes_toplevel` - overview of class mapping styles. zclsregistry._ClsRegistryType_class_registryz;weakref.WeakKeyDictionary[ClassManager[Any], Literal[True]] _managersz5weakref.WeakKeyDictionary[Mapper[Any], Literal[True]]_non_primary_mappersr;rtz-CallableReference[Callable[(Ellipsis, None)]]r_MutableTypeAnnotationMapTyperzSet[_RegistryType] _dependents _dependenciesrS _new_mappersN)rtrrrrrrrc Cs|pt}|dkrt}||_t|_t|_||_||_i|_ |dk rX| |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. :param type_annotation_map: optional dictionary of Python types to SQLAlchemy :class:`_types.TypeEngine` classes or instances. The provided dict will update the default type mapping. This is used exclusively by the :class:`_orm.MappedColumn` construct to produce column types based on annotations within the :class:`_orm.Mapped` type. .. versionadded:: 2.0 .. seealso:: :ref:`orm_declarative_mapped_column_type_map` NFT)r;weakrefWeakValueDictionaryrWeakKeyDictionaryrrrtrrupdate_type_annotation_mapsetrrrrZ_CONFIGURE_MUTEXZ_mapper_registries)rrtrrrZ lcl_metadatar[r[r\r{s /    zregistry.__init___TypeAnnotationMapTyper`)rrVcCs|jdd|DdS)zQupdate the :paramref:`_orm.registry.type_annotation_map` with new values.cSs,i|]$\}}tj|dddD] }||qqS)T)Z include_unionZ discard_none) compat_typingZ expand_unions)rtypZsqltypeZsub_typer[r[r\rsz7registry.update_type_annotation_map..N)rrr)rrr[r[r\r s z#registry.update_type_annotation_maprNz"Optional[sqltypes.TypeEngine[Any]]) python_typerVc s }t|r|j}q|kt|rZt|rHtd|}|ft|ff}q|j}|ff}nPt|rvt|}|ff}n4t |t r|}fdd|j D}n|}|ff}|D]V\}}|j |}|dkrt|}|dk rt|}||||} | dk r| SqdS)Nrc3s|]}r|n|fVqdSrr[)rptZ check_is_ptrr[r\ sz)registry._resolve_type..)rE __value__rBrCrrF __origin__rDrAr~rfrXrr}r8Z _type_map_getZ to_instanceZ_resolve_for_python_type) rrZpython_type_to_checkZpython_type_typesearchrZ flattenedZsql_typeZ sql_type_instZresolved_sql_typer[rr\ _resolve_typesH           zregistry._resolve_typezFrozenSet[Mapper[Any]]rcCstdd|jD|jS)z9read only collection of all :class:`_orm.Mapper` objects.css|] }|jVqdSr)rrrr[r[r\rsz#registry.mappers..) frozensetrunionrrr[r[r\mappers szregistry.mappersru)rvrVcCs(||kr dS|j||j|dSr)raddr)rrvr[r[r\_set_depends_ons zregistry._set_depends_onz Mapper[Any])rrVcCs,d|_|jrdS||hD] }d|_qdSNT)_ready_for_configurer_recurse_with_dependents)rrrr[r[r\_flag_new_mappers zregistry._flag_new_mapperzSet[RegistryType]zIterator[RegistryType]) registriesrVccsP|}t}|rL|}||||j||V||j|q dSr)r poprrr differencerUr"tododonerr[r[r\r #s z!registry._recurse_with_dependentsccsP|}t}|rL|}||||j||V||j|q dSr)r r#rrrr$r%r[r[r\_recurse_with_dependencies6s z#registry._recurse_with_dependencieszIterator[Mapper[Any]]cCs,tddt|jDddt|jDS)Ncss*|]"}|jr|jjs|jjr|jVqdSr)rr configuredrrr[r[r\rLs z1registry._mappers_to_configure..css|]}|js|jr|VqdSr)r)r)rZnpmr[r[r\rSs) itertoolschainlistrrrr[r[r\_mappers_to_configureJszregistry._mappers_to_configure) np_mapperrVcCsd|j|<dSr)r)rr.r[r[r\_add_non_primary_mapperZsz registry._add_non_primary_mapperrRrTcCst|j||jdSr)rZ remove_classrjrrrUr[r[r\ _dispose_cls]szregistry._dispose_clszClassManager[Any])rrVcCs8d|j|<|jr td|j|jdks.t||_dS)NTz1Class '%s' already has a primary mapper defined. )rrr5 ArgumentErrorrZrvr)rrr[r[r\ _add_manager`s zregistry._add_managerF)cascaderVcCstj|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 r4N)rZ_configure_registriesrr4r[r[r\ configurejs'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` r5N)rZ_dispose_registriesr6r[r[r\disposeszregistry.disposecCs8d|jkr|j}||j}||tj|dS)Nr)rerZ_set_dispose_flagsrZr1rZ_instrumentation_factory unregister)rrrrZr[r[r\_dispose_manager_and_mappers   z$registry._dispose_manager_and_mapperrrrr_r)rrUrrrVc Cs|j}t|t r|fp|}t||d}t|tr<|j|d<|jdk rP|j|d<d|d<|rd||d<t|drd d d d d d }||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 __init__ = mapper_registry.constructor .. versionchanged:: 2.0 Note that the :meth:`_orm.registry.generate_base` method is superseded by the new :class:`_orm.DeclarativeBase` class, which generates a new "base" class using subclassing, rather than return value of a function. This allows an approach that is compatible with :pep:`484` typing tools. 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 :class:`_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` )rvrtroNrTr|Z__mapper_cls____class_getitem__rr)rUrarVcSs|Srr[rir[r[r\r;sz1registry.generate_base..__class_getitem__)rtr~tupledictrfrorr) rrrUrrrtrx class_dictr;r[r[r\rsN      zregistry.generate_baserp)_registry__clsrVcCsdSrr[)rr?r[r[r\mapped_as_dataclassszregistry.mapped_as_dataclass.rz Literal[None]rrzCallable[[Type[_O]], Type[_O]]) r?rrrrrrrrrVc CsdSrr[) rr?rrrrrrrrr[r[r\r@.s zOptional[Type[_O]]z/Union[Type[_O], Callable[[Type[_O]], Type[_O]]]c s8dddf dd } |r0| |S| SdS)a_Class decorator that will apply the Declarative mapping process to a given class, and additionally convert the class to be a Python dataclass. .. seealso:: :ref:`orm_declarative_native_dataclasses` - complete background on SQLAlchemy native dataclass mapping .. versionadded:: 2.0 rRrTc s0t|ddt||j|S)Nrr)setattrr'rer rrrrrrrrrr[r\r[sz.registry.mapped_as_dataclass..decorateNr[) rr?rrrrrrrrrr[rBr\r@=s$cCst|||j|S)aClass 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. .. seealso:: :meth:`_orm.registry.mapped_as_dataclass` )r'rer0r[r[r\mappedrs%zregistry.mappedCallable[[Type[_T]], Type[_T]]rc sdddfdd }|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: @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`. rrTcs|d<|jd<jfS)NrUr)rjrrrzrr[r\rs z.registry.as_declarative_base..decorater[)rrzrr[rEr\as_declarative_baseszregistry.as_declarative_basez Mapper[_O]cCst|||j|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` )r'rerdr0r[r[r\map_declarativelys-zregistry.map_declarativelyr)rZ local_tablerzrVcKst||||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 now-removed SQLAlchemy ``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 :class:`_orm.Mapper` constructor directly. .. seealso:: :ref:`orm_imperative_mapping` :ref:`orm_declarative_mapping` r,)rrZrHrzr[r[r\map_imperativelys6zregistry.map_imperatively)F)F).)N)N)-rjrkrlrorr)rr rpropertyrrr!rr r(r-r/r1r3r7r8r:rrsrrdataclass_transformr1r2r.r/rrrrrrr@r9rrCrFrGrIr[r[r[r\rvPs  D= ) g &$5(#3rvrDrcKs.|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: @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` rtNr)rtr)r#rvrF)rzrtrr[r[r\as_declarative-s  rLzOptional[Mapper[Any]]cCs(t|}|dkr$t|r$t||Sr)r!r*Zhas_clsZraise_unmapped_for_cls)rUmpr[r[r\_inspect_decl_metaSs   rN)F)ro __future__rr*rr?rrrrrrr r r r r rrrrrrrrrrrrrZ_orm_constructorsrrrrrr rr!r"r#r$Z decl_baser&r'r(r)r*r+r-Zdescriptor_propsr.r/rrr0 propertiesr1Z relationshipsr2stater3r5r6r7sqlr8Zsql.baser9Z sql.elementsr:Z sql.schemar;Zsql.selectabler<r=r>rZ util.typingr@rArBrCrDrErFrGZ_typingrHrIrJrKrLZ sql._typingrMZ sql.type_apirNrOrQr rZ_DeclaredAttrDecoratedr]rfr^Z InspectablermrKrrrsrrrZ_MappedAttributerrrrrrrrrrrrvrurLZ _inspectsrNr[r[r[r\s0                                                                                   *A*)A  U  k"{[&