§
    eŠtjò-  ã                  óî   — 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rd
dlmZ d
dlmZ dgZ e	d¦  «        Z G d„ dee         ¦  «        ZdS )a7  Define attributes on ORM-mapped classes that have "index" attributes for
columns with :class:`_types.Indexable` types.

"index" means the attribute is associated with an element of an
:class:`_types.Indexable` column with the predefined index to access it.
The :class:`_types.Indexable` types include types such as
:class:`_types.ARRAY`, :class:`_types.JSON` and
:class:`_postgresql.HSTORE`.



The :mod:`~sqlalchemy.ext.indexable` extension provides
:class:`_schema.Column`-like interface for any element of an
:class:`_types.Indexable` typed column. In simple cases, it can be
treated as a :class:`_schema.Column` - mapped attribute.

Synopsis
========

Given ``Person`` as a model with a primary key and JSON data field.
While this field may have any number of elements encoded within it,
we would like to refer to the element called ``name`` individually
as a dedicated attribute which behaves like a standalone column::

    from sqlalchemy import Column, JSON, Integer
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.ext.indexable import index_property

    Base = declarative_base()


    class Person(Base):
        __tablename__ = "person"

        id = Column(Integer, primary_key=True)
        data = Column(JSON)

        name = index_property("data", "name")

Above, the ``name`` attribute now behaves like a mapped column.   We
can compose a new ``Person`` and set the value of ``name``::

    >>> person = Person(name="Alchemist")

The value is now accessible::

    >>> person.name
    'Alchemist'

Behind the scenes, the JSON field was initialized to a new blank dictionary
and the field was set::

    >>> person.data
    {'name': 'Alchemist'}

The field is mutable in place::

    >>> person.name = "Renamed"
    >>> person.name
    'Renamed'
    >>> person.data
    {'name': 'Renamed'}

When using :class:`.index_property`, the change that we make to the indexable
structure is also automatically tracked as history; we no longer need
to use :class:`~.mutable.MutableDict` in order to track this change
for the unit of work.

Deletions work normally as well::

    >>> del person.name
    >>> person.data
    {}

Above, deletion of ``person.name`` deletes the value from the dictionary,
but not the dictionary itself.

A missing key will produce ``AttributeError``::

    >>> person = Person()
    >>> person.name
    AttributeError: 'name'

Unless you set a default value::

    >>> class Person(Base):
    ...     __tablename__ = "person"
    ...
    ...     id = Column(Integer, primary_key=True)
    ...     data = Column(JSON)
    ...
    ...     name = index_property("data", "name", default=None)  # See default

    >>> person = Person()
    >>> print(person.name)
    None


The attributes are also accessible at the class level.
Below, we illustrate ``Person.name`` used to generate
an indexed SQL criteria::

    >>> from sqlalchemy.orm import Session
    >>> session = Session()
    >>> query = session.query(Person).filter(Person.name == "Alchemist")

The above query is equivalent to::

    >>> query = session.query(Person).filter(Person.data["name"] == "Alchemist")

Multiple :class:`.index_property` objects can be chained to produce
multiple levels of indexing::

    from sqlalchemy import Column, JSON, Integer
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.ext.indexable import index_property

    Base = declarative_base()


    class Person(Base):
        __tablename__ = "person"

        id = Column(Integer, primary_key=True)
        data = Column(JSON)

        birthday = index_property("data", "birthday")
        year = index_property("birthday", "year")
        month = index_property("birthday", "month")
        day = index_property("birthday", "day")

Above, a query such as::

    q = session.query(Person).filter(Person.year == "1980")

On a PostgreSQL backend, the above query will render as:

.. sourcecode:: sql

    SELECT person.id, person.data
    FROM person
    WHERE person.data -> %(data_1)s -> %(param_1)s = %(param_2)s

Default Values
==============

:class:`.index_property` includes special behaviors for when the indexed
data structure does not exist, and a set operation is called:

* For an :class:`.index_property` that is given an integer index value,
  the default data structure will be a Python list of ``None`` values,
  at least as long as the index value; the value is then set at its
  place in the list.  This means for an index value of zero, the list
  will be initialized to ``[None]`` before setting the given value,
  and for an index value of five, the list will be initialized to
  ``[None, None, None, None, None]`` before setting the fifth element
  to the given value.   Note that an existing list is **not** extended
  in place to receive a value.

* for an :class:`.index_property` that is given any other kind of index
  value (e.g. strings usually), a Python dictionary is used as the
  default data structure.

* The default data structure can be set to any Python callable using the
  :paramref:`.index_property.datatype` parameter, overriding the previous
  rules.


Subclassing
===========

:class:`.index_property` can be subclassed, in particular for the common
use case of providing coercion of values or SQL expressions as they are
accessed.  Below is a common recipe for use with a PostgreSQL JSON type,
where we want to also include automatic casting plus ``astext()``::

    class pg_json_property(index_property):
        def __init__(self, attr_name, index, cast_type):
            super(pg_json_property, self).__init__(attr_name, index)
            self.cast_type = cast_type

        def expr(self, model):
            expr = super(pg_json_property, self).expr(model)
            return expr.astext.cast(self.cast_type)

