-- ============================================================
-- 计划↔目标↔试验 可追溯链（v2.27 批6）
-- ------------------------------------------------------------
-- 幂等。bre_plan 此前是彻底孤立的根表（无出向 FK、无入向 FK），
-- 目标/试验都无法上溯到计划。本脚本补齐两条闭合链：
--   plan → target → cross_combination → tree
--   plan → trial → trial_study → tree
-- 并让 trial 直接挂载目标（trial → target）。
-- 列均可空（既有数据不受影响），ON DELETE SET NULL（计划/目标删除不级联删下游）。
-- ============================================================

ALTER TABLE bre_target ADD COLUMN IF NOT EXISTS plan_id integer;
ALTER TABLE bre_target ADD CONSTRAINT fk_bre_target_plan_id
    FOREIGN KEY (plan_id) REFERENCES bre_plan(id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS ix_bre_target_plan_id ON bre_target(plan_id);
COMMENT ON COLUMN bre_target.plan_id IS '所属育种计划（bre_plan.id）；计划→目标→组合→树 可追溯链起点';

ALTER TABLE bre_trial ADD COLUMN IF NOT EXISTS plan_id integer;
ALTER TABLE bre_trial ADD CONSTRAINT fk_bre_trial_plan_id
    FOREIGN KEY (plan_id) REFERENCES bre_plan(id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS ix_bre_trial_plan_id ON bre_trial(plan_id);
COMMENT ON COLUMN bre_trial.plan_id IS '所属育种计划（bre_plan.id）；计划→试验→试验点→树 可追溯链起点';

ALTER TABLE bre_trial ADD COLUMN IF NOT EXISTS target_id integer;
ALTER TABLE bre_trial ADD CONSTRAINT fk_bre_trial_target_id
    FOREIGN KEY (target_id) REFERENCES bre_target(id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS ix_bre_trial_target_id ON bre_trial(target_id);
COMMENT ON COLUMN bre_trial.target_id IS '服务育种目标（bre_target.id）；试验直接挂载目标';
