L i   dZddlmZddlZddlZddlZddlmZddlmZddlmZddlm Z ddlm Z dd lm Z dd lm Z dd lm Z dd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#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*m/Z/dd*l*m0Z0dd+l*m1Z1dd,l2m3Z3dd-l2m4Z4dd-l2m4Z5dd.l6m7Z7dd/l8m9Z9dd0l:m;Z;dd1lZ>d2d4lm?Z?d2d5lm@Z@d2d6lAmBZBd2d7lCmDZDd2d8lEmFZFd2d9lGmHZHd2d:lImJZJd2d;l@mKZKd2dl@mNZNd2d?lOmPZPd2d@lOmQZQd2dAlOmRZRd2dBlOmSZSd2dClOmTZTd2dDlOmUZUd2dElOmVZVd2dFlOmWZWd2dGlOmXZXd2dHlOmYZYd2dIlOmZZZer0ddJl[m\Z\ddKl[m]Z]ddLl*m^Z^ddMlm_Z_ddNlm`Z`dd1leZdZUded<ded< ddZy)DeclarativeMetar;metadata RegistryTyperegistryc 8|j}t|dd}|>|jdd}t|tst j d||_|jjdds t|||tj||||y)N _sa_registryrziDeclarative base class has no 'registry' attribute, or registry is not a sqlalchemy.orm.registry() object __abstract__F) rdrYget isinstancerr5InvalidRequestErrorrr're__init__)rZ classnamebasesdict_kwregs r\rzDeclarativeMeta.__init__s   c>40 ;))J-Cc8,--L $' ||6 Ce , c9eU3r^N) rrrrrrrrrmrn)rorprq__annotations__rrrr^r\r|r|s;44$'4034;>4 4r^r|cdfd }|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. c t|S)N) map_column descriptor) _orm_synonym)fnrnames r\decoratezsynonym_for..decoratesDZBGGr^)rCallable[..., Any]rmz Synonym[Any]rr)rrrs`` r\ synonym_forrsHH Or^c4eZdZ d ddZddZddZy) _declared_attr_commonct|tr |j}||_||_||_|j |_yN)r classmethod__func__fget _cascading_quietrv)selfr cascadingquiets r\rz_declared_attr_common.__init__s7 b+ &B # zz r^c^tj|jjdS)Nrm)r7get_annotationsrrrs r\_collect_return_annotationz0_declared_attr_common._collect_return_annotation s"##DII.228< !   99S> !#335 +++00 3;t9 "iin ,CIJr^N)FF)rrrboolrr)rmzOptional[Type[Any]])rOptional[object]rrrmr)rorprqrrrrrr^r\rrs5  " "" "*=%r^rcXeZdZejr d ddZd dZd dZd dZd dZ yy) _declared_directivecyrrrrrrs r\rz_declared_directive.__init__; r^cyrrrrrrs r\rz_declared_directive.__get__Ar^cyrrrrrrhs r\__set__z_declared_directive.__set__Crr^cyrrrrrs r\ __delete__z_declared_directive.__delete__Err^cyrrrrrs r\__call__z_declared_directive.__call__Gs r^NF)rzCallable[..., _T]rr)rrrrrmrSrrrhrrmrnrrrmrn)rzCallable[..., _TT]rmz_declared_directive[_TT]) rorprqr?rrrrrrrrr^r\rr6s? $ !   MA8 r^rceZdZdZej r3 d d dZddZddZe ddZ e ddZ ddZ e ddZ e dd Ze dd Zy ) 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`. cyrrrrs r\rzdeclared_attr.__init__rr^cyrrrrs r\rzdeclared_attr.__set__rr^cyrrrrs r\rzdeclared_attr.__delete__rr^cyrrrrs r\rzdeclared_attr.__get__s),r^cyrrrrs r\rzdeclared_attr.__get__s?Br^cyrrrrs r\rzdeclared_attr.__get__s36r^c tdi|SNrr)_stateful_declared_attr)rZrs r\ _statefulzdeclared_attr._statefuls&,,,r^ctSr)rrZs r\ directivezdeclared_attr.directives #"r^c&|jdS)NT)r)rrs r\rzdeclared_attr.cascadings}}t},,r^Nr)r_DeclaredAttrDecorated[_T]rrrr)rrnrrrmzInstrumentedAttribute[_T])robjectrrrmrS)rrrrrmz$Union[InstrumentedAttribute[_T], _T]rrrm_stateful_declared_attr[_T])rmz_declared_directive[Any])rmr)rorprqrvr?rrrrrrr=rr>rrrrr^r\rrLsZx $ *   B8  ,  ,), , & ,  , B B 7, 758 7 1 7--##--r^rc:eZdZUded<ddZeddZd dZy) rzDict[str, Any]rc ||_yr)rrrs r\rz _stateful_declared_attr.__init__s r^c n|jj}|j|tdi|Sr)rcopyupdater)rrnew_kws r\rz!_stateful_declared_attr._statefuls+ b&000r^c.t|fi|jSr)rrrs r\rz _stateful_declared_attr.__call__sR+477++r^Nrrr)rrrmzdeclared_attr[_T])rorprqrrr=rrrrr^r\rrs&11 ,r^rc|S)aMark 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 .. legacy:: This api is considered legacy and will be deprecated in the next SQLAlchemy version. .. seealso:: :ref:`orm_mixins_toplevel` :ref:`mypy_declarative_mixins` - in the :ref:`Mypy plugin documentation ` rrrs r\declarative_mixinrs X Jr^cNd|jvr|jd}nd}d|jvr|jd}nd}|jjdd}|r^ceZdZUdZded<ded< ded< ded< d ed < ej rdd Zdd Zd ed< d ed< d ed< ddZ dfd Z xZ 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 rrrrr}rrcOptional[FromClause]rWcyrrrrs r\rz&DeclarativeBaseNoMeta._sa_inspect_typerr^cyrrrrs r\rz*DeclarativeBaseNoMeta._sa_inspect_instancerr^rrrrc yrrrrs r\rzDeclarativeBaseNoMeta.__init__rr^c t|jvrt|tt|n!t |j ||j t| di|yr) r'rrrr'rrdrrrs r\rz'DeclarativeBaseNoMeta.__init_subclass__sH CMM 1 "3(= > #C ( C,,c3<< @ !'B'r^rr rr!) rorprqrvrr?rrrrrr r s@r\r'r'as *)%%8! &%$# 7B    +((r^r'ct|||y)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%)targetrgattrs r\add_mapped_attributer0s 63%r^Baser}mapperrZrclass_registryrrr cFt||||j||||S)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` )r}r4rr)r3rZrr )r generate_baser2s r\declarative_baser7s;\ %/   m    r^c "eZdZUdZded<ded<ded<ded <d ed <d ed <ded<ded<ded<ddded d0dZ d1dZ d2 d3dZe d4dZ d5dZ d6dZ e d7dZe d7dZd8dZd9dZd:dZd;d Zd2dd'Z&e% d?d(d(d(d(d(d(d(d(d) d@d*Z& dAe'jPe'jPe'jPe'jPe'jPe'jPe'jPe'jPd) dBd+Z&dCd,Z)dDd-Z*dEd.Z+ dA dFd/Z,y)GraGeneralized 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;r}z&CallableReference[Callable[..., None]]r_MutableTypeAnnotationMapTyperzSet[_RegistryType] _dependents _dependenciesr _new_mappersN)r}r4rrc|xs t}|tj}||_tj|_tj|_||_||_i|_ ||j|t|_ t|_ d|_tj 5dtj"|<dddy#1swYyxYw)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;weakrefWeakValueDictionaryr9WeakKeyDictionaryr:r;r}rrupdate_type_annotation_mapsetr=r>r?r_CONFIGURE_MUTEX_mapper_registries)rr}r4rr lcl_metadatas r\rzregistry.__init__s^ -8:  !$88:N- 224$+$=$=$?!$ &#%  *  + +,? @5 U!  ' ' 615I ( ( . 6 6 6s ;CC!c |jj|jDcic]\}}t||c}}ycc}}w)zQupdate the :paramref:`_orm.registry.type_annotation_map` with new values.N)rrrrB)rrtypsqltypes r\rDz#registry.update_type_annotation_mapsL   ''%8$=$=$?  C+3/8   sA c. t|r5t|r| | fg fdtD}n?|j | ff}n-t |t r| d j D}n| | ff}|D]h\}}|jj|}|tj|}|;tj|}|j ||}|f|cS|rd} d} t|rH|} t| r.t| s#| j} t| r t| s#t!| } d} t#|r t%|} d} | G|j'| d} | 3| J| dk(rt)d| d|dd | St)d | d|d d | Sy) Nc3&K|]}|f ywrrr).0ltpython_type_types r\ z)registry._resolve_type..sEr+,Esc3$K|]}||f ywrrr)rNpts r\rQz)registry._resolve_type..sB2r2hBsz pep-695 typeNewTypeFz Matching to z 'z' in a recursive fashion without the recursed type being present in the type_annotation_map is deprecated; add this type or its recursed value to the type_annotation_map to allow it to match explicitly.z2.0zMatching the provided z' on its resolved value without matching it in the type_annotation_map is deprecated; add this type to the type_annotation_map to allow it to match explicitly.)rDrErJ __origin__rrerXrrr8 _type_map_get to_instance_resolve_for_python_typerHrG __value__rBrFrC _resolve_typer@) r python_type _do_fallbackssearchrS flattenedsql_type sql_type_instresolved_sql_typepython_type_to_checkkindres_after_fallbackrPs @r\rZzregistry._resolve_types& k "+&#. !"23E}E $/#9#9 &(89;  T ** B)9)A)ABF* "$457F# -MB //33B7H#11"5# ( 4 4X > %2$J$J$%! %0,,) -. (, D%'2$ 45i(?,@+I+I( 45i(?(B(($&+&'6{'C$ #/%)%7%7(%&"&1+++~-'*4&;-@**" (.-(4TF"[MJ** ".-r^cltd|jDj|jS)z9read only collection of all :class:`_orm.Mapper` objects.c34K|]}|jywr)r3rNrs r\rQz#registry.mappers..;sFGFs) frozensetr:unionr;rs r\mapperszregistry.mappers7s/Ft~~FFLL  % %  r^cz||ury|jj||jj|yr)r=addr>)rrs r\_set_depends_onzregistry._set_depends_on?s5 t    & x(r^chd|_|jry|j|hD] }d|_ yNT)_ready_for_configurer?_recurse_with_dependents)rr3rs r\_flag_new_mapperzregistry._flag_new_mapperEs:&*#    00$8 $C#C  $r^c#"K|}t}|r}|j}|j||j|jj |||j|jj ||r|yywr)rEpoprlrr= differencerZ registriestododoners r\rqz!registry._recurse_with_dependentsMsqu((*C HHSM KK2248 9I KK2248 9 B B Bc#"K|}t}|r}|j}|j||j|jj |||j|jj ||r|yywr)rErtrlrr>rurvs r\_recurse_with_dependenciesz#registry._recurse_with_dependencies`suu((*C HHSM KK))44T: ;I KK))44T: ;rzctjdt|jDdt|jDS)Nc3K|]H}|jr:|jjs$|jjr|jJywr)rr3 configuredrprgs r\rQz1registry._mappers_to_configure..vs? $$11NN77  sAAc3PK|]}|js|jr| ywr)rrp)rNnpms r\rQz1registry._mappers_to_configure..}s' ~~#*B*B s$&) itertoolschainlistr:r;rs r\_mappers_to_configurezregistry._mappers_to_configuretsA #DNN3   9 9:   r^c"d|j|<yro)r;)r np_mappers r\_add_non_primary_mapperz registry._add_non_primary_mappers/3!!),r^cZtj|j||jyr)r remove_classror9rrZs r\ _dispose_clszregistry._dispose_clss  sD4H4HIr^cd|j|<|jr"tjd|jz|j J||_y)NTz1Class '%s' already has a primary mapper defined. )r:rr5 ArgumentErrorr[r)rrs r\ _add_managerzregistry._add_managersW"&w   ##C..! '''r^c4tj|h|y)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)r_configure_registriesrrs r\ configurezregistry.configuresN ''@r^c4tj|h|y)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)r_dispose_registriesrs r\disposezregistry.disposes0 %%tfg>r^cd|jvr|j}|j|j}|j |t j j|y)Nr3)rdr3_set_dispose_flagsr[rr_instrumentation_factory unregister)rrr3r[s r\_dispose_manager_and_mapperz$registry._dispose_manager_and_mappersP w'' '^^F  % % ' &!00;;FCr^r1c2|j}t|t xr|fxs|}t||}t|tr|j |d<|j |j |d<d|d<|r||d<t|dr 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` )rr}rvrTr__mapper_cls____class_getitem__c|Srrrrks r\rz1registry.generate_base..__class_getitem__Bs r^)rZType[_T]rgrrmr)r}rtupledictrervrr) rr3rZrr r}r class_dictrs r\r6zregistry.generate_bases`==sE**5v<%)4(%K c4 $'KKJy !    '%)%5%5Jz "%) >" +1J' ( 3+ , /@J* +uj11r^rwcyrrr)r_registry__clss r\mapped_as_dataclasszregistry.mapped_as_dataclassJs ADr^.rcyrrr) rrrrrrrrrrs r\rzregistry.mapped_as_dataclassZs*-r^c H d f d } |r| |S| S)aClass 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 :func:`_orm.mapped_as_dataclass` - functional version that may provide better compatibility with mypy .. versionadded:: 2.0 c b t|d dt||j|S)Nrr)setattrr'rd) rZrrrrrrrrrs r\rz.registry.mapped_as_dataclass..decoratesE )  "#.",&*<   D#s|| 4Jr^rZType[_O]rmrrr) rrrrrrrrrrrs ` ```````` r\rzregistry.mapped_as_dataclassis#@  $ E? "Or^c4t|||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'rdrs r\mappedzregistry.mappedsL c3<<0 r^c dfd }|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`. cP|d<|jd<jdiS)NrZrrr)ror6)rZrrs r\rz.registry.as_declarative_base..decorates/BuIBvJ%4%%++ +r^rZrrmrrr)rrrs`` r\as_declarative_basezregistry.as_declarative_bases< , r^cHt|||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'rdrcrs r\map_declarativelyzregistry.map_declarativelys^ c3<<0~~r^c t||||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,)rr[ local_tablers r\map_imperativelyzregistry.map_imperatively sptV["55r^)r}Optional[MetaData]r4&Optional[clsregistry._ClsRegistryType]r Optional[_TypeAnnotationMapType]rCallable[..., None])r_TypeAnnotationMapTypermrnr)r[rRr\rrmz"Optional[sqltypes.TypeEngine[Any]])rmzFrozenSet[Mapper[Any]])rr~rmrn)r3 Mapper[Any]rmrn)rwzSet[RegistryType]rmzIterator[RegistryType])rmzIterator[Mapper[Any]])rrrmrn)rZrrmrn)rzClassManager[Any]rmrn)rrrmrn) r3$Optional[Callable[..., Mapper[Any]]]rZ Type[Any]rrlr rrmr)rrrmr).)rz Literal[None]rr rr rr rr rr rr rr rr rmCallable[[Type[_O]], Type[_O]]r)rzOptional[Type[_O]]rr rr rr rr rr rr rr rr rmz/Union[Type[_O], Callable[[Type[_O]], Type[_O]]]rrrrmzCallable[[Type[_T]], Type[_T]])rZrrm Mapper[_O])r[rrr(rrrmr)-rorprqrvrr)rrDrZpropertyrjrmrrrrqr|rrrrrrrrr|r6 compat_typingdataclass_transformr1r2r.r/rrrrrrrr9rrrrrrrr^r\rrZsk@21JJOO7766##%% (,AE@D+C B6%B6? B6 > B6 ) B6H  3     BG^)^:>^ +^@  ) $:*: ::$<*< <<& 4J 'AR?4D8<. g24g2g2 g2  g2 g2R']&&           C D  # -%($'"%%(+.*-'*FI - -" - " - -# -) -( -% -D - ( - - %)5%+MM$*MM"(--%+]]+1==*0--'-}} MM5!5" 5 " 5 5#5)5(5%5 5 95n'R#J0j-18686*86 86  86r^rc |jdd|jdd}}t||jdi|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` r}Nr4)r}r4rr)rtrr)rr}r4s r\as_declarativerbsQ> z4  &H  8.    r^rc 4|j||||||||S)aStandalone function form of :meth:`_orm.registry.mapped_as_dataclass` which may have better compatibility with mypy. The :class:`_orm.registry` is passed as the first argument to the decorator. e.g.:: from sqlalchemy.orm import Mapped from sqlalchemy.orm import mapped_as_dataclass from sqlalchemy.orm import mapped_column from sqlalchemy.orm import registry some_registry = registry() @mapped_as_dataclass(some_registry) class Relationships: __tablename__ = "relationships" entity_id1: Mapped[int] = mapped_column(primary_key=True) entity_id2: Mapped[int] = mapped_column(primary_key=True) level: Mapped[int] = mapped_column(Integer) .. versionadded:: 2.0.44 r)r) rrrrrrrrrs r\rrs5l  ' '   - (  r^ctt|}|*tj|rtj||Sr)r!r*has_clsraise_unmapped_for_cls)rZmps r\_inspect_decl_metars4!6c :B z ( ( - ! 8 8 = Ir^)rZrrmrr)rrlrrrmz,Callable[[Callable[..., Any]], Synonym[Any]]r)rZrrmrn)rZrr$rrmrn)r.rrgrlr/zMapperProperty[Any]rmrn)r}rr3rrZrrrlr4rrrrrr rrmrr)rr~rr rr rr rr rr rr rr rr rmr)rZrrmzOptional[Mapper[Any]])rv __future__rrrr?rrrrrr r r r r rrrrrrrrArrrrr_orm_constructorsrrrrrr r$r!r"r#r$ decl_baser&r'r(r)r*r+r-descriptor_propsr.r/rr3r0 propertiesr1 relationshipsr2stater3r5r6r7sqlr8sql.baser9 sql.elementsr: sql.schemar;sql.selectabler<r=r>rr@ util.typingrArBrCrDrErFrGrHrIrJrK_typingrLrMrNrOrP sql._typingrQ sql.type_apirRrSrUrr<_DeclaredAttrDecoratedr]rer` Inspectablertrrzr|rrr_MappedAttributerrrrrrrr'r0rr7rr~rrr _inspectsrrrr^r\rs8"  (',+&-'"%&-/,%'%5$/ ,!'!*"+4)$$$##!'&.-*$1- T e3!&@!@A $S*D%D E!vbz=,.?.CC DD & 'T ' 6#;' #""  8:8 8434>#(' ''1'T>>B/,E-J//35JE-P ,mB/ , ,^&0R>"8>BR(=-.+R(j  h(=-.h(V& &&&9& &*$(37=A<@'?*x x 1x  x  x ; x:x%xx xv~ 6~ 6B M% P#""   !' & $mm!''-}}&,mm#)==  22 2  2  2  2%2$2!22$2 2j_&Cr^