-- 1. 创建 doc_definition_organization 表主键自增序列
CREATE SEQUENCE doc_definition_organization_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;

-- 2. 创建科室文书对照表
CREATE TABLE "public"."doc_definition_organization" (
  -- 主键ID
  "id" int8 NOT NULL DEFAULT nextval('doc_definition_organization_id_seq'::regclass),
  -- 文书定义ID
  "definition_id" int8 NOT NULL,
  -- 文书业务编码
  "bus_no" varchar(100) COLLATE "pg_catalog"."default" NOT NULL DEFAULT ''::character varying,
  -- 科室ID
  "organization_id" int8 NOT NULL,
  -- 通用审计字段
  "tenant_id" int8 NOT NULL,
  "delete_flag" char(1) COLLATE "pg_catalog"."default" NOT NULL DEFAULT '0',
  "create_by" varchar(32) COLLATE "pg_catalog"."default" NOT NULL DEFAULT ''::character varying,
  "create_time" timestamptz(6) NOT NULL,
  "update_by" varchar(32) COLLATE "pg_catalog"."default",
  "update_time" timestamptz(6),
  
  -- 主键约束
  CONSTRAINT "doc_definition_organization_pkey" PRIMARY KEY ("id")
  
);

-- 3. 设置表所有者
ALTER TABLE "public"."doc_definition_organization" 
  OWNER TO "postgres";

-- 4. 表和字段注释
COMMENT ON TABLE "public"."doc_definition_organization" IS '科室文书对照表：记录文书与科室的关联关系';

COMMENT ON COLUMN "public"."doc_definition_organization"."id" IS 'ID';
COMMENT ON COLUMN "public"."doc_definition_organization"."definition_id" IS '文书定义ID';
COMMENT ON COLUMN "public"."doc_definition_organization"."bus_no" IS '文书业务编码';
COMMENT ON COLUMN "public"."doc_definition_organization"."organization_id" IS '科室ID';
COMMENT ON COLUMN "public"."doc_definition_organization"."tenant_id" IS '租户ID';
COMMENT ON COLUMN "public"."doc_definition_organization"."delete_flag" IS '删除状态：0-未删除，1-已删除';
COMMENT ON COLUMN "public"."doc_definition_organization"."create_by" IS '创建人';
COMMENT ON COLUMN "public"."doc_definition_organization"."create_time" IS '创建时间';
COMMENT ON COLUMN "public"."doc_definition_organization"."update_by" IS '更新人';
COMMENT ON COLUMN "public"."doc_definition_organization"."update_time" IS '更新时间';

-- 5. 索引设计
-- 按文书定义ID查询（高频场景）
CREATE INDEX "idx_doc_def_org_definition" ON "public"."doc_definition_organization" ("definition_id");
-- 按科室ID查询（高频场景）
CREATE INDEX "idx_doc_def_org_organization" ON "public"."doc_definition_organization" ("organization_id");
-- 按租户ID查询（管理后台场景）
--CREATE INDEX "idx_doc_def_org_tenant" ON "public"."doc_definition_organization" ("tenant_id");




-- 向迁移历史表插入记录
INSERT INTO __MigrationsHistory (MigrationId, ProductVersion)
VALUES ('202508181410 doc_definition_organization', '1.0.0');