Skip to content

Commit ef3d6ea

Browse files
committed
fix: lazy DB engine init for CI (no DATABASE_URL in test)
1 parent 9c7db54 commit ef3d6ea

1 file changed

Lines changed: 24 additions & 8 deletions

File tree

backend/app/database.py

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,35 @@
44

55
DATABASE_URL = os.environ.get("DATABASE_URL", "")
66

7-
engine = create_engine(DATABASE_URL, pool_pre_ping=True)
7+
_engine = None
8+
_SessionLocal = None
89

9-
# Set search_path to heynom schema on every new connection
10-
@event.listens_for(engine, "connect")
11-
def set_search_path(dbapi_connection, connection_record):
12-
cursor = dbapi_connection.cursor()
13-
cursor.execute("SET search_path TO heynom, public")
14-
cursor.close()
1510

16-
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
11+
def _get_engine():
12+
global _engine
13+
if _engine is None:
14+
if not DATABASE_URL:
15+
raise RuntimeError("DATABASE_URL not set")
16+
_engine = create_engine(DATABASE_URL, pool_pre_ping=True)
17+
18+
@event.listens_for(_engine, "connect")
19+
def set_search_path(dbapi_connection, connection_record):
20+
cursor = dbapi_connection.cursor()
21+
cursor.execute("SET search_path TO heynom, public")
22+
cursor.close()
23+
24+
return _engine
25+
26+
27+
def _get_session_local():
28+
global _SessionLocal
29+
if _SessionLocal is None:
30+
_SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=_get_engine())
31+
return _SessionLocal
1732

1833

1934
def get_db():
35+
SessionLocal = _get_session_local()
2036
db = SessionLocal()
2137
try:
2238
yield db

0 commit comments

Comments
 (0)