package store import "database/sql" // References to all available prepared statements. var ( votingInsert *sql.Stmt votingSelect *sql.Stmt voteEligible *sql.Stmt voteInsert *sql.Stmt voteSelect *sql.Stmt ) // initCreateTables takes an sql connection and creates all tables if they // don't yet exist. func initCreateTables(db *sql.DB) { var err error createTables := ` CREATE TABLE IF NOT EXISTS voting ( id TEXT PRIMARY KEY, referendum TEXT NOT NULL, created DATETIME WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, deadline DATETIME WITHOUT TIME ZONE NOT NULL, quorum TEXT NOT NULL DEFAULT 'SIMPLE', threshold TEXT NOT NULL DEFAULT 'SIMPLE', electors TEXT, anonymous BOOL NOT NULL DEFAULT false ); CREATE TABLE IF NOT EXISTS vote ( id BLOB PRIMARY KEY, voting TEXT NOT NULL, elector TEXT NOT NULL, choice TEXT NOT NULL, timestamp DATETIME WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY(voting) REFERENCES voting(id) ); CREATE INDEX IF NOT EXISTS vote_voting ON vote ( voting ); ` if _, err = db.Exec(createTables); err != nil { panic(err) } } // initStmts takes an initialized sql connection and initializes all prepared // statements. func initStmts(db *sql.DB) { initStmtVotingInsert(db) initStmtVotingSelect(db) initStmtVoteEligible(db) initStmtVoteInsert(db) initStmtVoteSelect(db) } func initStmtVotingInsert(db *sql.DB) { var err error if votingInsert, err = db.Prepare(` INSERT INTO voting ( id, referendum, deadline, quorum, threshold, electors, anonymous ) VALUES (?, ?, ?, ?, ?, ?, ?); `); err != nil { panic(err) } } func initStmtVotingSelect(db *sql.DB) { var err error if votingSelect, err = db.Prepare(` SELECT referendum, deadline, quorum, threshold, electors, anonymous FROM voting WHERE id = ?; `); err != nil { panic(err) } } func initStmtVoteEligible(db *sql.DB) { var err error if voteEligible, err = db.Prepare(` SELECT id, referendum, created, deadline, quorum, threshold FROM voting WHERE id = ? AND deadline > datetime('now') AND ( electors IS NULL OR ',' || electors || ',' LIKE '%,' || ? || ',%' ) LIMIT 1; `); err != nil { panic(err) } } func initStmtVoteInsert(db *sql.DB) { var err error if voteInsert, err = db.Prepare(` INSERT INTO vote ( id, voting, elector, choice ) VALUES ( ?, ?, ?, ? ); `); err != nil { panic(err) } } func initStmtVoteSelect(db *sql.DB) { var err error if voteSelect, err = db.Prepare(` SELECT id, elector, choice, timestamp FROM vote WHERE voting = ?; `); err != nil { panic(err) } }