feat: Add agent configuration and cleanup scripts for database migrations
This commit is contained in:
@@ -0,0 +1,199 @@
|
||||
# 数据库迁移说明
|
||||
|
||||
## 📋 迁移文件列表
|
||||
|
||||
### MySQL
|
||||
```
|
||||
mysql/
|
||||
├── 00-init-db.sql # ❗️初始化脚本(包含后期添加的字段)
|
||||
├── 02-add-agent-config-if-missing.sql # ✅ 兼容性迁移(检查并添加缺失字段)
|
||||
└── 03-cleanup-unreferenced-models.sql # 🧹 清理未引用模型(维护脚本)
|
||||
```
|
||||
|
||||
### ParadeDB/PostgreSQL
|
||||
```
|
||||
paradedb/
|
||||
├── 01-migrate-to-paradedb.sql # ❗️ParadeDB 初始化
|
||||
├── 02-add-agent-config-if-missing.sql # ✅ 兼容性迁移(检查并添加缺失字段)
|
||||
└── 03-cleanup-unreferenced-models.sql # 🧹 清理未引用模型(维护脚本)
|
||||
```
|
||||
|
||||
## ⚠️ 重要说明
|
||||
|
||||
### 关于 `agent_config` 等字段
|
||||
|
||||
你可能会注意到 `agent_config`、`context_config`、`agent_steps` 这些字段**同时出现在**:
|
||||
- ✅ 初始化脚本中(`00-init-db.sql`)
|
||||
- ✅ 迁移脚本中(`02-add-agent-config-if-missing.sql`)
|
||||
|
||||
**这不是错误!** 这是为了兼容两种场景:
|
||||
|
||||
#### 场景1: 全新安装 🆕
|
||||
运行 `00-init-db.sql` 时,会直接创建包含所有字段的表(包括 `agent_config`)。
|
||||
当运行 `02-add-agent-config-if-missing.sql` 时,会检测到字段已存在,跳过添加。
|
||||
|
||||
#### 场景2: 旧版本升级 ⬆️
|
||||
如果你的数据库是从旧版本(不包含 `agent_config` 的版本)升级:
|
||||
- `00-init-db.sql` 早已运行过(但那时还没有 `agent_config` 字段)
|
||||
- 运行 `02-add-agent-config-if-missing.sql` 时,会检测到字段不存在,然后添加
|
||||
|
||||
### 为什么会这样?
|
||||
|
||||
根据 `AGENT_CONFIG_TENANT_REFACTORING.md` 文档,`agent_config` 是后来添加的功能。理论上:
|
||||
|
||||
**❌ 不应该做的(但已经做了):**
|
||||
```sql
|
||||
-- 00-init-db.sql 被修改了,添加了后来才加的字段
|
||||
CREATE TABLE tenants (
|
||||
agent_config JSON DEFAULT NULL, -- 这个字段是后来加的!
|
||||
...
|
||||
);
|
||||
```
|
||||
|
||||
**✅ 应该做的:**
|
||||
```sql
|
||||
-- 00-init-db.sql(保持不变)
|
||||
CREATE TABLE tenants (
|
||||
-- 没有 agent_config
|
||||
...
|
||||
);
|
||||
|
||||
-- 02-add-agent-config.sql(新文件)
|
||||
ALTER TABLE tenants ADD COLUMN agent_config JSON DEFAULT NULL;
|
||||
```
|
||||
|
||||
但由于初始化脚本已经被修改,我们创建了一个**智能的兼容性迁移脚本** `02-add-agent-config-if-missing.sql`,它:
|
||||
- ✅ 检查字段是否存在
|
||||
- ✅ 只在字段不存在时才添加
|
||||
- ✅ 对新旧数据库都安全
|
||||
|
||||
## 🚀 使用方法
|
||||
|
||||
### 方法1: 全新部署
|
||||
|
||||
```bash
|
||||
# 直接运行所有迁移
|
||||
./scripts/migrate.sh up
|
||||
|
||||
# 结果:
|
||||
# - 00-init-db.sql: 创建表(包含 agent_config)
|
||||
# - 02-add-agent-config-if-missing.sql: 检测到字段已存在,跳过
|
||||
```
|
||||
|
||||
### 方法2: 从旧版本升级
|
||||
|
||||
```bash
|
||||
# 运行新的迁移
|
||||
docker exec -i paradedb_container psql -U postgres -d WeKnora \
|
||||
< migrations/paradedb/02-add-agent-config-if-missing.sql
|
||||
|
||||
# 结果:
|
||||
# - 检测到 agent_config 不存在
|
||||
# - 添加 agent_config、context_config、agent_steps 字段
|
||||
# - 创建 GIN 索引提高查询性能
|
||||
```
|
||||
|
||||
### 方法3: 验证字段是否存在
|
||||
|
||||
#### MySQL
|
||||
```sql
|
||||
SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = 'WeKnora'
|
||||
AND TABLE_NAME = 'tenants'
|
||||
AND COLUMN_NAME = 'agent_config';
|
||||
```
|
||||
|
||||
#### PostgreSQL
|
||||
```sql
|
||||
SELECT column_name, data_type, is_nullable, column_default
|
||||
FROM information_schema.columns
|
||||
WHERE table_name = 'tenants'
|
||||
AND column_name = 'agent_config';
|
||||
```
|
||||
|
||||
## 📝 涉及的字段
|
||||
|
||||
以下字段是通过 `02-add-agent-config-if-missing.sql` 处理的:
|
||||
|
||||
### `tenants` 表
|
||||
- `agent_config` (JSON/JSONB): 租户级别的 Agent 配置
|
||||
|
||||
### `sessions` 表
|
||||
- `agent_config` (JSON/JSONB): 会话级别的 Agent 配置
|
||||
- `context_config` (JSON/JSONB): LLM 上下文管理配置
|
||||
|
||||
### `messages` 表
|
||||
- `agent_steps` (JSON/JSONB): Agent 执行步骤(推理过程和工具调用)
|
||||
|
||||
## 🎯 最佳实践建议
|
||||
|
||||
### 对于新字段的添加
|
||||
|
||||
如果你需要添加新字段,**不要修改 `00-init-db.sql`**!应该:
|
||||
|
||||
1. 创建新的迁移文件:`03-your-feature.sql`
|
||||
2. 使用 `ALTER TABLE` 添加字段
|
||||
3. 使用 `IF NOT EXISTS` 确保幂等性
|
||||
|
||||
示例:
|
||||
```sql
|
||||
-- 03-add-new-feature.sql
|
||||
ALTER TABLE tenants
|
||||
ADD COLUMN IF NOT EXISTS new_field VARCHAR(255) DEFAULT NULL;
|
||||
```
|
||||
|
||||
### 对于现有字段的修改
|
||||
|
||||
```sql
|
||||
-- 04-modify-field.sql
|
||||
ALTER TABLE tenants
|
||||
MODIFY COLUMN existing_field TEXT NULL;
|
||||
```
|
||||
|
||||
## 📚 更多信息
|
||||
|
||||
详细的迁移指南请参考:[MIGRATION_GUIDE.md](./MIGRATION_GUIDE.md)
|
||||
|
||||
## 🧹 维护脚本
|
||||
|
||||
### 03-cleanup-unreferenced-models.sql
|
||||
|
||||
**用途**: 清理数据库中未被任何知识库引用的模型
|
||||
|
||||
**清理条件**(必须同时满足):
|
||||
- ❌ 未被 `knowledge_bases` 引用(embedding/summary/rerank/vlm 模型)
|
||||
- ❌ 未被 `knowledges` 引用(embedding 模型)
|
||||
- ❌ 非默认模型(`is_default = FALSE`)
|
||||
- ❌ 非系统模型(`tenant_id != 0`)
|
||||
- ❌ 未软删除(`deleted_at IS NULL`)
|
||||
|
||||
**使用步骤**:
|
||||
1. 📊 运行 DRY RUN 查询查看将被删除的模型
|
||||
2. 💾 备份数据库
|
||||
3. 🔄 选择软删除(推荐)或硬删除
|
||||
4. ✅ 验证结果
|
||||
|
||||
**详细说明**: 请查看 [CLEANUP_GUIDE.md](./CLEANUP_GUIDE.md)
|
||||
|
||||
**⚠️ 重要**:
|
||||
- 软删除可以回滚,硬删除不可逆
|
||||
- 建议先在测试环境验证
|
||||
- 可设置定时任务自动清理
|
||||
|
||||
## 🔗 相关文档
|
||||
|
||||
- `AGENT_CONFIG_TENANT_REFACTORING.md` - Agent 配置重构说明
|
||||
- `CONTEXT_MANAGER_IMPLEMENTATION.md` - 上下文管理器实现
|
||||
- `MIGRATION_GUIDE.md` - 完整的迁移指南
|
||||
- `CLEANUP_GUIDE.md` - 模型清理指南 🆕
|
||||
|
||||
---
|
||||
|
||||
**创建时间**: 2025-11-03
|
||||
**问题发现**: Agent Config 字段既在初始化脚本中,又应该在增量迁移中
|
||||
**解决方案**: 创建智能兼容性迁移脚本,同时支持新旧数据库
|
||||
|
||||
**更新时间**: 2025-11-03
|
||||
**新增功能**: 添加未引用模型清理脚本,支持软删除和硬删除
|
||||
|
||||
@@ -16,6 +16,7 @@ CREATE TABLE tenants (
|
||||
business VARCHAR(255) NOT NULL,
|
||||
storage_quota BIGINT NOT NULL DEFAULT 10737418240,
|
||||
storage_used BIGINT NOT NULL DEFAULT 0,
|
||||
agent_config JSON DEFAULT NULL COMMENT 'Tenant-level agent configuration in JSON format',
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
deleted_at TIMESTAMP NULL DEFAULT NULL
|
||||
@@ -104,6 +105,8 @@ CREATE TABLE sessions (
|
||||
rerank_threshold FLOAT NOT NULL DEFAULT 0.65,
|
||||
summary_model_id VARCHAR(64),
|
||||
summary_parameters JSON NOT NULL,
|
||||
agent_config JSON DEFAULT NULL COMMENT 'Session-level agent configuration in JSON format',
|
||||
context_config JSON DEFAULT NULL COMMENT 'LLM context management configuration (separate from message storage)',
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
deleted_at TIMESTAMP NULL DEFAULT NULL
|
||||
@@ -118,6 +121,7 @@ CREATE TABLE messages (
|
||||
role VARCHAR(50) NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
knowledge_references JSON NOT NULL,
|
||||
agent_steps JSON DEFAULT NULL COMMENT 'Agent execution steps (reasoning process and tool calls)',
|
||||
is_completed BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
-- 增量迁移:添加 agent_config 字段(如果不存在)
|
||||
-- 创建时间:2025-11-03
|
||||
-- 目的:为旧版本数据库添加 agent_config 支持
|
||||
-- 注意:新数据库可能已经有这些字段(通过00-init-db.sql),使用 IF NOT EXISTS 确保兼容
|
||||
|
||||
-- ============================================
|
||||
-- 1. 为 tenants 表添加 agent_config
|
||||
-- ============================================
|
||||
|
||||
-- 检查并添加字段
|
||||
SET @dbname = DATABASE();
|
||||
SET @tablename = 'tenants';
|
||||
SET @columnname = 'agent_config';
|
||||
SET @preparedStatement = (SELECT IF(
|
||||
(
|
||||
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE
|
||||
TABLE_SCHEMA = @dbname
|
||||
AND TABLE_NAME = @tablename
|
||||
AND COLUMN_NAME = @columnname
|
||||
) > 0,
|
||||
'SELECT 1', -- 字段已存在,不做任何操作
|
||||
CONCAT('ALTER TABLE ', @tablename, ' ADD COLUMN ', @columnname, ' JSON DEFAULT NULL COMMENT ''Tenant-level agent configuration in JSON format''')
|
||||
));
|
||||
|
||||
PREPARE alterIfNotExists FROM @preparedStatement;
|
||||
EXECUTE alterIfNotExists;
|
||||
DEALLOCATE PREPARE alterIfNotExists;
|
||||
|
||||
-- ============================================
|
||||
-- 2. 为 sessions 表添加 agent_config
|
||||
-- ============================================
|
||||
|
||||
SET @dbname = DATABASE();
|
||||
SET @tablename = 'sessions';
|
||||
SET @columnname = 'agent_config';
|
||||
SET @preparedStatement = (SELECT IF(
|
||||
(
|
||||
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE
|
||||
TABLE_SCHEMA = @dbname
|
||||
AND TABLE_NAME = @tablename
|
||||
AND COLUMN_NAME = @columnname
|
||||
) > 0,
|
||||
'SELECT 1', -- 字段已存在,不做任何操作
|
||||
CONCAT('ALTER TABLE ', @tablename, ' ADD COLUMN ', @columnname, ' JSON DEFAULT NULL COMMENT ''Session-level agent configuration in JSON format''')
|
||||
));
|
||||
|
||||
PREPARE alterIfNotExists FROM @preparedStatement;
|
||||
EXECUTE alterIfNotExists;
|
||||
DEALLOCATE PREPARE alterIfNotExists;
|
||||
|
||||
-- ============================================
|
||||
-- 3. 为 sessions 表添加 context_config
|
||||
-- ============================================
|
||||
|
||||
SET @dbname = DATABASE();
|
||||
SET @tablename = 'sessions';
|
||||
SET @columnname = 'context_config';
|
||||
SET @preparedStatement = (SELECT IF(
|
||||
(
|
||||
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE
|
||||
TABLE_SCHEMA = @dbname
|
||||
AND TABLE_NAME = @tablename
|
||||
AND COLUMN_NAME = @columnname
|
||||
) > 0,
|
||||
'SELECT 1', -- 字段已存在,不做任何操作
|
||||
CONCAT('ALTER TABLE ', @tablename, ' ADD COLUMN ', @columnname, ' JSON DEFAULT NULL COMMENT ''LLM context management configuration (separate from message storage)''')
|
||||
));
|
||||
|
||||
PREPARE alterIfNotExists FROM @preparedStatement;
|
||||
EXECUTE alterIfNotExists;
|
||||
DEALLOCATE PREPARE alterIfNotExists;
|
||||
|
||||
-- ============================================
|
||||
-- 4. 为 messages 表添加 agent_steps
|
||||
-- ============================================
|
||||
|
||||
SET @dbname = DATABASE();
|
||||
SET @tablename = 'messages';
|
||||
SET @columnname = 'agent_steps';
|
||||
SET @preparedStatement = (SELECT IF(
|
||||
(
|
||||
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE
|
||||
TABLE_SCHEMA = @dbname
|
||||
AND TABLE_NAME = @tablename
|
||||
AND COLUMN_NAME = @columnname
|
||||
) > 0,
|
||||
'SELECT 1', -- 字段已存在,不做任何操作
|
||||
CONCAT('ALTER TABLE ', @tablename, ' ADD COLUMN ', @columnname, ' JSON DEFAULT NULL COMMENT ''Agent execution steps (reasoning process and tool calls)''')
|
||||
));
|
||||
|
||||
PREPARE alterIfNotExists FROM @preparedStatement;
|
||||
EXECUTE alterIfNotExists;
|
||||
DEALLOCATE PREPARE alterIfNotExists;
|
||||
|
||||
-- ============================================
|
||||
-- 验证:显示所有表的结构
|
||||
-- ============================================
|
||||
|
||||
SELECT 'Verifying tenants table...' as status;
|
||||
SHOW COLUMNS FROM tenants LIKE 'agent_config';
|
||||
|
||||
SELECT 'Verifying sessions table...' as status;
|
||||
SHOW COLUMNS FROM sessions LIKE 'agent_config';
|
||||
SHOW COLUMNS FROM sessions LIKE 'context_config';
|
||||
|
||||
SELECT 'Verifying messages table...' as status;
|
||||
SHOW COLUMNS FROM messages LIKE 'agent_steps';
|
||||
|
||||
SELECT 'Migration completed successfully!' as status;
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
-- ============================================================================
|
||||
-- Migration: Cleanup Unreferenced Models
|
||||
-- Description: Remove models that are not referenced by any knowledge base
|
||||
-- Created: 2025-11-03
|
||||
-- ============================================================================
|
||||
|
||||
-- This script removes models from the models table that meet ALL of these conditions:
|
||||
-- 1. Not referenced by any knowledge_bases (embedding_model_id, summary_model_id, rerank_model_id, vlm_model_id)
|
||||
-- 2. Not referenced by any knowledges (embedding_model_id)
|
||||
-- 3. Not a default model (is_default = false)
|
||||
-- 4. Not a system model (tenant_id != 0)
|
||||
-- 5. Not soft-deleted (deleted_at IS NULL)
|
||||
|
||||
-- WARNING: This operation is irreversible. Make sure to backup your database before running.
|
||||
-- Recommended: Run the SELECT query first to review which models will be deleted.
|
||||
|
||||
-- ============================================================================
|
||||
-- Step 1: Review models that will be deleted (DRY RUN)
|
||||
-- ============================================================================
|
||||
SELECT
|
||||
m.id,
|
||||
m.tenant_id,
|
||||
m.name,
|
||||
m.type,
|
||||
m.source,
|
||||
m.is_default,
|
||||
m.status,
|
||||
m.created_at
|
||||
FROM models m
|
||||
WHERE m.deleted_at IS NULL
|
||||
AND m.is_default = FALSE
|
||||
AND m.tenant_id != 0
|
||||
AND m.id NOT IN (
|
||||
-- Models referenced by knowledge_bases
|
||||
SELECT DISTINCT embedding_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND embedding_model_id != ''
|
||||
UNION
|
||||
SELECT DISTINCT summary_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND summary_model_id != ''
|
||||
UNION
|
||||
SELECT DISTINCT rerank_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND rerank_model_id != ''
|
||||
UNION
|
||||
SELECT DISTINCT vlm_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND vlm_model_id != ''
|
||||
UNION
|
||||
-- Models referenced by knowledges
|
||||
SELECT DISTINCT embedding_model_id FROM knowledges WHERE deleted_at IS NULL AND embedding_model_id IS NOT NULL AND embedding_model_id != ''
|
||||
)
|
||||
ORDER BY m.created_at DESC;
|
||||
|
||||
-- ============================================================================
|
||||
-- Step 2: Soft delete unreferenced models (set deleted_at timestamp)
|
||||
-- ============================================================================
|
||||
-- Uncomment the following line to perform soft delete:
|
||||
-- UPDATE models m
|
||||
-- SET deleted_at = CURRENT_TIMESTAMP
|
||||
-- WHERE m.deleted_at IS NULL
|
||||
-- AND m.is_default = FALSE
|
||||
-- AND m.tenant_id != 0
|
||||
-- AND m.id NOT IN (
|
||||
-- SELECT DISTINCT embedding_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND embedding_model_id != ''
|
||||
-- UNION
|
||||
-- SELECT DISTINCT summary_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND summary_model_id != ''
|
||||
-- UNION
|
||||
-- SELECT DISTINCT rerank_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND rerank_model_id != ''
|
||||
-- UNION
|
||||
-- SELECT DISTINCT vlm_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND vlm_model_id != ''
|
||||
-- UNION
|
||||
-- SELECT DISTINCT embedding_model_id FROM knowledges WHERE deleted_at IS NULL AND embedding_model_id IS NOT NULL AND embedding_model_id != ''
|
||||
-- );
|
||||
|
||||
-- ============================================================================
|
||||
-- Step 3: Hard delete unreferenced models (PERMANENT DELETION)
|
||||
-- ============================================================================
|
||||
-- WARNING: This is permanent and cannot be undone!
|
||||
-- Only use this if you're sure you want to permanently remove the records.
|
||||
-- Uncomment the following line to perform hard delete:
|
||||
-- DELETE FROM models
|
||||
-- WHERE deleted_at IS NULL
|
||||
-- AND is_default = FALSE
|
||||
-- AND tenant_id != 0
|
||||
-- AND id NOT IN (
|
||||
-- SELECT DISTINCT embedding_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND embedding_model_id != ''
|
||||
-- UNION
|
||||
-- SELECT DISTINCT summary_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND summary_model_id != ''
|
||||
-- UNION
|
||||
-- SELECT DISTINCT rerank_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND rerank_model_id != ''
|
||||
-- UNION
|
||||
-- SELECT DISTINCT vlm_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND vlm_model_id != ''
|
||||
-- UNION
|
||||
-- SELECT DISTINCT embedding_model_id FROM knowledges WHERE deleted_at IS NULL AND embedding_model_id IS NOT NULL AND embedding_model_id != ''
|
||||
-- );
|
||||
|
||||
-- ============================================================================
|
||||
-- Additional Queries for Statistics
|
||||
-- ============================================================================
|
||||
|
||||
-- Count total models by type
|
||||
SELECT
|
||||
type,
|
||||
COUNT(*) as total_count,
|
||||
SUM(CASE WHEN is_default = TRUE THEN 1 ELSE 0 END) as default_count,
|
||||
SUM(CASE WHEN deleted_at IS NULL THEN 1 ELSE 0 END) as active_count
|
||||
FROM models
|
||||
GROUP BY type;
|
||||
|
||||
-- Count models referenced by knowledge bases
|
||||
SELECT
|
||||
'embedding_model' as model_type,
|
||||
COUNT(DISTINCT embedding_model_id) as referenced_count
|
||||
FROM knowledge_bases
|
||||
WHERE deleted_at IS NULL AND embedding_model_id != ''
|
||||
UNION ALL
|
||||
SELECT
|
||||
'summary_model' as model_type,
|
||||
COUNT(DISTINCT summary_model_id) as referenced_count
|
||||
FROM knowledge_bases
|
||||
WHERE deleted_at IS NULL AND summary_model_id != ''
|
||||
UNION ALL
|
||||
SELECT
|
||||
'rerank_model' as model_type,
|
||||
COUNT(DISTINCT rerank_model_id) as referenced_count
|
||||
FROM knowledge_bases
|
||||
WHERE deleted_at IS NULL AND rerank_model_id != ''
|
||||
UNION ALL
|
||||
SELECT
|
||||
'vlm_model' as model_type,
|
||||
COUNT(DISTINCT vlm_model_id) as referenced_count
|
||||
FROM knowledge_bases
|
||||
WHERE deleted_at IS NULL AND vlm_model_id != '';
|
||||
|
||||
-- ============================================================================
|
||||
-- Rollback Strategy
|
||||
-- ============================================================================
|
||||
-- If you performed a soft delete and need to rollback:
|
||||
-- UPDATE models
|
||||
-- SET deleted_at = NULL
|
||||
-- WHERE deleted_at > 'YOUR_DELETION_TIMESTAMP';
|
||||
-- ============================================================================
|
||||
|
||||
@@ -16,11 +16,14 @@ CREATE TABLE IF NOT EXISTS tenants (
|
||||
business VARCHAR(255) NOT NULL,
|
||||
storage_quota BIGINT NOT NULL DEFAULT 10737418240, -- 默认10GB配额(Bytes)
|
||||
storage_used BIGINT NOT NULL DEFAULT 0, -- 已使用的存储空间(Bytes)
|
||||
agent_config JSONB DEFAULT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted_at TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
|
||||
COMMENT ON COLUMN tenants.agent_config IS 'Tenant-level agent configuration in JSON format';
|
||||
|
||||
-- Set the starting value for tenants id sequence
|
||||
ALTER SEQUENCE tenants_id_seq RESTART WITH 10000;
|
||||
|
||||
@@ -122,11 +125,16 @@ CREATE TABLE IF NOT EXISTS sessions (
|
||||
rerank_threshold FLOAT NOT NULL DEFAULT 0.65,
|
||||
summary_model_id VARCHAR(64),
|
||||
summary_parameters JSONB NOT NULL DEFAULT '{}',
|
||||
agent_config JSONB DEFAULT NULL,
|
||||
context_config JSONB DEFAULT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted_at TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
|
||||
COMMENT ON COLUMN sessions.agent_config IS 'Session-level agent configuration in JSON format';
|
||||
COMMENT ON COLUMN sessions.context_config IS 'LLM context management configuration (separate from message storage)';
|
||||
|
||||
-- Create Index for sessions
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_tenant_id ON sessions(tenant_id);
|
||||
|
||||
@@ -139,12 +147,15 @@ CREATE TABLE IF NOT EXISTS messages (
|
||||
role VARCHAR(50) NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
knowledge_references JSONB NOT NULL DEFAULT '[]',
|
||||
agent_steps JSONB DEFAULT NULL,
|
||||
is_completed BOOLEAN NOT NULL DEFAULT false,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted_at TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
|
||||
COMMENT ON COLUMN messages.agent_steps IS 'Agent execution steps (reasoning process and tool calls)';
|
||||
|
||||
-- Create Index for messages
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_session_id ON messages(session_id);
|
||||
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
-- 增量迁移:添加 agent_config 字段(如果不存在)
|
||||
-- 创建时间:2025-11-03
|
||||
-- 目的:为旧版本数据库添加 agent_config 支持
|
||||
-- 注意:新数据库可能已经有这些字段(通过01-migrate-to-paradedb.sql),使用 IF NOT EXISTS 确保兼容
|
||||
|
||||
-- ============================================
|
||||
-- 1. 为 tenants 表添加 agent_config
|
||||
-- ============================================
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.columns
|
||||
WHERE table_name = 'tenants'
|
||||
AND column_name = 'agent_config'
|
||||
) THEN
|
||||
ALTER TABLE tenants
|
||||
ADD COLUMN agent_config JSONB DEFAULT NULL;
|
||||
|
||||
COMMENT ON COLUMN tenants.agent_config IS 'Tenant-level agent configuration in JSON format';
|
||||
|
||||
RAISE NOTICE 'Added agent_config column to tenants table';
|
||||
ELSE
|
||||
RAISE NOTICE 'agent_config column already exists in tenants table';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- ============================================
|
||||
-- 2. 为 sessions 表添加 agent_config
|
||||
-- ============================================
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.columns
|
||||
WHERE table_name = 'sessions'
|
||||
AND column_name = 'agent_config'
|
||||
) THEN
|
||||
ALTER TABLE sessions
|
||||
ADD COLUMN agent_config JSONB DEFAULT NULL;
|
||||
|
||||
COMMENT ON COLUMN sessions.agent_config IS 'Session-level agent configuration in JSON format';
|
||||
|
||||
RAISE NOTICE 'Added agent_config column to sessions table';
|
||||
ELSE
|
||||
RAISE NOTICE 'agent_config column already exists in sessions table';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- ============================================
|
||||
-- 3. 为 sessions 表添加 context_config
|
||||
-- ============================================
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.columns
|
||||
WHERE table_name = 'sessions'
|
||||
AND column_name = 'context_config'
|
||||
) THEN
|
||||
ALTER TABLE sessions
|
||||
ADD COLUMN context_config JSONB DEFAULT NULL;
|
||||
|
||||
COMMENT ON COLUMN sessions.context_config IS 'LLM context management configuration (separate from message storage)';
|
||||
|
||||
RAISE NOTICE 'Added context_config column to sessions table';
|
||||
ELSE
|
||||
RAISE NOTICE 'context_config column already exists in sessions table';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- ============================================
|
||||
-- 4. 为 messages 表添加 agent_steps
|
||||
-- ============================================
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.columns
|
||||
WHERE table_name = 'messages'
|
||||
AND column_name = 'agent_steps'
|
||||
) THEN
|
||||
ALTER TABLE messages
|
||||
ADD COLUMN agent_steps JSONB DEFAULT NULL;
|
||||
|
||||
COMMENT ON COLUMN messages.agent_steps IS 'Agent execution steps (reasoning process and tool calls)';
|
||||
|
||||
RAISE NOTICE 'Added agent_steps column to messages table';
|
||||
ELSE
|
||||
RAISE NOTICE 'agent_steps column already exists in messages table';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- ============================================
|
||||
-- 5. 为 JSON 字段添加 GIN 索引(提高查询性能)
|
||||
-- ============================================
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
-- 为 tenants.agent_config 添加索引
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_indexes
|
||||
WHERE tablename = 'tenants'
|
||||
AND indexname = 'idx_tenants_agent_config'
|
||||
) THEN
|
||||
CREATE INDEX idx_tenants_agent_config ON tenants USING GIN (agent_config);
|
||||
RAISE NOTICE 'Created index idx_tenants_agent_config';
|
||||
ELSE
|
||||
RAISE NOTICE 'Index idx_tenants_agent_config already exists';
|
||||
END IF;
|
||||
|
||||
-- 为 sessions.agent_config 添加索引
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_indexes
|
||||
WHERE tablename = 'sessions'
|
||||
AND indexname = 'idx_sessions_agent_config'
|
||||
) THEN
|
||||
CREATE INDEX idx_sessions_agent_config ON sessions USING GIN (agent_config);
|
||||
RAISE NOTICE 'Created index idx_sessions_agent_config';
|
||||
ELSE
|
||||
RAISE NOTICE 'Index idx_sessions_agent_config already exists';
|
||||
END IF;
|
||||
|
||||
-- 为 sessions.context_config 添加索引
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_indexes
|
||||
WHERE tablename = 'sessions'
|
||||
AND indexname = 'idx_sessions_context_config'
|
||||
) THEN
|
||||
CREATE INDEX idx_sessions_context_config ON sessions USING GIN (context_config);
|
||||
RAISE NOTICE 'Created index idx_sessions_context_config';
|
||||
ELSE
|
||||
RAISE NOTICE 'Index idx_sessions_context_config already exists';
|
||||
END IF;
|
||||
|
||||
-- 为 messages.agent_steps 添加索引
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_indexes
|
||||
WHERE tablename = 'messages'
|
||||
AND indexname = 'idx_messages_agent_steps'
|
||||
) THEN
|
||||
CREATE INDEX idx_messages_agent_steps ON messages USING GIN (agent_steps);
|
||||
RAISE NOTICE 'Created index idx_messages_agent_steps';
|
||||
ELSE
|
||||
RAISE NOTICE 'Index idx_messages_agent_steps already exists';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- ============================================
|
||||
-- 验证:显示所有表的字段
|
||||
-- ============================================
|
||||
|
||||
SELECT 'Verifying tenants table...' as status;
|
||||
SELECT column_name, data_type, is_nullable, column_default
|
||||
FROM information_schema.columns
|
||||
WHERE table_name = 'tenants' AND column_name = 'agent_config';
|
||||
|
||||
SELECT 'Verifying sessions table...' as status;
|
||||
SELECT column_name, data_type, is_nullable, column_default
|
||||
FROM information_schema.columns
|
||||
WHERE table_name = 'sessions' AND column_name IN ('agent_config', 'context_config');
|
||||
|
||||
SELECT 'Verifying messages table...' as status;
|
||||
SELECT column_name, data_type, is_nullable, column_default
|
||||
FROM information_schema.columns
|
||||
WHERE table_name = 'messages' AND column_name = 'agent_steps';
|
||||
|
||||
SELECT 'Migration completed successfully!' as status;
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
-- ============================================================================
|
||||
-- Migration: Cleanup Unreferenced Models (PostgreSQL/ParadeDB)
|
||||
-- Description: Remove models that are not referenced by any knowledge base
|
||||
-- Created: 2025-11-03
|
||||
-- ============================================================================
|
||||
|
||||
-- This script removes models from the models table that meet ALL of these conditions:
|
||||
-- 1. Not referenced by any knowledge_bases (embedding_model_id, summary_model_id, rerank_model_id, vlm_model_id)
|
||||
-- 2. Not referenced by any knowledges (embedding_model_id)
|
||||
-- 3. Not a default model (is_default = false)
|
||||
-- 4. Not a system model (tenant_id != 0)
|
||||
-- 5. Not soft-deleted (deleted_at IS NULL)
|
||||
|
||||
-- WARNING: This operation is irreversible. Make sure to backup your database before running.
|
||||
-- Recommended: Run the SELECT query first to review which models will be deleted.
|
||||
|
||||
-- ============================================================================
|
||||
-- Step 1: Review models that will be deleted (DRY RUN)
|
||||
-- ============================================================================
|
||||
SELECT
|
||||
m.id,
|
||||
m.tenant_id,
|
||||
m.name,
|
||||
m.type,
|
||||
m.source,
|
||||
m.is_default,
|
||||
m.status,
|
||||
m.created_at
|
||||
FROM models m
|
||||
WHERE m.deleted_at IS NULL
|
||||
AND m.is_default = FALSE
|
||||
AND m.id NOT IN (
|
||||
-- Models referenced by knowledge_bases
|
||||
SELECT DISTINCT embedding_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND embedding_model_id != ''
|
||||
UNION
|
||||
SELECT DISTINCT summary_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND summary_model_id != ''
|
||||
UNION
|
||||
SELECT DISTINCT rerank_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND rerank_model_id != ''
|
||||
UNION
|
||||
SELECT DISTINCT vlm_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND vlm_model_id != ''
|
||||
UNION
|
||||
-- Models referenced by knowledges
|
||||
SELECT DISTINCT embedding_model_id FROM knowledges WHERE deleted_at IS NULL AND embedding_model_id IS NOT NULL AND embedding_model_id != ''
|
||||
)
|
||||
ORDER BY m.created_at DESC;
|
||||
|
||||
-- ============================================================================
|
||||
-- Step 2: Soft delete unreferenced models (set deleted_at timestamp)
|
||||
-- ============================================================================
|
||||
-- Uncomment the following line to perform soft delete:
|
||||
-- UPDATE models m
|
||||
-- SET deleted_at = CURRENT_TIMESTAMP
|
||||
-- WHERE m.deleted_at IS NULL
|
||||
-- AND m.is_default = FALSE
|
||||
-- AND m.tenant_id != 0
|
||||
-- AND m.id NOT IN (
|
||||
-- SELECT DISTINCT embedding_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND embedding_model_id != ''
|
||||
-- UNION
|
||||
-- SELECT DISTINCT summary_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND summary_model_id != ''
|
||||
-- UNION
|
||||
-- SELECT DISTINCT rerank_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND rerank_model_id != ''
|
||||
-- UNION
|
||||
-- SELECT DISTINCT vlm_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND vlm_model_id != ''
|
||||
-- UNION
|
||||
-- SELECT DISTINCT embedding_model_id FROM knowledges WHERE deleted_at IS NULL AND embedding_model_id IS NOT NULL AND embedding_model_id != ''
|
||||
-- );
|
||||
|
||||
-- ============================================================================
|
||||
-- Step 3: Hard delete unreferenced models (PERMANENT DELETION)
|
||||
-- ============================================================================
|
||||
-- WARNING: This is permanent and cannot be undone!
|
||||
-- Only use this if you're sure you want to permanently remove the records.
|
||||
-- Uncomment the following line to perform hard delete:
|
||||
-- DELETE FROM models
|
||||
-- WHERE deleted_at IS NULL
|
||||
-- AND is_default = FALSE
|
||||
-- AND tenant_id != 0
|
||||
-- AND id NOT IN (
|
||||
-- SELECT DISTINCT embedding_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND embedding_model_id != ''
|
||||
-- UNION
|
||||
-- SELECT DISTINCT summary_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND summary_model_id != ''
|
||||
-- UNION
|
||||
-- SELECT DISTINCT rerank_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND rerank_model_id != ''
|
||||
-- UNION
|
||||
-- SELECT DISTINCT vlm_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND vlm_model_id != ''
|
||||
-- UNION
|
||||
-- SELECT DISTINCT embedding_model_id FROM knowledges WHERE deleted_at IS NULL AND embedding_model_id IS NOT NULL AND embedding_model_id != ''
|
||||
-- );
|
||||
|
||||
-- ============================================================================
|
||||
-- Alternative: Using CTE for better performance (PostgreSQL specific)
|
||||
-- ============================================================================
|
||||
-- This version uses Common Table Expressions for better readability and performance
|
||||
|
||||
-- DRY RUN with CTE:
|
||||
WITH referenced_models AS (
|
||||
SELECT embedding_model_id AS model_id FROM knowledge_bases WHERE deleted_at IS NULL AND embedding_model_id != ''
|
||||
UNION
|
||||
SELECT summary_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND summary_model_id != ''
|
||||
UNION
|
||||
SELECT rerank_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND rerank_model_id != ''
|
||||
UNION
|
||||
SELECT vlm_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND vlm_model_id != ''
|
||||
UNION
|
||||
SELECT embedding_model_id FROM knowledges WHERE deleted_at IS NULL AND embedding_model_id IS NOT NULL AND embedding_model_id != ''
|
||||
)
|
||||
SELECT
|
||||
m.id,
|
||||
m.tenant_id,
|
||||
m.name,
|
||||
m.type,
|
||||
m.source,
|
||||
m.is_default,
|
||||
m.status,
|
||||
m.created_at
|
||||
FROM models m
|
||||
WHERE m.deleted_at IS NULL
|
||||
AND m.is_default = FALSE
|
||||
AND m.id NOT IN (SELECT model_id FROM referenced_models)
|
||||
ORDER BY m.created_at DESC;
|
||||
|
||||
-- Soft delete with CTE:
|
||||
WITH referenced_models AS (
|
||||
SELECT embedding_model_id AS model_id FROM knowledge_bases WHERE deleted_at IS NULL AND embedding_model_id != ''
|
||||
UNION
|
||||
SELECT summary_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND summary_model_id != ''
|
||||
UNION
|
||||
SELECT rerank_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND rerank_model_id != ''
|
||||
UNION
|
||||
SELECT vlm_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND vlm_model_id != ''
|
||||
UNION
|
||||
SELECT embedding_model_id FROM knowledges WHERE deleted_at IS NULL AND embedding_model_id IS NOT NULL AND embedding_model_id != ''
|
||||
)
|
||||
UPDATE models m
|
||||
SET deleted_at = CURRENT_TIMESTAMP
|
||||
WHERE m.deleted_at IS NULL
|
||||
AND m.is_default = FALSE
|
||||
AND m.id NOT IN (SELECT model_id FROM referenced_models);
|
||||
|
||||
-- Hard delete with CTE:
|
||||
-- WITH referenced_models AS (
|
||||
-- SELECT embedding_model_id AS model_id FROM knowledge_bases WHERE deleted_at IS NULL AND embedding_model_id != ''
|
||||
-- UNION
|
||||
-- SELECT summary_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND summary_model_id != ''
|
||||
-- UNION
|
||||
-- SELECT rerank_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND rerank_model_id != ''
|
||||
-- UNION
|
||||
-- SELECT vlm_model_id FROM knowledge_bases WHERE deleted_at IS NULL AND vlm_model_id != ''
|
||||
-- UNION
|
||||
-- SELECT embedding_model_id FROM knowledges WHERE deleted_at IS NULL AND embedding_model_id IS NOT NULL AND embedding_model_id != ''
|
||||
-- )
|
||||
-- DELETE FROM models
|
||||
-- WHERE deleted_at IS NULL
|
||||
-- AND is_default = FALSE
|
||||
-- AND tenant_id != 0
|
||||
-- AND id NOT IN (SELECT model_id FROM referenced_models);
|
||||
|
||||
-- ============================================================================
|
||||
-- Additional Queries for Statistics
|
||||
-- ============================================================================
|
||||
|
||||
-- Count total models by type
|
||||
SELECT
|
||||
type,
|
||||
COUNT(*) as total_count,
|
||||
SUM(CASE WHEN is_default = TRUE THEN 1 ELSE 0 END) as default_count,
|
||||
SUM(CASE WHEN deleted_at IS NULL THEN 1 ELSE 0 END) as active_count
|
||||
FROM models
|
||||
GROUP BY type;
|
||||
|
||||
-- Count models referenced by knowledge bases
|
||||
SELECT
|
||||
'embedding_model' as model_type,
|
||||
COUNT(DISTINCT embedding_model_id) as referenced_count
|
||||
FROM knowledge_bases
|
||||
WHERE deleted_at IS NULL AND embedding_model_id != ''
|
||||
UNION ALL
|
||||
SELECT
|
||||
'summary_model' as model_type,
|
||||
COUNT(DISTINCT summary_model_id) as referenced_count
|
||||
FROM knowledge_bases
|
||||
WHERE deleted_at IS NULL AND summary_model_id != ''
|
||||
UNION ALL
|
||||
SELECT
|
||||
'rerank_model' as model_type,
|
||||
COUNT(DISTINCT rerank_model_id) as referenced_count
|
||||
FROM knowledge_bases
|
||||
WHERE deleted_at IS NULL AND rerank_model_id != ''
|
||||
UNION ALL
|
||||
SELECT
|
||||
'vlm_model' as model_type,
|
||||
COUNT(DISTINCT vlm_model_id) as referenced_count
|
||||
FROM knowledge_bases
|
||||
WHERE deleted_at IS NULL AND vlm_model_id != '';
|
||||
|
||||
-- List all referenced models with their reference count
|
||||
WITH model_references AS (
|
||||
SELECT embedding_model_id AS model_id, 'embedding' AS ref_type FROM knowledge_bases WHERE deleted_at IS NULL AND embedding_model_id != ''
|
||||
UNION ALL
|
||||
SELECT summary_model_id, 'summary' FROM knowledge_bases WHERE deleted_at IS NULL AND summary_model_id != ''
|
||||
UNION ALL
|
||||
SELECT rerank_model_id, 'rerank' FROM knowledge_bases WHERE deleted_at IS NULL AND rerank_model_id != ''
|
||||
UNION ALL
|
||||
SELECT vlm_model_id, 'vlm' FROM knowledge_bases WHERE deleted_at IS NULL AND vlm_model_id != ''
|
||||
UNION ALL
|
||||
SELECT embedding_model_id, 'knowledge_embedding' FROM knowledges WHERE deleted_at IS NULL AND embedding_model_id IS NOT NULL AND embedding_model_id != ''
|
||||
)
|
||||
SELECT
|
||||
m.id,
|
||||
m.name,
|
||||
m.type,
|
||||
STRING_AGG(DISTINCT mr.ref_type, ', ' ORDER BY mr.ref_type) AS referenced_as,
|
||||
COUNT(*) AS reference_count
|
||||
FROM models m
|
||||
INNER JOIN model_references mr ON m.id = mr.model_id
|
||||
WHERE m.deleted_at IS NULL
|
||||
GROUP BY m.id, m.name, m.type
|
||||
ORDER BY reference_count DESC, m.name;
|
||||
|
||||
-- ============================================================================
|
||||
-- Rollback Strategy
|
||||
-- ============================================================================
|
||||
-- If you performed a soft delete and need to rollback:
|
||||
-- UPDATE models
|
||||
-- SET deleted_at = NULL
|
||||
-- WHERE deleted_at > 'YOUR_DELETION_TIMESTAMP';
|
||||
-- ============================================================================
|
||||
|
||||
Reference in New Issue
Block a user