Files

60 lines
1.9 KiB
Python

import sqlite3
import uuid
from contextlib import closing
from datetime import datetime
from pathlib import Path
from flask import g
DB_PATH = Path(__file__).parent / "results.db"
def init_db():
with closing(sqlite3.connect(DB_PATH)) as con:
con.execute("PRAGMA journal_mode=WAL") # bessere Parallelität beim Schreiben
con.executescript("""
CREATE TABLE IF NOT EXISTS participants (
id TEXT PRIMARY KEY, -- zufällige ID pro Teilnahme
name TEXT NOT NULL,
created TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS ratings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
participant_id TEXT NOT NULL,
song_id NOT NULL, -- bewusst ohne Typ: bleibt Zahl oder Text wie in songs.json
choice TEXT NOT NULL, -- 'a', 'b' oder 'non'
truth TEXT NOT NULL, -- Position des Originals ('a' oder 'b')
original_chosen INTEGER NOT NULL, -- 1 = Original als besser gewählt
edit TEXT, -- welche Bearbeitung gespielt wurde
created TEXT NOT NULL,
UNIQUE (participant_id, song_id) -- Doppelklick erzeugt keine zweite Zeile
);
""")
con.commit()
def get_db():
if "db" not in g:
g.db = sqlite3.connect(DB_PATH, timeout=10) # wartet bei gleichzeitigem Schreiben
g.db.row_factory = sqlite3.Row
return g.db
def close_db(_exc=None):
db = g.pop("db", None)
if db is not None:
db.close()
def now():
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def create_participant(name):
pid = uuid.uuid4().hex
db = get_db()
with db:
db.execute("INSERT INTO participants (id, name, created) VALUES (?, ?, ?)",
(pid, name, now()))
return pid