
    AhU                     v    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ej                        Zy)	zModels and base API    N)reduce)Q)modelsrouterconnections)InvalidPositionMissingNodeOrderByc                   8   e Zd ZdZdZed        Zed        Zed        Zed8d       Z	ed9d       Z
ed	        Zed
        Zed        Zed        Zed        Zed:d       Zed:d       Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z d Z!d:d Z"d! Z#d" Z$d# Z%d$ Z&d;d%Z'd:d&Z(d' Z)de)_*        de)_+        d( Z,d)Z-d*Z.d+ Z/e-d,z   Z0e.d-z   Z1d. Z2d/ Z3ed0        Z4ed<d1       Z5ed2        Z6ed3        Z7ed4        Z8ed5        Z9 G d6 d7      Z:y)=Nodez
Node classNc                     t         )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
        NotImplementedError)clskwargss     @/home/dcms/DCMS/lib/python3.12/site-packages/treebeard/models.pyadd_rootzNode.add_root   s
    & "!    c                     i }| j                   j                  D ]I  }|j                         dk(  s|j                  dk7  s'|j                  j
                  ||j                  <   K |S )zhGet foreign keys and models they refer to, so we can pre-process
        the data for load_bulk
        
ForeignKeyparent)_metafieldsget_internal_typenameremote_fieldmodel)r   foreign_keysfields      r   get_foreign_keyszNode.get_foreign_keys&   sc    
 YY%% 	DE'')\9

h&+0+=+=+C+CUZZ(	D r   c                     |j                         D ],  }||v s||   j                  j                  ||         ||<   . y)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keys       r   _process_foreign_keyszNode._process_foreign_keys4   sO      $$& 	'Ci!-c!2!:!:!>!> ~ "? "'	#	'r   c                    g }|ddd   D cg c]  }||f }}| j                         }| j                  j                  j                  }|r|j	                         \  }}	|	d   j                         }
| j                  ||
       |r|	|   |
|<   |r |j                  di |
}n | j                  di |
}|j                  |j                         d|	v r*|j                  |	d   ddd   D cg c]  }||f c}       |r|S c c}w c c}w )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.
        Ndatachildren )r   r   r"   attnamepopcopyr(   	add_childr   appendextend)r   	bulk_datar   keep_idsaddednodestackr   pk_fieldnode_structr&   node_objs               r   	load_bulkzNode.load_bulk?   s"   H ,5ddO<D&$<<++-99<<''"'))+FK#F+002I%%lI>&1(&;	(#+6++8i8'3<<4)4LL%[(  +J 7" = t$  & / =&s   D,DTc                     t         )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`
        r   )r   r   r5   s      r   	dump_bulkzNode.dump_bulk~   s
    $ "!r   c                     t         )z;:returns: A queryset containing the root nodes in the tree.r   r   s    r   get_root_nodeszNode.get_root_nodes   
     "!r   c                 H    	 | j                         d   S # t        $ r Y yw xY w)zd
        :returns:

            The first root node in the tree or ``None`` if it is empty.
        r   N)rA   
IndexErrorr@   s    r   get_first_root_nodezNode.get_first_root_node   s-    	%%'** 		    	!!c                 d    	 | j                         j                         d   S # t        $ r Y yw xY w)zc
        :returns:

            The last root node in the tree or ``None`` if it is empty.
        r   N)rA   reverserD   r@   s    r   get_last_root_nodezNode.get_last_root_node   s6    	%%'//1!44 		    # 	//c                     t         )z*Checks for problems in the tree structure.r   r@   s    r   find_problemszNode.find_problems   rB   r   c                     t         )z
        Solves problems that can appear when transactions are not used and
        a piece of code breaks, leaving the tree in an inconsistent state.
        r   r@   s    r   fix_treezNode.fix_tree   s
     "!r   c                     t         )z
        :returns:

            A list of nodes ordered as DFS, including the parent. If
            no parent is given, the entire tree is returned.
        r   )r   r   s     r   get_treezNode.get_tree   
     "!r   c                     || j                         }n|j                         }t        |      }|D ]  }|j                         |_         |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`.
        )rA   get_childrenlistget_descendant_countdescendants_count)r   r   qsetnodesr7   s        r   get_descendants_group_countz Node.get_descendants_group_count   sU      >%%'D&&(DT
 	AD%)%>%>%@D"	Ar   c                     t         )z':returns: the depth (level) of the noder   selfs    r   	get_depthzNode.get_depth       !!r   c                     t         )zv
        :returns:

            A queryset of all the node's siblings, including the node
            itself.
        r   r[   s    r   get_siblingszNode.get_siblings   
     "!r   c                     t         )z/:returns: A queryset of all the node's childrenr   r[   s    r   rS   zNode.get_children   r^   r   c                 >    | j                         j                         S )z+:returns: The number of the node's children)rS   countr[   s    r   get_children_countzNode.get_children_count   s      "((**r   c                     t         )z
        :returns:

            A queryset of all the node's descendants, doesn't
            include the node itself (some subclasses may return a list).
        r   r[   s    r   get_descendantszNode.get_descendants   ra   r   c                 >    | j                         j                         S )z.:returns: the number of descendants of a node.)rg   rd   r[   s    r   rU   zNode.get_descendant_count   s    ##%++--r   c                 H    	 | j                         d   S # t        $ r Y yw xY w)zb
        :returns:

            The leftmost node's child, or None if it has no children.
        r   N)rS   rD   r[   s    r   get_first_childzNode.get_first_child  s-    	$$&q)) 		rF   c                 d    	 | j                         j                         d   S # t        $ r Y yw xY w)zc
        :returns:

            The rightmost node's child, or None if it has no children.
        r   N)rS   rH   rD   r[   s    r   get_last_childzNode.get_last_child  s6    	$$&..033 		rJ   c                 (    | j                         d   S )z
        :returns:

            The leftmost node's sibling, can return the node itself if
            it was the leftmost sibling.
        r   )r`   r[   s    r   get_first_siblingzNode.get_first_sibling  s       "1%%r   c                 D    | j                         j                         d   S )z
        :returns:

            The rightmost node's sibling, can return the node itself if
            it was the rightmost sibling.
        r   )r`   rH   r[   s    r   get_last_siblingzNode.get_last_sibling   s!       "**,Q//r   c                     | j                         }|D cg c]  }|j                   }}| j                  |v r)|j                  | j                        }|dkD  r||dz
     S yyc c}w )zy
        :returns:

            The previous node's sibling, or None if it was the leftmost
            sibling.
        r      N)r`   r"   indexr\   siblingsobjidsidxs        r   get_prev_siblingzNode.get_prev_sibling)  sk     $$&!)*#svv**77c>))DGG$CQwa((   +s   A"c                     | j                         }|D cg c]  }|j                   }}| j                  |v r5|j                  | j                        }|t        |      dz
  k  r||dz      S yyc c}w )zv
        :returns:

            The next node's sibling, or None if it was the rightmost
            sibling.
        rr   N)r`   r"   rs   lenrt   s        r   get_next_siblingzNode.get_next_sibling7  su     $$&!)*#svv**77c>))DGG$CS]Q&&a(( '  +s   A.c                 r    | j                         j                  |j                        j                         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!   )r`   filterr"   existsr\   r7   s     r   is_sibling_ofzNode.is_sibling_ofE  .       "))TWW)5<<>>r   c                 r    |j                         j                  | j                        j                         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!   )rS   r~   r"   r   r   s     r   is_child_ofzNode.is_child_ofP  r   r   c                     t         )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
        r   r   s     r   is_descendant_ofzNode.is_descendant_of[  s
     "!r   c                     t         )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
        r   )r\   r   s     r   r1   zNode.add_childf  s
    ( "!r   c                     t         )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
        r   )r\   posr   s      r   add_siblingzNode.add_sibling|  s    J "!r   c                     t         )z4:returns: the root node for the current node object.r   r[   s    r   get_rootzNode.get_root  r^   r   c                 P    | j                         j                  | j                  k(  S )z?:returns: True if the node is a root node (else, returns False))r   r"   r[   s    r   is_rootzNode.is_root  s    }}!!TWW,,r   c                 @    | j                         j                          S )z?:returns: True if the node is a leaf node (else, returns False))rS   r   r[   s    r   is_leafzNode.is_leaf  s    $$&--///r   c                     t         )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)
        r   r[   s    r   get_ancestorszNode.get_ancestors  rQ   r   c                     t         )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.
        r   )r\   updates     r   
