package models import ( "database/sql" "time" ) type ElectionModelInterface interface { Insert(name string, tokens int, areVotersKnown bool, maxVoters int, Choices []string, ExpiresAt time.Time) (int, error) GetById(id int) (*Election, error) } type ElectionModel struct { DB *sql.DB } type Election struct { ID int 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) (int, error) { tx, err := e.DB.Begin() if err != nil { return 0, 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 } func (e *ElectionModel) GetById(id int) (*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 }