2024-11-26 21:36:40 +00:00
|
|
|
package gormstore
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2024-11-26 23:30:58 +00:00
|
|
|
"git.itzana.me/strafesnet/maps-service/pkg/datastore"
|
|
|
|
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
2024-11-26 21:36:40 +00:00
|
|
|
"git.itzana.me/strafesnet/utils/logger"
|
|
|
|
log "github.com/sirupsen/logrus"
|
2024-11-26 23:30:58 +00:00
|
|
|
"github.com/urfave/cli/v2"
|
2024-11-26 21:36:40 +00:00
|
|
|
"gorm.io/driver/postgres"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
)
|
|
|
|
|
2024-11-26 23:30:58 +00:00
|
|
|
func New(ctx *cli.Context) (datastore.Datastore, error) {
|
|
|
|
db, err := gorm.Open(
|
|
|
|
postgres.Open(
|
|
|
|
fmt.Sprintf(
|
|
|
|
"host=%s user=%s password=%s dbname=%s port=%s",
|
|
|
|
ctx.String("pg-host"),
|
|
|
|
ctx.String("pg-user"),
|
|
|
|
ctx.String("pg-password"),
|
|
|
|
ctx.String("pg-db"),
|
|
|
|
ctx.Int("pg-port")),
|
|
|
|
), &gorm.Config{
|
|
|
|
Logger: logger.New(),
|
|
|
|
})
|
2024-11-26 21:36:40 +00:00
|
|
|
if err != nil {
|
2024-11-26 23:30:58 +00:00
|
|
|
log.WithError(err).Errorln("failed to connect to database")
|
2024-11-26 21:36:40 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2024-11-26 23:30:58 +00:00
|
|
|
if ctx.Bool("pg-migrate") {
|
|
|
|
if err := db.AutoMigrate(&model.Submission{}); err != nil {
|
|
|
|
log.WithError(err).Errorln("database migration failed")
|
2024-11-26 21:36:40 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-11-26 23:30:58 +00:00
|
|
|
return &Gormstore{db}, nil
|
2024-11-26 21:36:40 +00:00
|
|
|
}
|