The above subclass can be used with the PostgreSQL-specific
version of :class:`_postgresql.JSON`::

    from sqlalchemy import Column, Integer
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.dialects.postgresql import JSON

    Base = declarative_base()


    class Person(Base):
        __tablename__ = "person"

        id = Column(Integer, primary_key=True)
        data = Column(JSON)

        age = pg_json_property("data", "age", Integer)

The ``age`` attribute at the instance level works as before; however
when rendering SQL, PostgreSQL's ``->>`` operator will be used
for indexed access, instead of the usual index operator of ``->``::

    >>> query = session.query(Person).filter(Person.age < 20)

The above query will render:

.. sourcecode:: sql

    SELECT person.id, person.data
    FROM person
    WHERE CAST(person.data ->> %(data_1)s AS INTEGER) < %(param_1)s

é    )Úannotations)ÚAny)ÚCallable)Úcast)ÚOptional)ÚTYPE_CHECKING)ÚTypeVar)ÚUnioné   )Úinspect)Úhybrid_property)Úflag_modified)ÚSQLColumnExpression)Ú_HasClauseElementÚindex_propertyÚ_Tc                  ó€   ‡ — e Zd ZdZ ee e¦   «         ¦  «        Zedddfdˆ fd„Zd d!d„Z	d"d„Z
d#d„Zd$d„Zd%d„Zˆ xZS )&r   zÌA property generator. The generated property describes an object
    attribute that corresponds to an :class:`_types.Indexable`
    column.

    .. seealso::

        :mod:`sqlalchemy.ext.indexable`

    NTÚ	attr_nameÚstrÚindexúUnion[int, str]Údefaultr   ÚdatatypeúOptional[Callable[[], Any]]ÚmutableÚboolÚonebasedc                óŒ  •‡— |r9t          ¦   «                              | j        | j        | j        | j        ¦  «         n.t          ¦   «                              | j        dd| j        ¦  «         || _        ‰| _        || _        t          ‰t          ¦  «        }|o|}|�|| _        n|rˆfd„| _        nt          | _        || _        dS )a}  Create a new :class:`.index_property`.

        :param attr_name:
            An attribute name of an `Indexable` typed column, or other
            attribute that returns an indexable structure.
        :param index:
            The index to be used for getting and setting this value.  This
            should be the Python-side index value for integers.
        :param default:
            A value which will be returned instead of `AttributeError`
            when there is not a value at given index.
        :param datatype: default datatype to use when the field is empty.
            By default, this is derived from the type of index used; a
            Python list for an integer index, or a Python dictionary for
            any other style of index.   For a list, the list will be
            initialized to a list of None values that is at least
            ``index`` elements long.
        :param mutable: if False, writes and deletes to the attribute will
            be disallowed.
        :param onebased: assume the SQL representation of this value is
            one-based; that is, the first index in SQL is 1, not zero.
        Nc                 ó<   •— d„ t          ‰ dz   ¦  «        D ¦   «         S )Nc                ó   — g | ]}d ‘ŒS ©N© )Ú.0Úxs     úV/var/www/html/CA-Chatbot/venv/lib/python3.11/site-packages/sqlalchemy/ext/indexable.pyú
