go-urlsh/internal/db/initialize.go

67 lines
1.7 KiB
Go
Raw Normal View History

2023-04-25 18:43:01 +02:00
package db
import (
"context"
"database/sql"
2024-09-30 13:19:01 +02:00
"code.lila.network/adoralaura/go-urlsh/internal/config"
2024-05-04 17:06:01 +02:00
"code.lila.network/adoralaura/go-urlsh/models"
2024-09-30 13:19:01 +02:00
"github.com/rs/zerolog"
2023-04-25 18:43:01 +02:00
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/pgdialect"
"github.com/uptrace/bun/driver/pgdriver"
)
2024-09-30 13:19:01 +02:00
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())
2023-04-25 18:43:01 +02:00
2024-09-30 13:19:01 +02:00
models.DB = db
_, err := db.NewCreateTable().IfNotExists().Model((*models.Link)(nil)).Exec(context.Background())
2023-04-25 18:43:01 +02:00
if err != nil {
2024-09-30 13:19:01 +02:00
dbError(err, logger)
2023-04-25 18:43:01 +02:00
}
2023-04-27 10:37:42 +02:00
_, err = db.NewCreateTable().IfNotExists().Model((*models.User)(nil)).Exec(context.Background())
2023-04-27 10:37:42 +02:00
if err != nil {
2024-09-30 13:19:01 +02:00
dbError(err, logger)
2023-04-27 10:37:42 +02:00
}
_, err = db.NewCreateTable().IfNotExists().Model((*models.Session)(nil)).Exec(context.Background())
2023-04-27 10:37:42 +02:00
if err != nil {
2024-09-30 13:19:01 +02:00
dbError(err, logger)
2023-04-27 10:37:42 +02:00
}
_, err = db.NewCreateTable().IfNotExists().Model((*models.ApiKey)(nil)).Exec(context.Background())
2023-04-27 10:37:42 +02:00
if err != nil {
2024-09-30 13:19:01 +02:00
dbError(err, logger)
2024-05-04 17:06:01 +02:00
}
_, err = db.NewCreateTable().IfNotExists().Model((*models.MFALoginTransaction)(nil)).Exec(context.Background())
2024-05-04 17:06:01 +02:00
if err != nil {
2024-09-30 13:19:01 +02:00
dbError(err, logger)
2024-05-04 17:06:01 +02:00
}
_, err = db.NewCreateTable().IfNotExists().Model((*models.MFAConfig)(nil)).Exec(context.Background())
2024-05-04 17:06:01 +02:00
if err != nil {
2024-09-30 13:19:01 +02:00
dbError(err, logger)
2024-05-04 17:06:01 +02:00
}
_, err = db.NewCreateTable().IfNotExists().Model((*models.MFAScratchCode)(nil)).Exec(context.Background())
if err != nil {
2024-09-30 13:19:01 +02:00
dbError(err, logger)
}
2024-09-30 13:19:01 +02:00
err = doMigrations(db, logger)
2024-05-04 17:06:01 +02:00
if err != nil {
2024-09-30 13:19:01 +02:00
dbError(err, logger)
2023-04-27 10:37:42 +02:00
}
return db
2023-04-25 18:43:01 +02:00
}