2022-05-01 15:50:59 +02:00

68 lines
1.3 KiB
Go

package api
import (
"fmt"
"log"
"os"
"time"
"gitlab.celogeek.com/photos/api/internal/photos/models"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
type DBConfig struct {
Host string
User string
Password string
Port uint
Database string
}
func (d *DBConfig) DSN() string {
return fmt.Sprintf(
"host=%s user=%s password=%s dbname=%s port=%d sslmode=disable TimeZone=UTC",
d.Host,
d.User,
d.Password,
d.Database,
d.Port,
)
}
func (s *Service) Migrate() {
tx := s.DB
tx.AutoMigrate(&models.Account{})
tx.AutoMigrate(&models.Session{})
tx.AutoMigrate(&models.File{})
tx.AutoMigrate(&models.FileChunk{})
}
func (s *Service) DBConnect() {
db, err := gorm.Open(postgres.Open(s.Config.DB.DSN()), &gorm.Config{
Logger: logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{
SlowThreshold: time.Second, // Slow SQL threshold
LogLevel: logger.Error, // Log level
IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger
Colorful: true, // Disable color
},
),
SkipDefaultTransaction: true,
PrepareStmt: true,
})
if err != nil {
s.LogErr.Fatal("DB", err)
}
s.DB = db
}
func (s *Service) SetupDB() {
s.DBConnect()
s.Migrate()
}