/* Drop not_operating indoor plans with all slaves */

CREATE TEMPORARY TABLE deleted_indoor_ft
(
    ft_id bigint NOT NULL
);

WITH RECURSIVE recursive_slaves AS
(
    (SELECT ft_id
        FROM ft
        JOIN ft_attr USING (ft_id)
        WHERE key = 'not_operating'
        AND ft_type_id = 2301 /* indoor-plan */)

    UNION
 
    (SELECT ft.ft_id
        FROM ft
        JOIN recursive_slaves 
        ON recursive_slaves.ft_id = ft.p_ft_id /* all nested slaves of indoor-plan */)
)
INSERT INTO deleted_indoor_ft
SELECT * FROM recursive_slaves;

CREATE INDEX ON deleted_indoor_ft (ft_id);

DELETE FROM ft_isocode
USING deleted_indoor_ft
WHERE ft_isocode.ft_id = deleted_indoor_ft.ft_id;

DELETE FROM node_isocode
USING deleted_indoor_ft, ft_center
WHERE ft_center.ft_id = deleted_indoor_ft.ft_id
AND ft_center.node_id = node_isocode.node_id;

DELETE FROM edge_isocode
USING deleted_indoor_ft, ft_edge
WHERE ft_edge.ft_id = deleted_indoor_ft.ft_id
AND ft_edge.edge_id = edge_isocode.edge_id;

DELETE FROM face_isocode
USING deleted_indoor_ft, ft_face
WHERE ft_face.ft_id = deleted_indoor_ft.ft_id
AND ft_face.face_id = face_isocode.face_id;

DROP TABLE deleted_indoor_ft;
