Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
indexable.cpython-313.pyc275 linesDownload Raw Back to __pycache__
1�

2��j^/����SrSSKJr SSKJr SSKJr SSKJr SSKJr SSKJr SSKJ	r	 SS	KJ3r4 S5SKJr S6SK
Jr S7S
KJr \(aS8SKJr S9SKJr S/r\	"S5r"SS\\5rg)a7Define attributes on ORM-mapped classes that have "index" attributes for10columns with :class:`_types.Indexable` types.11 12"index" means the attribute is associated with an element of an13:class:`_types.Indexable` column with the predefined index to access it.14The :class:`_types.Indexable` types include types such as15:class:`_types.ARRAY`, :class:`_types.JSON` and16:class:`_postgresql.HSTORE`.17 18 19 20The :mod:`~sqlalchemy.ext.indexable` extension provides21:class:`_schema.Column`-like interface for any element of an22:class:`_types.Indexable` typed column. In simple cases, it can be23treated as a :class:`_schema.Column` - mapped attribute.24 25Synopsis26========27 28Given ``Person`` as a model with a primary key and JSON data field.29While this field may have any number of elements encoded within it,30we would like to refer to the element called ``name`` individually31as a dedicated attribute which behaves like a standalone column::32 33    from sqlalchemy import Column, JSON, Integer34    from sqlalchemy.ext.declarative import declarative_base35    from sqlalchemy.ext.indexable import index_property36 37    Base = declarative_base()38 39 40    class Person(Base):41        __tablename__ = "person"42 43        id = Column(Integer, primary_key=True)44        data = Column(JSON)45 46        name = index_property("data", "name")47 48Above, the ``name`` attribute now behaves like a mapped column.   We49can compose a new ``Person`` and set the value of ``name``::50 51    >>> person = Person(name="Alchemist")52 53The value is now accessible::54 55    >>> person.name56    'Alchemist'57 58Behind the scenes, the JSON field was initialized to a new blank dictionary59and the field was set::60 61    >>> person.data62    {'name': 'Alchemist'}63 64The field is mutable in place::65 66    >>> person.name = "Renamed"67    >>> person.name68    'Renamed'69    >>> person.data70    {'name': 'Renamed'}71 72When using :class:`.index_property`, the change that we make to the indexable73structure is also automatically tracked as history; we no longer need74to use :class:`~.mutable.MutableDict` in order to track this change75for the unit of work.76 77Deletions work normally as well::78 79    >>> del person.name80    >>> person.data81    {}82 83Above, deletion of ``person.name`` deletes the value from the dictionary,84but not the dictionary itself.85 86A missing key will produce ``AttributeError``::87 88    >>> person = Person()89    >>> person.name90    AttributeError: 'name'91 92Unless you set a default value::93 94    >>> class Person(Base):95    ...     __tablename__ = "person"96    ...97    ...     id = Column(Integer, primary_key=True)98    ...     data = Column(JSON)99    ...100    ...     name = index_property("data", "name", default=None)  # See default101 102    >>> person = Person()103    >>> print(person.name)104    None105 106 107The attributes are also accessible at the class level.108Below, we illustrate ``Person.name`` used to generate109an indexed SQL criteria::110 111    >>> from sqlalchemy.orm import Session112    >>> session = Session()113    >>> query = session.query(Person).filter(Person.name == "Alchemist")114 115The above query is equivalent to::116 117    >>> query = session.query(Person).filter(Person.data["name"] == "Alchemist")118 119Multiple :class:`.index_property` objects can be chained to produce120multiple levels of indexing::121 122    from sqlalchemy import Column, JSON, Integer123    from sqlalchemy.ext.declarative import declarative_base124    from sqlalchemy.ext.indexable import index_property125 126    Base = declarative_base()127 128 129    class Person(Base):130        __tablename__ = "person"131 132        id = Column(Integer, primary_key=True)133        data = Column(JSON)134 135        birthday = index_property("data", "birthday")136        year = index_property("birthday", "year")137        month = index_property("birthday", "month")138        day = index_property("birthday", "day")139 140Above, a query such as::141 142    q = session.query(Person).filter(Person.year == "1980")143 144On a PostgreSQL backend, the above query will render as:145 146.. sourcecode:: sql147 148    SELECT person.id, person.data149    FROM person150    WHERE person.data -> %(data_1)s -> %(param_1)s = %(param_2)s151 152Default Values153==============154 155:class:`.index_property` includes special behaviors for when the indexed156data structure does not exist, and a set operation is called:157 158* For an :class:`.index_property` that is given an integer index value,159  the default data structure will be a Python list of ``None`` values,160  at least as long as the index value; the value is then set at its161  place in the list.  This means for an index value of zero, the list162  will be initialized to ``[None]`` before setting the given value,163  and for an index value of five, the list will be initialized to164  ``[None, None, None, None, None]`` before setting the fifth element165  to the given value.   Note that an existing list is **not** extended166  in place to receive a value.167 168* for an :class:`.index_property` that is given any other kind of index169  value (e.g. strings usually), a Python dictionary is used as the170  default data structure.171 172* The default data structure can be set to any Python callable using the173  :paramref:`.index_property.datatype` parameter, overriding the previous174  rules.175 176 177Subclassing178===========179 180:class:`.index_property` can be subclassed, in particular for the common181use case of providing coercion of values or SQL expressions as they are182accessed.  Below is a common recipe for use with a PostgreSQL JSON type,183where we want to also include automatic casting plus ``astext()``::184 185    class pg_json_property(index_property):186        def __init__(self, attr_name, index, cast_type):187            super(pg_json_property, self).__init__(attr_name, index)188            self.cast_type = cast_type189 190        def expr(self, model):191            expr = super(pg_json_property, self).expr(model)192            return expr.astext.cast(self.cast_type)193 194The above subclass can be used with the PostgreSQL-specific195version of :class:`_postgresql.JSON`::196 197    from sqlalchemy import Column, Integer198    from sqlalchemy.ext.declarative import declarative_base199    from sqlalchemy.dialects.postgresql import JSON200 201    Base = declarative_base()202 203 204    class Person(Base):205        __tablename__ = "person"206 207        id = Column(Integer, primary_key=True)208        data = Column(JSON)209 210        age = pg_json_property("data", "age", Integer)211 212The ``age`` attribute at the instance level works as before; however213when rendering SQL, PostgreSQL's ``->>`` operator will be used214for indexed access, instead of the usual index operator of ``->``::215 216    >>> query = session.query(Person).filter(Person.age < 20)217 218The above query will render:219 220.. sourcecode:: sql221 222    SELECT person.id, person.data223    FROM person224    WHERE CAST(person.data ->> %(data_1)s AS INTEGER) < %(param_1)s225 226�)�annotations)�Any)�Callable)�cast)�Optional)�
TYPE_CHECKING)�TypeVar)�Union�)�inspect)�hybrid_property)�
flag_modified)�SQLColumnExpression)�_HasClauseElement�index_property�_Tc�^�\rSrSrSr\"\\"55r\SSS4SU4Sjjjr	S
SSjjr227SSjrSSjrSS	jr
SS228jrSrU=r$)r��z�A property generator. The generated property describes an object229attribute that corresponds to an :class:`_types.Indexable`230column.231 232.. seealso::233 234    :mod:`sqlalchemy.ext.indexable`235 236NTc�>^�U(a;[TU]URURURUR2375 O&[TU]URSSUR2385 XlTUlX0l[T[5nU=(a UnUbX@lOU(aU4SjUlO[UlX`l
g)a�Create a new :class:`.index_property`.239 240:param attr_name:241    An attribute name of an `Indexable` typed column, or other242    attribute that returns an indexable structure.243:param index:244    The index to be used for getting and setting this value.  This245    should be the Python-side index value for integers.246:param default:247    A value which will be returned instead of `AttributeError`248    when there is not a value at given index.249:param datatype: default datatype to use when the field is empty.250    By default, this is derived from the type of index used; a251    Python list for an integer index, or a Python dictionary for252    any other style of index.   For a list, the list will be253    initialized to a list of None values that is at least254    ``index`` elements long.255:param mutable: if False, writes and deletes to the attribute will256    be disallowed.257:param onebased: assume the SQL representation of this value is258    one-based; that is, the first index in SQL is 1, not zero.259Nc�L>�[TS-5Vs/sHnSPM sn$s snf�N�)�range)�x�indexs ��^D:\code\apps\devtools\python\user_packages\Python313\site-packages\sqlalchemy/ext/indexable.py�<lambda>�)index_property.__init__.<locals>.<lambda>6s"���u�U�Q�Y�7G�(H�7G�!��7G�(H��(Hs�!)�super�__init__�fget�fset�fdel�expr�	attr_namer�default�260isinstance�int�datatype�dict�onebased)	�selfr%rr&r)�mutabler+�261is_numeric�	__class__s	  `     �rr �index_property.__init__s����@��G��T�Y�Y��	�	�4�9�9�d�i�i�H��G��T�Y�Y��d�D�I�I�>�"����262�����s�+�263��*�(����$�M�� H��
� $��
� �
�c�z�URUR:Xa[UR5UeUR$�N)r&�_NO_DEFAULT_ARGUMENT�AttributeErrorr%)r,�errs  r�
_fget_default�index_property._fget_default;s/���<�<�4�4�4�4� ����0�c�9��<�<�r1c���URn[X5nUcUR5$X0RnU$![[2644anURU5sSnA$SnAff=fr3)r%�getattrr7r�KeyError�265IndexError)r,�_index_property__instancer%�column_value�valuer6s      rr!�index_property.fgetAsj���N�N�	��z�5�����%�%�'�'�	� ���,�E��L���*�%�	+��%�%�c�*�*��	+�s�<�A'�A"�A'�"A'c��URn[XS5nUcUR5n[XU5 X$UR'[XU5 U[U5RR;a[X5 ggr3)	r%r:r)�setattrrr�mapper�attrsr)r,�instancer?r%r>s     rr"�index_property.fsetMsn���N�N�	��x�D�9�����=�=�?�L��H��6�#(�T�Z�Z� ���\�2����)�0�0�6�6�6��(�.�7r1c���URn[X5nUc[UR5eX0R	[	XU5 [X5 g![an[UR5UeSnAff=fr3)r%r:r5rrBrr;)r,rEr%r>r6s     rr#�index_property.fdelXsp���N�N�	��x�3���� ����0�0�	/��Z�Z�(�
�H��6��(�.��	�	:� ����0�c�9��	:�s�A�266A:�A5�5A:c�x�[XR5nURnUR(aUS-
nX#$r)r:r%rr+)r,�model�columnrs    rr$�index_property.expres3������/���267�268���=�=��Q�J�E��}�r1)r%r)r&rr+)r%�strrzUnion[int, str]r&rr)zOptional[Callable[[], Any]]r-�boolr+rNr3)r6zOptional[BaseException]�returnr)r=rrOr)rErr?rrO�None)rErrOrP)rJrrOz5Union[_HasClauseElement[_T], SQLColumnExpression[_T]])�__name__�269__module__�__qualname__�__firstlineno__�__doc__rr�objectr4r r7r!r"r#r$�__static_attributes__�
__classcell__)r/s@rrr�s����� ��F�H�-��+�04���1!��1!��1!��	1!�270.�1!��
1!��1!�1!�f �271�	/�/����	>��r1N)rU�272__future__r�typingrrrrrr	r273�r�274ext.hybridr
�orm.attributesr�sqlr�sql._typingr�__all__rr�r1r�<module>rbs^��Y�v#����� ����(�*��)�/��275���T�]��q�_�R�(�qr1
codekingpro/portable-devtools · Team Ai