teldrive/internal/database/database.go

68 lines
1.5 KiB
Go
Raw Normal View History

package database
import (
"time"
"github.com/divyam234/teldrive/internal/config"
"github.com/divyam234/teldrive/internal/logging"
2024-06-01 07:14:47 +08:00
extraClausePlugin "github.com/WinterYukky/gorm-extra-clause-plugin"
"go.uber.org/zap/zapcore"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
// NewDatabase creates a new database with given config
func NewDatabase(cfg *config.Config) (*gorm.DB, error) {
var (
db *gorm.DB
err error
2024-02-13 00:02:55 +08:00
logger = NewLogger(time.Second, true, zapcore.Level(cfg.DB.LogLevel))
)
2024-06-04 16:46:03 +08:00
for i := 0; i <= 5; i++ {
db, err = gorm.Open(postgres.New(postgres.Config{
DSN: cfg.DB.DataSource,
PreferSimpleProtocol: !cfg.DB.PrepareStmt,
}), &gorm.Config{
Logger: logger,
NamingStrategy: schema.NamingStrategy{
TablePrefix: "teldrive.",
SingularTable: false,
},
NowFunc: func() time.Time {
return time.Now().UTC()
},
})
if err == nil {
break
}
logging.DefaultLogger().Warnf("failed to open database: %v", err)
time.Sleep(500 * time.Millisecond)
}
2024-06-04 16:46:03 +08:00
if err != nil {
2024-04-19 04:46:47 +08:00
logging.DefaultLogger().Fatalf("database: %v", err)
}
2024-06-04 16:46:03 +08:00
db.Use(extraClausePlugin.New())
2024-06-04 16:46:03 +08:00
if cfg.DB.Pool.Enable {
rawDB, err := db.DB()
if err != nil {
return nil, err
}
2024-06-04 16:46:03 +08:00
rawDB.SetMaxOpenConns(cfg.DB.Pool.MaxOpenConnections)
rawDB.SetMaxIdleConns(cfg.DB.Pool.MaxIdleConnections)
rawDB.SetConnMaxLifetime(cfg.DB.Pool.MaxLifetime)
}
sqlDb, _ := db.DB()
err = migrateDB(sqlDb)
if err != nil {
return nil, err
}
2024-06-04 16:46:03 +08:00
return db, nil
}