maps-service/pkg/datastore/gormstore/db.go

45 lines
1000 B
Go
Raw Permalink Normal View History

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(
2024-11-27 00:06:43 +00:00
"host=%s user=%s password=%s dbname=%s port=%d",
2024-11-26 23:30:58 +00:00
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:59:52 +00:00
if ctx.Bool("migrate") {
2024-12-05 01:27:49 +00:00
if err := db.AutoMigrate(
&model.Submission{},
&model.Script{},
&model.ScriptPolicy{},
); err != nil {
2024-11-26 23:30:58 +00:00
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
}