49 lines
1.4 KiB
Python
49 lines
1.4 KiB
Python
from flask_sqlalchemy import SQLAlchemy
|
|
from flask import g
|
|
import os
|
|
import sqlite3
|
|
from pathlib import Path
|
|
|
|
def get_db():
|
|
if 'db' not in g:
|
|
db_path = Path(__file__).parent / 'database' / 'db.sqlite3'
|
|
db_path.parent.mkdir(exist_ok=True) # Ensure /database folder exists
|
|
g.db = sqlite3.connect(db_path)
|
|
return g.db
|
|
|
|
def create_leaderboard_table():
|
|
db = get_db()
|
|
cursor = db.cursor()
|
|
cursor.execute('''
|
|
CREATE TABLE IF NOT EXISTS leaderboard (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
username TEXT,
|
|
problem_id INTEGER,
|
|
runtime REAL,
|
|
memory_used INTEGER,
|
|
line_number INTEGER,
|
|
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
)
|
|
''')
|
|
db.commit()
|
|
|
|
def log_leaderboard(username, problem_id, runtime, memory_used, line_number):
|
|
db = get_db()
|
|
cursor = db.cursor()
|
|
cursor.execute('''
|
|
INSERT INTO leaderboard (username, problem_id, runtime, memory_used, line_number)
|
|
VALUES (?, ?, ?, ?, ?)
|
|
''', (username, problem_id, runtime, memory_used, line_number))
|
|
db.commit()
|
|
|
|
def get_leaderboard():
|
|
db = get_db()
|
|
cursor = db.cursor()
|
|
cursor.execute('''
|
|
SELECT username, problem_id, runtime, memory_used, line_number, timestamp
|
|
FROM leaderboard
|
|
ORDER BY runtime ASC, memory_used ASC
|
|
LIMIT 20
|
|
''')
|
|
return cursor.fetchall()
|