Files
Lyra/fix_databases.py
Dani d9c526fa5c feat: Add database setup guide and local configuration files
- Added DATABASE_SETUP.md with comprehensive guide for PostgreSQL and Redis installation on Windows
- Created .claude/settings.local.json with permission settings for pytest and database fix scripts
- Updated .gitignore to exclude .env.backup file
- Included database connection test utilities in lyra/database_setup.py
- Added environment variable configuration examples for local development
2025-09-29 16:29:18 -04:00

216 lines
7.5 KiB
Python

"""
Fix database setup for Lyra AI.
This script helps reset PostgreSQL password and set up Redis.
"""
import subprocess
import sys
import os
import time
def run_command(cmd, shell=True, timeout=30):
"""Run a command and return the result."""
try:
result = subprocess.run(
cmd,
shell=shell,
capture_output=True,
text=True,
timeout=timeout
)
return result.returncode == 0, result.stdout, result.stderr
except subprocess.TimeoutExpired:
return False, "", "Command timed out"
except Exception as e:
return False, "", str(e)
def check_postgresql_service():
"""Check if PostgreSQL service is running."""
print("Checking PostgreSQL service...")
success, stdout, stderr = run_command('net start | findstr postgresql')
if success and 'postgresql' in stdout.lower():
print("✅ PostgreSQL service is running")
return True
else:
print("❌ PostgreSQL service not found")
return False
def reset_postgresql_password():
"""Guide user through PostgreSQL password reset."""
print("\n🔧 PostgreSQL Password Setup")
print("=" * 50)
print("\nOption 1: Set PostgreSQL to trust local connections (easiest)")
print("This allows connections without a password from localhost.")
response = input("\nWould you like to configure PostgreSQL for password-free local access? (y/n): ").lower()
if response == 'y':
try:
# Find pg_hba.conf file
pg_data_dir = r"C:\Program Files\PostgreSQL\17\data"
pg_hba_file = os.path.join(pg_data_dir, "pg_hba.conf")
if os.path.exists(pg_hba_file):
print(f"\nFound PostgreSQL config at: {pg_hba_file}")
print("\n⚠️ Manual step required:")
print("1. Open Command Prompt as Administrator")
print("2. Run these commands:")
print(f' notepad "{pg_hba_file}"')
print("3. Find the line that starts with:")
print(" host all all 127.0.0.1/32 scram-sha-256")
print("4. Change 'scram-sha-256' to 'trust'")
print("5. Save the file")
print("6. Restart PostgreSQL service:")
print(" net stop postgresql-x64-17")
print(" net start postgresql-x64-17")
print("\nAfter making these changes, PostgreSQL will allow local connections without a password.")
return True
else:
print(f"❌ Could not find pg_hba.conf at {pg_hba_file}")
return False
except Exception as e:
print(f"❌ Error: {e}")
return False
else:
print("\nOption 2: Set a password for PostgreSQL")
print("You'll need to set a password and update the .env file.")
password = input("Enter a password for PostgreSQL user 'postgres': ")
if password:
print(f"\n💡 Remember to update your .env file:")
print(f"DATABASE_URL=postgresql://postgres:{password}@localhost:5432/lyra")
return True
else:
print("❌ No password provided")
return False
def install_redis_alternative():
"""Install Redis using Chocolatey or provide manual instructions."""
print("\n🔴 Redis Setup")
print("=" * 50)
print("Checking for Redis alternatives...")
# Try to install Redis using Chocolatey if available
success, stdout, stderr = run_command("choco --version", timeout=5)
if success:
print("✅ Chocolatey found! Installing Redis...")
success, stdout, stderr = run_command("choco install redis-64 -y", timeout=120)
if success:
print("✅ Redis installed via Chocolatey")
# Try to start Redis service
success, stdout, stderr = run_command("net start redis")
if success:
print("✅ Redis service started")
return True
else:
print("⚠️ Redis installed but service not started")
print("Try running: net start redis")
return True
else:
print("❌ Redis installation via Chocolatey failed")
# Fallback: Manual Redis installation instructions
print("\n📋 Manual Redis Installation:")
print("1. Download Redis for Windows from:")
print(" https://github.com/microsoftarchive/redis/releases")
print("2. Download Redis-x64-3.0.504.msi")
print("3. Install with default settings")
print("4. Start Redis service: net start redis")
print("\n📋 Alternative: Use Docker (if you have it):")
print(" docker run -d -p 6379:6379 redis:alpine")
print("\n📋 Alternative: Use Redis Cloud (free tier):")
print(" 1. Go to https://app.redislabs.com/")
print(" 2. Create free account")
print(" 3. Create database")
print(" 4. Update REDIS_URL in .env with cloud connection string")
return False
def update_env_file():
"""Update .env file with simplified database configuration."""
print("\n📝 Updating .env file...")
env_path = ".env"
if not os.path.exists(env_path):
print(f"❌ .env file not found at {env_path}")
return False
try:
# Read current .env
with open(env_path, 'r') as f:
lines = f.readlines()
# Update database configuration
new_lines = []
for line in lines:
if line.startswith('DATABASE_URL='):
# Set to trust local connection (no password)
new_lines.append('DATABASE_URL=postgresql://postgres@localhost:5432/lyra\n')
print("✅ Updated DATABASE_URL for local trust authentication")
elif line.startswith('REDIS_URL='):
# Keep Redis as-is
new_lines.append(line)
else:
new_lines.append(line)
# Write back to .env
with open(env_path, 'w') as f:
f.writelines(new_lines)
print("✅ .env file updated")
return True
except Exception as e:
print(f"❌ Error updating .env file: {e}")
return False
def main():
"""Main setup function."""
print("=" * 60)
print("LYRA AI - DATABASE SETUP FIXER")
print("=" * 60)
# Check if we're in the right directory
if not os.path.exists('.env'):
print("❌ Please run this script from the Lyra project directory")
print(" (The directory containing the .env file)")
return
# Step 1: Check PostgreSQL
if check_postgresql_service():
# Step 2: Fix PostgreSQL authentication
if reset_postgresql_password():
print("✅ PostgreSQL configuration ready")
else:
print("❌ PostgreSQL configuration failed")
# Step 3: Set up Redis
if install_redis_alternative():
print("✅ Redis setup complete")
else:
print("⚠️ Redis needs manual setup (see instructions above)")
# Step 4: Update .env file
update_env_file()
print("\n" + "=" * 60)
print("🎯 NEXT STEPS:")
print("1. If you chose PostgreSQL trust authentication:")
print(" - Edit pg_hba.conf as shown above")
print(" - Restart PostgreSQL service")
print("2. Set up Redis using one of the methods above")
print("3. Run: python test_database_connections.py")
print("4. If tests pass, run: python -m lyra.main")
print("=" * 60)
if __name__ == "__main__":
main()