2024-12-27 14:38:30 +01:00
|
|
|
package models
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ElectionModelInterface interface {
|
2024-12-30 23:01:32 +01:00
|
|
|
Insert(name string, tokens int, areVotersKnown bool, maxVoters int, Choices []string, ExpiresAt time.Time) (int, error)
|
2024-12-27 14:38:30 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
type ElectionModel struct {
|
|
|
|
DB *sql.DB
|
|
|
|
}
|
|
|
|
|
2024-12-30 23:01:32 +01:00
|
|
|
func (e *ElectionModel) Insert(name string, tokens int, areVotersKnown bool, maxVoters int, choices []string, expiresAt time.Time) (int, error) {
|
2024-12-30 20:41:28 +01:00
|
|
|
tx, err := e.DB.Begin()
|
|
|
|
if err != nil {
|
2024-12-30 23:01:32 +01:00
|
|
|
return 0, err
|
2024-12-30 20:41:28 +01:00
|
|
|
}
|
|
|
|
defer tx.Rollback()
|
|
|
|
|
2024-12-30 23:47:40 +01:00
|
|
|
stmt, err := tx.Prepare(`
|
|
|
|
INSERT INTO elections (name, tokens, are_voters_known, max_voters, expires_at)
|
|
|
|
VALUES (?, ?, ?, ?, ?)`)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
result, err := stmt.Exec(name, tokens, areVotersKnown, maxVoters, expiresAt)
|
2024-12-30 20:41:28 +01:00
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
electionID, err := result.LastInsertId()
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
2024-12-30 23:47:40 +01:00
|
|
|
stmt, err = tx.Prepare(`
|
2024-12-30 20:41:28 +01:00
|
|
|
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
|
2024-12-27 14:38:30 +01:00
|
|
|
}
|