get_parentzNode.get_parent  ra   r   c                     t         )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
        r   )r\   targetr   s      r   movez	Node.move  s    d "!r   c                      | j                   j                  j                  | j                        j                  |i |S )z(Removes a node and all it's descendants.r!   )	__class__r$   r~   r"   delete)r\   argsr   s      r   r   zNode.delete  s6    ?t~~%%,,,8??PPPr   c                     || j                   rd}nd}||vrt        d|      | j                   r%||vr!t        ddj                  |      d|d      ||v r| j                   st        d      |S )	Nsorted-siblinglast-siblingzInvalid relative position: z	Must use z or z in z when node_order_by is enabledz Missing node_order_by attribute.)node_order_byr   joinr	   )r\   r   method_name	valid_posvalid_sorted_poss        r   _prepare_pos_varzNode._prepare_pos_var  s    ;!!&$i!S"KLL#-="=!KK 01;@A A ""4+=+=$%GHH
r   )zfirst-siblingleftrightr   r   )r   c                 R    | j                  |d| j                  | j                        S )Nr   )r   _valid_pos_for_add_sibling!_valid_pos_for_sorted_add_siblingr\   r   s     r    _prepare_pos_var_for_add_siblingz%Node._prepare_pos_var_for_add_sibling  s-    $$++22	4 	4r   )zfirst-childz
last-childsorted-child)r   c                 R    | j                  |d| j                  | j                        S )Nr   )r   _valid_pos_for_move_valid_pos_for_sorted_mover   s     r   _prepare_pos_var_for_movezNode._prepare_pos_var_for_move  s-    $$$$++	- 	-r   c                 V   g g }}| j                   D ]h  }t        ||      }|j                  t        |D cg c]  \  }}t        di ||i c}}t        di d|z  |igz           |j                  ||f       j |j	                  t        t        j                  |            S c c}}w )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
        z%s__gtr-   )r   getattrr2   r   r~   r   operatoror_)	r\   ru   newobjr   filtersr   valuefvs	            r   get_sorted_pos_querysetzNode.get_sorted_pos_queryset$  s     b'' 	*EFE*ENN.45daak1a&k548e+U3456 MM5%.)	* vhllG<== 6s   B%c                 6   g i }}d\  }}|D ]e  }|j                         }||}|xr |du xs ||kD  }| ||k  rt        t        d||z
              |d<   |g ||z
  d}|j                  ||f       |}g |r#|dkD  rt        t        d||z
  dz               |d<   |S )z9
        Gets an annotated list from a queryset.
        NNNr   close)openr   levelrr   )r]   rT   ranger2   )	r   qsresultinfostart_depth
prev_depthr7   depthr   s	            r   get_annotated_list_qszNode.get_annotated_list_qs<  s    
 2".Z 		DNN$E"#HzT1GUZ5GD%%**< $U1j5.@%A BW 28KLDMM4-(J		 ;? q*{*BQ*F!GHDMr   c                     g i }}d\  }}| j                  |      }|r|j                  |      }| j                  |      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   )
depth__lte)rP   r~   r   )r   r   	max_depthr   r   r   r   r   s           r   get_annotated_listzNode.get_annotated_listQ  sI      2".Z\\&!i0B((,,r   c                     | }|j                   j                  r-|j                   j                  }|j                   j                  r-|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   proxyproxy_for_model)r   current_classs     r   _get_serializable_modelzNode._get_serializable_modelh  s@     !!'')//??M !!''r   c                 z    t         t        j                  |          t         t        j                  |          d|   S )N)readwrite)r   r   db_for_readdb_for_writer   actions     r   _get_database_connectionzNode._get_database_connectionv  s>       2 23 78 !4!4S!9:
  	r   c                 8    | j                  |      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   s     r   get_database_vendorzNode.get_database_vendor}  s     ++F3:::r   c                 @    | j                  |      j                         S N)r   cursorr   s     r   _get_database_cursorzNode._get_database_cursor  s    ++F3::<<r   c                       e Zd ZdZdZy)	Node.MetazAbstract model.TN)__name__
__module____qualname____doc__abstractr-   r   r   Metar     s
    r   r   )NF)NTr   )Fr   );r   r   r   r   _db_connectionclassmethodr   r   r(   r<   r>   rA   rE   rI   rL   rN   rP   rY   r]   r`   rS   re   rg   rU   rj   rl   rn   rp   ry   r|   r   r   r   r1   r   r   r   r   r   r   r   r   alters_dataqueryset_onlyr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r-   r   r   r   r      sN   N" "(   ' ' < <| " "& " " 	 	 	 	 " " " " " "  0"""+".		&0))	?	?	"",%"N"-0""2"hQ FF "D(;%4 5 85 5!B F "->0  ( - -,     ; ; = = r   r   )r   r   	functoolsr   django.db.modelsr   	django.dbr   r   r   treebeard.exceptionsr   r	   Modelr   r-   r   r   <module>r      s,        1 1 DE
6<< E
r   