u
This commit is contained in:
1 parent
d03ac2b00a
commit
cf4291652a
43 files changed
+359
-6254
No files matched your search
@@ -0,0 +1,56 @@
|
||||
// db/db.go
|
||||
package db
|
||||
|
||||
import (
|
||||
"cn/oneao/base-go/config"
|
||||
sqlcg "cn/oneao/base-go/db/sqlc"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
DB *pgxpool.Pool
|
||||
DBClient *sqlcg.Queries
|
||||
)
|
||||
|
||||
func InitDB() error {
|
||||
cfg := config.Db
|
||||
|
||||
sslMode := "disable"
|
||||
if cfg.SllMode {
|
||||
sslMode = "require"
|
||||
}
|
||||
|
||||
// 构建 DSN
|
||||
dsn := fmt.Sprintf(
|
||||
"postgres://%s:%s@%s:%d/%s?sslmode=%s&TimeZone=%s",
|
||||
cfg.User, cfg.Password, cfg.Host, cfg.Port, cfg.Dbname, sslMode, cfg.TimeZone,
|
||||
)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
pool, err := pgxpool.New(ctx, dsn)
|
||||
if err != nil {
|
||||
return fmt.Errorf("unable to connect to database: %w", err)
|
||||
}
|
||||
|
||||
// 测试连接
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
return fmt.Errorf("ping database failed: %w", err)
|
||||
}
|
||||
|
||||
DB = pool
|
||||
|
||||
// 初始化 sqlc Queries,全局可用
|
||||
DBClient = sqlcg.New(DB)
|
||||
|
||||
// 可选:设置连接池参数
|
||||
pool.Config().MaxConns = int32(cfg.MaxOpenConns)
|
||||
pool.Config().MinConns = int32(cfg.MaxIdleConns)
|
||||
pool.Config().MaxConnLifetime = cfg.ConnMaxLifetime
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user