Spaces:
Sleeping
Sleeping
Create database.py
Browse files- database.py +64 -0
database.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Database initialization and session management
|
| 3 |
+
"""
|
| 4 |
+
import os
|
| 5 |
+
from urllib.parse import urlparse, parse_qs
|
| 6 |
+
from sqlalchemy import create_engine, event
|
| 7 |
+
from sqlalchemy.orm import sessionmaker, Session
|
| 8 |
+
from sqlalchemy.pool import StaticPool
|
| 9 |
+
from models import Base
|
| 10 |
+
|
| 11 |
+
# Database URL from environment or use SQLite
|
| 12 |
+
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./hf_uploader.db")
|
| 13 |
+
|
| 14 |
+
# Parse and fix the database URL for TiDB Cloud
|
| 15 |
+
if DATABASE_URL and DATABASE_URL.startswith("mysql://"):
|
| 16 |
+
# Parse the URL
|
| 17 |
+
parsed = urlparse(DATABASE_URL)
|
| 18 |
+
|
| 19 |
+
# Build a clean URL without SSL parameters
|
| 20 |
+
clean_url = f"mysql+pymysql://{parsed.username}:{parsed.password}@{parsed.hostname}:{parsed.port or 3306}{parsed.path}"
|
| 21 |
+
|
| 22 |
+
# Add SSL parameters properly formatted for PyMySQL
|
| 23 |
+
clean_url += "?ssl_verify_cert=false&ssl_verify_identity=false"
|
| 24 |
+
|
| 25 |
+
DATABASE_URL = clean_url
|
| 26 |
+
|
| 27 |
+
# Create engine with proper configuration
|
| 28 |
+
if "sqlite" in DATABASE_URL:
|
| 29 |
+
engine = create_engine(
|
| 30 |
+
DATABASE_URL,
|
| 31 |
+
connect_args={"check_same_thread": False},
|
| 32 |
+
poolclass=StaticPool,
|
| 33 |
+
echo=False
|
| 34 |
+
)
|
| 35 |
+
# Enable foreign keys for SQLite
|
| 36 |
+
@event.listens_for(engine, "connect")
|
| 37 |
+
def set_sqlite_pragma(dbapi_conn, connection_record):
|
| 38 |
+
cursor = dbapi_conn.cursor()
|
| 39 |
+
cursor.execute("PRAGMA foreign_keys=ON")
|
| 40 |
+
cursor.close()
|
| 41 |
+
else:
|
| 42 |
+
engine = create_engine(
|
| 43 |
+
DATABASE_URL,
|
| 44 |
+
echo=False,
|
| 45 |
+
pool_pre_ping=True,
|
| 46 |
+
pool_recycle=3600
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
# Create session factory
|
| 50 |
+
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def init_db():
|
| 54 |
+
"""Initialize database tables"""
|
| 55 |
+
Base.metadata.create_all(bind=engine)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def get_db() -> Session:
|
| 59 |
+
"""Get database session"""
|
| 60 |
+
db = SessionLocal()
|
| 61 |
+
try:
|
| 62 |
+
yield db
|
| 63 |
+
finally:
|
| 64 |
+
db.close()
|