a
    CgU                     @   s^   d Z ddlZddlmZ ddlmZ ddlmZmZm	Z	 ddl
mZmZ G dd dejZdS )	zModels and base API    N)reduceQ)modelsrouterconnections)InvalidPositionMissingNodeOrderByc                   @   s  e Zd ZdZdZedd Zedd Zedd Zedgd
dZ	edhddZ
edd Zedd Zedd Zedd Zedd ZediddZedjddZdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zd7d8 Zd9d: Z d;d< Z!dkd=d>Z"d?d@ Z#dAdB Z$dCdD Z%dEdF Z&dldGdHZ'dmdIdJZ(dKdL Z)de)_*de)_+dMdN Z,dOZ-dPZ.dQdR Z/e-dS Z0e.dT Z1dUdV Z2dWdX Z3edYdZ Z4ednd[d\Z5ed]d^ Z6ed_d` Z7edadb Z8edcdd Z9G dedf dfZ:dS )oNodez
Node classNc                 K   s   t dS )a  
        Adds a root node to the tree. The new root node will be the new
        rightmost root node. If you want to insert a root node at a specific
        position, use :meth:`add_sibling` in an already existing root node
        instead.

        :param `**kwargs`: object creation data that will be passed to the
            inherited Node model
        :param instance: Instead of passing object creation data, you can
            pass an already-constructed (but not yet saved) model instance to
            be inserted into the tree.

        :returns: the created node object. It will be save()d by this method.

        :raise NodeAlreadySaved: when the passed ``instance`` already exists
            in the database
        NNotImplementedError)clskwargs r   O/var/www/lab.imftr.de/x/nb_venv/lib/python3.9/site-packages/treebeard/models.pyadd_root   s    zNode.add_rootc                 C   s:   i }| j jD ](}| dkr|jdkr|jj||j< q|S )zhGet foreign keys and models they refer to, so we can pre-process
        the data for load_bulk
        Z
ForeignKeyparent)_metafieldsZget_internal_typenameZremote_fieldmodel)r   foreign_keysfieldr   r   r   get_foreign_keys&   s    
zNode.get_foreign_keysc                 C   s4   |  D ]&}||v r|| jj|| d||< qdS )zFor each foreign key try to load the actual object so load_bulk
        doesn't fail trying to load an int where django expects a
        model instance
        pkN)keysobjectsget)r   r   	node_datakeyr   r   r   _process_foreign_keys4   s
    
zNode._process_foreign_keysFc           
         s   g }fdd|ddd D }|   }| jjj}|r| \}|d  }	| ||	 |rj|| |	|< rjf i |	 n| jf i |	 |	 j d|v r2|
 fdd|d ddd D  q2|S )a  
        Loads a list/dictionary structure to the tree.


        :param bulk_data:

            The data that will be loaded, the structure is a list of
            dictionaries with 2 keys:

            - ``data``: will store arguments that will be passed for object
              creation, and

            - ``children``: a list of dictionaries, each one has it's own
              ``data`` and ``children`` keys (a recursive structure)


        :param parent:

            The node that will receive the structure as children, if not
            specified the first level of the structure will be loaded as root
            nodes


        :param keep_ids:

            If enabled, loads the nodes with the same primary keys that are
            given in the structure. Will error if there are nodes without
            primary key info or if the primary keys are already used.


        :returns: A list of the added node ids.
        c                    s   g | ]} |fqS r   r   .0node)r   r   r   
<listcomp>e       z"Node.load_bulk.<locals>.<listcomp>Ndatachildrenc                    s   g | ]} |fqS r   r   r"   )node_objr   r   r%   x   s   )r   r   r   Zattnamepopcopyr!   	add_childr   appendextend)
r   Z	bulk_datar   keep_idsaddedstackr   Zpk_fieldZnode_structr   r   )r*   r   r   	load_bulk?   s&    $

