ALTER TABLE public.flow_task_instance
ADD COLUMN IF NOT EXISTS task_template_code varchar(100),
ADD COLUMN IF NOT EXISTS is_loop bool NOT NULL DEFAULT false;

UPDATE public.flow_task_instance AS ti
SET
    task_template_code = tt.code,
    is_loop = COALESCE(tt.is_loop, false)
FROM public.flow_task_template AS tt
WHERE ti.task_template_id = tt.id
  AND (
      ti.task_template_code IS DISTINCT FROM tt.code
      OR ti.is_loop IS DISTINCT FROM COALESCE(tt.is_loop, false)
  );

UPDATE public.flow_task_instance
SET task_template_code = COALESCE(task_template_code, task_template_id)
WHERE task_template_code IS NULL;

CREATE INDEX IF NOT EXISTS ix_flow_task_instance_task_template_code
ON public.flow_task_instance (task_template_code);
