amo-server/scripts/setup_postgres.py
Maxim Snesarev 33d6bb7ebd Refactor AMO CRM Data Collection Service to use PostgreSQL
- Updated database configuration to switch from SQLite to PostgreSQL, including changes to alembic.ini, Docker Compose, and environment settings.
- Refactored application code to utilize PostgreSQL database adapters, ensuring compatibility with the new database structure.
- Enhanced API routes and data handling to support the new database, including adjustments in data models and query logic.
- Introduced new job processing mechanisms for full synchronization of AMO CRM entities, leveraging FastStream for background tasks.
- Improved logging and error handling across the application to facilitate better monitoring and debugging.
- Removed obsolete SQLite adapter files and migrations, streamlining the project structure for PostgreSQL integration.
2025-11-05 00:38:37 +03:00

127 lines
3.7 KiB
Python

#!/usr/bin/env python3
"""
Setup PostgreSQL database and run migrations.
This script helps set up the PostgreSQL database for the AMO CRM service.
"""
import subprocess
import sys
import time
from pathlib import Path
# Add project root to Python path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from utils.config import settings
def check_postgres_connection():
"""Check if PostgreSQL is accessible."""
try:
from sqlalchemy import create_engine
engine = create_engine(settings.DATABASE_URL)
with engine.connect() as conn:
conn.execute("SELECT 1")
print("✓ PostgreSQL connection successful")
return True
except Exception as e:
print(f"✗ PostgreSQL connection failed: {e}")
return False
def run_migrations():
"""Run Alembic migrations."""
try:
print("\nRunning database migrations...")
result = subprocess.run(
["alembic", "upgrade", "head"],
cwd=project_root,
capture_output=True,
text=True
)
if result.returncode == 0:
print("✓ Migrations completed successfully")
print(result.stdout)
return True
else:
print("✗ Migration failed:")
print(result.stderr)
return False
except Exception as e:
print(f"✗ Error running migrations: {e}")
return False
def start_postgres_docker():
"""Start PostgreSQL using Docker Compose."""
try:
print("Starting PostgreSQL container...")
result = subprocess.run(
["docker-compose", "up", "-d", "postgres"],
cwd=project_root,
capture_output=True,
text=True
)
if result.returncode == 0:
print("✓ PostgreSQL container started")
# Wait for PostgreSQL to be ready
print("Waiting for PostgreSQL to be ready...")
time.sleep(5)
return True
else:
print("✗ Failed to start PostgreSQL:")
print(result.stderr)
return False
except Exception as e:
print(f"✗ Error starting PostgreSQL: {e}")
return False
def main():
"""Main setup function."""
print("=" * 60)
print("PostgreSQL Setup for AMO CRM Service")
print("=" * 60)
print(f"\nDatabase URL: {settings.DATABASE_URL}")
print()
# Check if PostgreSQL is already running
if check_postgres_connection():
print("\nPostgreSQL is already running and accessible.")
else:
print("\nPostgreSQL is not accessible. Starting Docker container...")
if not start_postgres_docker():
print("\n❌ Failed to start PostgreSQL. Please check Docker and try again.")
sys.exit(1)
# Check connection again
print("\nChecking PostgreSQL connection...")
for i in range(10):
if check_postgres_connection():
break
print(f"Attempt {i+1}/10: Waiting for PostgreSQL to be ready...")
time.sleep(2)
else:
print("\n❌ PostgreSQL is not responding. Please check logs.")
sys.exit(1)
# Run migrations
if not run_migrations():
print("\n❌ Migration failed. Please check the error messages above.")
sys.exit(1)
print("\n" + "=" * 60)
print("✓ PostgreSQL setup completed successfully!")
print("=" * 60)
print("\nYou can now start the application with:")
print(" uvicorn app:app --reload")
print("\nOr start all services with Docker:")
print(" docker-compose up -d")
print()
if __name__ == "__main__":
main()