37 lines
622 B
Go
37 lines
622 B
Go
|
package models
|
||
|
|
||
|
import (
|
||
|
"database/sql"
|
||
|
)
|
||
|
|
||
|
type VoterModelInterface interface {
|
||
|
Insert(identity string, electionID int) (int, error)
|
||
|
}
|
||
|
|
||
|
type VoterModel struct {
|
||
|
DB *sql.DB
|
||
|
}
|
||
|
|
||
|
func (v *VoterModel) Insert(identity string, electionID int) (int, error) {
|
||
|
tx, err := v.DB.Begin()
|
||
|
if err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
defer tx.Rollback()
|
||
|
|
||
|
result, err := tx.Exec(`
|
||
|
INSERT INTO voters (identity, election_id)
|
||
|
VALUES (?, ?)`,
|
||
|
identity, electionID)
|
||
|
if err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
|
||
|
if err = tx.Commit(); err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
|
||
|
voterId, err := result.LastInsertId()
|
||
|
return int(voterId), nil
|
||
|
}
|