2024-01-16 01:58:20 +00:00
|
|
|
package db
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"git.lumeweb.com/LumeWeb/portal/db/models"
|
|
|
|
"git.lumeweb.com/LumeWeb/portal/interfaces"
|
|
|
|
"github.com/spf13/viper"
|
|
|
|
"go.uber.org/zap"
|
|
|
|
"gorm.io/driver/mysql"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
_ interfaces.Database = (*DatabaseImpl)(nil)
|
|
|
|
)
|
|
|
|
|
|
|
|
type DatabaseImpl struct {
|
2024-01-16 06:24:47 +00:00
|
|
|
db *gorm.DB
|
2024-01-16 01:58:20 +00:00
|
|
|
portal interfaces.Portal
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewDatabase(p interfaces.Portal) interfaces.Database {
|
|
|
|
return &DatabaseImpl{
|
|
|
|
portal: p,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Init initializes the database connection
|
2024-01-19 17:43:16 +00:00
|
|
|
func (d *DatabaseImpl) Init() error {
|
2024-01-16 01:58:20 +00:00
|
|
|
// Retrieve DB config from Viper
|
|
|
|
username := viper.GetString("core.db.username")
|
|
|
|
password := viper.GetString("core.db.password")
|
|
|
|
host := viper.GetString("core.db.host")
|
|
|
|
port := viper.GetString("core.db.port")
|
2024-01-16 05:00:54 +00:00
|
|
|
dbname := viper.GetString("core.db.name")
|
2024-01-16 01:58:20 +00:00
|
|
|
charset := viper.GetString("core.db.charset")
|
|
|
|
|
|
|
|
// Construct DSN
|
|
|
|
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local", username, password, host, port, dbname, charset)
|
|
|
|
|
|
|
|
// Open DB connection
|
|
|
|
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
|
|
|
|
if err != nil {
|
2024-01-19 17:43:16 +00:00
|
|
|
d.portal.Logger().Error("Failed to connect to database", zap.Error(err))
|
2024-01-16 01:58:20 +00:00
|
|
|
}
|
2024-01-16 06:24:47 +00:00
|
|
|
d.db = db
|
2024-01-16 01:58:20 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start performs any additional setup
|
|
|
|
func (d *DatabaseImpl) Start() error {
|
2024-01-16 06:24:47 +00:00
|
|
|
return d.db.AutoMigrate(
|
2024-01-16 01:58:20 +00:00
|
|
|
&models.APIKey{},
|
|
|
|
&models.Blocklist{},
|
|
|
|
&models.Download{},
|
|
|
|
&models.Pin{},
|
|
|
|
&models.PublicKey{},
|
|
|
|
&models.Upload{},
|
|
|
|
&models.User{},
|
2024-01-16 19:18:36 +00:00
|
|
|
&models.S5Challenge{},
|
2024-01-16 01:58:20 +00:00
|
|
|
)
|
|
|
|
}
|
2024-01-16 06:24:47 +00:00
|
|
|
|
|
|
|
func (d *DatabaseImpl) Get() *gorm.DB {
|
|
|
|
return d.db
|
|
|
|
}
|