File size: 1,236 Bytes
29665de
 
3b5d530
 
29665de
 
c884cb3
 
 
 
 
 
423e1d1
c884cb3
3b5d530
423e1d1
c884cb3
 
 
 
29665de
c884cb3
 
 
29665de
c884cb3
 
 
 
 
 
07da77f
 
 
c884cb3
 
 
 
3b5d530
29665de
3b5d530
c884cb3
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
from __future__ import annotations

import os

from sqlalchemy import create_engine

# ---------------------------------------------------------------------------
# Lazy engine — built on first get_connection() call, not at import time.
# This allows db.py (and other modules) to import remote_db safely even when
# DATABASE_URL is not yet in the environment at import time.
# RuntimeError is raised when get_connection() is first called without a URL.
# ---------------------------------------------------------------------------

_engine = None


def _get_engine():
    global _engine
    if _engine is not None:
        return _engine

    database_url = os.getenv("DATABASE_URL", "").strip()
    if not database_url:
        raise RuntimeError("DATABASE_URL is not set")

    # CockroachDB requires the cockroachdb:// dialect for SQLAlchemy
    if database_url.startswith("postgresql://"):
        database_url = "cockroachdb://" + database_url[len("postgresql://"):]

    _engine = create_engine(
        database_url,
        pool_size=10,
        max_overflow=20,
        pool_timeout=60,
        pool_pre_ping=True,
        pool_recycle=300,
    )
    return _engine


def get_connection():
    return _get_engine().connect()