32 lines
721 B
Go
32 lines
721 B
Go
package platform
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
"time"
|
|
|
|
_ "github.com/jackc/pgx/v5/stdlib"
|
|
)
|
|
|
|
func OpenDatabase(ctx context.Context, cfg Config) (*sql.DB, error) {
|
|
if cfg.DatabaseMode == DatabaseModeMemory {
|
|
return nil, nil
|
|
}
|
|
database, err := sql.Open("pgx", cfg.DatabaseURL)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("open Sense PostgreSQL: %w", err)
|
|
}
|
|
database.SetMaxOpenConns(20)
|
|
database.SetMaxIdleConns(5)
|
|
database.SetConnMaxLifetime(30 * time.Minute)
|
|
|
|
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
if err := database.PingContext(pingCtx); err != nil {
|
|
database.Close()
|
|
return nil, fmt.Errorf("connect Sense PostgreSQL: %w", err)
|
|
}
|
|
return database, nil
|
|
}
|