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