-
This commit is contained in:
34
user/internal/database/database.go
Normal file
34
user/internal/database/database.go
Normal file
@ -0,0 +1,34 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user