82 lines
1.7 KiB
Python
82 lines
1.7 KiB
Python
#datatbase.py
|
|
|
|
import os
|
|
import psycopg2
|
|
from psycopg2 import OperationalError
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker, declarative_base
|
|
from sqlalchemy.engine.url import URL
|
|
from dotenv import load_dotenv
|
|
|
|
# Load env variables
|
|
load_dotenv()
|
|
|
|
# Neon DB credentials
|
|
DB_NAME = os.getenv("DB_NAME")
|
|
DB_USER = os.getenv("DB_USER")
|
|
DB_PASSWORD = os.getenv("DB_PASSWORD")
|
|
DB_HOST = os.getenv("DB_HOST")
|
|
DB_PORT = os.getenv("DB_PORT", "5432")
|
|
|
|
# Create DATABASE URL
|
|
DATABASE_URL = URL.create(
|
|
drivername="postgresql",
|
|
username=DB_USER,
|
|
password=DB_PASSWORD,
|
|
host=DB_HOST,
|
|
port=DB_PORT,
|
|
database=DB_NAME,
|
|
query={
|
|
"sslmode": "require" # 🔥 MUST for Neon
|
|
}
|
|
)
|
|
|
|
# Create engine
|
|
engine = create_engine(
|
|
DATABASE_URL,
|
|
pool_pre_ping=True,
|
|
pool_recycle=300,
|
|
pool_size=5,
|
|
max_overflow=10,
|
|
echo=False
|
|
)
|
|
|
|
# Session
|
|
SessionLocal = sessionmaker(
|
|
autoflush=False,
|
|
autocommit=False,
|
|
bind=engine
|
|
)
|
|
|
|
# Base model
|
|
Base = declarative_base()
|
|
|
|
# Dependency for FastAPI
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
# Test connection
|
|
def test_connection():
|
|
try:
|
|
connection = psycopg2.connect(
|
|
host=DB_HOST,
|
|
database=DB_NAME,
|
|
user=DB_USER,
|
|
password=DB_PASSWORD,
|
|
port=DB_PORT,
|
|
sslmode="require"
|
|
)
|
|
print("✅ Neon PostgreSQL connection successful!")
|
|
connection.close()
|
|
|
|
except OperationalError as e:
|
|
print(f"❌ Error: {e}")
|
|
print("Failed to connect to Neon database.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
test_connection() |