File size: 1,453 Bytes
55c41a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import psycopg2
from decouple import config
from urllib.parse import urlparse
import re
import sys
import shutil
import threading
import time
import os
import time
from datetime import datetime, timedelta, datetime
from colorama import Fore, Style, Back, init
init(autoreset=True)

def db_connection():
    """Establishes a connection to the database with SSL and keepalives."""
    # Parse DATABASE_URL
    url = urlparse(config("DATABASE_URL"))
    
    # Extract connection details from the DATABASE_URL
    host = url.hostname
    port = url.port
    user = url.username
    password = url.password
    database = url.path[1:]

    try:
        # Connect using individual parameters
        conn = psycopg2.connect(
            host=host,
            port=port,
            user=user,
            password=password,
            dbname=database,
            sslmode="require",               # Use SSL
            keepalives=1,                    # Enable keepalives
            keepalives_idle=300,             # Set idle time before keepalives (in seconds)
            keepalives_interval=60,          # Interval for keepalives (in seconds)
            keepalives_count=5               # Number of keepalive retries before disconnecting
        )
        
        return conn
    except psycopg2.OperationalError as db_error:
            return    
    except Exception as e:
        print(f"Database connection error: {e}"), 500
        return conn