
    ,hKL                    0   S r SSKJr  SSKrSSKrSSKJr  SSKJr  SSKJr  SSKJ	r	  SS	K
Jr  SS
KJr  SSKJr  SS	KJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  \(       a  SSKJ r    " S S5      r! " S S\!5      r" " S S5      r#g)z1Public API functions and helpers for declarative.    )annotationsN)Any)Callable)TYPE_CHECKING)Union   )exc)
Connection)Engine)relationships)_mapper_or_none)	_resolver)_DeferredMapperConfig)polymorphic_unionTable)OrderedDict)MetaDatac                  8    \ rS rSrSr\S 5       r\S 5       rSrg)ConcreteBase$   a  A helper class for 'concrete' declarative mappings.

:class:`.ConcreteBase` will use the :func:`.polymorphic_union`
function automatically, against all tables mapped as a subclass
to this class.   The function is called via the
``__declare_last__()`` function, which is essentially
a hook for the :meth:`.after_configured` event.

:class:`.ConcreteBase` produces a mapped
table for the class itself.  Compare to :class:`.AbstractConcreteBase`,
which does not.

Example::

    from sqlalchemy.ext.declarative import ConcreteBase


    class Employee(ConcreteBase, Base):
        __tablename__ = "employee"
        employee_id = Column(Integer, primary_key=True)
        name = Column(String(50))
        __mapper_args__ = {
            "polymorphic_identity": "employee",
            "concrete": True,
        }


    class Manager(Employee):
        __tablename__ = "manager"
        employee_id = Column(Integer, primary_key=True)
        name = Column(String(50))
        manager_data = Column(String(40))
        __mapper_args__ = {
            "polymorphic_identity": "manager",
            "concrete": True,
        }

The name of the discriminator column used by :func:`.polymorphic_union`
defaults to the name ``type``.  To suit the use case of a mapping where an
actual column in a mapped table is already named ``type``, the
discriminator name can be configured by setting the
``_concrete_discriminator_name`` attribute::

    class Employee(ConcreteBase, Base):
        _concrete_discriminator_name = "_concrete_discriminator"

.. versionadded:: 1.3.19 Added the ``_concrete_discriminator_name``
   attribute to :class:`_declarative.ConcreteBase` so that the
   virtual discriminator column name can be customized.

.. versionchanged:: 1.4.2 The ``_concrete_discriminator_name`` attribute
   need only be placed on the basemost class to take correct effect for
   all subclasses.   An explicit error message is now raised if the
   mapped column names conflict with the discriminator name, whereas
   in the 1.3.x series there would be some warnings and then a non-useful
   query would be generated.

.. seealso::

    :class:`.AbstractConcreteBase`

    :ref:`concrete_inheritance`


