
    +h@                         d Z ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddl	m
Z
 ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ  ej(                  dd      d        Z G d de      Z G d de      Z G d de      Zy)z1Public API functions and helpers for declarative.   )
inspection)util)exc)registry)relationships)_mapper_or_none)	_resolver)_DeferredMapperConfig)polymorphic_union)Table)OrderedDictz2.0zthe instrument_declarative function is deprecated and will be removed in SQLAlhcemy 2.0.  Please use :meth:`_orm.registry.map_declarativelyc                 <    t        ||      j                  |        y)zGiven a class, configure the class declaratively,
    using the given registry, which can be any dictionary, and
    MetaData object.

    )metadataclass_registryN)r   map_declaratively)clscls_registryr   s      X/var/www/html/venv/lib/python3.12/site-packages/sqlalchemy/ext/declarative/extensions.pyinstrument_declarativer      s     h|<NN    c                   0    e Zd ZdZed        Zed        Zy)ConcreteBasea_	  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                 <    t        t        d |D              |d      S )Nc              3   L   K   | ]  }|j                   |j                  f  y wN)polymorphic_identitylocal_table).0mps     r   	<genexpr>z9ConcreteBase._create_polymorphic_union.<locals>.<genexpr>k   s$      >@(("..9s   "$pjoin)r   r   )r   mappersdiscriminator_names      r   _create_polymorphic_unionz&ConcreteBase._create_polymorphic_unionh   s,      DK  
 	
r   c                    | j                   }|j                  ry t        | dd       xs d}t        |j                        }| j                  ||      }|j                  d|f       |j                  |j                  |          y )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__zConcreteBase.__declare_first__r   s    NN C7>H& 	 q--.--g7IJ	e-	egg&89:r   N)__name__
__module____qualname____doc__classmethodr$   r2    r   r   r   r   (   s0    =~ 
 
 ; ;r   r   c                   D    e Zd ZdZdZed        Zed        Zed        Zy)AbstractConcreteBasea$  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_last__()`` function, which is essentially
    a hook for the :meth:`.after_configured` event.

    :class:`.AbstractConcreteBase` does produce a mapped class
    for the base class, however it is not persisted to any table; it
    is instead mapped directly to the "polymorphic" selectable directly
    and is only used for selecting.  Compare to :class:`.ConcreteBase`,
    which does create a persisted table for the base class.

    .. 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.ext.declarative import AbstractConcreteBase
        from sqlalchemy.orm import declarative_base

        Base = declarative_base()

        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 system.

    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`::

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

        class Employee(AbstractConcreteBase, Base):
            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))
        )

    .. seealso::

        :class:`.ConcreteBase`

        :ref:`concrete_inheritance`

        :ref:`abstract_concrete_base`

    Tc                 $    | j                          y r   )_sa_decl_prepare_nocascader   s    r   r2   z&AbstractConcreteBase.__declare_first__   s    &&(r   c                 X   t        | dd       ry t        j                  |       }g }t        | j	                               }|rP|j                         }|j                  |j	                                t        |      }||j                  |       |rPt        | dd       xs d| j                  |      t        |j                        }t        |j                  j                               D ]0  \  }}||v sj                  |j                     |j                  |<   2 |_        |j"                  xs t$        fd}	|	|_        |j'                         }
| j	                         D ]=  }t        |      }|s|j(                  s| |j*                  v s-|j-                  |
       ? y )Nr)   r&   r'   c                  :            } j                      | d<   | S )Npolymorphic_on)r0   )argsr#   m_argsr!   s    r   mapper_argszDAbstractConcreteBase._sa_decl_prepare_nocascade.<locals>.mapper_args#  s$    8D%*WW-?%@D!"Kr   )r+   r
   config_for_clsr,   __subclasses__popextendr   appendr$   setdeclared_columns
