Files
life-echo/api/migrations_legacy/add_section_image_id_fk.sql

19 lines
790 B
SQL
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
-- section 表用 image_id 关联 memoir_images不再存 JSON
-- 执行顺序1) 本文件 2) 回填后执行 DROP 语句(或由脚本完成)
-- 执行方式: psql -U <user> -d <database> -f api/migrations/add_section_image_id_fk.sql
-- 1. 添加外键列(可空,无默认)
ALTER TABLE chapter_sections
ADD COLUMN IF NOT EXISTS image_id VARCHAR REFERENCES memoir_images(id) ON DELETE SET NULL;
-- 2. 回填:已有 memoir_images 且 section_id 指向本行的,把其 id 写入本行 image_id
UPDATE chapter_sections cs
SET image_id = sub.id
FROM (
SELECT id, section_id FROM memoir_images WHERE section_id IS NOT NULL
) sub
WHERE sub.section_id = cs.id AND cs.image_id IS NULL;
-- 3. 删除旧的 JSON 列
ALTER TABLE chapter_sections DROP COLUMN IF EXISTS image;