zNode.load_bulkTc                 C   s   t dS )a  
        Dumps a tree branch to a python data structure.

        :param parent:

            The node whose descendants will be dumped. The node itself will be
            included in the dump. If not given, the entire tree will be dumped.

        :param keep_ids:

            Stores the pk value (primary key) of every node. Enabled by
            default.

        :returns: A python data structure, described with detail in
                  :meth:`load_bulk`
        Nr   )r   r   r0   r   r   r   	dump_bulk~   s    zNode.dump_bulkc                 C   s   t dS )z;:returns: A queryset containing the root nodes in the tree.Nr   r   r   r   r   get_root_nodes   s    zNode.get_root_nodesc                 C   s(   z|   d W S  ty"   Y dS 0 dS )zd
        :returns:

            The first root node in the tree or ``None`` if it is empty.
        r   N)r6   
IndexErrorr5   r   r   r   get_first_root_node   s    zNode.get_first_root_nodec                 C   s,   z|    d W S  ty&   Y dS 0 dS )zc
        :returns:

            The last root node in the tree or ``None`` if it is empty.
        r   N)r6   reverser7   r5   r   r   r   get_last_root_node   s    zNode.get_last_root_nodec                 C   s   t dS )z*Checks for problems in the tree structure.Nr   r5   r   r   r   find_problems   s    zNode.find_problemsc                 C   s   t dS )z
        Solves problems that can appear when transactions are not used and
        a piece of code breaks, leaving the tree in an inconsistent state.
        Nr   r5   r   r   r   fix_tree   s    zNode.fix_treec                 C   s   t dS )z
        :returns:

            A list of nodes ordered as DFS, including the parent. If
            no parent is given, the entire tree is returned.
        Nr   )r   r   r   r   r   get_tree   s    zNode.get_treec                 C   s:   |du r|   }n| }t|}|D ]}| |_q&|S )a  
        Helper for a very common case: get a group of siblings and the number
        of *descendants* (not only children) in every sibling.

        :param parent:

            The parent of the siblings to return. If no parent is given, the
            root nodes will be returned.

        :returns:

            A `list` (**NOT** a Queryset) of node objects with an extra
            attribute: `descendants_count`.
        N)r6   get_childrenlistget_descendant_countZdescendants_count)r   r   Zqsetnodesr$   r   r   r   get_descendants_group_count   s    
