41 lines
1.0 KiB
Go
41 lines
1.0 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"lincodex/backend/config"
|
|
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
|
"lincodex/backend/internal/port/outbound"
|
|
)
|
|
|
|
type HealthChecker struct {
|
|
pool *pgxpool.Pool
|
|
queries *sqlc.Queries
|
|
}
|
|
|
|
func NewHealthChecker(ctx context.Context, config config.Config) (*HealthChecker, func(), error) {
|
|
if config.DatabaseURL == "" {
|
|
return &HealthChecker{}, func() {}, nil
|
|
}
|
|
|
|
pool, err := NewPool(ctx, config.DatabaseURL)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("postgres.NewHealthChecker - create pool: %w", err)
|
|
}
|
|
|
|
return &HealthChecker{pool: pool, queries: sqlc.New(pool)}, pool.Close, nil
|
|
}
|
|
|
|
func (checker *HealthChecker) Check(ctx context.Context) error {
|
|
if checker.pool == nil || checker.queries == nil {
|
|
return fmt.Errorf("HealthChecker.Check - check configured database: %w", outbound.ErrNotReady)
|
|
}
|
|
if _, err := checker.queries.Ping(ctx); err != nil {
|
|
return fmt.Errorf("HealthChecker.Check - query PostgreSQL: %w", err)
|
|
}
|
|
return nil
|
|
}
|