docs: def rebuild_collection_tree(old_collection_ident, new_document_id_map, plpy):
      """Create a new tree for the collection based on the old tree.
  
      This uses new document ids, replacing old ones.
      """
      get_tree = plpy.prepare('''
      WITH RECURSIVE t(node, parent, document, title, childorder, latest, path)
          AS (SELECT tr.nodeid, tr.parent_id, tr.documentid, tr.title,
                     tr.childorder, tr.latest, ARRAY[tr.nodeid]
              FROM trees tr
              WHERE tr.documentid = $1 AND tr.is_collated = 'False'
      UNION ALL
          SELECT c.nodeid, c.parent_id, c.documentid, c.title,
                 c.childorder, c.latest, path || ARRAY[c.nodeid]
          FROM trees c JOIN t ON (c.parent_id = t.node)
          WHERE not c.nodeid = ANY(t.path)
      )
      SELECT * FROM t
      ''', ('integer',))
  
      def get_old_tree():
          return plpy.execute(get_tree, (old_collection_ident,))
  
      tree = {}  # { old_nodeid: {'data': ...}, ...}
      children = {}  # { nodeid: [child_nodeid, ...], child_nodeid: [...]}
      for i in get_old_tree():
          tree[i['node']] = {'data': i, 'new_nodeid': None}
          children.setdefault(i['parent'], [])
          children[i['parent']].append(i['node'])
  
      insert_tree = plpy.prepare('''
      INSERT INTO trees (nodeid, parent_id, documentid,
          title, childorder, latest)
      VALUES (DEFAULT, $1, $2, $3, $4, $5)
      RETURNING nodeid
      ''', ('integer', 'integer', 'text', 'integer', 'boolean'))
  
      def execute(fields):
          results = plpy.execute(insert_tree, fields, 1)
          return results[0]['nodeid']
  
      root_node = children[None][0]
  
      def build_tree(node, parent):
          data = tree[node]['data']
          new_node = execute([parent, new_document_id_map.get(data['document'],
                              data['document']), data['title'],
                              data['childorder'], data['latest']])
          for i in children.get(node, []):
              build_tree(i, new_node)
      build_tree(root_node, None)