Skip to main content

cc_switch_lib/database/
migration.rs

1//! JSON → SQLite 数据迁移
2//!
3//! 将旧版 config.json (MultiAppConfig) 数据迁移到 SQLite 数据库。
4
5use super::{lock_conn, to_json_string, Database};
6use crate::app_config::MultiAppConfig;
7use crate::error::AppError;
8use rusqlite::{params, Connection};
9
10impl Database {
11    /// 从 MultiAppConfig 迁移数据到数据库
12    pub fn migrate_from_json(&self, config: &MultiAppConfig) -> Result<(), AppError> {
13        let mut conn = lock_conn!(self.conn);
14        let tx = conn
15            .transaction()
16            .map_err(|e| AppError::Database(e.to_string()))?;
17
18        Self::migrate_from_json_tx(&tx, config)?;
19
20        tx.commit()
21            .map_err(|e| AppError::Database(format!("Commit migration failed: {e}")))?;
22        Ok(())
23    }
24
25    /// 运行迁移的 dry-run 模式(在内存数据库中验证,不写入磁盘)
26    ///
27    /// 用于部署前验证迁移逻辑是否正确。
28    pub fn migrate_from_json_dry_run(config: &MultiAppConfig) -> Result<(), AppError> {
29        let mut conn =
30            Connection::open_in_memory().map_err(|e| AppError::Database(e.to_string()))?;
31        Self::create_tables_on_conn(&conn)?;
32        Self::apply_schema_migrations_on_conn(&conn)?;
33
34        let tx = conn
35            .transaction()
36            .map_err(|e| AppError::Database(e.to_string()))?;
37        Self::migrate_from_json_tx(&tx, config)?;
38
39        // 显式 drop transaction 而不提交(内存数据库会被丢弃)
40        drop(tx);
41        Ok(())
42    }
43
44    /// 在事务中执行迁移
45    fn migrate_from_json_tx(
46        tx: &rusqlite::Transaction<'_>,
47        config: &MultiAppConfig,
48    ) -> Result<(), AppError> {
49        // 1. 迁移 Providers
50        Self::migrate_providers(tx, config)?;
51
52        // 2. 迁移 MCP Servers
53        Self::migrate_mcp_servers(tx, config)?;
54
55        // 3. 迁移 Prompts
56        Self::migrate_prompts(tx, config)?;
57
58        // 4. 迁移 Skills
59        Self::migrate_skills(tx, config)?;
60
61        // 5. 迁移 Common Config
62        Self::migrate_common_config(tx, config)?;
63
64        Ok(())
65    }
66
67    /// 迁移供应商数据
68    fn migrate_providers(
69        tx: &rusqlite::Transaction<'_>,
70        config: &MultiAppConfig,
71    ) -> Result<(), AppError> {
72        for (app_key, manager) in &config.apps {
73            let app_type = app_key;
74            let current_id = &manager.current;
75
76            for (id, provider) in &manager.providers {
77                let is_current = if id == current_id { 1 } else { 0 };
78
79                // 处理 meta 和 endpoints
80                let mut meta_clone = provider.meta.clone().unwrap_or_default();
81                let endpoints = std::mem::take(&mut meta_clone.custom_endpoints);
82
83                tx.execute(
84                    "INSERT OR REPLACE INTO providers (
85                        id, app_type, name, settings_config, website_url, category,
86                        created_at, sort_index, notes, icon, icon_color, meta, is_current
87                    ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)",
88                    params![
89                        id,
90                        app_type,
91                        provider.name,
92                        to_json_string(&provider.settings_config)?,
93                        provider.website_url,
94                        provider.category,
95                        provider.created_at,
96                        provider.sort_index,
97                        provider.notes,
98                        provider.icon,
99                        provider.icon_color,
100                        to_json_string(&meta_clone)?,
101                        is_current,
102                    ],
103                )
104                .map_err(|e| AppError::Database(format!("Migrate provider failed: {e}")))?;
105
106                // 迁移 Endpoints
107                for (url, endpoint) in endpoints {
108                    tx.execute(
109                        "INSERT INTO provider_endpoints (provider_id, app_type, url, added_at)
110                         VALUES (?1, ?2, ?3, ?4)",
111                        params![id, app_type, url, endpoint.added_at],
112                    )
113                    .map_err(|e| AppError::Database(format!("Migrate endpoint failed: {e}")))?;
114                }
115            }
116        }
117        Ok(())
118    }
119
120    /// 迁移 MCP 服务器数据
121    fn migrate_mcp_servers(
122        tx: &rusqlite::Transaction<'_>,
123        config: &MultiAppConfig,
124    ) -> Result<(), AppError> {
125        if let Some(servers) = &config.mcp.servers {
126            for (id, server) in servers {
127                tx.execute(
128                    "INSERT OR REPLACE INTO mcp_servers (
129                        id, name, server_config, description, homepage, docs, tags,
130                        enabled_claude, enabled_codex, enabled_gemini, enabled_opencode, enabled_hermes
131                    ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
132                    params![
133                        id,
134                        server.name,
135                        to_json_string(&server.server)?,
136                        server.description,
137                        server.homepage,
138                        server.docs,
139                        to_json_string(&server.tags)?,
140                        server.apps.claude,
141                        server.apps.codex,
142                        server.apps.gemini,
143                        server.apps.opencode,
144                        server.apps.hermes,
145                    ],
146                )
147                .map_err(|e| AppError::Database(format!("Migrate mcp server failed: {e}")))?;
148            }
149        }
150        Ok(())
151    }
152
153    /// 迁移提示词数据
154    fn migrate_prompts(
155        tx: &rusqlite::Transaction<'_>,
156        config: &MultiAppConfig,
157    ) -> Result<(), AppError> {
158        let migrate_app_prompts = |prompts_map: &std::collections::HashMap<
159            String,
160            crate::prompt::Prompt,
161        >,
162                                   app_type: &str|
163         -> Result<(), AppError> {
164            for (id, prompt) in prompts_map {
165                tx.execute(
166                        "INSERT OR REPLACE INTO prompts (
167                            id, app_type, name, content, description, enabled, created_at, updated_at
168                        ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
169                        params![
170                            id,
171                            app_type,
172                            prompt.name,
173                            prompt.content,
174                            prompt.description,
175                            prompt.enabled,
176                            prompt.created_at,
177                            prompt.updated_at,
178                        ],
179                    )
180                    .map_err(|e| AppError::Database(format!("Migrate prompt failed: {e}")))?;
181            }
182            Ok(())
183        };
184
185        migrate_app_prompts(&config.prompts.claude.prompts, "claude")?;
186        migrate_app_prompts(&config.prompts.codex.prompts, "codex")?;
187        migrate_app_prompts(&config.prompts.gemini.prompts, "gemini")?;
188
189        Ok(())
190    }
191
192    /// 迁移 Skills 数据
193    fn migrate_skills(
194        tx: &rusqlite::Transaction<'_>,
195        config: &MultiAppConfig,
196    ) -> Result<(), AppError> {
197        // v3.10.0+:Skills 的 SSOT 已迁移到文件系统(~/.cc-switch-tui/skills/)+ 数据库统一结构。
198        //
199        // 旧版 config.json 里的 `skills.skills` 仅记录“安装状态”,但不包含完整元数据,
200        // 且无法保证 SSOT 目录中一定存在对应的 skill 文件。
201        //
202        // 因此这里不再直接把旧的安装状态写入新 skills 表,避免产生“数据库显示已安装但文件缺失”的不一致。
203        // 迁移后可通过:
204        // - 前端「导入已有」(扫描各应用的 skills 目录并复制到 SSOT)
205        // - 或后续启动时的自动扫描逻辑
206        // 来重建已安装技能记录。
207
208        for repo in &config.skills.repos {
209            tx.execute(
210                "INSERT OR REPLACE INTO skill_repos (owner, name, branch, enabled) VALUES (?1, ?2, ?3, ?4)",
211                params![repo.owner, repo.name, repo.branch, repo.enabled],
212            ).map_err(|e| AppError::Database(format!("Migrate skill repo failed: {e}")))?;
213        }
214
215        Ok(())
216    }
217
218    /// 迁移通用配置片段
219    fn migrate_common_config(
220        tx: &rusqlite::Transaction<'_>,
221        config: &MultiAppConfig,
222    ) -> Result<(), AppError> {
223        if let Some(snippet) = &config.common_config_snippets.claude {
224            tx.execute(
225                "INSERT OR REPLACE INTO settings (key, value) VALUES (?1, ?2)",
226                params!["common_config_claude", snippet],
227            )
228            .map_err(|e| AppError::Database(format!("Migrate settings failed: {e}")))?;
229        }
230        if let Some(snippet) = &config.common_config_snippets.codex {
231            tx.execute(
232                "INSERT OR REPLACE INTO settings (key, value) VALUES (?1, ?2)",
233                params!["common_config_codex", snippet],
234            )
235            .map_err(|e| AppError::Database(format!("Migrate settings failed: {e}")))?;
236        }
237        if let Some(snippet) = &config.common_config_snippets.gemini {
238            tx.execute(
239                "INSERT OR REPLACE INTO settings (key, value) VALUES (?1, ?2)",
240                params!["common_config_gemini", snippet],
241            )
242            .map_err(|e| AppError::Database(format!("Migrate settings failed: {e}")))?;
243        }
244
245        Ok(())
246    }
247}