bottin-agenda/data/data.go

98 lines
1.7 KiB
Go
Raw Normal View History

package data
import (
"errors"
"log"
"github.com/spf13/viper"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
var db *gorm.DB
type Membre struct {
gorm.Model
NumEtud string `mapper:"num_etud" json:"num_etud"`
Nom string `mapper:"-" json:"-"`
}
func OpenDatabase() error {
var err error
var dialector gorm.Dialector
switch t := viper.GetString("db.type"); t {
case "sqlite":
log.Println("Using driver gorm.io/driver/sqlite")
db_sqlite_path := viper.GetString("db.sqlite.path")
if db_sqlite_path == "" {
log.Fatal("No valid database file found in `--db-sqlite-path` or `db.sqlite.path`.")
}
log.Println("Using database file:", db_sqlite_path)
dialector = sqlite.Open(db_sqlite_path)
default:
log.Fatalf("Unrecognized database driver requested (%s).\n", t)
}
db, err = gorm.Open(dialector, &gorm.Config{})
if err != nil {
return err
}
sqlDB, err := db.DB()
if err != nil {
return err
}
return sqlDB.Ping()
}
func MigrateDatabase() error {
err := db.AutoMigrate(&Membre{})
return err
}
func ReadMembre(num_etud string) (Membre, error) {
var membre Membre
result := db.Limit(1).Find(&membre, "num_etud = ?", num_etud)
if result.Error != nil {
return membre, result.Error
}
return membre, nil
}
func InsertMembre(membre *Membre) (error, uint) {
// Reset ID before insertion
membre.ID = 0
// Insert membre into database
result := db.Create(&membre)
if result.Error != nil {
return result.Error, 0
}
return nil, membre.ID
}
func InsertMembres(membres []*Membre, batch_size int) error {
if len(membres) == 0 {
return errors.New("Cannot insert empty batch of membres.")
}
for _, membre := range membres {
membre.ID = 0
}
db.CreateInBatches(&membres, batch_size)
return nil
}