Spaces:
Sleeping
Sleeping
File size: 9,492 Bytes
c5292d8 |
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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 |
"""Database models and operations for instructor system."""
import json
from datetime import datetime
from typing import Any
from sqlalchemy import (
Column,
DateTime,
Float,
Integer,
String,
Text,
create_engine,
)
from sqlalchemy.orm import declarative_base, sessionmaker
from shared.config import settings
from shared.logger import setup_logger
logger = setup_logger(__name__)
Base = declarative_base()
class Task(Base):
"""Task records sent to students."""
__tablename__ = "tasks"
id = Column(Integer, primary_key=True)
timestamp = Column(DateTime, default=datetime.utcnow, nullable=False)
email = Column(String(255), nullable=False, index=True)
task = Column(String(255), nullable=False, index=True)
round = Column(Integer, nullable=False)
nonce = Column(String(255), nullable=False, unique=True)
brief = Column(Text, nullable=False)
attachments = Column(Text, nullable=False) # JSON serialized
checks = Column(Text, nullable=False) # JSON serialized
evaluation_url = Column(String(512), nullable=False)
endpoint = Column(String(512), nullable=False)
statuscode = Column(Integer, nullable=True)
secret = Column(String(255), nullable=False)
def to_dict(self) -> dict[str, Any]:
"""Convert to dictionary."""
return {
"id": self.id,
"timestamp": self.timestamp.isoformat() if self.timestamp else None,
"email": self.email,
"task": self.task,
"round": self.round,
"nonce": self.nonce,
"brief": self.brief,
"attachments": json.loads(self.attachments) if self.attachments else [],
"checks": json.loads(self.checks) if self.checks else [],
"evaluation_url": self.evaluation_url,
"endpoint": self.endpoint,
"statuscode": self.statuscode,
}
class Repo(Base):
"""Repository submissions from students."""
__tablename__ = "repos"
id = Column(Integer, primary_key=True)
timestamp = Column(DateTime, default=datetime.utcnow, nullable=False)
email = Column(String(255), nullable=False, index=True)
task = Column(String(255), nullable=False, index=True)
round = Column(Integer, nullable=False)
nonce = Column(String(255), nullable=False, unique=True)
repo_url = Column(String(512), nullable=False)
commit_sha = Column(String(255), nullable=False)
pages_url = Column(String(512), nullable=False)
def to_dict(self) -> dict[str, Any]:
"""Convert to dictionary."""
return {
"id": self.id,
"timestamp": self.timestamp.isoformat() if self.timestamp else None,
"email": self.email,
"task": self.task,
"round": self.round,
"nonce": self.nonce,
"repo_url": self.repo_url,
"commit_sha": self.commit_sha,
"pages_url": self.pages_url,
}
class Result(Base):
"""Evaluation results."""
__tablename__ = "results"
id = Column(Integer, primary_key=True)
timestamp = Column(DateTime, default=datetime.utcnow, nullable=False)
email = Column(String(255), nullable=False, index=True)
task = Column(String(255), nullable=False, index=True)
round = Column(Integer, nullable=False)
repo_url = Column(String(512), nullable=False)
commit_sha = Column(String(255), nullable=False)
pages_url = Column(String(512), nullable=False)
check = Column(String(512), nullable=False)
score = Column(Float, nullable=False)
reason = Column(Text, nullable=False)
logs = Column(Text, nullable=True)
def to_dict(self) -> dict[str, Any]:
"""Convert to dictionary."""
return {
"id": self.id,
"timestamp": self.timestamp.isoformat() if self.timestamp else None,
"email": self.email,
"task": self.task,
"round": self.round,
"repo_url": self.repo_url,
"commit_sha": self.commit_sha,
"pages_url": self.pages_url,
"check": self.check,
"score": self.score,
"reason": self.reason,
"logs": self.logs,
}
class Database:
"""Database manager for instructor system."""
def __init__(self, database_url: str | None = None) -> None:
"""Initialize database connection.
Args:
database_url: Database URL (uses settings if not provided)
"""
self.database_url = database_url or settings.database_url
self.engine = create_engine(self.database_url, echo=False)
self.SessionLocal = sessionmaker(bind=self.engine)
logger.info(f"Initialized database: {self.database_url}")
def create_tables(self) -> None:
"""Create all tables."""
Base.metadata.create_all(self.engine)
logger.info("Created database tables")
def drop_tables(self) -> None:
"""Drop all tables (use with caution)."""
Base.metadata.drop_all(self.engine)
logger.warning("Dropped all database tables")
def get_session(self):
"""Get database session."""
return self.SessionLocal()
# Task operations
def add_task(self, task_data: dict[str, Any]) -> Task:
"""Add a task record.
Args:
task_data: Task data dictionary
Returns:
Created task record
"""
session = self.get_session()
try:
task = Task(
email=task_data["email"],
task=task_data["task"],
round=task_data["round"],
nonce=task_data["nonce"],
brief=task_data["brief"],
attachments=json.dumps(task_data.get("attachments", [])),
checks=json.dumps(task_data.get("checks", [])),
evaluation_url=task_data["evaluation_url"],
endpoint=task_data["endpoint"],
statuscode=task_data.get("statuscode"),
secret=task_data["secret"],
)
session.add(task)
session.commit()
session.refresh(task)
logger.info(f"Added task: {task.task}, round {task.round}")
return task
finally:
session.close()
def get_task_by_nonce(self, nonce: str) -> Task | None:
"""Get task by nonce.
Args:
nonce: Task nonce
Returns:
Task or None
"""
session = self.get_session()
try:
return session.query(Task).filter(Task.nonce == nonce).first()
finally:
session.close()
def task_exists(self, email: str, task: str, round: int) -> bool:
"""Check if task exists.
Args:
email: Student email
task: Task ID
round: Round number
Returns:
True if exists
"""
session = self.get_session()
try:
return (
session.query(Task)
.filter(Task.email == email, Task.task == task, Task.round == round)
.first()
is not None
)
finally:
session.close()
# Repo operations
def add_repo(self, repo_data: dict[str, Any]) -> Repo:
"""Add a repo submission.
Args:
repo_data: Repo data dictionary
Returns:
Created repo record
"""
session = self.get_session()
try:
repo = Repo(**repo_data)
session.add(repo)
session.commit()
session.refresh(repo)
logger.info(f"Added repo: {repo.task}, round {repo.round}")
return repo
finally:
session.close()
def get_repos(self, email: str | None = None) -> list[Repo]:
"""Get repo submissions.
Args:
email: Filter by email (optional)
Returns:
List of repos
"""
session = self.get_session()
try:
query = session.query(Repo)
if email:
query = query.filter(Repo.email == email)
return query.all()
finally:
session.close()
# Result operations
def add_result(self, result_data: dict[str, Any]) -> Result:
"""Add an evaluation result.
Args:
result_data: Result data dictionary
Returns:
Created result record
"""
session = self.get_session()
try:
result = Result(**result_data)
session.add(result)
session.commit()
session.refresh(result)
logger.debug(f"Added result: {result.task}, {result.check}")
return result
finally:
session.close()
def get_results(
self, email: str | None = None, task: str | None = None
) -> list[Result]:
"""Get evaluation results.
Args:
email: Filter by email (optional)
task: Filter by task (optional)
Returns:
List of results
"""
session = self.get_session()
try:
query = session.query(Result)
if email:
query = query.filter(Result.email == email)
if task:
query = query.filter(Result.task == task)
return query.all()
finally:
session.close()
|