1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
U
¸ý°dÐ9ã@sÞdZddlmZddlmZddlmZddlmZddlmZddlmZdd    l    m
Z
dd
l    m Z ed ƒZ ee ee ge fZd gZd"ddddddœdd „Zdd„Zdd„Zdd„Zdd„ZGdd„dee ƒZd d!„Zd S)#aÅA custom list that manages index/position information for contained
elements.
 
:author: Jason Kirtland
 
``orderinglist`` is a helper for mutable ordered relationships.  It will
intercept list operations performed on a :func:`_orm.relationship`-managed
collection and
automatically synchronize changes in list position onto a target scalar
attribute.
 
Example: A ``slide`` table, where each row refers to zero or more entries
in a related ``bullet`` table.   The bullets within a slide are
displayed in order based on the value of the ``position`` column in the
``bullet`` table.   As entries are reordered in memory, the value of the
``position`` attribute should be updated to reflect the new sort order::
 
 
    Base = declarative_base()
 
    class Slide(Base):
        __tablename__ = 'slide'
 
        id = Column(Integer, primary_key=True)
        name = Column(String)
 
        bullets = relationship("Bullet", order_by="Bullet.position")
 
    class Bullet(Base):
        __tablename__ = 'bullet'
        id = Column(Integer, primary_key=True)
        slide_id = Column(Integer, ForeignKey('slide.id'))
        position = Column(Integer)
        text = Column(String)
 
The standard relationship mapping will produce a list-like attribute on each
``Slide`` containing all related ``Bullet`` objects,
but coping with changes in ordering is not handled automatically.
When appending a ``Bullet`` into ``Slide.bullets``, the ``Bullet.position``
attribute will remain unset until manually assigned.   When the ``Bullet``
is inserted into the middle of the list, the following ``Bullet`` objects
will also need to be renumbered.
 
The :class:`.OrderingList` object automates this task, managing the
``position`` attribute on all ``Bullet`` objects in the collection.  It is
constructed using the :func:`.ordering_list` factory::
 
    from sqlalchemy.ext.orderinglist import ordering_list
 
    Base = declarative_base()
 
    class Slide(Base):
        __tablename__ = 'slide'
 
        id = Column(Integer, primary_key=True)
        name = Column(String)
 
        bullets = relationship("Bullet", order_by="Bullet.position",
                                collection_class=ordering_list('position'))
 
    class Bullet(Base):
        __tablename__ = 'bullet'
        id = Column(Integer, primary_key=True)
        slide_id = Column(Integer, ForeignKey('slide.id'))
        position = Column(Integer)
        text = Column(String)
 
With the above mapping the ``Bullet.position`` attribute is managed::
 
    s = Slide()
    s.bullets.append(Bullet())
    s.bullets.append(Bullet())
    s.bullets[1].position
    >>> 1
    s.bullets.insert(1, Bullet())
    s.bullets[2].position
    >>> 2
 
The :class:`.OrderingList` construct only works with **changes** to a
collection, and not the initial load from the database, and requires that the
list be sorted when loaded.  Therefore, be sure to specify ``order_by`` on the
:func:`_orm.relationship` against the target ordering attribute, so that the
ordering is correct when first loaded.
 
.. warning::
 
  :class:`.OrderingList` only provides limited functionality when a primary
  key column or unique column is the target of the sort.  Operations
  that are unsupported or are problematic include:
 
    * two entries must trade values.  This is not supported directly in the
      case of a primary key or unique constraint because it means at least
      one row would need to be temporarily removed first, or changed to
      a third, neutral value while the switch occurs.
 
    * an entry must be deleted in order to make room for a new entry.
      SQLAlchemy's unit of work performs all INSERTs before DELETEs within a
      single flush.  In the case of a primary key, it will trade
      an INSERT/DELETE of the same primary key for an UPDATE statement in order
      to lessen the impact of this limitation, however this does not take place
      for a UNIQUE column.
      A future feature will allow the "DELETE before INSERT" behavior to be
      possible, alleviating this limitation, though this feature will require
      explicit configuration at the mapper level for sets of columns that
      are to be handled in this way.
 
