Ver código fonte

fix(database): 允许 templates.base_document_id 为空

- 移除 NOT NULL 约束,支持创建空白模板
- 外键约束改为 ON DELETE SET NULL
- 添加迁移脚本 V2026_01_27_01
何文松 1 mês atrás
pai
commit
17f093ead8

+ 2 - 2
backend/sql/all_tables.sql

@@ -554,7 +554,7 @@ CREATE TABLE IF NOT EXISTS templates (
     user_id VARCHAR(36) NOT NULL REFERENCES users(id) ON DELETE CASCADE,
     name VARCHAR(255) NOT NULL,
     description TEXT,
-    base_document_id VARCHAR(36) NOT NULL REFERENCES documents(id) ON DELETE RESTRICT,
+    base_document_id VARCHAR(36) REFERENCES documents(id) ON DELETE SET NULL,
     status VARCHAR(32) DEFAULT 'draft',          -- draft/published/archived
     config JSONB DEFAULT '{}',
     is_public BOOLEAN DEFAULT FALSE,
@@ -573,7 +573,7 @@ CREATE INDEX IF NOT EXISTS idx_templates_is_public ON templates(is_public);
 CREATE INDEX IF NOT EXISTS idx_templates_base_document ON templates(base_document_id);
 
 COMMENT ON TABLE templates IS '报告模板表 - 示例文档驱动的模板';
-COMMENT ON COLUMN templates.base_document_id IS '示例报告文档ID';
+COMMENT ON COLUMN templates.base_document_id IS '示例报告文档ID(可选,空白模板可为空)';
 COMMENT ON COLUMN templates.status IS 'draft-草稿, published-已发布, archived-已归档';
 COMMENT ON COLUMN templates.is_public IS '是否公开给其他用户使用';
 

+ 2 - 2
backend/sql/template_tables.sql

@@ -24,7 +24,7 @@ CREATE TABLE templates (
     user_id VARCHAR(36) NOT NULL REFERENCES users(id) ON DELETE CASCADE,
     name VARCHAR(255) NOT NULL,
     description TEXT,
-    base_document_id VARCHAR(36) NOT NULL REFERENCES documents(id) ON DELETE RESTRICT,
+    base_document_id VARCHAR(36) REFERENCES documents(id) ON DELETE SET NULL,
     status VARCHAR(32) DEFAULT 'draft',
     config JSONB DEFAULT '{}',
     is_public BOOLEAN DEFAULT FALSE,
@@ -43,7 +43,7 @@ CREATE INDEX idx_templates_is_public ON templates(is_public);
 CREATE INDEX idx_templates_base_document ON templates(base_document_id);
 
 COMMENT ON TABLE templates IS '报告模板';
-COMMENT ON COLUMN templates.base_document_id IS '示例报告文档ID,关联 documents 表';
+COMMENT ON COLUMN templates.base_document_id IS '示例报告文档ID(可选,空白模板可为空)';
 COMMENT ON COLUMN templates.status IS 'draft-草稿, published-已发布, archived-已归档';
 COMMENT ON COLUMN templates.config IS '模板配置,如默认AI模型等';
 COMMENT ON COLUMN templates.is_public IS '是否公开给其他用户使用';

+ 15 - 0
database/migrations/V2026_01_27_01__make_base_document_id_nullable.sql

@@ -0,0 +1,15 @@
+-- 使 templates 表的 base_document_id 字段可为空
+-- 支持创建空白模板(不需要基础文档)
+
+-- 移除外键约束
+ALTER TABLE templates DROP CONSTRAINT IF EXISTS templates_base_document_id_fkey;
+
+-- 修改列为可空
+ALTER TABLE templates ALTER COLUMN base_document_id DROP NOT NULL;
+
+-- 重新添加外键约束(允许 NULL)
+ALTER TABLE templates ADD CONSTRAINT templates_base_document_id_fkey 
+    FOREIGN KEY (base_document_id) REFERENCES documents(id) ON DELETE SET NULL;
+
+-- 更新注释
+COMMENT ON COLUMN templates.base_document_id IS '示例报告文档ID(可选,空白模板可为空)';