Fix slow-ass code
This commit is contained in:
@ -6,7 +6,7 @@ import (
|
||||
)
|
||||
|
||||
type VoterModelInterface interface {
|
||||
Insert(identity string, electionID int) (int, error)
|
||||
InsertMultiple(identities []string, electionID int) ([]int, error)
|
||||
CountByElection(electionID int) (int, error)
|
||||
Exists(voterIdentity string, electionID int) (bool, error)
|
||||
}
|
||||
@ -15,27 +15,45 @@ type VoterModel struct {
|
||||
DB *sql.DB
|
||||
}
|
||||
|
||||
func (v *VoterModel) Insert(identity string, electionID int) (int, error) {
|
||||
func (v *VoterModel) InsertMultiple(identities []string, electionID int) ([]int, error) {
|
||||
tx, err := v.DB.Begin()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
result, err := tx.Exec(`
|
||||
// Prepare the statement once to reuse
|
||||
stmt, err := tx.Prepare(`
|
||||
INSERT INTO voters (identity, election_id)
|
||||
VALUES (?, ?)`,
|
||||
identity, electionID)
|
||||
VALUES (?, ?)`)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
return nil, err
|
||||
}
|
||||
defer stmt.Close()
|
||||
|
||||
// Store all voter IDs
|
||||
voterIDs := make([]int, 0, len(identities))
|
||||
|
||||
// Execute statement for each identity
|
||||
for _, identity := range identities {
|
||||
result, err := stmt.Exec(identity, electionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
voterID, err := result.LastInsertId()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
voterIDs = append(voterIDs, int(voterID))
|
||||
}
|
||||
|
||||
if err = tx.Commit(); err != nil {
|
||||
return 0, err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
voterId, err := result.LastInsertId()
|
||||
return int(voterId), nil
|
||||
return voterIDs, nil
|
||||
}
|
||||
|
||||
func (v *VoterModel) CountByElection(electionID int) (int, error) {
|
||||
|
Reference in New Issue
Block a user