:func:`.ordering_list` takes the name of the related object's ordering
attribute as an argument.  By default, the zero-based integer index of the
object's position in the :func:`.ordering_list` is synchronized with the
ordering attribute: index 0 will get position 0, index 1 position 1, etc.  To
start numbering at 1 or some other integer, provide ``count_from=1``.
 
 
é)Ú annotations)ÚCallable)ÚList)ÚOptional)ÚSequence)ÚTypeVaré)Ú
collection)Úcollection_adapterÚ_TÚ ordering_listNFÚstrz Optional[int]úOptional[OrderingFunc]ÚboolzCallable[[], OrderingList])ÚattrÚ
count_fromÚ ordering_funcÚreorder_on_appendÚreturncst|||d‰‡‡fdd„S)aPrepares an :class:`OrderingList` factory for use in mapper definitions.
 
    Returns an object suitable for use as an argument to a Mapper
    relationship's ``collection_class`` option.  e.g.::
 
        from sqlalchemy.ext.orderinglist import ordering_list
 
        class Slide(Base):
            __tablename__ = 'slide'
 
            id = Column(Integer, primary_key=True)
            name = Column(String)
 
            bullets = relationship("Bullet", order_by="Bullet.position",
                                    collection_class=ordering_list('position'))
 
    :param attr:
      Name of the mapped attribute to use for storage and retrieval of
      ordering information
 
    :param count_from:
      Set up an integer-based ordering, starting at ``count_from``.  For
      example, ``ordering_list('pos', count_from=1)`` would create a 1-based
      list in SQL, storing the value in the 'pos' column.  Ignored if
      ``ordering_func`` is supplied.
 
    Additional arguments are passed to the :class:`.OrderingList` constructor.
 
    )rrrcs tˆfˆŽS©N)Ú OrderingList©©rÚkwrúRd:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\sqlalchemy/ext/orderinglist.pyÚ<lambda>¶ózordering_list.<locals>.<lambda>)Ú_unsugar_count_from)rrrrrrrr s $ýcCs|S)z7Numbering function: consecutive integers starting at 0.r©Úindexr    rrrÚ count_from_0¼sr cCs|dS)z7Numbering function: consecutive integers starting at 1.érrrrrÚ count_from_1Âsr"cs4‡fdd„}zdˆ|_Wntk
r.YnX|S)zENumbering function: consecutive integers starting at arbitrary start.cs|ˆSrrr©ÚstartrrÚfËszcount_from_n_factory.<locals>.fz count_from_%i)Ú__name__Ú    TypeError)r$r%rr#rÚcount_from_n_factoryÈs  r(cKsX| dd¡}| dd¡dkrT|dk    rT|dkr6t|d<n|dkrHt|d<n t|ƒ|d<|S)zÍBuilds counting functions from keyword arguments.
 
    Keyword argument filter, prepares a simple ``ordering_func`` from a
    ``count_from`` argument, otherwise passes ``ordering_func`` on unchanged.
    rNrrr!)ÚpopÚgetr r"r()rrrrrrÕs 
 
 rcsHeZdZUdZded<ded<ded<d0d
d dd œd d„Zdd„Zdd„Zddœdd„ZeZ    d1dd„Z
‡fdd„Z ‡fdd„Z e  d¡e ƒZ ‡fdd „Z‡fd!d"„Zd2‡fd$d%„    Z‡fd&d'„Z‡fd(d)„Z‡fd*d+„Z‡fd,d-„Zd.d/„Zeeƒ ¡ƒD]B\ZZeeƒrøejekrøejsøeeeƒrøeeeƒje_qø[[‡ZS)3rzýA custom list that manages position information for its children.
 
    The :class:`.OrderingList` object is normally set up using the
    :func:`.ordering_list` factory function, used in conjunction with
    the :func:`_orm.relationship` function.
 
    r Ú ordering_attrÚ OrderingFuncrrrNFz Optional[str]r)r+rrcCs"||_|dkrt}||_||_dS)aŠ    A custom list that manages position information for its children.
 
        ``OrderingList`` is a ``collection_class`` list implementation that
        syncs position in a Python list with a position attribute on the
        mapped objects.
 
        This implementation relies on the list starting in the proper order,
        so be **sure** to put an ``order_by`` on your relationship.
 
        :param ordering_attr:
          Name of the attribute that stores the object's order in the
          relationship.
 
        :param ordering_func: Optional.  A function that maps the position in
          the Python list to a value to store in the
          ``ordering_attr``.  Values returned are usually (but need not be!)
          integers.
 
          An ``ordering_func`` is called with two positional parameters: the
          index of the element in the list, and the list itself.
 
          If omitted, Python list indexes are used for the attribute values.
          Two basic pre-built numbering functions are provided in this module:
          ``count_from_0`` and ``count_from_1``.  For more exotic examples
          like stepped numbering, alphabetical and Fibonacci numbering, see
          the unit tests.
 
        :param reorder_on_append:
          Default False.  When appending an object with an existing (non-None)
          ordering value, that value will be left untouched unless
          ``reorder_on_append`` is true.  This is an optimization to avoid a
          variety of dangerous unexpected database writes.
 
          SQLAlchemy will add instances to the list via append() when your
          object loads.  If for some reason the result set from the database
          skips a step in the ordering (say, row '1' is missing but you get
          '2', '3', and '4'), reorder_on_append=True would immediately
          renumber the items to '1', '2', '3'.  If you have multiple sessions
          making changes, any of whom happen to load this collection even in
          passing, all of the sessions would try to "clean up" the numbering
          in their commits, possibly causing all but one to fail with a
          concurrent modification error.
 
          Recommend leaving this with the default of False, and just call
          ``reorder()`` if you're doing ``append()`` operations with
          previously ordered instances or when doing some housekeeping after
          manual sql operations.
 
        N)r+r rr)Úselfr+rrrrrÚ__init__ôs