<listcomp>z=index_property.__init__.<locals>.<lambda>.<locals>.<listcomp>6  s   € Ð(HÐ(HÐ(H°!¨Ð(HÐ(HÐ(Hó    é   )Úrange)r   s   €r%   ú<lambda>z)index_property.__init__.<locals>.<lambda>6  s"   ø€ Ð(HÐ(Hµu¸UÀQ¹YÑ7GÔ7GÐ(HÑ(HÔ(H€ r'   )ÚsuperÚ__init__ÚfgetÚfsetÚfdelÚexprr   r   r   Ú
isinstanceÚintr   Údictr   )	Úselfr   r   r   r   r   r   Ú
is_numericÚ	__class__s	     `     €r%   r,   zindex_property.__init__  sÃ   øø€ ð@ ð 	?Ý‰GŒG×Ò˜TœY¨¬	°4´9¸d¼iÑHÔHÐHÐHå‰GŒG×Ò˜TœY¨¨d°D´IÑ>Ô>Ð>Ø"ˆŒØˆŒ
ØˆŒÝ ¥sÑ+Ô+ˆ
ØÐ* (ˆàÐØ$ˆDŒMˆMàð %Ø HÐ HÐ HÐ H�”�å $�”Ø ˆŒˆˆr'   ÚerrúOptional[BaseException]Úreturnc                óZ   — | j         | j        k    rt          | j        ¦  «        |‚| j         S r!   )r   Ú_NO_DEFAULT_ARGUMENTÚAttributeErrorr   )r4   r7   s     r%   Ú_fget_defaultzindex_property._fget_default;  s,   € ØŒ<˜4Ô4Ò4Ð4Ý  ¤Ñ0Ô0°cÐ9à”<Ðr'   Ú_index_property__instancer   c                óâ   — | j         }t          ||¦  «        }|€|                      ¦   «         S 	 || j                 }|S # t          t
          f$ r}|                      |¦  «        cY d }~S d }~ww xY wr!   )r   Úgetattrr=   r   ÚKeyErrorÚ
IndexError)r4   r>   r   Úcolumn_valueÚvaluer7   s         r%   r-   zindex_property.fgetA  s‘   € Ø”Nˆ	Ý˜z¨9Ñ5Ô5ˆØÐØ×%Ò%Ñ'Ô'Ð'ð	Ø  ¤Ô,ˆEð ˆLøõ �*Ð%ð 	+ð 	+ð 	+Ø×%Ò% cÑ*Ô*Ð*Ð*Ð*Ð*Ð*Ð*øøøøð	+øøøs   ¯> ¾A.ÁA)Á#A.Á)A.ÚinstancerD   ÚNonec                ó  — | j         }t          ||d ¦  «        }|€%|                      ¦   «         }t          |||¦  «         ||| j        <   t          |||¦  «         |t          |¦  «        j        j        v rt          ||¦  «         d S d S r!   )	r   r@   r   Úsetattrr   r   ÚmapperÚattrsr   )r4   rE   rD   r   rC   s        r%   r.   zindex_property.fsetM  s”   € Ø”Nˆ	Ý˜x¨°DÑ9Ô9ˆØÐØŸ=š=™?œ?ˆLÝ�H˜i¨Ñ6Ô6Ð6Ø#(ˆ�T”ZÑ Ý�˜) \Ñ2Ô2Ð2Ø� Ñ)Ô)Ô0Ô6Ð6Ð6Ý˜( IÑ.Ô.Ð.Ð.Ð.ð 7Ð6r'   c                ó  — | j         }t          ||¦  «        }|€t          | j         ¦  «        ‚	 || j        = t	          |||¦  «         t          ||¦  «         d S # t          $ r}t          | j         ¦  «        |‚d }~ww xY wr!   )r   r@   r<   r   rH   r   rA   )r4   rE   r   rC   r7   s        r%   r/   zindex_property.fdelX  sš   € Ø”Nˆ	Ý˜x¨Ñ3Ô3ˆØÐÝ  ¤Ñ0Ô0Ð0ð	/Ø˜TœZÐ(õ �H˜i¨Ñ6Ô6Ð6Ý˜( IÑ.Ô.Ð.Ð.Ð.øõ	 ð 	:ð 	:ð 	:Ý  ¤Ñ0Ô0°cÐ9øøøøð	:øøøs   ¯A Á
A>Á$A9Á9A>Úmodelú5Union[_HasClauseElement[_T], SQLColumnExpression[_T]]c                ób   — t          || j        ¦  «        }| j        }| j        r|dz  }||         S )Nr(   )r@   r   r   r   )r4   rL   Úcolumnr   s       r%   r0   zindex_property.expre  s9   € õ ˜ ¤Ñ/Ô/ˆØ”
ˆØŒ=ð 	Ø�Q‰JˆEØ�eŒ}Ðr'   )r   r   r   r   r   r   r   r   r   r   r   r   r!   )r7   r8   r9   r   )r>   r   r9   r   )rE   r   rD   r   r9   rF   )rE   r   r9   rF   )rL   r   r9   rM   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   Úobjectr;   r,   r=   r-   r.   r/   r0   Ú__classcell__)r6   s   @r%   r   r   û   sÞ   ø€ € € € € ðð ð  ˜4  F F¡H¤HÑ-Ô-Ðð +Ø04ØØð1!ð 1!ð 1!ð 1!ð 1!ð 1!ð 1!ðf ð  ð  ð  ð  ð
ð 
ð 
ð 
ð	/ð 	/ð 	/ð 	/ð/ð /ð /ð /ðð ð ð ð ð ð ð r'   N)rS   Ú
__future__r   Útypingr   r   r   r   r   r	   r
   Ú r   Ú
ext.hybridr   Úorm.attributesr   Úsqlr   Úsql._typingr   Ú__all__r   r   r"   r'   r%   ú<module>r^      s`  ððYð Yðv #Ð "Ð "Ð "Ð "Ð "à Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð Ø  Ð  Ð  Ð  Ð  Ð  Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð à Ð Ð Ð Ð Ð Ø (Ð (Ð (Ð (Ð (Ð (Ø *Ð *Ð *Ð *Ð *Ð *àð 0Ø)Ð)Ð)Ð)Ð)Ð)Ø/Ð/Ð/Ð/Ð/Ð/ð Ð
€à€WˆT�]„]€ðqð qð qð qð q�_ RÔ(ñ qô qð qð qð qr'   