File size: 5,215 Bytes
6069ba8
 
 
 
 
 
 
 
 
 
 
 
 
76bf02c
 
6069ba8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e819c6
 
 
f559cc3
 
 
 
 
 
598ed33
 
 
 
 
4e819c6
 
 
 
 
 
 
 
 
 
f559cc3
4e819c6
 
6069ba8
 
76bf02c
6069ba8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Database connection testing utilities
"""
import os
import sys
import warnings


def test_database_connection():
    """
    Test database connection before running migrations.
    Returns True if connection is successful, False otherwise.
    """
    from django.db.utils import OperationalError
    
    try:
        # Set up Django environment
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pms_server.settings')
        
        import django
        django.setup()
        
        from django.db import connection
        
        # Test the connection
        with connection.cursor() as cursor:
            cursor.execute("SELECT 1")
            result = cursor.fetchone()
            
        print("βœ… Database connection successful!")
        return True
        
    except OperationalError as e:
        error_msg = str(e)
        
        if "no certificate or crl found" in error_msg:
            print("❌ SSL Certificate error:")
            print("   The AIVEN_CA_CERT environment variable is missing or invalid.")
            print("   Please ensure you have the correct SSL certificate from Aiven.")
            print("   For development, you can temporarily disable SSL, but this is not recommended.")
            
        elif "Access denied" in error_msg:
            print("❌ Authentication error:")
            print("   Please check your AIVEN_DB_USER and AIVEN_DB_PASSWORD.")
            
        elif "Unknown database" in error_msg:
            print("❌ Database not found:")
            print("   Please check your AIVEN_DB_NAME.")
            
        elif "Can't connect" in error_msg or "Connection refused" in error_msg:
            print("❌ Connection error:")
            print("   Please check your AIVEN_DB_HOST and AIVEN_DB_PORT.")
            print("   Make sure your IP is whitelisted in Aiven.")
            
        else:
            print(f"❌ Database connection failed: {error_msg}")
            
        return False
        
    except Exception as e:
        error_msg = str(e)
        
        if "'bool' object has no attribute 'get'" in error_msg:
            print("❌ SSL Configuration error:")
            print("   PyMySQL SSL parameter format issue detected.")
            print("   This has been fixed with a simplified SSL configuration.")
            print("   Try running the debug_ssl.py script to test different configurations.")
        elif "no certificate or crl found" in error_msg:
            print("❌ SSL Certificate validation error:")
            print("   This is a common issue with SSL certificate validation.")
            print("   The configuration has been updated to use basic SSL without strict verification.")
            print("   This should resolve the certificate validation issue while maintaining security.")
        elif "unexpected keyword argument" in error_msg and "ssl" in error_msg.lower():
            print("❌ SSL Configuration error:")
            print("   PyMySQL SSL configuration issue. This has been fixed.")
            print("   Please redeploy with the updated configuration.")
        elif "Connection.__init__()" in error_msg:
            print("❌ Database connection parameter error:")
            print("   Invalid connection parameters for PyMySQL.")
            print("   This is likely an SSL configuration issue that has been fixed.")
        else:
            print(f"❌ Unexpected error: {error_msg}")
            
        print(f"\nπŸ”§ Debug suggestion: Run 'python debug_ssl.py' to test SSL configurations")
        return False
        
    except ImportError as e:
        print(f"❌ Django import error: {e}")
        print("   This might be due to missing dependencies or configuration issues.")
        return False
        
    except Exception as e:
        print(f"❌ Unexpected error: {e}")
        return False


def check_required_variables():
    """
    Check if all required database environment variables are set.
    """
    required_vars = [
        'AIVEN_DB_NAME',
        'AIVEN_DB_USER', 
        'AIVEN_DB_PASSWORD',
        'AIVEN_DB_HOST'
    ]
    
    missing_vars = []
    for var in required_vars:
        if not os.getenv(var):
            missing_vars.append(var)
    
    if missing_vars:
        print("❌ Missing required database environment variables:")
        for var in missing_vars:
            print(f"   - {var}")
        print("\nPlease set these variables in your .env file or environment.")
        return False
    
    # Check optional SSL certificate
    if not os.getenv('AIVEN_CA_CERT'):
        warnings.warn(
            "AIVEN_CA_CERT not provided. SSL connection may fail in production.",
            RuntimeWarning
        )
    
    return True


if __name__ == "__main__":
    print("=" * 50)
    print("Database Connection Test")
    print("=" * 50)
    
    # Check environment variables first
    if not check_required_variables():
        sys.exit(1)
    
    # Test database connection
    if test_database_connection():
        print("Database is ready for Django migrations!")
        sys.exit(0)
    else:
        print("Database connection failed. Please fix the issues above.")
        sys.exit(1)