INSERT INTO permission (id, permission_code, permission_name, module)
VALUES
    (1203, 'tenant.switch', '切换租户', 'system')
ON DUPLICATE KEY UPDATE permission_name = VALUES(permission_name), module = VALUES(module);

SET @next_role_permission_id := (SELECT IFNULL(MAX(id), 0) FROM role_permission);

INSERT INTO role_permission (id, tenant_id, role_id, permission_id)
SELECT
    (@next_role_permission_id := @next_role_permission_id + 1) AS id,
    r.tenant_id,
    r.id AS role_id,
    p.id AS permission_id
FROM role r
JOIN permission p ON p.permission_code = 'tenant.switch'
LEFT JOIN role_permission rp
    ON rp.tenant_id = r.tenant_id
    AND rp.role_id = r.id
    AND rp.permission_id = p.id
WHERE r.role_code = 'TENANT_ADMIN'
  AND r.is_deleted = 0
  AND rp.id IS NULL;
