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:"nom" json:"nom"` } 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 { var membre Membre db.First(&membre, "num_etud = ?", num_etud) return membre } 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 }