34 lines
799 B
Go
34 lines
799 B
Go
package database
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
_ "github.com/lib/pq" // PostgreSQL driver
|
|
)
|
|
|
|
// NewPostgresProvider creates a new PostgreSQL database connection
|
|
func NewPostgresProvider(dsn string, maxOpenConns, maxIdleConns int, maxLifetime string) (*sqlx.DB, error) {
|
|
db, err := sqlx.Connect("postgres", dsn)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to connect to database: %w", err)
|
|
}
|
|
|
|
// Set connection pool settings
|
|
db.SetMaxOpenConns(maxOpenConns)
|
|
db.SetMaxIdleConns(maxIdleConns)
|
|
|
|
if maxLifetime != "" {
|
|
if lifetime, err := time.ParseDuration(maxLifetime); err == nil {
|
|
db.SetConnMaxLifetime(lifetime)
|
|
}
|
|
}
|
|
|
|
// Test connection
|
|
if err := db.Ping(); err != nil {
|
|
return nil, fmt.Errorf("failed to ping database: %w", err)
|
|
}
|
|
|
|
return db, nil
|
|
} |