Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
indexable.py365 linesDownload Raw Back to ext
1# ext/indexable.py
2# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3# <see AUTHORS file>
4#
5# This module is part of SQLAlchemy and is released under
6# the MIT License: https://www.opensource.org/licenses/mit-license.php
7
8"""Define attributes on ORM-mapped classes that have "index" attributes for
9columns with :class:`_types.Indexable` types.
10
11"index" means the attribute is associated with an element of an
12:class:`_types.Indexable` column with the predefined index to access it.
13The :class:`_types.Indexable` types include types such as
14:class:`_types.ARRAY`, :class:`_types.JSON` and
15:class:`_postgresql.HSTORE`.
16
17
18
19The :mod:`~sqlalchemy.ext.indexable` extension provides
20:class:`_schema.Column`-like interface for any element of an
21:class:`_types.Indexable` typed column. In simple cases, it can be
22treated as a :class:`_schema.Column` - mapped attribute.
23
24Synopsis
25========
26
27Given ``Person`` as a model with a primary key and JSON data field.
28While this field may have any number of elements encoded within it,
29we would like to refer to the element called ``name`` individually
30as a dedicated attribute which behaves like a standalone column::
31
32    from sqlalchemy import Column, JSON, Integer
33    from sqlalchemy.ext.declarative import declarative_base
34    from sqlalchemy.ext.indexable import index_property
35
36    Base = declarative_base()
37
38
39    class Person(Base):
40        __tablename__ = "person"
41
42        id = Column(Integer, primary_key=True)
43        data = Column(JSON)
44
45        name = index_property("data", "name")
46
47Above, the ``name`` attribute now behaves like a mapped column.   We
48can compose a new ``Person`` and set the value of ``name``::
49
50    >>> person = Person(name="Alchemist")
51
52The value is now accessible::
53
54    >>> person.name
55    'Alchemist'
56
57Behind the scenes, the JSON field was initialized to a new blank dictionary
58and the field was set::
59
60    >>> person.data
61    {'name': 'Alchemist'}
62
63The field is mutable in place::
64
65    >>> person.name = "Renamed"
66    >>> person.name
67    'Renamed'
68    >>> person.data
69    {'name': 'Renamed'}
70
71When using :class:`.index_property`, the change that we make to the indexable
72structure is also automatically tracked as history; we no longer need
73to use :class:`~.mutable.MutableDict` in order to track this change
74for the unit of work.
75
76Deletions work normally as well::
77
78    >>> del person.name
79    >>> person.data
80    {}
81
82Above, deletion of ``person.name`` deletes the value from the dictionary,
83but not the dictionary itself.
84
85A missing key will produce ``AttributeError``::
86
87    >>> person = Person()
88    >>> person.name
89    AttributeError: 'name'
90
91Unless you set a default value::
92
93    >>> class Person(Base):
94    ...     __tablename__ = "person"
95    ...
96    ...     id = Column(Integer, primary_key=True)
97    ...     data = Column(JSON)
98    ...
99    ...     name = index_property("data", "name", default=None)  # See default
100
101    >>> person = Person()
102    >>> print(person.name)
103    None
104
105
106The attributes are also accessible at the class level.
107Below, we illustrate ``Person.name`` used to generate
108an indexed SQL criteria::
109
110    >>> from sqlalchemy.orm import Session
111    >>> session = Session()
112    >>> query = session.query(Person).filter(Person.name == "Alchemist")
113
114The above query is equivalent to::
115
116    >>> query = session.query(Person).filter(Person.data["name"] == "Alchemist")
117
118Multiple :class:`.index_property` objects can be chained to produce
119multiple levels of indexing::
120
121    from sqlalchemy import Column, JSON, Integer
122    from sqlalchemy.ext.declarative import declarative_base
123    from sqlalchemy.ext.indexable import index_property
124
125    Base = declarative_base()
126
127
128    class Person(Base):
129        __tablename__ = "person"
130
131        id = Column(Integer, primary_key=True)
132        data = Column(JSON)
133
134        birthday = index_property("data", "birthday")
135        year = index_property("birthday", "year")
136        month = index_property("birthday", "month")
137        day = index_property("birthday", "day")
138
139Above, a query such as::
140
141    q = session.query(Person).filter(Person.year == "1980")
142
143On a PostgreSQL backend, the above query will render as:
144
145.. sourcecode:: sql
146
147    SELECT person.id, person.data
148    FROM person
149    WHERE person.data -> %(data_1)s -> %(param_1)s = %(param_2)s
150
151Default Values
152==============
153
154:class:`.index_property` includes special behaviors for when the indexed
155data structure does not exist, and a set operation is called:
156
157* For an :class:`.index_property` that is given an integer index value,
158  the default data structure will be a Python list of ``None`` values,
159  at least as long as the index value; the value is then set at its
160  place in the list.  This means for an index value of zero, the list
161  will be initialized to ``[None]`` before setting the given value,
162  and for an index value of five, the list will be initialized to
163  ``[None, None, None, None, None]`` before setting the fifth element
164  to the given value.   Note that an existing list is **not** extended
165  in place to receive a value.
166
167* for an :class:`.index_property` that is given any other kind of index
168  value (e.g. strings usually), a Python dictionary is used as the
169  default data structure.
170
171* The default data structure can be set to any Python callable using the
172  :paramref:`.index_property.datatype` parameter, overriding the previous
173  rules.
174
175
176Subclassing
177===========
178
179:class:`.index_property` can be subclassed, in particular for the common
180use case of providing coercion of values or SQL expressions as they are
181accessed.  Below is a common recipe for use with a PostgreSQL JSON type,
182where we want to also include automatic casting plus ``astext()``::
183
184    class pg_json_property(index_property):
185        def __init__(self, attr_name, index, cast_type):
186            super(pg_json_property, self).__init__(attr_name, index)
187            self.cast_type = cast_type
188
189        def expr(self, model):
190            expr = super(pg_json_property, self).expr(model)
191            return expr.astext.cast(self.cast_type)
192
193The above subclass can be used with the PostgreSQL-specific
194version of :class:`_postgresql.JSON`::
195
196    from sqlalchemy import Column, Integer
197    from sqlalchemy.ext.declarative import declarative_base
198    from sqlalchemy.dialects.postgresql import JSON
199
200    Base = declarative_base()
201
202
203    class Person(Base):
204        __tablename__ = "person"
205
206        id = Column(Integer, primary_key=True)
207        data = Column(JSON)
208
209        age = pg_json_property("data", "age", Integer)
210
211The ``age`` attribute at the instance level works as before; however
212when rendering SQL, PostgreSQL's ``->>`` operator will be used
213for indexed access, instead of the usual index operator of ``->``::
214
215    >>> query = session.query(Person).filter(Person.age < 20)
216
217The above query will render:
218
219.. sourcecode:: sql
220
221    SELECT person.id, person.data
222    FROM person
223    WHERE CAST(person.data ->> %(data_1)s AS INTEGER) < %(param_1)s
224
225"""  # noqa
226
227from __future__ import annotations
228
229from typing import Any
230from typing import Callable
231from typing import cast
232from typing import Optional
233from typing import TYPE_CHECKING
234from typing import TypeVar
235from typing import Union
236
237from .. import inspect
238from ..ext.hybrid import hybrid_property
239from ..orm.attributes import flag_modified
240
241if TYPE_CHECKING:
242    from ..sql import SQLColumnExpression
243    from ..sql._typing import _HasClauseElement
244
245
246__all__ = ["index_property"]
247
248_T = TypeVar("_T")
249
250
251class index_property(hybrid_property[_T]):
252    """A property generator. The generated property describes an object
253    attribute that corresponds to an :class:`_types.Indexable`
254    column.
255
256    .. seealso::
257
258        :mod:`sqlalchemy.ext.indexable`
259
260    """
261
262    _NO_DEFAULT_ARGUMENT = cast(_T, object())
263
264    def __init__(
265        self,
266        attr_name: str,
267        index: Union[int, str],
268        default: _T = _NO_DEFAULT_ARGUMENT,
269        datatype: Optional[Callable[[], Any]] = None,
270        mutable: bool = True,
271        onebased: bool = True,
272    ):
273        """Create a new :class:`.index_property`.
274
275        :param attr_name:
276            An attribute name of an `Indexable` typed column, or other
277            attribute that returns an indexable structure.
278        :param index:
279            The index to be used for getting and setting this value.  This
280            should be the Python-side index value for integers.
281        :param default:
282            A value which will be returned instead of `AttributeError`
283            when there is not a value at given index.
284        :param datatype: default datatype to use when the field is empty.
285            By default, this is derived from the type of index used; a
286            Python list for an integer index, or a Python dictionary for
287            any other style of index.   For a list, the list will be
288            initialized to a list of None values that is at least
289            ``index`` elements long.
290        :param mutable: if False, writes and deletes to the attribute will
291            be disallowed.
292        :param onebased: assume the SQL representation of this value is
293            one-based; that is, the first index in SQL is 1, not zero.
294        """
295
296        if mutable:
297            super().__init__(self.fget, self.fset, self.fdel, self.expr)
298        else:
299            super().__init__(self.fget, None, None, self.expr)
300        self.attr_name = attr_name
301        self.index = index
302        self.default = default
303        is_numeric = isinstance(index, int)
304        onebased = is_numeric and onebased
305
306        if datatype is not None:
307            self.datatype = datatype
308        else:
309            if is_numeric:
310                self.datatype = lambda: [None for x in range(index + 1)]  # type: ignore[operator]  # noqa: E501
311            else:
312                self.datatype = dict
313        self.onebased = onebased
314
315    def _fget_default(self, err: Optional[BaseException] = None) -> _T:
316        if self.default == self._NO_DEFAULT_ARGUMENT:
317            raise AttributeError(self.attr_name) from err
318        else:
319            return self.default
320
321    def fget(self, __instance: Any) -> _T:
322        attr_name = self.attr_name
323        column_value = getattr(__instance, attr_name)
324        if column_value is None:
325            return self._fget_default()
326        try:
327            value = column_value[self.index]
328        except (KeyError, IndexError) as err:
329            return self._fget_default(err)
330        else:
331            return value  # type: ignore[no-any-return]
332
333    def fset(self, instance: Any, value: _T) -> None:
334        attr_name = self.attr_name
335        column_value = getattr(instance, attr_name, None)
336        if column_value is None:
337            column_value = self.datatype()
338            setattr(instance, attr_name, column_value)
339        column_value[self.index] = value
340        setattr(instance, attr_name, column_value)
341        if attr_name in inspect(instance).mapper.attrs:
342            flag_modified(instance, attr_name)
343
344    def fdel(self, instance: Any) -> None:
345        attr_name = self.attr_name
346        column_value = getattr(instance, attr_name)
347        if column_value is None:
348            raise AttributeError(self.attr_name)
349        try:
350            del column_value[self.index]
351        except KeyError as err:
352            raise AttributeError(self.attr_name) from err
353        else:
354            setattr(instance, attr_name, column_value)
355            flag_modified(instance, attr_name)
356
357    def expr(
358        self, model: Any
359    ) -> Union[_HasClauseElement[_T], SQLColumnExpression[_T]]:
360        column = getattr(model, self.attr_name)
361        index = self.index
362        if self.onebased:
363            index += 1  # type: ignore[operator]
364        return column[index]  # type: ignore[no-any-return]
365 
codekingpro/portable-devtools · Team Ai