🔍 System Status
npm run db:statusShows current configuration, active provider, and available options.
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.
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.
This error appears when the system can’t find valid database credentials.
Symptoms:
npm run db:status shows “❌ No database providers configured”Check what’s missing:
npm run db:statusRun the setup wizard:
npm run db:wizardFollow the interactive prompts to configure your database
Check your .env file has required variables:
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:
ls -la .envwc -l .env # Should show more than just commentsDatabase operations timeout or fail to connect to the server.
Symptoms:
Test connectivity to both providers:
npm run db:manage test --verboseCheck network connectivity (Supabase):
curl -I https://your-project.supabase.coTest from different network if possible
Turso: Verify token hasn’t expired
Supabase: Verify project is active
Test with fresh credentials
Auto-detection doesn’t select the expected database provider.
Symptoms:
npm run db:status shows unexpected active providerSolutions:
Set Explicit Provider (Recommended):
# Set explicit provider in .envecho "DATABASE_PROVIDER=turso" >> .env# orecho "DATABASE_PROVIDER=supabase" >> .envClear Auto-Detection Issues:
# Remove auto-detection, use explicit choicesed -i 's/DATABASE_PROVIDER=auto/DATABASE_PROVIDER=turso/' .envUnderstand Priority Logic:
DATABASE_PROVIDER to overrideOperations succeed but data doesn’t match expectations.
Symptoms:
npm run db:schema# Shows detailed schema comparison between providersFor Turso:
npm run db:migrateFor Supabase:
Manual Schema Verification:
# List tables in current databasenpm run db:manage tables
# Compare with expected schema in docsInvalid 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:
TURSO_AUTH_TOKEN in .envDatabase Not Found
Problem: Database doesn’t exist in Turso
Fix:
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:
Project Paused
Problem: Free tier project paused due to inactivity
Fix:
Switching command fails before making configuration changes.
Symptoms:
.env.backup file is not createdCheck filesystem permissions:
ls -la .envls -la .env.backup 2>/dev/null || echo "Backup doesn't exist"Fix permissions if needed:
chmod 644 .envRetry switching operation
Create backup manually:
cp .env .env.backupVerify backup was created:
ls -la .env.backupProceed with switching operation
Switching appears successful but database doesn’t change.
Diagnosis Steps:
Check if .env file is writable:
ls -la .envVerify current provider:
npm run db:status | grep "Active Provider"Check file contents:
cat .env | grep DATABASE_PROVIDERSolutions:
# 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.Switch completed but new database configuration doesn’t work.
Immediate Rollback:
npm run db:restoreVerify Restoration:
npm run db:statusManual Rollback (if automatic fails):
cp .env.backup .envnpm run db:status # Verify restorationDiagnose Original Issue:
# Test the problematic configurationnpm run db:manage testnpm run db:manage health --verboseSymptoms:
Solutions:
Clear Node modules and package lock:
rm -rf node_modules package-lock.jsonReinstall dependencies:
npm installCheck TypeScript configuration:
npm run type-checkClear npm cache:
npm cache clean --forceClear TypeScript cache:
npx tsc --build --cleanRestart development server:
npm run startDatabase 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:
# This should show changes immediatelynpm run db:statusTest API Endpoint for real-time switching:
curl http://localhost:4321/api/supabase-test# Response should show current active providerForce Restart if needed:
# Kill existing processespkill -f "npm run"
# Start freshnpm run startSymptoms:
Check Production Environment Variables:
DATABASE_PROVIDER is set explicitlySet Explicit Provider in production:
DATABASE_PROVIDER=supabase # or tursoValidate Network Access:
Compare Environment Files:
# Localcat .env | grep -E "(DATABASE|TURSO|SUPABASE)" | sort
# Production (if accessible)env | grep -E "(DATABASE|TURSO|SUPABASE)" | sortTest Production Database Access:
# From production environmentnpm run db:manage testnpm run db:manage healthAPI endpoints report incorrect or inconsistent provider information.
Diagnosis:
Test API Endpoint:
curl http://localhost:4321/api/supabase-testCheck System Status:
npm run db:statusCompare Results: API response should match system status
Solutions:
.env files in different locationsgetDatabase() correctlySymptoms:
Test Direct Database Connection:
npm run db:manage testCheck API Logs in development:
npm run dev# Look for console errors in terminalVerify Database Tables:
npm run db:manage tablesCheck Permissions (Supabase):
Symptoms:
Run Health Check with timing:
npm run db:manage health --verboseCheck Network Latency:
Compare Providers:
# Switch and compare performancenpm run db:switch:turso# Test operations...
npm run db:switch:supabase# Test same operations...Symptoms:
Solutions:
Use Dry-Run Mode first:
node scripts/switch-database.js --to turso --dry-runStop Other Processes before switching:
# Stop dev server and other resource-intensive processespkill -f "npm run"Switch Without Other Operations running:
npm run db:switch:turso# Then restart other processesnpm run startSymptoms:
.env filesFix File Permissions:
chmod 644 .env .env.backupchmod +x scripts/*.jsCheck Directory Permissions:
ls -la .# Verify you can read/write in current directoryFix Ownership Issues (if needed):
# Only if files are owned by different usersudo chown $USER:$USER .env .env.backupProblem: Git wants to commit .env.backup files, causing merge conflicts.
Ensure Backup Files are Ignored:
echo ".env.backup*" >> .gitignoreecho ".env.*.backup" >> .gitignoreRemove from Git if already tracked:
git rm --cached .env.backupgit rm --cached .env.*.backupClean Up Repository:
git add .gitignoregit commit -m "Add .env backup files to .gitignore"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 --verboseTest 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('messages') .select('count');console.log('Result:', data, 'Error:', error);"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-configIf all else fails, reset the entire database configuration:
Backup Current State:
cp .env .env.emergency-backupcp .env.backup .env.backup.emergency 2>/dev/null || trueRun Fresh Setup:
npm run db:wizard# Follow prompts to reconfigure from scratchTest New Configuration:
npm run db:statusnpm run db:manage testRestore if Needed:
# If new setup doesn't workcp .env.emergency-backup .envWhen 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.txtAdd these to your development routine:
# Weekly health checknpm run db:statusnpm run db:manage health
# Before major changesnpm run db:backupnpm run db:schemaAlways Backup before experiments:
npm run db:backupTest Changes with dry-run first:
node scripts/switch-database.js --to turso --dry-runValidate Configuration after changes:
npm run db:schemanpm run db:manage testKeep Emergency Backup:
# Maintain a known-good configurationcp .env .env.known-good# 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.