package db import ( "context" "database/sql" "code.lila.network/adoralaura/go-urlsh/internal/config" "code.lila.network/adoralaura/go-urlsh/models" "github.com/rs/zerolog" "github.com/uptrace/bun" "github.com/uptrace/bun/dialect/pgdialect" "github.com/uptrace/bun/driver/pgdriver" ) func dbError(err error, logger *zerolog.Logger) { logger.Fatal().Str("error", err.Error()).Msg("[DB] couldn't create database") } func InitializeDB(cfg *config.Config, logger *zerolog.Logger) *bun.DB { sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(cfg.DatabaseDSN))) db := bun.NewDB(sqldb, pgdialect.New()) models.DB = db _, err := db.NewCreateTable().IfNotExists().Model((*models.Link)(nil)).Exec(context.Background()) if err != nil { dbError(err, logger) } _, err = db.NewCreateTable().IfNotExists().Model((*models.User)(nil)).Exec(context.Background()) if err != nil { dbError(err, logger) } _, err = db.NewCreateTable().IfNotExists().Model((*models.Session)(nil)).Exec(context.Background()) if err != nil { dbError(err, logger) } _, err = db.NewCreateTable().IfNotExists().Model((*models.ApiKey)(nil)).Exec(context.Background()) if err != nil { dbError(err, logger) } _, err = db.NewCreateTable().IfNotExists().Model((*models.MFALoginTransaction)(nil)).Exec(context.Background()) if err != nil { dbError(err, logger) } _, err = db.NewCreateTable().IfNotExists().Model((*models.MFAConfig)(nil)).Exec(context.Background()) if err != nil { dbError(err, logger) } _, err = db.NewCreateTable().IfNotExists().Model((*models.MFAScratchCode)(nil)).Exec(context.Background()) if err != nil { dbError(err, logger) } err = doMigrations(db, logger) if err != nil { dbError(err, logger) } return db }