\chapter{Arborescences}

On a un exemple de remplissage/vidage d'une closure table, mais il faudrait en fait présenter les listes adjacentes et les autres structures de données.
Comme ça on pourra introduire les graphs juste après.

\begin{minted}{python}
# <app>/management/commands/rebuild.py
"""This command manages Closure Tables implementation
It adds new levels and cleans links between entities.
This way, it's relatively easy to fetch an entire tree with just one tiny
request.
"""

from django.core.management.base import BaseCommand

from structure.models import Entity, EntityTreePath


class Command(BaseCommand):
    def handle(self, *args, **options):
        entities = Entity.objects.all()

        for entity in entities:
            breadcrumb = [node for node in entity.breadcrumb()]
            tree = set(EntityTreePath.objects.filter(descendant=entity))
            
            for idx, node in enumerate(breadcrumb):
                tree_path, _ = EntityTreePath.objects.get_or_create(
                    ancestor=node, descendant=entity, weight=idx + 1
                )
                
                if tree_path in tree:
                    tree.remove(tree_path)
            for tree_path in tree:
                tree_path.delete()
\end{minted}