From db0310a6a0cb0231648595b87bda52c5f7314ee5 Mon Sep 17 00:00:00 2001 From: timerzz Date: Mon, 26 Aug 2024 16:58:47 +0800 Subject: [PATCH] =?UTF-8?q?feat=20=E6=B7=BB=E5=8A=A0=E9=BB=98=E8=AE=A4?= =?UTF-8?q?=E5=8A=A0=E8=BD=BD=E6=95=B0=E6=8D=AE=E5=BA=93=E7=9A=84=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/database/init.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/pkg/database/init.go b/pkg/database/init.go index 915f279..83e0939 100644 --- a/pkg/database/init.go +++ b/pkg/database/init.go @@ -2,12 +2,40 @@ package database import ( "fmt" + "log" + "os" + "time" "gorm.io/driver/postgres" "gorm.io/gorm" + "gorm.io/gorm/logger" ) func InitDatabase(opt *DBOption) (*gorm.DB, error) { dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=Asia/Shanghai", opt.Host, opt.User, opt.Password, opt.DBName, opt.Port) return gorm.Open(postgres.Open(dsn), &gorm.Config{}) } + +func InitDefaultDatabase() (*gorm.DB, error) { + path := os.Getenv(ConfigPathEnvKey) + if path != "" { + path = DefaultConfigPath + } + cfg, err := LoadDBConfig(path) + if err != nil { + return nil, fmt.Errorf("获取数据库配置失败:%v", err) + } + db, err := InitDatabase(cfg) + if err != nil { + return nil, fmt.Errorf("初始化数据库失败:%v", err) + } + db.Logger = logger.New( + log.New(os.Stdout, "\r\n", log.LstdFlags), + logger.Config{ + SlowThreshold: time.Second, + LogLevel: logger.Warn, + Colorful: true, + }, + ) + return db, nil +}