Paramjit Singh commited on
Commit
da7167e
Β·
unverified Β·
2 Parent(s): c14805c0774d12

Merge pull request #195 from rishab11250/feature/hf-token-column

Browse files
backend/app/database.py CHANGED
@@ -3,11 +3,13 @@ SQLAlchemy database setup with SQLite.
3
  Uses synchronous SQLAlchemy for simplicity and compatibility.
4
  """
5
  import os
6
- from sqlalchemy import create_engine
 
7
  from sqlalchemy.orm import sessionmaker, declarative_base
8
  from app.config import get_settings
9
 
10
  settings = get_settings()
 
11
 
12
  # ── Ensure data directory exists ─────────────────────
13
  db_path = settings.DATABASE_URL.replace("sqlite:///", "")
@@ -34,7 +36,34 @@ def get_db():
34
  db.close()
35
 
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  def init_db():
38
- """Create all tables on startup."""
39
  from app import models # noqa: F401 β€” import to register models
40
  Base.metadata.create_all(bind=engine)
 
 
3
  Uses synchronous SQLAlchemy for simplicity and compatibility.
4
  """
5
  import os
6
+ import logging
7
+ from sqlalchemy import create_engine, inspect, text
8
  from sqlalchemy.orm import sessionmaker, declarative_base
9
  from app.config import get_settings
10
 
11
  settings = get_settings()
12
+ logger = logging.getLogger(__name__)
13
 
14
  # ── Ensure data directory exists ─────────────────────
15
  db_path = settings.DATABASE_URL.replace("sqlite:///", "")
 
36
  db.close()
37
 
38
 
39
+ def _migrate_schema():
40
+ """Apply schema migrations for existing databases (SQLite-compatible).
41
+
42
+ SQLAlchemy's ``create_all`` only creates new tables and does **not**
43
+ add missing columns to existing tables. This helper fills that gap
44
+ for non-destructive changes such as new nullable columns.
45
+ """
46
+ inspector = inspect(engine)
47
+ existing_columns = {c["name"] for c in inspector.get_columns("users")}
48
+
49
+ migrations = [
50
+ ("users", "hf_token", "ALTER TABLE users ADD COLUMN hf_token VARCHAR(255)"),
51
+ ]
52
+
53
+ for table, column, ddl in migrations:
54
+ if column not in existing_columns:
55
+ try:
56
+ with engine.begin() as conn:
57
+ conn.execute(text(ddl))
58
+ logger.info("Migration: added column %s.%s", table, column)
59
+ except Exception:
60
+ logger.warning(
61
+ "Migration skipped (may already exist): %s.%s", table, column
62
+ )
63
+
64
+
65
  def init_db():
66
+ """Create all tables on startup and apply schema migrations."""
67
  from app import models # noqa: F401 β€” import to register models
68
  Base.metadata.create_all(bind=engine)
69
+ _migrate_schema()
backend/app/models.py CHANGED
@@ -22,6 +22,7 @@ class User(Base):
22
  is_admin = Column(Boolean, default=False)
23
  created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
24
  last_login = Column(DateTime, nullable=True, index=True)
 
25
 
26
  # Relationships
27
  documents = relationship("Document", back_populates="owner", cascade="all, delete-orphan")
 
22
  is_admin = Column(Boolean, default=False)
23
  created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
24
  last_login = Column(DateTime, nullable=True, index=True)
25
+ hf_token = Column(String(255), nullable=True)
26
 
27
  # Relationships
28
  documents = relationship("Document", back_populates="owner", cascade="all, delete-orphan")
backend/app/schemas.py CHANGED
@@ -53,11 +53,17 @@ class RefreshRequest(BaseModel):
53
  refresh_token: str
54
 
55
 
 
 
 
 
 
56
  class UserResponse(BaseModel):
57
  id: str
58
  username: str
59
  email: str
60
  is_admin: bool
 
61
  created_at: datetime
62
 
63
  class Config:
 
53
  refresh_token: str
54
 
55
 
56
+ class HFTokenUpdate(BaseModel):
57
+ """Request schema for updating the user's HuggingFace token."""
58
+ hf_token: str
59
+
60
+
61
  class UserResponse(BaseModel):
62
  id: str
63
  username: str
64
  email: str
65
  is_admin: bool
66
+ hf_token: Optional[str] = None
67
  created_at: datetime
68
 
69
  class Config: