CREATE TABLE election (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    tokens INTEGER NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE choices (
    text TEXT NOT NULL,
    election_id INTEGER NOT NULL,
    PRIMARY KEY (text, election_id),
    FOREIGN KEY (election_id) REFERENCES election (id)
);

CREATE TABLE voters (
    passcode TEXT NOT NULL,
    election_id INTEGER NOT NULL,
    PRIMARY KEY (passcode, election_id),
    FOREIGN KEY (election_id) REFERENCES election (id)
);

CREATE TABLE votes (
    voter_passcode TEXT NOT NULL,
    election_id INTEGER NOT NULL,
    choice_text TEXT NOT NULL,
    tokens INTEGER NOT NULL,
    calculated_vote_count GENERATED ALWAYS AS (sqrt(tokens)) VIRTUAL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (voter_passcode, choice_text),
    FOREIGN KEY (voter_passcode, election_id) REFERENCES voters (passcode, election_id),
    FOREIGN KEY (choice_text, election_id) REFERENCES choices (text, election_id)
);

PRAGMA foreign_keys = ON; -- run after opening the connection so foreign key constraints are checked