teldrive/internal/database/database.go

62 lines
1.4 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-04-19 04:46:47 +08:00
for i := 0; i <= 10; i++ {
2024-02-13 00:02:55 +08:00
db, err = gorm.Open(postgres.Open(cfg.DB.DataSource), &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-01 07:14:47 +08:00
db.Use(extraClausePlugin.New())
if err != nil {
2024-04-19 04:46:47 +08:00
logging.DefaultLogger().Fatalf("database: %v", err)
}
rawDB, err := db.DB()
if err != nil {
return nil, err
}
rawDB.SetMaxOpenConns(cfg.DB.Pool.MaxOpenConnections)
rawDB.SetMaxIdleConns(cfg.DB.Pool.MaxIdleConnections)
2024-02-13 00:02:55 +08:00
rawDB.SetConnMaxLifetime(cfg.DB.Pool.MaxLifetime)
2024-02-13 00:02:55 +08:00
if cfg.DB.Migrate.Enable {
err := migrateDB(rawDB)
if err != nil {
return nil, err
}
}
return db, nil
}