-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
33 lines (23 loc) · 894 Bytes
/
database.py
File metadata and controls
33 lines (23 loc) · 894 Bytes
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
import os
from sqlalchemy import text
from sqlmodel import Session, SQLModel, create_engine
DATABASE_URL = os.environ.get("DATABASE_URL", "")
if not DATABASE_URL:
raise RuntimeError(
"DATABASE_URL environment variable is required. "
"On Convox, link a postgres resource. "
"For local dev, see .env.example."
)
# Convox provides postgres:// but SQLAlchemy requires postgresql://
if DATABASE_URL.startswith("postgres://"):
DATABASE_URL = DATABASE_URL.replace("postgres://", "postgresql://", 1)
engine = create_engine(DATABASE_URL, pool_pre_ping=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def get_session():
with Session(engine) as session:
yield session
def check_db():
"""Run a simple query to verify database connectivity."""
with engine.connect() as conn:
conn.execute(text("SELECT 1"))