12 KiB
DatabaseUtil to PlatformServiceMixin Migration Plan
Migration Overview
This plan migrates database utility functions from src/db/databaseUtil.ts
to src/utils/PlatformServiceMixin.ts
to consolidate database operations and reduce boilerplate code across the application.
Priority Levels
🔴 PRIORITY 1 (Critical - Migrate First)
Functions used in 50+ files that are core to application functionality
🟡 PRIORITY 2 (High - Migrate Second)
Functions used in 10-50 files that are important but not critical
🟢 PRIORITY 3 (Medium - Migrate Third)
Functions used in 5-10 files that provide utility but aren't frequently used
🔵 PRIORITY 4 (Low - Migrate Last)
Functions used in <5 files or specialized functions
Detailed Migration Plan
🔴 PRIORITY 1 - Critical Functions
1. retrieveSettingsForActiveAccount()
- Usage: 60+ files
- Current:
databaseUtil.retrieveSettingsForActiveAccount()
- Target:
this.$settings()
(already exists in PlatformServiceMixin) - Migration: Replace all calls with
this.$settings()
- Files to migrate: All view files, components, and services
2. logConsoleAndDb()
and logToDb()
- Usage: 40+ files
- Current:
databaseUtil.logConsoleAndDb()
/databaseUtil.logToDb()
- Target: Add
$log()
and$logError()
methods to PlatformServiceMixin - Migration: Replace with
this.$log()
andthis.$logError()
- Files to migrate: All error handling and logging code
3. mapQueryResultToValues()
and mapColumnsToValues()
- Usage: 30+ files
- Current:
databaseUtil.mapQueryResultToValues()
/databaseUtil.mapColumnsToValues()
- Target:
this.$mapResults()
(already exists in PlatformServiceMixin) - Migration: Replace with
this.$mapResults()
- Files to migrate: All data processing components
🟡 PRIORITY 2 - High Priority Functions
4. updateDefaultSettings()
and updateDidSpecificSettings()
- Usage: 20+ files
- Current:
databaseUtil.updateDefaultSettings()
/databaseUtil.updateDidSpecificSettings()
- Target:
this.$saveSettings()
andthis.$saveUserSettings()
(already exist) - Migration: Replace with existing mixin methods
- Files to migrate: Settings management components
5. parseJsonField()
- Usage: 15+ files
- Current:
databaseUtil.parseJsonField()
or direct import - Target: Add
$parseJson()
method to PlatformServiceMixin - Migration: Replace with
this.$parseJson()
- Files to migrate: Data processing components
6. generateInsertStatement()
and generateUpdateStatement()
- Usage: 10+ files
- Current:
databaseUtil.generateInsertStatement()
/databaseUtil.generateUpdateStatement()
- Target:
this.$insertEntity()
andthis.$updateEntity()
(expand existing methods) - Migration: Replace with high-level entity methods
- Files to migrate: Data manipulation components
🟢 PRIORITY 3 - Medium Priority Functions
7. insertDidSpecificSettings()
- Usage: 8 files
- Current:
databaseUtil.insertDidSpecificSettings()
- Target:
this.$insertUserSettings()
(new method) - Migration: Replace with new mixin method
- Files to migrate: Account creation and import components
8. debugSettingsData()
- Usage: 5 files
- Current:
databaseUtil.debugSettingsData()
- Target:
this.$debugSettings()
(new method) - Migration: Replace with new mixin method
- Files to migrate: Debug and testing components
🔵 PRIORITY 4 - Low Priority Functions
9. retrieveSettingsForDefaultAccount()
- Usage: 3 files
- Current:
databaseUtil.retrieveSettingsForDefaultAccount()
- Target:
this.$getDefaultSettings()
(new method) - Migration: Replace with new mixin method
- Files to migrate: Settings management components
10. Memory logs and cleanup functions
- Usage: 2 files
- Current:
databaseUtil.memoryLogs
, cleanup functions - Target:
this.$memoryLogs
andthis.$cleanupLogs()
(new methods) - Migration: Replace with new mixin methods
- Files to migrate: Log management components
Implementation Strategy
Phase 0: Untangle Logger and DatabaseUtil (Prerequisite)
This must be done FIRST to eliminate circular dependencies before any mixin migration.
-
Create self-contained logger.ts:
- Remove
import { logToDb } from "../db/databaseUtil"
- Add direct database access via
PlatformServiceFactory.getInstance()
- Implement
logger.toDb()
andlogger.toConsoleAndDb()
methods
- Remove
-
Remove databaseUtil imports from PlatformServiceMixin:
- Remove
import { mapColumnsToValues, parseJsonField } from "@/db/databaseUtil"
- Remove
import * as databaseUtil from "@/db/databaseUtil"
- Add self-contained implementations of utility methods
- Remove
-
Test logger independence:
- Verify logger works without databaseUtil
- Ensure no circular dependencies exist
- Test all logging functionality
Phase 1: Add Missing Methods to PlatformServiceMixin
-
Add logging methods (now using independent logger):
$log(message: string, level?: string): Promise<void> $logError(message: string): Promise<void>
-
Add JSON parsing method (self-contained):
$parseJson<T>(value: unknown, defaultValue: T): T
-
Add entity update method:
$updateEntity(tableName: string, entity: Record<string, unknown>, whereClause: string, whereParams: unknown[]): Promise<boolean>
-
Add user settings insertion:
$insertUserSettings(did: string, settings: Partial<Settings>): Promise<boolean>
Phase 2: File-by-File Migration
Migration Order (by priority)
Prerequisite: Phase 0 (Logger/DatabaseUtil untangling) must be completed first.
-
Start with most critical files:
src/App.vue
(main application)src/views/AccountViewView.vue
(core account management)src/views/ContactsView.vue
(core contact management)
-
Migrate high-usage components:
- All view files in
src/views/
- Core components in
src/components/
- All view files in
-
Migrate services and utilities:
src/libs/util.ts
src/services/
filessrc/utils/logger.ts
-
Migrate remaining components:
- Specialized components
- Test files
Phase 3: Cleanup and Validation
- Remove databaseUtil imports from migrated files
- Update TypeScript interfaces to reflect new methods
- Run comprehensive tests to ensure functionality
- Remove unused databaseUtil functions after all migrations complete
Migration Commands Template
For each file migration:
# 1. Update imports
# Remove: import * as databaseUtil from "../db/databaseUtil";
# Add: import { PlatformServiceMixin } from "@/utils/PlatformServiceMixin";
# 2. Add mixin to component
# Add: mixins: [PlatformServiceMixin],
# 3. Replace function calls
# Replace: databaseUtil.retrieveSettingsForActiveAccount()
# With: this.$settings()
# 4. Test the migration
npm run test
# 5. Commit the change
git add .
git commit -m "Migrate [filename] from databaseUtil to PlatformServiceMixin"
Benefits of Migration
- Reduced Boilerplate: Eliminate repeated
PlatformServiceFactory.getInstance()
calls - Better Caching: Leverage existing caching in PlatformServiceMixin
- Consistent Error Handling: Centralized error handling and logging
- Type Safety: Better TypeScript integration with mixin methods
- Performance: Cached platform service access and optimized database operations
- Maintainability: Single source of truth for database operations
Risk Mitigation
- Incremental Migration: Migrate one file at a time to minimize risk
- Comprehensive Testing: Test each migration thoroughly
- Rollback Plan: Keep databaseUtil.ts until all migrations are complete
- Documentation: Update documentation as methods are migrated
Smart Logging Integration Strategy
Current State Analysis
Current Logging Architecture
src/utils/logger.ts
- Main logger with console + database loggingsrc/db/databaseUtil.ts
- Database-specific logging (logToDb
,logConsoleAndDb
)- Circular dependency - logger.ts imports logToDb from databaseUtil.ts
Current Issues
- Circular dependency between logger and databaseUtil
- Duplicate functionality - both systems log to database
- Inconsistent interfaces - different method signatures
- Scattered logging logic - logging rules spread across multiple files
Recommended Solution: Hybrid Approach (Option 3)
Core Concept: Enhanced logger + PlatformServiceMixin convenience methods with zero circular dependencies.
Implementation
// 1. Enhanced logger.ts (single source of truth - NO databaseUtil imports)
export const logger = {
// Existing methods...
// New database-focused methods (self-contained)
toDb: async (message: string, level?: string) => {
// Direct database access without databaseUtil dependency
const platform = PlatformServiceFactory.getInstance();
await platform.dbExec("INSERT INTO logs (date, message) VALUES (?, ?)", [
new Date().toDateString(),
`[${level?.toUpperCase() || 'INFO'}] ${message}`
]);
},
toConsoleAndDb: async (message: string, isError?: boolean) => {
// Console output
if (isError) {
console.error(message);
} else {
console.log(message);
}
// Database output
await logger.toDb(message, isError ? 'error' : 'info');
},
// Component context methods
withContext: (componentName?: string) => ({
log: (message: string, level?: string) => logger.toDb(`[${componentName}] ${message}`, level),
error: (message: string) => logger.toDb(`[${componentName}] ${message}`, 'error')
})
};
// 2. PlatformServiceMixin convenience methods (NO databaseUtil imports)
methods: {
$log(message: string, level?: string): Promise<void> {
return logger.toDb(message, level);
},
$logError(message: string): Promise<void> {
return logger.toDb(message, 'error');
},
$logAndConsole(message: string, isError = false): Promise<void> {
return logger.toConsoleAndDb(message, isError);
},
// Self-contained utility methods (no databaseUtil dependency)
$mapResults<T>(results: QueryExecResult | undefined, mapper: (row: unknown[]) => T): T[] {
if (!results) return [];
return results.values.map(mapper);
},
$parseJson<T>(value: unknown, defaultValue: T): T {
if (typeof value === 'string') {
try {
return JSON.parse(value);
} catch {
return defaultValue;
}
}
return value as T || defaultValue;
}
}
Benefits
- Single source of truth - logger.ts handles all database logging
- No circular dependencies - logger.ts doesn't import from databaseUtil
- Component convenience - PlatformServiceMixin provides easy access
- Backward compatibility - existing code can be migrated gradually
- Context awareness - logging can include component context
- Performance optimized - caching and batching in logger
Migration Strategy
- Phase 1: Create self-contained logger.ts with direct database access (no databaseUtil imports)
- Phase 2: Add self-contained convenience methods to PlatformServiceMixin (no databaseUtil imports)
- Phase 3: Migrate existing code to use new methods
- Phase 4: Remove old logging methods from databaseUtil
- Phase 5: Remove databaseUtil imports from PlatformServiceMixin
Key Features
- Smart filtering - prevent logging loops and initialization noise
- Context tracking - include component names in logs
- Performance optimization - batch database writes
- Error handling - graceful fallback when database unavailable
- Platform awareness - different behavior for web/mobile/desktop
Integration with Migration Plan
This logging integration will be implemented as part of Phase 1 of the migration plan, specifically:
- Add logging methods to PlatformServiceMixin (Priority 1, Item 2)
- Migrate logConsoleAndDb and logToDb usage across all files
- Consolidate logging logic in logger.ts
- Remove circular dependencies between logger and databaseUtil
Author: Matthew Raymer Created: 2025-07-05 Status: Planning Phase Last Updated: 2025-07-05