-- 章节拆分为 chapter_sections:每段正文 + 配图独立存储,chapters 只保留封面图 -- 执行顺序: 1) 本文件 2) python -m scripts.migrate_chapters_to_sections -- 执行方式: psql -U -d -f api/migrations/add_chapter_sections.sql -- ========== 1. 新建 chapter_sections 表 ========== CREATE TABLE IF NOT EXISTS chapter_sections ( id VARCHAR NOT NULL PRIMARY KEY, chapter_id VARCHAR NOT NULL REFERENCES chapters(id) ON DELETE CASCADE, order_index INTEGER NOT NULL, content TEXT NOT NULL, image JSONB, updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS ix_chapter_sections_chapter_id ON chapter_sections(chapter_id); CREATE INDEX IF NOT EXISTS ix_chapter_sections_order ON chapter_sections(chapter_id, order_index); -- 若 chapter_sections 已存在且已提前切换到 image_id 结构,重跑迁移时需要临时补回 image 列, -- 以便后续 Python 脚本先完成 JSON -> memoir_images 的数据搬迁。 DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'chapter_sections' AND column_name = 'image' ) THEN ALTER TABLE chapter_sections ADD COLUMN image JSONB; RAISE NOTICE '已补回 chapter_sections.image,供数据迁移使用'; END IF; END $$; -- ========== 2. chapters 表增加 cover_image ========== DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'chapters' AND column_name = 'cover_image') THEN ALTER TABLE chapters ADD COLUMN cover_image JSONB; RAISE NOTICE '已添加 chapters.cover_image'; END IF; END $$; -- ========== 3. 回填与删列由脚本 scripts.migrate_chapters_to_sections 完成 ==========