chore: initial import
This commit is contained in:
47
internal/database/database.go
Normal file
47
internal/database/database.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/company/ai-ops/internal/config"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// Pool 是全局数据库连接池
|
||||
var Pool *pgxpool.Pool
|
||||
|
||||
// Init 初始化数据库连接
|
||||
func Init(cfg config.DatabaseConfig) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
poolConfig, err := pgxpool.ParseConfig(cfg.DSN())
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse db config: %w", err)
|
||||
}
|
||||
|
||||
poolConfig.MaxConns = int32(cfg.PoolSize)
|
||||
poolConfig.MinConns = 2
|
||||
poolConfig.MaxConnLifetime = 30 * time.Minute
|
||||
poolConfig.MaxConnIdleTime = 10 * time.Minute
|
||||
|
||||
Pool, err = pgxpool.NewWithConfig(ctx, poolConfig)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create db pool: %w", err)
|
||||
}
|
||||
|
||||
if err := Pool.Ping(ctx); err != nil {
|
||||
return fmt.Errorf("ping db: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close 关闭数据库连接
|
||||
func Close() {
|
||||
if Pool != nil {
|
||||
Pool.Close()
|
||||
}
|
||||
}
|
||||
37
internal/database/database_test.go
Normal file
37
internal/database/database_test.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/company/ai-ops/internal/config"
|
||||
)
|
||||
|
||||
func TestInitAndCloseWithLocalPostgres(t *testing.T) {
|
||||
ports := []int{15432, 5432}
|
||||
var lastErr error
|
||||
for _, port := range ports {
|
||||
lastErr = Init(config.DatabaseConfig{Host: "localhost", Port: port, User: "aiops", Password: "aiops123", DBName: "ai_ops", SSLMode: "disable", PoolSize: 4})
|
||||
if lastErr == nil {
|
||||
break
|
||||
}
|
||||
Close()
|
||||
Pool = nil
|
||||
}
|
||||
if lastErr != nil {
|
||||
t.Skipf("PostgreSQL integration database not available: %v", lastErr)
|
||||
}
|
||||
if Pool == nil {
|
||||
t.Fatal("pool not initialized")
|
||||
}
|
||||
Close()
|
||||
Pool = nil
|
||||
}
|
||||
|
||||
func TestInitReturnsErrorForInvalidConfig(t *testing.T) {
|
||||
if err := Init(config.DatabaseConfig{Host: "::::bad-host::::", Port: 1, User: "u", Password: "p", DBName: "d", SSLMode: "disable", PoolSize: 1}); err == nil {
|
||||
Close()
|
||||
Pool = nil
|
||||
t.Fatal("expected invalid db config error")
|
||||
}
|
||||
Pool = nil
|
||||
}
|
||||
Reference in New Issue
Block a user