Améliorer insert error management

This commit is contained in:
Victor Lacasse-Beaudoin 2023-05-25 05:03:46 -04:00
parent ef4e9f7050
commit 3e37e8ffef

View file

@ -1,6 +1,7 @@
package data package data
import ( import (
"errors"
"fmt" "fmt"
"git.agecem.com/agecem/bottin/v4/models" "git.agecem.com/agecem/bottin/v4/models"
@ -68,12 +69,23 @@ func (d *DataClient) InsertMembres(membres []models.Membre) (int64, error) {
} }
for _, membre := range membres { for _, membre := range membres {
_, err := tx.NamedExec("INSERT INTO membres (id, last_name, first_name, prefered_name, programme_id) VALUES (:id, :last_name, :first_name, :prefered_name, :programme_id);", &membre) if membre.ID == "" {
tx.Rollback()
return 0, errors.New("Cannot insert membre with no membre_id")
}
result, err := tx.NamedExec("INSERT INTO membres (id, last_name, first_name, prefered_name, programme_id) VALUES (:id, :last_name, :first_name, :prefered_name, :programme_id);", &membre)
if err != nil { if err != nil {
tx.Rollback() tx.Rollback()
return rowsInserted, err return 0, err
} }
rowsInserted++
rows, err := result.RowsAffected()
if err != nil {
tx.Rollback()
return 0, err
}
rowsInserted += rows
} }
err = tx.Commit() err = tx.Commit()
@ -93,12 +105,24 @@ func (d *DataClient) InsertProgrammes(programmes []models.Programme) (int64, err
} }
for _, programme := range programmes { for _, programme := range programmes {
_, err := tx.NamedExec("INSERT INTO programmes (id, titre) VALUES (:id, :titre);", &programme) if programme.ID == "" {
tx.Rollback()
return 0, errors.New("Cannot insert programme with no programme_id")
}
result, err := tx.NamedExec("INSERT INTO programmes (id, titre) VALUES (:id, :titre);", &programme)
if err != nil { if err != nil {
tx.Rollback() tx.Rollback()
return rowsInserted, err return 0, err
} }
rowsInserted++
rows, err := result.RowsAffected()
if err != nil {
tx.Rollback()
return 0, err
}
rowsInserted += rows
} }
err = tx.Commit() err = tx.Commit()