Refactor Plex Database Repair Logic

- Created a centralized database repair script (`plex-database-repair.sh`) to handle all database integrity checks and repairs for Plex Media Server.
- Updated the main Plex management script (`plex.sh`) to integrate the new repair functionality and fixed Unicode/ASCII display issues.
- Refactored the backup script (`backup-plex.sh`) to remove duplicate repair functions and ensure it utilizes the new repair script.
- Conducted thorough code validation and functional testing to ensure all scripts operate correctly with the new changes.
- Enhanced documentation for the new repair script, detailing usage, features, and integration points with other scripts.
- Fixed critical bugs related to WAL file handling and corrected typos in script options.
This commit is contained in:
Peter Wood
2025-06-21 06:30:07 -04:00
parent d066f32b10
commit 2bc9e91229
5 changed files with 1387 additions and 938 deletions

View File

@@ -0,0 +1,116 @@
# Plex Database Repair Refactoring - Completion Summary
## Task Description
Refactor Plex Media Server management scripts to centralize database repair logic in a shared script (`plex-database-repair.sh`), remove duplicate/legacy repair logic from other scripts, and fix Unicode/ASCII display issues.
## Completed Work
### ✅ 1. Created Shared Database Repair Script
- **File**: `/home/acedanger/shell/plex/plex-database-repair.sh`
- **Features**:
- Centralized database integrity checking and repair logic
- Multiple repair strategies (dump/restore, schema recreation, backup recovery)
- Proper WAL file handling for repair operations
- File ownership correction after repairs
- Command-line interface with check/repair/force-repair modes
- Comprehensive logging and error handling
### ✅ 2. Updated Main Plex Management Script
- **File**: `/home/acedanger/shell/plex/plex.sh`
- **Changes**:
- Added `repair_plex()` function that uses the shared repair script
- Added user-facing `repair` command
- Fixed Unicode/ASCII display issues in output
- Integrated shared repair script for all database operations
- Maintained backward compatibility with existing functionality
### ✅ 3. Refactored Backup Script
- **File**: `/home/acedanger/shell/plex/backup-plex.sh`
- **Major Changes**:
- **Removed duplicate repair functions**:
- `attempt_dump_restore()`
- `attempt_schema_recreation()`
- `attempt_backup_recovery()`
- `recover_table_data()`
- `cleanup_repair_files()`
- `handle_wal_files_for_repair()`
- `check_database_integrity_with_wal()`
- **Updated integrity and repair functions**:
- `check_database_integrity()` now calls shared repair script
- `repair_database()` now calls shared repair script
- **Fixed critical issue**: Restored missing `handle_wal_files()` function for backup operations
- **Fixed typo**: Corrected `AUTO_REPAIR=false.service` to `AUTO_REPAIR=false`
### ✅ 4. Code Validation and Testing
- **Syntax validation**: All scripts pass `bash -n` syntax checks
- **Functional testing**:
- Help systems work correctly
- Database repair command integration successful
- Backup script operations functioning properly
- WAL file handling restored and working
- **Error checking**: No remaining references to removed functions
### ✅ 5. Documentation
- **File**: `/home/acedanger/shell/docs/plex-database-repair.md`
- **Content**: Complete documentation of the shared repair script usage and features
## Key Benefits Achieved
### 1. **Code Deduplication**
- Eliminated duplicate repair logic across multiple scripts
- Centralized repair strategies in single, well-tested script
- Reduced maintenance burden and potential for inconsistencies
### 2. **Improved Maintainability**
- All repair logic in one place for easier updates
- Consistent repair behavior across all scripts
- Single source of truth for database repair procedures
### 3. **Enhanced User Experience**
- Fixed Unicode/ASCII display issues
- Consistent repair interface across scripts
- Clear command-line interface for repair operations
### 4. **Better Error Handling**
- Centralized error handling and logging
- Consistent return codes across scripts
- Proper file ownership correction after repairs
### 5. **Preserved Functionality**
- All existing backup and management functionality maintained
- Backward compatibility preserved
- No breaking changes to existing workflows
## Files Modified
1. **Created**: `/home/acedanger/shell/plex/plex-database-repair.sh`
2. **Updated**: `/home/acedanger/shell/plex/plex.sh`
3. **Updated**: `/home/acedanger/shell/plex/backup-plex.sh`
4. **Created**: `/home/acedanger/shell/docs/plex-database-repair.md`
## Critical Bug Fixes
1. **Restored missing `handle_wal_files()` function** - Critical for backup WAL operations
2. **Fixed typo in `--disable-auto-repair` option** - Was setting incorrect value
3. **Fixed Unicode display issues** - Proper ASCII character usage in plex.sh
4. **Corrected function references** - All calls now use shared repair script
## Verification Status
- ✅ All scripts pass syntax validation
- ✅ Help systems functioning correctly
- ✅ Database repair integration working
- ✅ Backup script operations successful
- ✅ WAL file handling restored
- ✅ No orphaned function references
- ✅ All error handling preserved
## Final State
The refactoring is complete and fully functional. All Plex management scripts now use the centralized database repair system while maintaining their individual responsibilities:
- **plex.sh**: Service management and user interface
- **backup-plex.sh**: Backup operations with integrity checking
- **plex-database-repair.sh**: Specialized database repair operations
The system is ready for production use with improved maintainability and reduced code duplication.

