This repository has been archived on 2026-03-15. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
cau-praktikum/app/db.py
T

69 lines
2.2 KiB
Python

import sqlite3
from flask import g
DATABASE = 'sqlite.db'
def get_db():
if 'db' not in g:
g.db = sqlite3.connect(DATABASE)
g.db.row_factory = sqlite3.Row
return g.db
def close_db(e=None):
db = g.pop('db', None)
if db is not None:
db.close()
def init_db(app):
with app.app_context():
db = get_db()
db.execute("PRAGMA journal_mode=WAL;")
db.execute("PRAGMA foreign_keys=ON;")
# create inital tables
db.executescript("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,username TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS games (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
final_fen TEXT,
termination TEXT CHECK(termination IN ('checkmate', 'resignation', 'timeout', 'draw', 'other'))
);
CREATE TABLE IF NOT EXISTS game_players (
game_id INTEGER NOT NULL,
player_id INTEGER NOT NULL,
color TEXT NOT NULL CHECK(color IN ('white', 'black')),
PRIMARY KEY (game_id, player_id),
UNIQUE (game_id, color),
FOREIGN KEY (game_id) REFERENCES games(id) ON DELETE CASCADE,
FOREIGN KEY (player_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_game_players_game_id
ON game_players(game_id);
CREATE INDEX IF NOT EXISTS idx_game_players_player_id
ON game_players(player_id);
CREATE TABLE IF NOT EXISTS friendships (
requester_id INTEGER NOT NULL,
addressee_id INTEGER NOT NULL,
status TEXT NOT NULL CHECK(status IN ('pending','accepted','blocked')),
PRIMARY KEY (requester_id, addressee_id),
FOREIGN KEY (requester_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (addressee_id) REFERENCES users(id) ON DELETE CASCADE
);
"""
)
db.commit()