File size: 5,264 Bytes
30be4c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
"""
Quick setup checker for database configuration.
Run this before importing data to verify your setup.
"""

import os
import sys
from pathlib import Path

print("=" * 60)
print("Database Setup Checker")
print("=" * 60)

# Check 1: DATABASE_URL
print("\n1. Checking DATABASE_URL environment variable...")
database_url = os.getenv("DATABASE_URL")
if database_url:
    print(f"   βœ“ DATABASE_URL is set")
    # Mask password in output
    if "@" in database_url:
        parts = database_url.split("@")
        if ":" in parts[0]:
            user_pass = parts[0].split("://")[1] if "://" in parts[0] else parts[0]
            if ":" in user_pass:
                user, _ = user_pass.split(":", 1)
                masked_url = database_url.replace(f":{user_pass.split(':')[1]}", ":****")
                print(f"   URL: {masked_url}")
    else:
        print(f"   URL: {database_url}")
else:
    print("   βœ— DATABASE_URL is NOT set")
    print("\n   Please set it using:")
    print("   Windows PowerShell:")
    print('     $env:DATABASE_URL="postgresql+asyncpg://postgres:YOUR_PASSWORD@localhost:5432/navigation_app"')
    print("   Windows CMD:")
    print('     set DATABASE_URL=postgresql+asyncpg://postgres:YOUR_PASSWORD@localhost:5432/navigation_app')
    sys.exit(1)

# Check 2: JSON files
print("\n2. Checking data files...")
script_dir = Path(__file__).parent
cameras_file = script_dir / "tn_complete_cameras_detailed.json"
speed_limits_file = script_dir / "chennai_speed_limit.json"

if cameras_file.exists():
    print(f"   βœ“ Speed cameras file found: {cameras_file.name}")
else:
    print(f"   βœ— Speed cameras file NOT found: {cameras_file.name}")

if speed_limits_file.exists():
    print(f"   βœ“ Speed limits file found: {speed_limits_file.name}")
else:
    print(f"   βœ— Speed limits file NOT found: {speed_limits_file.name}")

# Check 3: Test database connection
print("\n3. Testing database connection...")
try:
    import asyncio
    from database.database import check_db_health, AsyncSessionLocal
    from sqlalchemy import text
    
    async def test_connection():
        try:
            is_healthy = await check_db_health()
            if is_healthy:
                print("   βœ“ Database connection successful!")
                
                # Try to check if database exists and has tables
                try:
                    async with AsyncSessionLocal() as session:
                        result = await session.execute(
                            text("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public'")
                        )
                        table_count = result.scalar()
                        print(f"   βœ“ Found {table_count} tables in database")
                except Exception as e:
                    print(f"   ⚠ Could not check tables: {e}")
                
                return True
            else:
                print("   βœ— Database connection failed!")
                print("\n   Possible issues:")
                print("   - PostgreSQL is not running")
                print("   - Wrong password in DATABASE_URL")
                print("   - Database 'navigation_app' does not exist")
                print("   - PostgreSQL is not listening on the expected port")
                return False
        except Exception as e:
            print(f"   βœ— Connection error: {e}")
            print("\n   Possible issues:")
            print("   - PostgreSQL is not running")
            print("   - Wrong password in DATABASE_URL")
            print("   - Database 'navigation_app' does not exist")
            return False
    
    result = asyncio.run(test_connection())
    if not result:
        sys.exit(1)
        
except ImportError as e:
    print(f"   βœ— Error importing database modules: {e}")
    print("\n   Please install dependencies:")
    print("     pip install -r requirements.txt")
    sys.exit(1)
except Exception as e:
    print(f"   βœ— Connection error: {e}")
    print("\n   Please check:")
    print("   - PostgreSQL is running")
    print("   - DATABASE_URL is correct")
    print("   - Database 'navigation_app' exists")
    sys.exit(1)

# Check 4: PostGIS extension
print("\n4. Checking PostGIS extension...")
try:
    import asyncio
    from database.database import AsyncSessionLocal
    from sqlalchemy import text
    
    async def check_postgis():
        async with AsyncSessionLocal() as session:
            result = await session.execute(
                text("SELECT EXISTS(SELECT 1 FROM pg_extension WHERE extname = 'postgis')")
            )
            has_postgis = result.scalar()
            if has_postgis:
                print("   βœ“ PostGIS extension is enabled")
                return True
            else:
                print("   βœ— PostGIS extension is NOT enabled")
                print("\n   Please run in psql:")
                print("     CREATE EXTENSION IF NOT EXISTS postgis;")
                return False
    
    if not asyncio.run(check_postgis()):
        sys.exit(1)
        
except Exception as e:
    print(f"   ⚠ Could not check PostGIS: {e}")

print("\n" + "=" * 60)
print("βœ“ Setup check complete! You can now run:")
print("  python import_data.py")
print("=" * 60)