z Node.get_descendants_group_countc                 C   s   t dS )z':returns: the depth (level) of the nodeNr   selfr   r   r   	get_depth   s    zNode.get_depthc                 C   s   t dS )zv
        :returns:

            A queryset of all the node's siblings, including the node
            itself.
        Nr   rC   r   r   r   get_siblings   s    zNode.get_siblingsc                 C   s   t dS )z/:returns: A queryset of all the node's childrenNr   rC   r   r   r   r>      s    zNode.get_childrenc                 C   s   |    S )z+:returns: The number of the node's children)r>   countrC   r   r   r   get_children_count   s    zNode.get_children_countc                 C   s   t dS )z
        :returns:

            A queryset of all the node's descendants, doesn't
            include the node itself (some subclasses may return a list).
        Nr   rC   r   r   r   get_descendants   s    zNode.get_descendantsc                 C   s   |    S )z.:returns: the number of descendants of a node.)rI   rG   rC   r   r   r   r@      s    zNode.get_descendant_countc                 C   s(   z|   d W S  ty"   Y dS 0 dS )zb
        :returns:

            The leftmost node's child, or None if it has no children.
        r   N)r>   r7   rC   r   r   r   get_first_child  s    zNode.get_first_childc                 C   s,   z|    d W S  ty&   Y dS 0 dS )zc
        :returns:

            The rightmost node's child, or None if it has no children.
        r   N)r>   r9   r7   rC   r   r   r   get_last_child  s    zNode.get_last_childc                 C   s   |   d S )z
        :returns:

            The leftmost node's sibling, can return the node itself if
            it was the leftmost sibling.
        r   )rF   rC   r   r   r   get_first_sibling  s    zNode.get_first_siblingc                 C   s   |    d S )z
        :returns:

            The rightmost node's sibling, can return the node itself if
            it was the rightmost sibling.
        r   )rF   r9   rC   r   r   r   get_last_sibling   s    zNode.get_last_siblingc                 C   sD   |   }dd |D }| j|v r@|| j}|dkr@||d  S dS )zy
        :returns:

            The previous node's sibling, or None if it was the leftmost
            sibling.
        c                 S   s   g | ]
}|j qS r   r   r#   objr   r   r   r%   1  r&   z)Node.get_prev_sibling.<locals>.<listcomp>r      N)rF   r   indexrD   siblingsidsidxr   r   r   get_prev_sibling)  s    
zNode.get_prev_siblingc                 C   sL   |   }dd |D }| j|v rH|| j}|t|d k rH||d  S dS )zv
        :returns:

            The next node's sibling, or None if it was the rightmost
            sibling.
        c                 S   s   g | ]
}|j qS r   r   rN   r   r   r   r%   ?  r&   z)Node.get_next_sibling.<locals>.<listcomp>rP   N)rF   r   rQ   lenrR   r   r   r   get_next_sibling7  s    
zNode.get_next_siblingc                 C   s   |   j|jd S )z
        :returns: ``True`` if the node is a sibling of another node given as an
            argument, else, returns ``False``

        :param node:

            The node that will be checked as a sibling
        r   )rF   filterr   existsrD   r$   r   r   r   is_sibling_ofE  s    	zNode.is_sibling_ofc                 C   s   |  j| jd S )z
        :returns: ``True`` if the node is a child of another node given as an
            argument, else, returns ``False``

        :param node:

            The node that will be checked as a parent
        r   )r>   rY   r   rZ   r[   r   r   r   is_child_ofP  s    	zNode.is_child_ofc                 C   s   t dS )z
        :returns: ``True`` if the node is a descendant of another node given
            as an argument, else, returns ``False``

        :param node:

            The node that will be checked as an ancestor
        Nr   r[   r   r   r   is_descendant_of[  s    	zNode.is_descendant_ofc                 K   s   t dS )a  
        Adds a child to the node. The new node will be the new rightmost
        child. If you want to insert a node at a specific position,
        use the :meth:`add_sibling` method of an already existing
        child node instead.

        :param `**kwargs`:

            Object creation data that will be passed to the inherited Node
            model
        :param instance: Instead of passing object creation data, you can
            pass an already-constructed (but not yet saved) model instance to
            be inserted into the tree.

        :returns: The created node object. It will be save()d by this method.

        :raise NodeAlreadySaved: when the passed ``instance`` already exists
            in the database
        Nr   )rD   r   r   r   r   r-   f  s    zNode.add_childc                 K   s   t dS )a  
        Adds a new node as a sibling to the current node object.


        :param pos:
            The position, relative to the current node object, where the
            new node will be inserted, can be one of:

            - ``first-sibling``: the new node will be the new leftmost sibling
            - ``left``: the new node will take the node's place, which will be
              moved to the right 1 position
            - ``right``: the new node will be inserted at the right of the node
            - ``last-sibling``: the new node will be the new rightmost sibling
            - ``sorted-sibling``: the new node will be at the right position
              according to the value of node_order_by

        :param `**kwargs`:

            Object creation data that will be passed to the inherited
            Node model
        :param instance: Instead of passing object creation data, you can
            pass an already-constructed (but not yet saved) model instance to
            be inserted into the tree.

        :returns:

            The created node object. It will be saved by this method.

        :raise InvalidPosition: when passing an invalid ``pos`` parm
        :raise InvalidPosition: when :attr:`node_order_by` is enabled and the
           ``pos`` parm wasn't ``sorted-sibling``
        :raise MissingNodeOrderBy: when passing ``sorted-sibling`` as ``pos``
           and the :attr:`node_order_by` attribute is missing
        :raise NodeAlreadySaved: when the passed ``instance`` already exists
            in the database
        Nr   )rD   posr   r   r   r   add_sibling|  s    %zNode.add_siblingc                 C   s   t dS )z4:returns: the root node for the current node object.Nr   rC   r   r   r   get_root  s    zNode.get_rootc                 C   s   |   j| jkS )z?:returns: True if the node is a root node (else, returns False))ra   r   rC   r   r   r   is_root  s    zNode.is_rootc                 C   s   |     S )z?:returns: True if the node is a leaf node (else, returns False))r>   rZ   rC   r   r   r   is_leaf  s    zNode.is_leafc                 C   s   t dS )z
        :returns:

            A queryset containing the current node object's ancestors,
            starting by the root node and descending to the parent.
            (some subclasses may return a list)
        Nr   rC   r   r   r   get_ancestors  s    zNode.get_ancestorsc                 C   s   t dS )z
        :returns: the parent node of the current node object.
            Caches the result in the object itself to help in loops.

        :param update: Updates the cached value.
        Nr   )rD   updater   r   r   