View File

@@ -0,0 +1,154 @@
# Plex Database Repair Utility
## Overview
The `plex-database-repair.sh` script provides comprehensive database repair functionality for Plex Media Server. It has been extracted from the `backup-plex.sh` script to be reusable across multiple scripts in the Plex management suite.
## Features
- **Database Integrity Verification**: Uses Plex's custom SQLite binary for accurate integrity checking
- **WAL File Management**: Properly handles Write-Ahead Logging files during repair operations
- **Multiple Repair Strategies**:
1. SQL Dump/Restore approach with validation
2. Schema recreation with data recovery
3. Recovery from previous backups
- **Comprehensive Error Handling**: Graceful recovery and rollback on failure
- **Ownership Preservation**: Ensures proper file ownership for the plex user
## Usage
### Command Line Interface
```bash
# Check database integrity only
./plex-database-repair.sh check <database_file>
# Attempt to repair corrupted database
./plex-database-repair.sh repair <database_file>
# Force repair without prompts (for automation)
./plex-database-repair.sh force-repair <database_file>
```
### Integration with Other Scripts
The repair script is designed to be called from other scripts:
```bash
# Source the script to use its functions
source /path/to/plex-database-repair.sh
# Use functions directly
check_database_integrity "/path/to/database.db"
repair_database "/path/to/database.db" false
```
## Examples
### Basic Integrity Check
```bash
./plex-database-repair.sh check "/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Plug-in Support/Databases/com.plexapp.plugins.library.db"
```
### Repair Corrupted Database
```bash
./plex-database-repair.sh repair "/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Plug-in Support/Databases/com.plexapp.plugins.library.db"
```
## Exit Codes
- **0**: Success (database is healthy or successfully repaired)
- **1**: Database has issues but repair failed
- **2**: Critical error (cannot access database or repair tools)
## Dependencies
- **Plex Media Server**: Must be installed with the custom SQLite binary
- **Standard Unix tools**: `cp`, `mv`, `rm`, `chown`, `sync`
- **sudo access**: Required for accessing Plex files and changing ownership
## Integration Points
### plex.sh
The main Plex management script uses this repair utility for:
- Pre-startup integrity checking
- Manual database repair command (`plex.sh repair`)
### backup-plex.sh
The backup script uses this utility for:
- Pre-backup integrity verification
- Automatic repair during backup process
- Database corruption detection and handling
## Technical Details
### Repair Strategies
1. **SQL Dump/Restore**:
- Creates a complete SQL dump of the corrupted database
- Validates dump contains essential Plex tables
- Creates new database from validated dump
- Verifies integrity of repaired database
2. **Schema Recreation**:
- Extracts schema from corrupted database
- Creates new database with clean schema
- Attempts table-by-table data recovery
- Considers successful if 80% of tables recovered
3. **Backup Recovery**:
- Locates most recent valid backup
- Extracts and validates backup database
- Replaces corrupted database with backup version
### WAL File Handling
The script properly manages SQLite Write-Ahead Logging files:
- **Prepare**: Performs WAL checkpoint and creates backups
- **Cleanup**: Removes WAL/SHM files and restores WAL mode
- **Restore**: Restores WAL/SHM files if repair fails
### Safety Measures
- Creates pre-repair backups before any modifications
- Uses atomic file operations where possible
- Forces filesystem sync after critical operations
- Preserves original database if all repair strategies fail
- Ensures proper file ownership and permissions
## Troubleshooting
### Common Issues
1. **Permission Denied**: Ensure script has sudo access and Plex files are accessible
2. **Plex SQLite Not Found**: Verify Plex Media Server is properly installed
3. **Insufficient Disk Space**: Repair process requires significant temporary space
4. **Service Access**: Ensure Plex service can be stopped/started during repair
### Recovery Options
If repair fails:
1. Check `backup-plex.sh` for recent backups
2. Examine corrupted database directories for recovery files
3. Consider manual database reconstruction using Plex tools
4. Contact Plex support for advanced recovery options
## Related Scripts
- **plex.sh**: Main Plex service management
- **backup-plex.sh**: Comprehensive backup solution
- **restore-plex.sh**: Backup restoration utilities
- **validate-plex-backups.sh**: Backup validation tools
## Changelog
### v1.0 (2025-06-18)
- Initial extraction from backup-plex.sh
- Added standalone command-line interface
- Enhanced ownership preservation
- Improved error handling and logging