Insert election with uuid instead of auto-generated id
This commit is contained in:
@ -2,12 +2,13 @@ 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) (int, error)
|
||||
GetById(id int) (*Election, error)
|
||||
Insert(name string, tokens int, areVotersKnown bool, maxVoters int, Choices []string, ExpiresAt time.Time) (string, error)
|
||||
GetById(id string) (*Election, error)
|
||||
}
|
||||
|
||||
type ElectionModel struct {
|
||||
@ -15,7 +16,7 @@ type ElectionModel struct {
|
||||
}
|
||||
|
||||
type Election struct {
|
||||
ID int
|
||||
ID string
|
||||
Name string
|
||||
Tokens int
|
||||
AreVotersKnown bool
|
||||
@ -25,48 +26,48 @@ type Election struct {
|
||||
Choices []string
|
||||
}
|
||||
|
||||
func (e *ElectionModel) Insert(name string, tokens int, areVotersKnown bool, maxVoters int, choices []string, expiresAt time.Time) (int, error) {
|
||||
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 0, err
|
||||
return "", 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)
|
||||
electionID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
return "", err
|
||||
}
|
||||
|
||||
electionID, err := result.LastInsertId()
|
||||
_, 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 0, err
|
||||
return "", err
|
||||
}
|
||||
|
||||
stmt, err := tx.Prepare(`
|
||||
INSERT INTO choices (text, election_id)
|
||||
VALUES (?, ?)`)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
return "", err
|
||||
}
|
||||
defer stmt.Close()
|
||||
|
||||
for _, choice := range choices {
|
||||
_, err = stmt.Exec(choice, electionID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
if err = tx.Commit(); err != nil {
|
||||
return 0, err
|
||||
return "0", err
|
||||
}
|
||||
|
||||
return int(electionID), nil
|
||||
return electionID.String(), nil
|
||||
}
|
||||
|
||||
func (e *ElectionModel) GetById(id int) (*Election, error) {
|
||||
func (e *ElectionModel) GetById(id string) (*Election, error) {
|
||||
query := `
|
||||
SELECT id, name, tokens, are_voters_known, max_voters, created_at, expires_at
|
||||
FROM elections
|
||||
|
Reference in New Issue
Block a user