go-urlsh/internal/db/initialize.go

61 lines
1.7 KiB
Go

package db
import (
"context"
"database/sql"
"os"
"log"
"code.lila.network/adoralaura/go-urlsh/models"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/pgdialect"
"github.com/uptrace/bun/driver/pgdriver"
)
func InitializeDB() *bun.DB {
sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(os.Getenv("DATABASE_URL"))))
db := bun.NewDB(sqldb, pgdialect.New())
_, err := db.NewCreateTable().IfNotExists().Model((*models.Link)(nil)).Exec(context.Background())
if err != nil {
log.Panicf("[DB] couldn't create database: [%w]", err)
}
_, err = db.NewCreateTable().IfNotExists().Model((*models.User)(nil)).Exec(context.Background())
if err != nil {
log.Panicf("[DB] couldn't create database: [%w]", err)
}
_, err = db.NewCreateTable().IfNotExists().Model((*models.Session)(nil)).Exec(context.Background())
if err != nil {
log.Panicf("[DB] couldn't create database: [%w]", err)
}
_, err = db.NewCreateTable().IfNotExists().Model((*models.ApiKey)(nil)).Exec(context.Background())
if err != nil {
log.Panicf("[DB] couldn't create database: [%w]", err)
}
_, err = db.NewCreateTable().IfNotExists().Model((*models.MFALoginTransaction)(nil)).Exec(context.Background())
if err != nil {
log.Panicf("[DB] couldn't create database: [%w]", err)
}
_, err = db.NewCreateTable().IfNotExists().Model((*models.MFAConfig)(nil)).Exec(context.Background())
if err != nil {
log.Panicf("[DB] couldn't create database: [%w]", err)
}
_, err = db.NewCreateTable().IfNotExists().Model((*models.MFAScratchCode)(nil)).Exec(context.Background())
if err != nil {
log.Panicf("[DB] couldn't create database: [%w]", err)
}
err = doMigrations(db)
if err != nil {
log.Panicf("[DB] Error during Migrations: [%w]", err)
}
return db
}