File size: 2,175 Bytes
b1b7d52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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()