mirror of
https://github.com/CherryHQ/cherry-studio.git
synced 2026-01-04 20:00:00 +08:00
- Implemented detailed preparation, execution, and validation phases for migrating chat topics and messages from Dexie to SQLite. - Added robust logging and error handling to track migration progress and issues. - Introduced data transformation strategies to convert old message structures into a new tree format, ensuring data integrity and consistency. - Updated migration guide documentation to reflect changes in migrator registration and detailed comments for maintainability.
4.7 KiB
4.7 KiB
Migration V2 (Main Process)
Architecture for the new one-shot migration from the legacy Dexie + Redux Persist stores into the SQLite schema. This module owns orchestration, data access helpers, migrator plugins, and IPC entry points used by the renderer migration window.
Directory Layout
src/main/data/migration/v2/
├── core/ # Engine + shared context
├── migrators/ # Domain-specific migrators and mappings
├── utils/ # Data source readers (Redux, Dexie, streaming JSON)
├── window/ # IPC handlers + migration window manager
└── index.ts # Public exports for main process
Core Contracts
core/MigrationEngine.tscoordinates all migrators in order, surfaces progress to the UI, and marks status inapp_state.key = 'migration_v2_status'. It will clear new-schema tables before running and abort on any validation failure.core/MigrationContext.tsbuilds the shared context passed to every migrator:sources:ConfigManager(ElectronStore),ReduxStateReader(parsed Redux Persist data),DexieFileReader(JSON exports)db: current SQLite connectionsharedData:Mapfor passing cross-cutting info between migratorslogger:loggerServicescoped to migration
@shared/data/migration/v2/typesdefines stages, results, and validation stats used across main and renderer.
Migrators
- Base contract: extend
migrators/BaseMigrator.tsand implement:id,name,description,order(lower runs first)prepare(ctx): dry-run checks, counts, and staging data; returnPrepareResultexecute(ctx): perform inserts/updates; manage your own transactions; report progress viareportProgressvalidate(ctx): verify counts and integrity; returnValidateResultwith stats (sourceCount,targetCount,skippedCount) and anyerrors
- Registration: list migrators (in order) in
migrators/index.tsso the engine can sort and run them. - Current migrators (see
migrators/README-<name>.mdfor detailed documentation):PreferencesMigrator(implemented): maps ElectronStore + Redux settings to thepreferencetable usingmappings/PreferencesMappings.ts.ChatMigrator(implemented): migrates topics and messages from Dexie to SQLite. SeeREADME-ChatMigrator.md.AssistantMigrator,KnowledgeMigrator(placeholders): scaffolding and TODO notes for future tables.
- Conventions:
- All logging goes through
loggerServicewith a migrator-specific context. - Use
MigrationContext.sourcesinstead of accessing raw files/stores directly. - Use
sharedDatato pass IDs or lookup tables between migrators (e.g., assistant -> chat references) instead of re-reading sources. - Stream large Dexie exports (
JSONStreamReader) and batch inserts to avoid memory spikes. - Count validation is mandatory; engine will fail the run if
targetCount < sourceCount - skippedCountor ifValidateResult.errorsis non-empty. - Keep migrations idempotent per run—engine clears target tables before it starts, but each migrator should tolerate retries within the same run.
- All logging goes through
Utilities
utils/ReduxStateReader.ts: safe accessor for categorized Redux Persist data with dot-path lookup.utils/DexieFileReader.ts: reads exported Dexie JSON tables; can stream large tables.utils/JSONStreamReader.ts: streaming reader with batching, counting, and sampling helpers for very large arrays.
Window & IPC Integration
window/MigrationIpcHandler.tsexposes IPC channels for the migration UI:- Receives Redux data and Dexie export path, starts the engine, and streams progress back to renderer.
- Manages backup flow (dialogs via
BackupManager) and retry/cancel/restart actions.
window/MigrationWindowManager.tscreates the frameless migration window, handles lifecycle, and relaunch instructions after completion in production.
Implementation Checklist for New Migrators
- Add mapping definitions (if needed) under
migrators/mappings/. - Implement
prepare/execute/validatewith explicit counts, batch inserts, and integrity checks. - Wire progress updates through
reportProgressso UI shows per-migrator progress. - Register the migrator in
migrators/index.tswith the correctorder. - Add any new target tables to
MigrationEngine.verifyAndClearNewTablesonce those tables exist. - Include detailed comments for maintainability (file-level, function-level, logic blocks).
- Create/update
migrators/README-<MigratorName>.mdwith detailed documentation including:- Data sources and target tables
- Key transformations
- Field mappings (source → target)
- Dropped fields and rationale
- Code quality notes