u
This commit is contained in:
1 parent
4ce951dd56
commit
8a3dea8545
44 files changed
+1599
-30
No files matched your search
@@ -0,0 +1,50 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"allapp/db/repo"
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func initDB() (*pgxpool.Pool, *repo.Queries, error) {
|
||||
cfg := conf.Postgres
|
||||
|
||||
sslMode := "disable"
|
||||
if cfg.SslMode {
|
||||
sslMode = "require"
|
||||
}
|
||||
|
||||
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()
|
||||
|
||||
// 使用可修改配置
|
||||
cfgPool, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("parse pgx config failed: %w", err)
|
||||
}
|
||||
|
||||
cfgPool.MaxConns = cfg.MaxOpenConns
|
||||
cfgPool.MinConns = cfg.MaxIdleConns
|
||||
cfgPool.MaxConnLifetime = cfg.ConnMaxLifetime
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfgPool)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("create pgx pool failed: %w", err)
|
||||
}
|
||||
|
||||
// 测试连接
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
return nil, nil, fmt.Errorf("ping database failed: %w", err)
|
||||
}
|
||||
|
||||
queries := repo.New(pool)
|
||||
return pool, queries, nil
|
||||
}
|
||||
Reference in new issue
Block a user