This comprehensive troubleshooting guide helps you diagnose and resolve issues with the database switching system. Whether you’re dealing with connection failures, switching problems, or configuration errors, this guide provides step-by-step solutions.
Quick Diagnostics
Section titled “Quick Diagnostics”Start with these commands to understand your current system state:
🔍 System Status
npm run db:statusShows current configuration, active provider, and available options.
🔗 Connection Test
npm run db:manage testTests connectivity to all configured database providers.
💊 Health Check
npm run db:manage healthRuns comprehensive diagnostics and performance checks.
🚨 Emergency Recovery
npm run db:restoreRestores previous configuration if switching failed.
Common Error Messages
Section titled “Common Error Messages””Database not configured”
Section titled “”Database not configured””This error appears when the system can’t find valid database credentials.
Symptoms:
- API endpoints return 503 Service Unavailable errors
- Dashboard shows “Database service unavailable”
npm run db:statusshows ”❌ No database providers configured”
-
Check what’s missing:
Terminal window npm run db:status -
Run the setup wizard:
Terminal window npm run db:wizard -
Follow the interactive prompts to configure your database
-
Check your
.envfile has required variables:Terminal window cat .env | grep -E "(TURSO|SUPABASE)" -
Add missing credentials to
.env:# For TursoTURSO_DATABASE_URL=libsql://your-db-name.turso.ioTURSO_AUTH_TOKEN=eyJ...# For SupabaseSUPABASE_URL=https://your-project.supabase.coSUPABASE_SERVICE_ROLE_KEY=eyJ... -
Verify file exists and has content:
Terminal window ls -la .envwc -l .env # Should show more than just comments
“Connection failed” During Operations
Section titled ““Connection failed” During Operations”Database operations timeout or fail to connect to the server.
Symptoms:
- Database operations timeout
- “Failed to connect” errors in logs
- API endpoints return 500 Internal Server errors
-
Test connectivity to both providers:
Terminal window npm run db:manage test --verbose -
Check network connectivity (Supabase):
Terminal window curl -I https://your-project.supabase.co -
Test from different network if possible
-
Turso: Verify token hasn’t expired
- Visit: https://app.turso.tech/[your-org]/[your-db]/settings/tokens
- Generate new token if expired
-
Supabase: Verify project is active
- Visit: https://supabase.com/dashboard/projects
- Check project status and billing
-
Test with fresh credentials
- Check provider status pages for outages
- Verify database instance is running
- Check for scheduled maintenance windows
- Verify database instance performance tier
”Provider detection failed”
Section titled “”Provider detection failed””Auto-detection doesn’t select the expected database provider.
Symptoms:
- Wrong database provider is selected automatically
- Inconsistent behavior between environments
npm run db:statusshows unexpected active provider
Solutions:
-
Set Explicit Provider (Recommended):
Terminal window # Set explicit provider in .envecho "DATABASE_PROVIDER=turso" >> .env# orecho "DATABASE_PROVIDER=supabase" >> .env -
Clear Auto-Detection Issues:
Terminal window # Remove auto-detection, use explicit choicesed -i 's/DATABASE_PROVIDER=auto/DATABASE_PROVIDER=turso/' .env -
Understand Priority Logic:
- Priority: Explicit choice → Supabase → Turso → Error
- Multiple providers? Set
DATABASE_PROVIDERto override
”Schema validation failed”
Section titled “”Schema validation failed””Operations succeed but data doesn’t match expectations.
Symptoms:
- Missing tables or columns
- Type conversion errors
- Inconsistent data between providers
npm run db:schema# Shows detailed schema comparison between providers-
For Turso:
Terminal window npm run db:migrate -
For Supabase:
- Open Supabase Dashboard
- Check migrations in Database → Migrations
- Apply pending migrations
-
Manual Schema Verification:
Terminal window # List tables in current databasenpm run db:manage tables# Compare with expected schema in docs
Database-Specific Issues
Section titled “Database-Specific Issues”Turso (LibSQL) Problems
Section titled “Turso (LibSQL) Problems”Invalid URL Format
Problem: TURSO_DATABASE_URL has wrong format
Fix:
# ✅ Correct format:TURSO_DATABASE_URL=libsql://database-name.turso.io
# ❌ Wrong format:TURSO_DATABASE_URL=https://database-name.turso.ioAuthentication Failed
Problem: Auth token expired or invalid
Fix:
- Visit: https://app.turso.tech/[org]/[db]/settings/tokens
- Generate new token
- Update
TURSO_AUTH_TOKENin.env
Database Not Found
Problem: Database doesn’t exist in Turso
Fix:
- Verify database exists in Turso dashboard
- Check organization and database name spelling
- Ensure you have access permissions
Supabase (PostgreSQL) Problems
Section titled “Supabase (PostgreSQL) Problems”Invalid API Key
Problem: Using wrong key type for operations
Fix:
# ❌ Don't use anon key for server operationsSUPABASE_ANON_KEY=eyJ...
# ✅ Use service role for server operationsSUPABASE_SERVICE_ROLE_KEY=eyJ...RLS Policy Violation
Problem: Row Level Security blocks operations
Fix:
- Check RLS policies in Supabase Dashboard
- Ensure service role can access required tables
- Review policy conditions for your use case
Project Paused
Problem: Free tier project paused due to inactivity
Fix:
- Visit Supabase Dashboard
- Unpause project in Settings
- Consider upgrading plan if needed frequently
Switching Operation Issues
Section titled “Switching Operation Issues”Backup Creation Failed
Section titled “Backup Creation Failed”Switching command fails before making configuration changes.
Symptoms:
- Switching stops with “backup creation failed”
.env.backupfile is not created- File permission errors
-
Check filesystem permissions:
Terminal window ls -la .envls -la .env.backup 2>/dev/null || echo "Backup doesn't exist" -
Fix permissions if needed:
Terminal window chmod 644 .env -
Retry switching operation
-
Create backup manually:
Terminal window cp .env .env.backup -
Verify backup was created:
Terminal window ls -la .env.backup -
Proceed with switching operation
Environment Update Failed
Section titled “Environment Update Failed”Switching appears successful but database doesn’t change.
Diagnosis Steps:
-
Check if
.envfile is writable:Terminal window ls -la .env -
Verify current provider:
Terminal window npm run db:status | grep "Active Provider" -
Check file contents:
Terminal window cat .env | grep DATABASE_PROVIDER
Solutions:
# Make .env writablechmod 644 .env
# Retry switching operationnpm run db:switch:turso # or supabase# Update environment manuallyecho "DATABASE_PROVIDER=turso" >> .env
# Or edit directly with your preferred editornano .env # or vim, code, etc.Rollback Required
Section titled “Rollback Required”Switch completed but new database configuration doesn’t work.
-
Immediate Rollback:
Terminal window npm run db:restore -
Verify Restoration:
Terminal window npm run db:status -
Manual Rollback (if automatic fails):
Terminal window cp .env.backup .envnpm run db:status # Verify restoration -
Diagnose Original Issue:
Terminal window # Test the problematic configurationnpm run db:manage testnpm run db:manage health --verbose
Development Environment Issues
Section titled “Development Environment Issues”Module Import Errors
Section titled “Module Import Errors”Symptoms:
- Import errors for database modules
- TypeScript compilation fails
- “Cannot find module” errors
Solutions:
-
Clear Node modules and package lock:
Terminal window rm -rf node_modules package-lock.json -
Reinstall dependencies:
Terminal window npm install -
Check TypeScript configuration:
Terminal window npm run type-check
-
Clear npm cache:
Terminal window npm cache clean --force -
Clear TypeScript cache:
Terminal window npx tsc --build --clean -
Restart development server:
Terminal window npm run start
Hot Reload Not Working
Section titled “Hot Reload Not Working”Database configuration changes don’t take effect without server restart.
Expected Behavior: The system supports real-time provider switching without server restart.
Troubleshooting Steps:
-
Check Current Provider in real-time:
Terminal window # This should show changes immediatelynpm run db:status -
Check the active provider for real-time switching:
Terminal window npm run db:status# Output should show the current active provider -
Force Restart if needed:
Terminal window # Kill existing processespkill -f "npm run"# Start freshnpm run start
Production vs Development Behavior
Section titled “Production vs Development Behavior”Symptoms:
- Works locally but fails in production
- Different database provider selected in different environments
-
Check Production Environment Variables:
- Ensure
DATABASE_PROVIDERis set explicitly - Verify all required credentials are present
- Use same credential format as local
- Ensure
-
Set Explicit Provider in production:
DATABASE_PROVIDER=supabase # or turso -
Validate Network Access:
- Test database connectivity from production environment
- Check firewall rules and security groups
-
Compare Environment Files:
Terminal window # Localcat .env | grep -E "(DATABASE|TURSO|SUPABASE)" | sort# Production (if accessible)env | grep -E "(DATABASE|TURSO|SUPABASE)" | sort -
Test Production Database Access:
Terminal window # From production environmentnpm run db:manage testnpm run db:manage health
API Endpoint Issues
Section titled “API Endpoint Issues”Wrong Provider Information
Section titled “Wrong Provider Information”API endpoints report incorrect or inconsistent provider information.
Diagnosis:
-
Test the database connection:
Terminal window npm run db:status -
Check System Status:
Terminal window npm run db:status -
Compare Results: API response should match system status
Solutions:
- Clear any cached environment variables
- Restart development server completely
- Check for multiple
.envfiles in different locations
- Verify API endpoints use
getDatabase()correctly - Check for hardcoded database client imports
- Ensure provider detection logic is working
Silent API Failures
Section titled “Silent API Failures”Symptoms:
- No errors but operations don’t work
- Empty results from database queries
- API returns success but no data changes
-
Test Direct Database Connection:
Terminal window npm run db:manage test -
Check API Logs in development:
Terminal window npm run dev# Look for console errors in terminal -
Verify Database Tables:
Terminal window npm run db:manage tables -
Check Permissions (Supabase):
- Review RLS policies in dashboard
- Verify service role permissions
Performance Issues
Section titled “Performance Issues”Slow Database Operations
Section titled “Slow Database Operations”Symptoms:
- API endpoints timeout frequently
- Dashboard takes long time to load
- Database queries are slower than expected
-
Run Health Check with timing:
Terminal window npm run db:manage health --verbose -
Check Network Latency:
- Test connection speed to database
- Consider geographic distance to database server
-
Compare Providers:
Terminal window # Switch and compare performancenpm run db:switch:turso# Test operations...npm run db:switch:supabase# Test same operations...
- Database Instance: Verify performance tier/plan
- Network: Check for network issues or proxy delays
- Provider Choice: Turso typically faster for simple queries
- Query Optimization: Review query patterns and indexes
Memory Issues During Switching
Section titled “Memory Issues During Switching”Symptoms:
- Switching process crashes
- Out of memory errors during database operations
Solutions:
-
Use Dry-Run Mode first:
Terminal window node scripts/switch-database.js --to turso --dry-run -
Stop Other Processes before switching:
Terminal window # Stop dev server and other resource-intensive processespkill -f "npm run" -
Switch Without Other Operations running:
Terminal window npm run db:switch:turso# Then restart other processesnpm run start
File System Issues
Section titled “File System Issues”Permission Denied Errors
Section titled “Permission Denied Errors”Symptoms:
- Cannot read or write
.envfiles - Script execution fails with permission errors
-
Fix File Permissions:
Terminal window chmod 644 .env .env.backupchmod +x scripts/*.js -
Check Directory Permissions:
Terminal window ls -la .# Verify you can read/write in current directory -
Fix Ownership Issues (if needed):
Terminal window # Only if files are owned by different usersudo chown $USER:$USER .env .env.backup
Git Conflicts with Backup Files
Section titled “Git Conflicts with Backup Files”Problem: Git wants to commit .env.backup files, causing merge conflicts.
-
Ensure Backup Files are Ignored:
Terminal window echo ".env.backup*" >> .gitignoreecho ".env.*.backup" >> .gitignore -
Remove from Git if already tracked:
Terminal window git rm --cached .env.backupgit rm --cached .env.*.backup -
Clean Up Repository:
Terminal window git add .gitignoregit commit -m "Add .env backup files to .gitignore"
Advanced Debugging
Section titled “Advanced Debugging”Enable Debug Mode
Section titled “Enable Debug Mode”For detailed troubleshooting information:
# Enable debug logging for all database operationsDEBUG=1 npm run db:manage testDEBUG=1 npm run db:switch:turso# Get detailed output for all operationsnpm run db:manage status --verbosenpm run db:manage health --verboseManual Database Testing
Section titled “Manual Database Testing”Test database connections directly outside the abstraction layer:
node -e "import { createClient } from '@libsql/client';const client = createClient({ url: process.env.TURSO_DATABASE_URL, authToken: process.env.TURSO_AUTH_TOKEN});console.log(await client.execute('SELECT 1 as test'));"node -e "import { createClient } from '@supabase/supabase-js';const client = createClient( process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_ROLE_KEY);const { data, error } = await client .from('clients') .select('count');console.log('Result:', data, 'Error:', error);"Environment Variable Debugging
Section titled “Environment Variable Debugging”Check for hidden characters or configuration issues:
# Check all database-related environment variablesenv | grep -E "(DATABASE|TURSO|SUPABASE)" | sort
# Check for invisible characters or extra spacesod -c .env | grep -E "(TURSO|SUPABASE|DATABASE)"
# Validate .env file formatnpm run db:manage validate-configRecovery Procedures
Section titled “Recovery Procedures”Complete System Reset
Section titled “Complete System Reset”If all else fails, reset the entire database configuration:
-
Backup Current State:
Terminal window cp .env .env.emergency-backupcp .env.backup .env.backup.emergency 2>/dev/null || true -
Run Fresh Setup:
Terminal window npm run db:wizard# Follow prompts to reconfigure from scratch -
Test New Configuration:
Terminal window npm run db:statusnpm run db:manage test -
Restore if Needed:
Terminal window # If new setup doesn't workcp .env.emergency-backup .env
Collecting Diagnostic Information
Section titled “Collecting Diagnostic Information”When reporting issues or asking for help, collect this information:
# Create comprehensive diagnostic report{ echo "=== System Information ===" echo "Node version: $(node --version)" echo "NPM version: $(npm --version)" echo "OS: $(uname -a)" echo
echo "=== Database Status ===" npm run db:status echo
echo "=== Health Check ===" npm run db:manage health echo
echo "=== Environment Variables ===" env | grep -E "(DATABASE|TURSO|SUPABASE)" | sed 's/=.*/=***/' | sort} > debug-report.txtPrevention Best Practices
Section titled “Prevention Best Practices”Regular Health Checks
Section titled “Regular Health Checks”Add these to your development routine:
# Weekly health checknpm run db:statusnpm run db:manage health
# Before major changesnpm run db:backupnpm run db:schemaSafe Development Workflow
Section titled “Safe Development Workflow”-
Always Backup before experiments:
Terminal window npm run db:backup -
Test Changes with dry-run first:
Terminal window node scripts/switch-database.js --to turso --dry-run -
Validate Configuration after changes:
Terminal window npm run db:schemanpm run db:manage test -
Keep Emergency Backup:
Terminal window # Maintain a known-good configurationcp .env .env.known-good
Version Control Safety
Section titled “Version Control Safety”# Always check before committinggit status | grep -E "(\.env|backup)" && echo "⚠️ Check .env files"
# Verify .gitignore is protecting secretsgit ls-files | grep -E "\.env" && echo "⚠️ .env files in git!"This troubleshooting guide covers the most common issues you might encounter with the database switching system. For additional help or to report new issues, refer to the main database switching guide or check the project’s GitHub repository for the latest updates and community support.