propertiesitemsr0   keyr   mapper_args_fndictmapconcrete	__bases___set_concrete_base)r   to_mapr"   stackklassmndeclared_colskvrC   r1   sclssmr#   rB   r!   s                @@@r   r<   z/AbstractConcreteBase._sa_decl_prepare_nocascade   s   3d+&55c: S'')*IIKELL--/0 'B~r"  C7>H& 	 --g7IJ F334**0023 	6DAqM!',wwquu~!!!$	6 #&&.$	
 !,JJL&&( 	)D &BbkkcT^^&;%%a(	)r   c                 \    t        j                  | dt        j                  |       z        )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_namer=   s    r   _sa_raise_deferred_configz.AbstractConcreteBase._sa_raise_deferred_config1  s2    ((2
 $$S)*
 	
r   N)	r3   r4   r5   r6   __no_table__r7   r2   r<   rd   r8   r   r   r:   r:      sK    pd L) ) 3) 3)j 	
 	
r   r:   c                   `    e Zd ZdZed        Zed        Zed        Zed        Zed        Z	y)DeferredReflectionaN
  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           	         t        j                  |       }t        j                  |      j	                         5 }|D ]s  }| j                  |j                  |       |j                          |j                  j                  }|j                  j                  }|j                  j                         D ]  }t        |t        j                         s|j"                  +t        |j"                  t$              r| j'                  |j"                  |       bt        |j"                  t(              s}t+        |j,                  j                  |      \  }}	 |	|j"                        |_        |j"                  xj.                  | j1                  ||      fz  c_        |j#                         |_         v 	 ddd       y# 1 sw Y   yxY w)zjReflect all :class:`_schema.Table` objects for all current
        :class:`.DeferredReflection` subclassesN)r
   classes_for_baser   inspect_inspection_context_sa_decl_preparer   rP   r   r)   class_r   _propsvalues
isinstancer   RelationshipProperty	secondaryr   _reflect_tablestrr	   parent
_resolvers_sa_deferred_table_resolver)
r   enginerT   inspthingymapperr   rel_resolve_args
             r   preparezDeferredReflection.prepare  sZ   
 '77<';;= 	<  <$$V%7%7>

..!==11!==//1 <C"3(J(JKMM5%cmmU;..s}}dC's;-6szz7H7H#-NNA{,7,FCMMM44 # ? ?$((!"9 4 -0MMOCM+<<	< 	< 	<s    BF=F=AF=/BF==Gc                       fd}|S )Nc                 D    t        |       }j                  |       |S r   )r   rs   )rM   t1r   	inspectorr   s     r   _resolvez@DeferredReflection._sa_deferred_table_resolver.<locals>._resolve  s$    sH%Br9-Ir   r8   )r   r   r   r   s   ``` r   rw   z.DeferredReflection._sa_deferred_table_resolver  s    	
 r   c                 .    || j                  ||       y y r   )rs   )r   r   r   s      r   rl   z#DeferredReflection._sa_decl_prepare  s     "{I6 #r   c                 \    t        j                  | dt        j                  |       z        )NzClass %s is a subclass of DeferredReflection.  Mappings are not produced until the .prepare() method is called on the class hierarchy.r^   r`   r=   s    r   rd   z,DeferredReflection._sa_raise_deferred_config  s2    ((7 $$S)*
 	
r   c                 b    t        |j                  |j                  dd||j                         y )NTF)extend_existingautoload_replaceautoload_withschema)r   namer   r   )r   tabler   s      r   rs   z!DeferredReflection._reflect_table  s(    JJNN "#<<	
r   N)
r3   r4   r5   r6   r7   r   rw   rl   rd   rs   r8   r   r   rg   rg   >  sn    EN !< !<F   7 7 
 
 
 
r   rg   N)r6    r   r   ormr   ra   r   r   orm.baser   orm.clsregistryr	   orm.decl_baser
   orm.utilr   r   r   r   
deprecatedr   objectr   r:   rg   r8   r   r   <module>r      s    8   !    ' ( 2 )   	-W;6 W;ty
< y
xQ
 Q
r   