abdullah9873 commited on
Commit
b1b7d52
·
verified ·
1 Parent(s): 7efb19e

Upload database.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. database.py +61 -0
database.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import sys
4
+ from datetime import datetime
5
+ from typing import List, Optional
6
+ from dotenv import load_dotenv
7
+
8
+ # CRITICAL: Load .env BEFORE reading DATABASE_URL
9
+ # This file runs at import time, so we must load .env here
10
+ load_dotenv()
11
+
12
+ from sqlalchemy import String, DateTime, JSON, create_engine, Text
13
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, sessionmaker
14
+
15
+ # Default to local SQLite, but support PostgreSQL via environment variable
16
+ DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./mock_api.db")
17
+
18
+ # Debug: Print which database we are connecting to (remove in production)
19
+ print(f"[DB] Connecting to: {'Neon Postgres' if 'neon' in DATABASE_URL else 'Local SQLite'}", file=sys.stderr)
20
+
21
+ # Neon/Postgres fix: SQLAlchemy requires postgresql:// instead of postgres://
22
+ if DATABASE_URL.startswith("postgres://"):
23
+ DATABASE_URL = DATABASE_URL.replace("postgres://", "postgresql://", 1)
24
+
25
+ # Remove channel_binding parameter (not supported by psycopg2)
26
+ if "channel_binding" in DATABASE_URL:
27
+ # Remove &channel_binding=require or ?channel_binding=require
28
+ import re
29
+ DATABASE_URL = re.sub(r'[&?]channel_binding=[^&]*', '', DATABASE_URL)
30
+
31
+ engine_args = {}
32
+ if "sqlite" in DATABASE_URL:
33
+ engine_args["connect_args"] = {"check_same_thread": False}
34
+ # For Postgres, sslmode is already in the URL, no need for connect_args
35
+
36
+ engine = create_engine(DATABASE_URL, **engine_args)
37
+
38
+ SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
39
+
40
+ class Base(DeclarativeBase):
41
+ pass
42
+
43
+ class MockApiSchema(Base):
44
+ __tablename__ = "mock_apis"
45
+
46
+ id: Mapped[str] = mapped_column(String, primary_key=True, index=True)
47
+ name: Mapped[str] = mapped_column(String)
48
+ user_id: Mapped[str] = mapped_column(String, index=True)
49
+ expires_at: Mapped[datetime] = mapped_column(DateTime)
50
+ # Store the actual mock data as JSON for flexibility
51
+ mock_data: Mapped[dict] = mapped_column(JSON, default={})
52
+
53
+ def init_db():
54
+ Base.metadata.create_all(bind=engine)
55
+
56
+ def get_db():
57
+ db = SessionLocal()
58
+ try:
59
+ yield db
60
+ finally:
61
+ db.close()