31 lines
681 B
Go
31 lines
681 B
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
)
|
|
|
|
// Ping bounds db.PingContext under timeout and returns a wrapped error so
|
|
// startup failures are easy to spot in service logs.
|
|
//
|
|
// timeout is typically taken from Config.OperationTimeout.
|
|
func Ping(ctx context.Context, db *sql.DB, timeout time.Duration) error {
|
|
if db == nil {
|
|
return errors.New("ping postgres: nil db")
|
|
}
|
|
if timeout <= 0 {
|
|
return errors.New("ping postgres: timeout must be positive")
|
|
}
|
|
|
|
pingCtx, cancel := context.WithTimeout(ctx, timeout)
|
|
defer cancel()
|
|
|
|
if err := db.PingContext(pingCtx); err != nil {
|
|
return fmt.Errorf("ping postgres: %w", err)
|
|
}
|
|
return nil
|
|
}
|