-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
41 lines (34 loc) · 1.51 KB
/
database.py
File metadata and controls
41 lines (34 loc) · 1.51 KB
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
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import os
from dotenv import load_dotenv
load_dotenv()
# Por defecto usa SQLite si no hay URL de Postgres configurada
# Vercel usa "POSTGRES_URL", "POSTGRES_PRISMA_URL", etc. Intentamos leer POSTGRES_URL si DATABASE_URL falla.
DATABASE_URL = os.getenv("DATABASE_URL")
if not DATABASE_URL:
DATABASE_URL = os.getenv("POSTGRES_URL")
if not DATABASE_URL:
# FALLBACK DIAGNOSTIC
print("WARNING: No DATABASE_URL or POSTGRES_URL found. Falling back to SQLite.")
# On Vercel, root is read-only. We must use /tmp if we really want to try SQLite (data will be lost)
if os.environ.get("VERCEL") or os.getcwd().startswith("/var/task"):
print("ERROR: Running on Vercel with SQLite (ReadOnly FS). This will likely crash.")
DATABASE_URL = "sqlite:///./crm.db"
else:
print(f"INFO: Database URL found (starts with {DATABASE_URL[:10]}...)")
# Fix para SQLAlchemy que removió soporte para 'postgres://' (Vercel lo usa por defecto)
if DATABASE_URL and DATABASE_URL.startswith("postgres://"):
DATABASE_URL = DATABASE_URL.replace("postgres://", "postgresql://", 1)
engine = create_engine(
DATABASE_URL, connect_args={"check_same_thread": False} if "sqlite" in DATABASE_URL else {}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()