49 lines
984 B
Go
49 lines
984 B
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"server/internal/config"
|
|
"server/internal/db/sqlc"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"go.uber.org/fx"
|
|
)
|
|
|
|
func NewDB(lc fx.Lifecycle, cfg *config.Config) (*pgxpool.Pool, error) {
|
|
ctx := context.Background()
|
|
dbConfig := cfg.Database
|
|
|
|
dsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=%s",
|
|
dbConfig.Host, dbConfig.Port, dbConfig.User, dbConfig.Password, dbConfig.DBName, dbConfig.SSLMode)
|
|
|
|
// 创建连接池
|
|
pool, err := pgxpool.New(ctx, dsn)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// 注册fx生命周期钩子
|
|
lc.Append(fx.Hook{
|
|
OnStart: func(ctx context.Context) error {
|
|
return nil
|
|
},
|
|
OnStop: func(ctx context.Context) error {
|
|
pool.Close()
|
|
return nil
|
|
},
|
|
})
|
|
|
|
// 测试连接
|
|
if err = pool.Ping(ctx); err != nil {
|
|
pool.Close()
|
|
return nil, fmt.Errorf("failed to ping database: %w", err)
|
|
}
|
|
|
|
return pool, nil
|
|
}
|
|
|
|
func NewQueries(pool *pgxpool.Pool) *db.Queries {
|
|
return db.New(pool)
|
|
}
|