Stored procedure to clean up a tree (removing unlinked nodes)

Hi,

I did this stored procedure for my needs but maybe that can be useful for other members too.

I wanted to delete from all the trees the unused nodes. I’m only attaching the example for the Geography tree but it works the same way for the other trees.

DELIMITER $$
DROP PROCEDURE IF EXISTS cleanGeographyTree;

CREATE PROCEDURE cleanGeographyTree(INOUT p1 INT)
BEGIN
  DECLARE done INT DEFAULT 0;
  
  -- Loop rank ids
  RANK1: LOOP
    -- Check if p1 is less than 0
    IF p1 < 1 THEN
      LEAVE RANK1;
    END IF;

    -- Perform DELETE operation
    DELETE g
    FROM geography g
    LEFT JOIN geography gchild ON gchild.ParentID = g.GeographyID
    LEFT JOIN geography gaccepted ON gaccepted.GeographyID = g.AcceptedID
    LEFT JOIN geography gsynonym ON gsynonym.AcceptedID = g.GeographyID
    LEFT JOIN locality l ON l.GeographyID = g.GeographyID
    WHERE g.RankID = p1
      AND l.LocalityID IS NULL
      AND gchild.GeographyID IS NULL
		AND gaccepted.GeographyID IS NULL
		AND gsynonym.GeographyID IS NULL;

    -- Decrement p1
    SET p1 = p1 - 1;
  END LOOP RANK1;

END$$

DELIMITER ;
SET @startValue = 1000;

-- Call the procedure
CALL cleanGeographyTree(@startValue);

-- Optionally, check the final value of the variable
SELECT @startValue AS FinalValue;
4 Likes

Very helpful! Thank you for posting!

I have no use for this myself, but very nice.

you’re welcome! May I ask you @Grant to change the

If p1 < 0

TO

If p1 < 1

Indeed, if you clean up an empty tree, it will remove the root node and you can’t then add it back from the graphical interface ! Thanks a lot (I can’t do it myself)

1 Like

Hi @alexis.beck,

I’ve updated the script. Thank you for your comment! :smiley:

Starting in Specify 7.10, there is a small tool in Specify 7 to create a root node in case it is removed accidentally. If you are looking at an empty tree, a :plus_: (plus) button appears and you can use it to create that node.

1 Like

Thanks a lot, I didn’t find it out this morning. Wanted to check our current version but there is a bug in display and there is nothing!

Hi @alexis.beck,

From version v7.9 until v7.9.6.2, the version number is missing in the "About Specify dialog. This has been fixed in all versions after v7.10. That means it is very likely that you are using one of those versions!