2024-01-16 01:58:20 +00:00
|
|
|
package db
|
|
|
|
|
|
|
|
import (
|
2024-01-28 07:20:59 +00:00
|
|
|
"context"
|
2024-01-16 01:58:20 +00:00
|
|
|
"fmt"
|
2024-02-22 08:30:40 +00:00
|
|
|
|
|
|
|
"git.lumeweb.com/LumeWeb/portal/config"
|
|
|
|
|
2024-01-16 01:58:20 +00:00
|
|
|
"git.lumeweb.com/LumeWeb/portal/db/models"
|
2024-01-28 07:20:59 +00:00
|
|
|
"go.uber.org/fx"
|
2024-01-16 01:58:20 +00:00
|
|
|
"gorm.io/driver/mysql"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
)
|
|
|
|
|
2024-01-28 07:20:59 +00:00
|
|
|
type DatabaseParams struct {
|
|
|
|
fx.In
|
2024-02-22 08:30:40 +00:00
|
|
|
Config *config.Manager
|
2024-01-16 01:58:20 +00:00
|
|
|
}
|
|
|
|
|
2024-01-28 07:20:59 +00:00
|
|
|
var Module = fx.Module("db",
|
|
|
|
fx.Options(
|
|
|
|
fx.Provide(NewDatabase),
|
|
|
|
),
|
|
|
|
)
|
2024-01-16 01:58:20 +00:00
|
|
|
|
2024-01-28 07:20:59 +00:00
|
|
|
func NewDatabase(lc fx.Lifecycle, params DatabaseParams) *gorm.DB {
|
2024-02-22 08:30:40 +00:00
|
|
|
username := params.Config.Config().Core.DB.Username
|
|
|
|
password := params.Config.Config().Core.DB.Password
|
|
|
|
host := params.Config.Config().Core.DB.Host
|
|
|
|
port := params.Config.Config().Core.DB.Port
|
|
|
|
dbname := params.Config.Config().Core.DB.Name
|
|
|
|
charset := params.Config.Config().Core.DB.Charset
|
2024-01-16 01:58:20 +00:00
|
|
|
|
2024-02-22 08:32:47 +00:00
|
|
|
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local", username, password, host, port, dbname, charset)
|
2024-01-16 01:58:20 +00:00
|
|
|
|
|
|
|
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
|
|
|
|
if err != nil {
|
2024-01-28 07:20:59 +00:00
|
|
|
panic(err)
|
2024-01-16 01:58:20 +00:00
|
|
|
}
|
2024-01-16 06:24:47 +00:00
|
|
|
|
2024-01-28 07:20:59 +00:00
|
|
|
lc.Append(fx.Hook{
|
|
|
|
OnStart: func(ctx context.Context) error {
|
|
|
|
return db.AutoMigrate(
|
|
|
|
&models.APIKey{},
|
|
|
|
&models.Blocklist{},
|
|
|
|
&models.Download{},
|
|
|
|
&models.Pin{},
|
|
|
|
&models.PublicKey{},
|
|
|
|
&models.Upload{},
|
|
|
|
&models.User{},
|
|
|
|
&models.S5Challenge{},
|
|
|
|
&models.TusLock{},
|
|
|
|
&models.TusUpload{},
|
|
|
|
)
|
|
|
|
},
|
|
|
|
})
|
|
|
|
|
|
|
|
return db
|
2024-01-16 06:24:47 +00:00
|
|
|
}
|