c                <    [        [        S U 5       5      US5      $ )Nc              3  P   #    U  H  oR                   UR                  4v   M     g 7fN)polymorphic_identitylocal_table).0mps     ]/var/www/auris/envauris/lib/python3.13/site-packages/sqlalchemy/ext/declarative/extensions.py	<genexpr>9ConcreteBase._create_polymorphic_union.<locals>.<genexpr>j   s       DKb(("..9Gs   $&pjoin)r   r   )clsmappersdiscriminator_names      r   _create_polymorphic_union&ConcreteBase._create_polymorphic_uniong   s,      DK  
 	
    c                   U R                   nUR                  (       a  g [        U SS 5      =(       d    Sn[        UR                  5      nU R                  X25      nUR                  SU45        UR                  UR                  U   5        g )N_concrete_discriminator_nametype*)	
__mapper__with_polymorphicgetattrlistself_and_descendantsr&   _set_with_polymorphic_set_polymorphic_onc)r#   mr%   r$   r"   s        r   __declare_first__ConcreteBase.__declare_first__q   s|    NN C7>H& 	 q--.--gJ	e-	egg&89:r(    N)	__name__
__module____qualname____firstlineno____doc__classmethodr&   r6   __static_attributes__r8   r(   r   r   r   $   s1    @D 
 
 ; ;r(   r   c                  L    \ rS rSrSrSr\S 5       r\S 5       r\S 5       r	Sr
g)	AbstractConcreteBase   aB  A helper class for 'concrete' declarative mappings.

:class:`.AbstractConcreteBase` will use the :func:`.polymorphic_union`
function automatically, against all tables mapped as a subclass
to this class.   The function is called via the
``__declare_first__()`` function, which is essentially
a hook for the :meth:`.before_configured` event.

:class:`.AbstractConcreteBase` applies :class:`_orm.Mapper` for its
immediately inheriting class, as would occur for any other
declarative mapped class. However, the :class:`_orm.Mapper` is not
mapped to any particular :class:`.Table` object.  Instead, it's
mapped directly to the "polymorphic" selectable produced by
:func:`.polymorphic_union`, and performs no persistence operations on its
own.  Compare to :class:`.ConcreteBase`, which maps its
immediately inheriting class to an actual
:class:`.Table` that stores rows directly.

.. note::

    The :class:`.AbstractConcreteBase` delays the mapper creation of the
    base class until all the subclasses have been defined,
    as it needs to create a mapping against a selectable that will include
    all subclass tables.  In order to achieve this, it waits for the
    **mapper configuration event** to occur, at which point it scans
    through all the configured subclasses and sets up a mapping that will
    query against all subclasses at once.

    While this event is normally invoked automatically, in the case of
    :class:`.AbstractConcreteBase`, it may be necessary to invoke it
    explicitly after **all** subclass mappings are defined, if the first
    operation is to be a query against this base class. To do so, once all
    the desired classes have been configured, the
    :meth:`_orm.registry.configure` method on the :class:`_orm.registry`
    in use can be invoked, which is available in relation to a particular
    declarative base class::

        Base.registry.configure()

Example::

    from sqlalchemy.orm import DeclarativeBase
    from sqlalchemy.ext.declarative import AbstractConcreteBase


    class Base(DeclarativeBase):
        pass


    class Employee(AbstractConcreteBase, Base):
        pass


    class Manager(Employee):
        __tablename__ = "manager"
        employee_id = Column(Integer, primary_key=True)
        name = Column(String(50))
        manager_data = Column(String(40))

        __mapper_args__ = {
            "polymorphic_identity": "manager",
            "concrete": True,
        }


    Base.registry.configure()

The abstract base class is handled by declarative in a special way;
at class configuration time, it behaves like a declarative mixin
or an ``__abstract__`` base class.   Once classes are configured
and mappings are produced, it then gets mapped itself, but
after all of its descendants.  This is a very unique system of mapping
not found in any other SQLAlchemy API feature.

Using this approach, we can specify columns and properties
that will take place on mapped subclasses, in the way that
we normally do as in :ref:`declarative_mixins`::

    from sqlalchemy.ext.declarative import AbstractConcreteBase


    class Company(Base):
        __tablename__ = "company"
        id = Column(Integer, primary_key=True)


    class Employee(AbstractConcreteBase, Base):
        strict_attrs = True

        employee_id = Column(Integer, primary_key=True)

        @declared_attr
        def company_id(cls):
            return Column(ForeignKey("company.id"))

        @declared_attr
        def company(cls):
            return relationship("Company")


    class Manager(Employee):
        __tablename__ = "manager"

        name = Column(String(50))
        manager_data = Column(String(40))

        __mapper_args__ = {
            "polymorphic_identity": "manager",
            "concrete": True,
        }


    Base.registry.configure()

When we make use of our mappings however, both ``Manager`` and
``Employee`` will have an independently usable ``.company`` attribute::

    session.execute(select(Employee).filter(Employee.company.has(id=5)))

:param strict_attrs: when specified on the base class, "strict" attribute
 mode is enabled which attempts to limit ORM mapped attributes on the
 base class to only those that are immediately present, while still
 preserving "polymorphic" loading behavior.

 .. versionadded:: 2.0

.. seealso::

    :class:`.ConcreteBase`

    :ref:`concrete_inheritance`

    :ref:`abstract_concrete_base`

Tc                $    U R                  5         g r   )_sa_decl_prepare_nocascader#   s    r   r6   &AbstractConcreteBase.__declare_first__  s    &&(r(   c                  ^^^^^ [        U SS 5      (       a  g [        R                  " U 5      n/ n[        U R	                  5       5      nU(       aW  UR                  5       nUR                  UR	                  5       5        [        U5      nUb  UR                  U5        U(       a  MW  [        U SS 5      =(       d    SmU R                  UT5      m[        UR                  5      nU Vs1 s H  owR                  iM     snm[        UR                  R                  5       5       HM  u  pX;   d  M  TR                  U	R                     UR                  U'   TR!                  U	R                  5        MO     TUl        U R$                  R'                  SS5      mUR(                  =(       d    [*        mUUUUU4S jn
Xl        UR-                  5         U /nU(       a  UR                  S5      nUR                  UR	                  5       5        [        U5      nU(       aY  UR.                  (       aH  UR0                  c;  UR2                  SS   H(  n[        U5      nU(       d  M  UR5                  U5          O   U(       a  M  g g s  snf )	Nr-   r*   r+   strict_attrsFc                    > T" 5       n TR                   T   U S'   SU S'   T(       a&  [        TR                  5      T-  T1-  U S'   ST4U S'   U $ )Npolymorphic_onTpolymorphic_abstractinclude_propertiesr,   r.   )r4   setprimary_key)argsdeclared_col_keysr%   m_argsr"   rH   s    r   mapper_argsDAbstractConcreteBase._sa_decl_prepare_nocascade.<locals>.mapper_args<  so    8D%*WW-?%@D!"+/D'())*'()*+ )*
 -0<'(Kr(   r      )r/   r   config_for_clsr0   __subclasses__popextendr   appendr&   rM   declared_columnskey
propertiesitemsr4   remover   __dict__getmapper_args_fndictmapconcreteinherits__mro___set_concrete_base)r#   to_mapr$   stackklassmndeclared_colsr4   kvrR   sclssmsup_sup_smrP   r%   rQ   r"   rH   s                  @@@@@r   rD   /AbstractConcreteBase._sa_decl_prepare_nocascade  s   3d++&55c: S'')*IIKELL--/0 'B~r" e C7>H& 	 --g7IJ F334,9:MqUUM:**0023DA!',wwquu~!!!$!((/ 4
 #||''>&&.$	 	 !,

99Q<DLL,,./ &Bbkkbkk&9 LL,D,T2Fv--f5	 - e= ;s   )Jc                Z    [         R                  " U S[         R                  " U 5      -  S9e)NzClass %s is a subclass of AbstractConcreteBase and has a mapping pending until all subclasses are defined. Call the sqlalchemy.orm.configure_mappers() function after all subclasses have been defined to complete the mapping of this class.msgorm_excUnmappedClassError_safe_cls_namerE   s    r   _sa_raise_deferred_config.AbstractConcreteBase._sa_raise_deferred_configY  s2    ((2
 $$S)*
 	
r(   r8   N)r9   r:   r;   r<   r=   __no_table__r>   r6   rD   r{   r?   r8   r(   r   rA   rA      sM    FP L) ) F FP 	
 	
r(   rA   c                  h    \ rS rSrSr\      S	S j5       r\    S
S j5       rSr\S 5       r	Sr
g)DeferredReflectionif  a	  A helper class for construction of mappings based on
a deferred reflection step.

Normally, declarative can be used with reflection by
setting a :class:`_schema.Table` object using autoload_with=engine
as the ``__table__`` attribute on a declarative class.
The caveat is that the :class:`_schema.Table` must be fully
reflected, or at the very least have a primary key column,
at the point at which a normal declarative mapping is
constructed, meaning the :class:`_engine.Engine` must be available
at class declaration time.

The :class:`.DeferredReflection` mixin moves the construction
of mappers to be at a later point, after a specific
method is called which first reflects all :class:`_schema.Table`
objects created so far.   Classes can define it as such::

    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.ext.declarative import DeferredReflection

    Base = declarative_base()


    class MyClass(DeferredReflection, Base):
        __tablename__ = "mytable"

Above, ``MyClass`` is not yet mapped.   After a series of
classes have been defined in the above fashion, all tables
can be reflected and mappings created using
:meth:`.prepare`::

    engine = create_engine("someengine://...")
    DeferredReflection.prepare(engine)

The :class:`.DeferredReflection` mixin can be applied to individual
classes, used as the base for the declarative base itself,
or used in a custom abstract class.   Using an abstract base
allows that only a subset of classes to be prepared for a
particular prepare step, which is necessary for applications
that use more than one engine.  For example, if an application
has two engines, you might use two bases, and prepare each
separately, e.g.::

    class ReflectedOne(DeferredReflection, Base):
        __abstract__ = True


    class ReflectedTwo(DeferredReflection, Base):
        __abstract__ = True


    class MyClass(ReflectedOne):
        __tablename__ = "mytable"


    class MyOtherClass(ReflectedOne):
        __tablename__ = "myothertable"


    class YetAnotherClass(ReflectedTwo):
        __tablename__ = "yetanothertable"


    # ... etc.

Above, the class hierarchies for ``ReflectedOne`` and
``ReflectedTwo`` can be configured separately::

    ReflectedOne.prepare(engine_one)
    ReflectedTwo.prepare(engine_two)

.. seealso::

    :ref:`orm_declarative_reflected_deferred_reflection` - in the
    :ref:`orm_declarative_table_config_toplevel` section.

c           
        [         R                  " U 5      n[        R                  " [        5      nU Hd  nUR
                  c  M  UUR
                  R                  UR
                  R                  4   R                  UR
                  R                  5        Mf     [        U[        5      (       a  Un[        R                  " US9nO@[        U[        5      (       a  UR                  5       nO[         R"                  " SU< 35      eU nUR%                  5        H   u  u  pn
UR&                  " U4U
U	SSS.UD6  M"     UR)                  5         U GH  nUR+                  5         UR,                  R.                  nUR0                  R                  nUR2                  R5                  5        GH  n[        U[6        R8                  5      (       d  M%  UR:                  R<                  R?                  5       (       d  MP  UR:                  R<                  n[        UR@                  [B        5      (       aB  UR@                  nUUR                  UR                  4   R                  UR                  5        M  [        UR@                  [D        5      (       d  M  [G        URH                  R0                  U5      u  nnU" UR@                  S5      nUXR
                  R                  4   R                  UR@                  5        U=RJ                  U RM                  U5      4-  sl%        U" 5       Ul         GM     GM     UR%                  5        H  u  u  pn
UR'                  UU
U	SSS9  M     SSS5        g! , (       d  f       g= f)a  Reflect all :class:`_schema.Table` objects for all current
:class:`.DeferredReflection` subclasses

:param bind: :class:`_engine.Engine` or :class:`_engine.Connection`
 instance

 ..versionchanged:: 2.0.16 a :class:`_engine.Connection` is also
 accepted.

:param \**reflect_kw: additional keyword arguments passed to
 :meth:`_schema.MetaData.reflect`, such as
 :paramref:`_schema.MetaData.reflect.views`.

 .. versionadded:: 2.0.16

N)enter_resultz#Expected Engine or Connection, got TF)onlyschemaextend_existingautoload_replace)'r   classes_for_basecollectionsdefaultdictrM   r   metadatar   addname
isinstancer
   
contextlibnullcontextr   connectsa_excArgumentErrorr]   reflectclearrc   r#   r-   class__propsvaluesr   RelationshipProperty
_init_args	secondary_is_populatedargumentr   strr   parent
_resolvers_sa_deferred_table_resolver)r#   bind
reflect_kwrh   metadata_to_tablethingyconnctxr   r   table_namesmapperrelsecondary_argsecondary_table_resolve_argresolvers                     r   prepareDeferredReflection.prepare  s   * '77<'33C8 F!!-!''00&2D2D2K2KL#f((--.	  dJ''D((d;Cf%%,,.C&&5dX>  D3D3J3J3L/"K  $!$(%* ! 4M ##% !

..!==11!==//1C"3(J(JKKNN44BBDD(+(@(@%m&<&<eDD.;.D.DO-$3$<$<$3$:$:!"
 "c/"6"67'(>(>DD-6szz7H7H#-NNA{'2 - 6 6(H .!)+=+=+D+D E!c-"8"89$// # ? ? I4 / 6>ZM2; 2 !J 4E3J3J3L/"K  $!$(%* !  4Mi SSs!   	CM.'M.:BM.CM..
M<c                   ^ SU4S jjnU$ )Nc                   > [        U T5      $ r   r   )r[   r   s    r   _resolve@DeferredReflection._sa_deferred_table_resolver.<locals>._resolve#  s     h''r(   )r[   r   returnr   r8   )r#   r   r   s    ` r   r   .DeferredReflection._sa_deferred_table_resolver  s    	(
 r(   Tc                Z    [         R                  " U S[         R                  " U 5      -  S9e)NzClass %s is a subclass of DeferredReflection.  Mappings are not produced until the .prepare() method is called on the class hierarchy.ru   rw   rE   s    r   r{   ,DeferredReflection._sa_raise_deferred_config,  s2    ((7 $$S)*
 	
r(   r8   N)r   zUnion[Engine, Connection]r   r   r   None)r   r   r   zCallable[[str], Table])r9   r:   r;   r<   r=   r>   r   r   _sa_decl_preparer{   r?   r8   r(   r   r   r   f  sy    L\ g,g<?g	g gR 	  
 
r(   r   )$r=   
__future__r   r   r   typingr   r   r   r    r	   r   enginer
   r   ormrx   r   orm.baser   orm.clsregistryr   orm.decl_baser   orm.utilr   r   r   utilr   
sql.schemar   r   rA   r   r8   r(   r   <module>r      sn    8 "            !   ' ( 2 )  &Z; Z;zb
< b
JN
 N
r(   