-- permission-v2 stage 1 organization backfill for MySQL 8.0
-- purpose:
-- 1. initialize org_type
-- 2. backfill path and level from parent_id
--
-- assumption:
-- 1. root organization nodes satisfy parent_id = 0
-- 2. system_dept currently has no parent cycle

START TRANSACTION;

UPDATE system_dept
SET org_type = 'dept'
WHERE org_type IS NULL OR org_type = '';

WITH RECURSIVE dept_tree AS (
  SELECT
    id,
    parent_id,
    CAST(CONCAT('/', id, '/') AS CHAR(1024)) AS new_path,
    1 AS new_level
  FROM system_dept
  WHERE parent_id = 0

  UNION ALL

  SELECT
    child.id,
    child.parent_id,
    CAST(CONCAT(parent.new_path, child.id, '/') AS CHAR(1024)) AS new_path,
    parent.new_level + 1 AS new_level
  FROM system_dept child
  INNER JOIN dept_tree parent ON child.parent_id = parent.id
)
UPDATE system_dept d
INNER JOIN dept_tree t ON d.id = t.id
SET
  d.path = t.new_path,
  d.level = t.new_level;

COMMIT;

-- verification:
-- SELECT id, name, parent_id, org_type, path, level FROM system_dept ORDER BY parent_id, sort, id;
