mock-api-mcp-server / database.py
abdullah9873's picture
Upload database.py with huggingface_hub
b1b7d52 verified
Raw History Blame Contribute Delete
2.18 kB
import os
import json
import sys
from datetime import datetime
from typing import List, Optional
from dotenv import load_dotenv
# CRITICAL: Load .env BEFORE reading DATABASE_URL
# This file runs at import time, so we must load .env here
load_dotenv()
from sqlalchemy import String, DateTime, JSON, create_engine, Text
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, sessionmaker
# Default to local SQLite, but support PostgreSQL via environment variable
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./mock_api.db")
# Debug: Print which database we are connecting to (remove in production)
print(f"[DB] Connecting to: {'Neon Postgres' if 'neon' in DATABASE_URL else 'Local SQLite'}", file=sys.stderr)
# Neon/Postgres fix: SQLAlchemy requires postgresql:// instead of postgres://
if DATABASE_URL.startswith("postgres://"):
DATABASE_URL = DATABASE_URL.replace("postgres://", "postgresql://", 1)
# Remove channel_binding parameter (not supported by psycopg2)
if "channel_binding" in DATABASE_URL:
# Remove &channel_binding=require or ?channel_binding=require
import re
DATABASE_URL = re.sub(r'[&?]channel_binding=[^&]*', '', DATABASE_URL)
engine_args = {}
if "sqlite" in DATABASE_URL:
engine_args["connect_args"] = {"check_same_thread": False}
# For Postgres, sslmode is already in the URL, no need for connect_args
engine = create_engine(DATABASE_URL, **engine_args)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
class Base(DeclarativeBase):
pass
class MockApiSchema(Base):
__tablename__ = "mock_apis"
id: Mapped[str] = mapped_column(String, primary_key=True, index=True)
name: Mapped[str] = mapped_column(String)
user_id: Mapped[str] = mapped_column(String, index=True)
expires_at: Mapped[datetime] = mapped_column(DateTime)
# Store the actual mock data as JSON for flexibility
mock_data: Mapped[dict] = mapped_column(JSON, default={})
def init_db():
Base.metadata.create_all(bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()