Files
Crimson-Gatekeeper/srv/internal/database/database-client.go

49 lines
952 B
Go
Raw Normal View History

2026-01-22 11:31:04 +08:00
package database
2026-01-13 00:08:49 +08:00
import (
2026-01-20 00:18:05 +08:00
"Crimson-Gatekeeper/internal/query"
"database/sql"
2026-01-13 13:02:27 +08:00
"fmt"
2026-01-13 00:08:49 +08:00
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
2026-01-13 13:02:27 +08:00
// GetDataBaseClient 获取数据库链接
//
// 返回值
// - 一个 gorm.DB 的指针
// - 一个清理所有数据库相关数据的函数
func GetDataBaseClient() (*gorm.DB, error) {
2026-01-13 00:08:49 +08:00
dsn := "host=localhost " +
"user=gatekeeper " +
"dbname=crimson " +
"sslmode=disable " +
"port=5432 " +
"password=crimson " +
"connect_timeout=20 "
2026-01-13 13:02:27 +08:00
client, ero := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if ero != nil {
fmt.Println("数据库链接建立失败")
return nil, ero
2026-01-13 13:02:27 +08:00
}
return client, nil
}
func GetPoolCfg(g *gorm.DB) (*sql.DB, error) {
pool, err := g.DB()
if err != nil {
2026-01-13 13:02:27 +08:00
fmt.Println("获取数据库链接池失败")
return nil, err
2026-01-20 00:18:05 +08:00
}
pool.SetConnMaxIdleTime(3)
pool.SetMaxOpenConns(10)
return pool, nil
2026-01-20 00:18:05 +08:00
}
func GetQuery(db *gorm.DB) *query.Query {
return query.Use(db)
2026-01-13 00:08:49 +08:00
}