
    h
:                        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  ed      Zeeee   gef   ZdgZ	 	 	 d	 	 	 	 	 	 	 	 	 ddZd Zd Zd Zd Z G d dee         Zd Zy)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_listNc                .     t        |||       fdS )a1  Prepares 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.

    )
count_fromordering_funcreorder_on_appendc                     t         fi S N)OrderingList)attrkws   DD:\EasyAligner\venv\Lib\site-packages\sqlalchemy/ext/orderinglist.py<lambda>zordering_list.<locals>.<lambda>   s    <++    )_unsugar_count_from)r   r   r   r   r   s   `   @r   r   r      s!    P 
#+
B
 ,+r   c                    | S )z7Numbering function: consecutive integers starting at 0. indexr
   s     r   count_from_0r      s	     Lr   c                    | dz   S )z7Numbering function: consecutive integers starting at 1.   r   r   s     r   count_from_1r"      s     19r   c                H      fd}	 d z  |_         |S # t        $ r Y |S w xY w)zENumbering function: consecutive integers starting at arbitrary start.c                    | z   S r   r   )r   r
   starts     r   fzcount_from_n_factory.<locals>.f   s    u}r   zcount_from_%i)__name__	TypeError)r%   r&   s   ` r   count_from_n_factoryr)      s9    $u,
 H  Hs   
 	!!c                     | j                  dd      }| j                  dd      0|.|dk(  rt        | d<   | S |dk(  rt        | d<   | S t	        |      | d<   | S )zBuilds counting functions from keyword arguments.

    Keyword argument filter, prepares a simple ``ordering_func`` from a
    ``count_from`` argument, otherwise passes ``ordering_func`` on unchanged.
    r   Nr   r   r!   )popgetr   r"   r)   )r   r   s     r   r   r      sr     d+J	vvot$,1G?".B
 I	 1_".B I #7z"BBIr   c                      e Zd ZU dZded<   ded<   ded<   	 	 	 d	 	 	 	 	 ddZd	 Zd
 ZddZeZ	ddZ
 fdZ fdZ  ej                  d      e      Z fdZ fdZd fd	Z fdZ fdZ fdZ fdZd Z e e       j3                               D ]M  \  ZZ ee      sej                   ek(  sej                  r, eee      s6 eee      j                  e_        O [[ xZS )r   zA 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.

    strordering_attrOrderingFuncr   boolr   c                >    || _         |t        }|| _        || _        y)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   r   r   )selfr/   r   r   s       r   __init__zOrderingList.__init__   s(    n + (M*!2r   c                .    t        || j                        S r   )getattrr/   )r3   entitys     r   _get_order_valuezOrderingList._get_order_value>  s    vt1122r   c                2    t        || j                  |       y r   )setattrr/   )r3   r7   values      r   _set_order_valuezOrderingList._set_order_valueA  s    **E2r   c                P    t        |       D ]  \  }}| j                  ||d        y)zSynchronize ordering for the entire collection.

        Sweeps through the list and ensures that each object has accurate
        ordering information set.

        TN)	enumerate_order_entity)r3   r   r7   s      r   reorderzOrderingList.reorderD  s(     't_ME6ufd3 -r   c                    | j                  |      }||sy | j                  ||       }||k7  r| j                  ||       y y r   )r8   r   r<   )r3   r   r7   r@   have	should_bes         r   r?   zOrderingList._order_entityQ  sN    $$V, G&&ud3	9!!&)4 r   c                v    t         |   |       | j                  t        |       dz
  || j                         y )Nr!   )superappendr?   lenr   r3   r7   	__class__s     r   rF   zOrderingList.append\  s/    v3t9q=&$2H2HIr   c                $    t         |   |       y)z%Append without any ordering behavior.N)rE   rF   rH   s     r   _raw_appendzOrderingList._raw_append`  s     	vr   r!   c                F    t         |   ||       | j                          y r   )rE   insert_reorderr3   r   r7   rI   s      r   rM   zOrderingList.insertg  s    uf%r   c                z    t         |   |       t        |       }|r|j                  r| j	                          y y y r   )rE   remover   _referenced_by_ownerrN   )r3   r7   adapterrI   s      r   rQ   zOrderingList.removek  s4    v$T*w33MMO 47r   c                F    t         |   |      }| j                          |S r   )rE   r+   rN   rO   s      r   r+   zOrderingList.popr  s    U#r   c                z   t        |t              r|j                  xs d}|j                  xs d}|dk  r|t	        |       z  }|j
                  xs t	        |       }|dk  r|t	        |       z  }t        |||      D ]  }| j                  |||           y | j                  ||d       t        |   ||       y )Nr!   r   T)

isinstanceslicestepr%   rG   stoprange__setitem__r?   rE   )r3   r   r7   rX   r%   rY   irI   s          r   r[   zOrderingList.__setitem__w  s    eU#::?DKK$1EqyT"::*TDaxD	!5$-  F1I. . ufd3Gv.r   c                D    t         |   |       | j                          y r   )rE   __delitem__rN   )r3   r   rI   s     r   r^   zOrderingList.__delitem__  s    E"r   c                H    t         |   |||       | j                          y r   )rE   __setslice__rN   )r3   r%   endvaluesrI   s       r   r`   zOrderingList.__setslice__  s    UC0r   c                F    t         |   ||       | j                          y r   )rE   __delslice__rN   )r3   r%   ra   rI   s      r   rd   zOrderingList.__delslice__  s    UC(r   c                R    t         | j                  | j                  t        |       ffS r   )_reconstituterI   __dict__list)r3   s    r   
__reduce__zOrderingList.__reduce__  s     t~~t}}d4jIIIr   NNF)r/   zOptional[str]r   Optional[OrderingFunc]r   r1   )returnNone)T)) r'   
__module____qualname____doc____annotations__r4   r8   r<   r@   rN   r?   rF   rK   r
   addsrM   rQ   r+   r[   r^   r`   rd   ri   rh   localsitems	func_namefunccallablehasattrr6   __classcell__)rI   s   @r   r   r      s     (,04"'	;3$;3 .;3  	;3~334 H	5J
 %/*//!$[1K
/ J   01	4TN*LLi("43;;DL 2 	4r   r   c                    | j                  |       }|j                  j                  |       t        j	                  ||       |S )zReconstitute an :class:`.OrderingList`.

    This is the adjoint to :meth:`.OrderingList.__reduce__`.  It is used for
    unpickling :class:`.OrderingList` objects.

    )__new__rg   updaterh   extend)clsdict_ru   objs       r   rf   rf     s7     ++c
CLLKKUJr   rj   )
r   r.   r   zOptional[int]r   rk   r   r1   rl   zCallable[[], OrderingList])rq   
__future__r   typingr   r   r   r   r   orm.collectionsr
   r   r   intr0   __all__r   r   r"   r)   r   r   rf   r   r   r   <module>r      s   xr #      ( 0T]hrl+S01 

 !%,0#	-,
-,-, *-, 	-,
  -,f
$l48 l^
r   