Updated
This commit is contained in:
@@ -1,31 +1,48 @@
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
import psycopg2
|
||||
import pyodbc
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Force reload environment variables from .env, ignoring system vars.
|
||||
load_dotenv(override=True)
|
||||
|
||||
DB_HOST = os.getenv("DB_HOST")
|
||||
DB_PORT = os.getenv("DB_PORT")
|
||||
DB_NAME = os.getenv("DB_NAME")
|
||||
DB_USER = os.getenv("DB_USER")
|
||||
DB_PASSWORD = os.getenv("DB_PASSWORD")
|
||||
|
||||
def _get_required_env(name: str) -> str:
|
||||
value = os.getenv(name, "").strip()
|
||||
if not value:
|
||||
raise RuntimeError(f"Missing {name} environment variable.")
|
||||
return value
|
||||
|
||||
|
||||
def connect_to_db() -> Optional[psycopg2.extensions.connection]:
|
||||
"""Establish a connection to the PostgreSQL database."""
|
||||
def _build_conn_str() -> str:
|
||||
explicit = os.getenv("MSSQL_CONN_STR", "").strip()
|
||||
if explicit:
|
||||
return explicit
|
||||
|
||||
driver = os.getenv("MSSQL_DRIVER", "ODBC Driver 18 for SQL Server").strip()
|
||||
server = _get_required_env("MSSQL_SERVER")
|
||||
database = _get_required_env("MSSQL_DATABASE")
|
||||
user = _get_required_env("MSSQL_USER")
|
||||
password = _get_required_env("MSSQL_PASSWORD")
|
||||
encrypt = os.getenv("MSSQL_ENCRYPT", "yes").strip() or "yes"
|
||||
trust_cert = os.getenv("MSSQL_TRUST_SERVER_CERT", "yes").strip() or "yes"
|
||||
|
||||
return (
|
||||
f"DRIVER={{{driver}}};"
|
||||
f"SERVER={server};"
|
||||
f"DATABASE={database};"
|
||||
f"UID={user};"
|
||||
f"PWD={password};"
|
||||
f"Encrypt={encrypt};"
|
||||
f"TrustServerCertificate={trust_cert};"
|
||||
)
|
||||
|
||||
|
||||
def connect_to_mssql() -> Optional[pyodbc.Connection]:
|
||||
"""Establish a connection to the Microsoft SQL Server database."""
|
||||
try:
|
||||
return psycopg2.connect(
|
||||
host=DB_HOST,
|
||||
port=DB_PORT,
|
||||
database=DB_NAME,
|
||||
user=DB_USER,
|
||||
password=DB_PASSWORD,
|
||||
# Set the client encoding to UTF-8.
|
||||
options="-c client_encoding=utf8",
|
||||
)
|
||||
except psycopg2.Error as exc:
|
||||
print(f"Error connecting to PostgreSQL database: {exc}")
|
||||
return pyodbc.connect(_build_conn_str())
|
||||
except pyodbc.Error as exc:
|
||||
print(f"Error connecting to MSSQL database: {exc}")
|
||||
return None
|
||||
|
||||
Reference in New Issue
Block a user