Files
qv/internal/models/elections.go

58 lines
1.2 KiB
Go

package models
import (
"database/sql"
"fmt"
"time"
)
type ElectionModelInterface interface {
Insert(name string, tokens int, areVotersKnown bool, maxVoters *int, Choices []string, ExpiresAt time.Time) (int, error)
}
type ElectionModel struct {
DB *sql.DB
}
func (e *ElectionModel) Insert(name string, tokens int, areVotersKnown bool, maxVoters *int, choices []string, expiresAt time.Time) (int, error) {
tx, err := e.DB.Begin()
if err != nil {
return 0, fmt.Errorf("begin transaction: %w", err)
}
defer tx.Rollback()
result, err := tx.Exec(`
INSERT INTO elections (name, tokens, are_voters_known, max_voters, expires_at)
VALUES (?, ?, ?, ?, ?)`,
name, tokens, areVotersKnown, maxVoters, expiresAt)
if err != nil {
return 0, err
}
electionID, err := result.LastInsertId()
if err != nil {
return 0, err
}
stmt, err := tx.Prepare(`
INSERT INTO choices (text, election_id)
VALUES (?, ?)`)
if err != nil {
return 0, err
}
defer stmt.Close()
for _, choice := range choices {
_, err = stmt.Exec(choice, electionID)
if err != nil {
return 0, err
}
}
if err = tx.Commit(); err != nil {
return 0, err
}
return int(electionID), nil
}