2025-11-10 00:19:30 +00:00
|
|
|
package database
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"database/sql"
|
2025-11-29 20:51:56 +00:00
|
|
|
"time"
|
2025-11-10 00:19:30 +00:00
|
|
|
|
|
|
|
|
"github.com/uptrace/bun"
|
|
|
|
|
"github.com/uptrace/bun/dialect/pgdialect"
|
|
|
|
|
"github.com/uptrace/bun/driver/pgdriver"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func NewFromPostgres(url string) *bun.DB {
|
|
|
|
|
sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(url)))
|
2025-11-29 20:51:56 +00:00
|
|
|
|
|
|
|
|
// Configure connection pool to prevent "database closed" errors
|
|
|
|
|
// SetMaxOpenConns sets the maximum number of open connections to the database
|
|
|
|
|
sqldb.SetMaxOpenConns(25)
|
|
|
|
|
// SetMaxIdleConns sets the maximum number of connections in the idle connection pool
|
|
|
|
|
sqldb.SetMaxIdleConns(5)
|
|
|
|
|
// SetConnMaxLifetime sets the maximum amount of time a connection may be reused
|
|
|
|
|
sqldb.SetConnMaxLifetime(5 * time.Minute)
|
|
|
|
|
// SetConnMaxIdleTime sets the maximum amount of time a connection may be idle
|
|
|
|
|
sqldb.SetConnMaxIdleTime(10 * time.Minute)
|
|
|
|
|
|
2025-11-10 00:19:30 +00:00
|
|
|
db := bun.NewDB(sqldb, pgdialect.New())
|
|
|
|
|
return db
|
|
|
|
|
}
|