7zOrderingList.__init__cCs t||jƒSr)Úgetattrr+©r-ÚentityrrrÚ_get_order_value3szOrderingList._get_order_valuecCst||j|ƒdSr)Úsetattrr+)r-r1ÚvaluerrrÚ_set_order_value6szOrderingList._set_order_valueÚNone)rcCs$t|ƒD]\}}| ||d¡qdS)z¦Synchronize ordering for the entire collection.
 
        Sweeps through the list and ensures that each object has accurate
        ordering information set.
 
        TN)Ú    enumerateÚ _order_entity©r-rr1rrrÚreorder9szOrderingList.reorderTcCs>| |¡}|dk    r|sdS| ||¡}||kr:| ||¡dSr)r2rr5)r-rr1r:ZhaveZ    should_berrrr8Fs 
  zOrderingList._order_entitycs(tƒ |¡| t|ƒd||j¡dS)Nr!)ÚsuperÚappendr8Úlenrr0©Ú    __class__rrr<Qs zOrderingList.appendcstƒ |¡dS)z%Append without any ordering behavior.N)r;r<r0r>rrÚ _raw_appendUszOrderingList._raw_appendr!cstƒ ||¡| ¡dSr)r;ÚinsertÚ_reorderr9r>rrrA\szOrderingList.insertcs*tƒ |¡t|ƒ}|r&|jr&| ¡dSr)r;Úremover
Z_referenced_by_ownerrB)r-r1Úadapterr>rrrC`s 
zOrderingList.removeéÿÿÿÿcstƒ |¡}| ¡|Sr)r;r)rBr9r>rrr)gs zOrderingList.popcs˜t|tƒrx|jpd}|jpd}|dkr2|t|ƒ7}|jp>t|ƒ}|dkrT|t|ƒ7}t|||ƒD]}| |||¡q`n| ||d¡t    ƒ ||¡dS)Nr!rT)
Ú
isinstanceÚsliceÚstepr$r=ÚstopÚrangeÚ __setitem__r8r;)r-rr1rHr$rIÚir>rrrKls
 
 
  zOrderingList.__setitem__cstƒ |¡| ¡dSr)r;Ú __delitem__rB)r-rr>rrrM|s zOrderingList.__delitem__cstƒ |||¡| ¡dSr)r;Ú __setslice__rB)r-r$ÚendÚvaluesr>rrrN€szOrderingList.__setslice__cstƒ ||¡| ¡dSr)r;Ú __delslice__rB)r-r$rOr>rrrQ„szOrderingList.__delslice__cCst|j|jt|ƒffSr)Ú _reconstituter?Ú__dict__Úlist)r-rrrÚ
__reduce__ˆszOrderingList.__reduce__)NNF)T)rE) r&Ú
__module__Ú __qualname__Ú__doc__Ú__annotations__r.r2r5r:rBr8r<r@r    ZaddsrArCr)rKrMrNrQrUrTÚlocalsÚitemsÚ    func_nameÚfuncÚcallableÚhasattrr/Ú __classcell__rrr>rrçsF
ü? 
       ÿþýürcCs&| |¡}|j |¡t ||¡|S)zªReconstitute an :class:`.OrderingList`.
 
    This is the adjoint to :meth:`.OrderingList.__reduce__`.  It is used for
    unpickling :class:`.OrderingList` objects.
 
    )Ú__new__rSÚupdaterTÚextend)ÚclsZdict_r[ÚobjrrrrR–s
  rR)NNF)rXÚ
__future__rÚtypingrrrrrZorm.collectionsr    r
r Úintr,Ú__all__r r r"r(rrrRrrrrÚ<module>    s,r        ü/ 0