get_parent  s    zNode.get_parentc                 C   s   t dS )ax  
        Moves the current node and all it's descendants to a new position
        relative to another node.

        :param target:

            The node that will be used as a relative child/sibling when moving

        :param pos:

            The position, relative to the target node, where the
            current node object will be moved to, can be one of:

            - ``first-child``: the node will be the new leftmost child of the
              ``target`` node
            - ``last-child``: the node will be the new rightmost child of the
              ``target`` node
            - ``sorted-child``: the new node will be moved as a child of the
              ``target`` node according to the value of :attr:`node_order_by`
            - ``first-sibling``: the node will be the new leftmost sibling of
              the ``target`` node
            - ``left``: the node will take the ``target`` node's place, which
              will be moved to the right 1 position
            - ``right``: the node will be moved to the right of the ``target``
              node
            - ``last-sibling``: the node will be the new rightmost sibling of
              the ``target`` node
            - ``sorted-sibling``: the new node will be moved as a sibling of
              the ``target`` node according to the value of
              :attr:`node_order_by`

            .. note::

               If no ``pos`` is given the library will use ``last-sibling``,
               or ``sorted-sibling`` if :attr:`node_order_by` is enabled.

        :returns: None

        :raise InvalidPosition: when passing an invalid ``pos`` parm
        :raise InvalidPosition: when :attr:`node_order_by` is enabled and the
           ``pos`` parm wasn't ``sorted-sibling`` or ``sorted-child``
        :raise InvalidMoveToDescendant: when trying to move a node to one of
           it's own descendants
        :raise PathOverflow: when the library can't make room for the
           node's new position
        :raise MissingNodeOrderBy: when passing ``sorted-sibling`` or
           ``sorted-child`` as ``pos`` and the :attr:`node_order_by`
           attribute is missing
        Nr   )rD   targetr_   r   r   r   move  s    2z	Node.movec                 O   s   | j jj| jdj|i |S )z(Removes a node and all it's descendants.r   )	__class__r   rY   r   delete)rD   argsr   r   r   r   rj     s    zNode.deletec                 C   sl   |d u r| j rd}nd}||vr.td|f | j rR||vrRtdd||f ||v rh| j shtd|S )Nsorted-siblinglast-siblingzInvalid relative position: %sz/Must use %s in %s when node_order_by is enabledz or z Missing node_order_by attribute.)node_order_byr   joinr	   )rD   r_   method_nameZ	valid_posZvalid_sorted_posr   r   r   _prepare_pos_var  s    
zNode._prepare_pos_var)zfirst-siblingleftrightrm   rl   )rl   c                 C   s   |  |d| j| jS )Nr`   )rq   _valid_pos_for_add_sibling!_valid_pos_for_sorted_add_siblingrD   r_   r   r   r    _prepare_pos_var_for_add_sibling  s    z%Node._prepare_pos_var_for_add_sibling)zfirst-childz
last-childsorted-child)rx   c                 C   s   |  |d| j| jS )Nrh   )rq   _valid_pos_for_move_valid_pos_for_sorted_moverv   r   r   r   _prepare_pos_var_for_move  s    zNode._prepare_pos_var_for_movec              
   C   sp   g g  }}| j D ]L}t||}|tdd |D tf i d| |ig   |||f q|ttj|S )am  
        :returns:

            A queryset of the nodes that must be moved to the right.
            Called only for Node models with :attr:`node_order_by`

        This function is based on _insertion_target_filters from django-mptt
        (BSD licensed) by Jonathan Buchanan:
        https://github.com/django-mptt/django-mptt/blob/0.3.0/mptt/signals.py
        c                 S   s"   g | ]\}}t f i ||iqS r   r   )r#   fvr   r   r   r%   5  r&   z0Node.get_sorted_pos_queryset.<locals>.<listcomp>z%s__gt)rn   getattrr.   r   rY   r   operatoror_)rD   rS   Znewobjr   filtersr   valuer   r   r   get_sorted_pos_queryset$  s    


zNode.get_sorted_pos_querysetc           	      C   s   g i  }}d\}}|D ]t}|  }|du r.|}|o@|du p@||k}|durh||k rhttd|| |d< |g || d}|||f |}q|r|dkrttd|| d |d< |S )z9
        Gets an annotated list from a queryset.
        NNNr   close)openr   levelrP   )rE   r?   ranger.   )	r   qsresultinfostart_depth
prev_depthr$   depthr   r   r   r   get_annotated_list_qs<  s    
zNode.get_annotated_list_qsc                 C   s6   g i  }}d\}}|  |}|r,|j|d}| |S )aR  
        Gets an annotated list from a tree branch.

        :param parent:

            The node whose descendants will be annotated. The node itself
            will be included in the list. If not given, the entire tree
            will be annotated.

        :param max_depth:

            Optionally limit to specified depth
        r   )Z
depth__lte)r=   rY   r   )r   r   Z	max_depthr   r   r   r   r   r   r   r   get_annotated_listQ  s    

zNode.get_annotated_listc                 C   s   | }|j jr|j j}q|S )z
        Returns a model with a valid _meta.local_fields (serializable).

        Basically, this means the original model, not a proxied model.

        (this is a workaround for a bug in django)
        )r   proxyZproxy_for_model)r   Zcurrent_classr   r   r   _get_serializable_modelh  s    	
zNode._get_serializable_modelc                 C   s"   t t|  t t|  d| S )N)readwrite)r   r   Zdb_for_readZdb_for_writer   actionr   r   r   _get_database_connectionv  s
    zNode._get_database_connectionc                 C   s   |  |jS )a  
        returns the supported database vendor used by a treebeard model when
        performing read (select) or write (update, insert, delete) operations.

        :param action:

            `read` or `write`

        :returns: postgresql, mysql or sqlite
        )r   vendorr   r   r   r   get_database_vendor}  s    zNode.get_database_vendorc                 C   s   |  | S )N)r   cursorr   r   r   r   _get_database_cursor  s    zNode._get_database_cursorc                   @   s   e Zd ZdZdZdS )z	Node.MetazAbstract model.TN)__name__
__module____qualname____doc__Zabstractr   r   r   r   Meta  s   r   )NF)NT)N)N)N)F)N)NN);r   r   r   r   Z_db_connectionclassmethodr   r   r!   r3   r4   r6   r8   r:   r;   r<   r=   rB   rE   rF   r>   rH   rI   r@   rJ   rK   rL   rM   rV   rX   r\   r]   r^   r-   r`   ra   rb   rc   rd   rf   rh   rj   Zalters_dataZqueryset_onlyrq   rt   ru   rw   ry   rz   r{   r   r   r   r   r   r   r   r   r   r   r   r   r
      s   



>




					
'

	
4




r
   )r   r   	functoolsr   Zdjango.db.modelsr   Z	django.dbr   r   r   Ztreebeard.exceptionsr   r	   ZModelr
   r   r   r   r   <module>   s   