113 lines
2.3 KiB
Go
113 lines
2.3 KiB
Go
package models
|
|
|
|
import (
|
|
"database/sql"
|
|
"github.com/google/uuid"
|
|
"time"
|
|
)
|
|
|
|
type ElectionModelInterface interface {
|
|
Insert(name string, tokens int, areVotersKnown bool, maxVoters int, Choices []string, ExpiresAt time.Time) (string, error)
|
|
GetById(id string) (*Election, error)
|
|
}
|
|
|
|
type ElectionModel struct {
|
|
DB *sql.DB
|
|
}
|
|
|
|
type Election struct {
|
|
ID string
|
|
Name string
|
|
Tokens int
|
|
AreVotersKnown bool
|
|
MaxVoters int
|
|
CreatedAt time.Time
|
|
ExpiresAt time.Time
|
|
Choices []string
|
|
}
|
|
|
|
func (e *ElectionModel) Insert(name string, tokens int, areVotersKnown bool, maxVoters int, choices []string, expiresAt time.Time) (string, error) {
|
|
tx, err := e.DB.Begin()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer tx.Rollback()
|
|
|
|
electionID, err := uuid.NewV7()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
_, err = tx.Exec(`
|
|
INSERT INTO elections (id, name, tokens, are_voters_known, max_voters, expires_at)
|
|
VALUES (?, ?, ?, ?, ?, ?)`, electionID, name, tokens, areVotersKnown, maxVoters, expiresAt)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
stmt, err := tx.Prepare(`
|
|
INSERT INTO choices (text, election_id)
|
|
VALUES (?, ?)`)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer stmt.Close()
|
|
|
|
for _, choice := range choices {
|
|
_, err = stmt.Exec(choice, electionID)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
}
|
|
|
|
if err = tx.Commit(); err != nil {
|
|
return "0", err
|
|
}
|
|
|
|
return electionID.String(), nil
|
|
}
|
|
|
|
func (e *ElectionModel) GetById(id string) (*Election, error) {
|
|
query := `
|
|
SELECT id, name, tokens, are_voters_known, max_voters, created_at, expires_at
|
|
FROM elections
|
|
WHERE id = ?
|
|
`
|
|
|
|
row := e.DB.QueryRow(query, id)
|
|
|
|
election := &Election{}
|
|
|
|
err := row.Scan(&election.ID, &election.Name, &election.Tokens, &election.AreVotersKnown, &election.MaxVoters, &election.CreatedAt, &election.ExpiresAt)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Retrieve choices for the election
|
|
queryChoices := `
|
|
SELECT text
|
|
FROM choices
|
|
WHERE election_id = ?
|
|
`
|
|
|
|
rows, err := e.DB.Query(queryChoices, id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
for rows.Next() {
|
|
var choice string
|
|
if err := rows.Scan(&choice); err != nil {
|
|
return nil, err
|
|
}
|
|
election.Choices = append(election.Choices, choice)
|
|
}
|
|
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return election, nil
|
|
}
|