summaryrefslogtreecommitdiff
path: root/app/db/connection.go
blob: d494f6c0b145155014ae1f0ff65885bcc5e0a173 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package db

import (
	"context"
	"database/sql"
	"fmt"

	_ "github.com/lib/pq"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/pls"
)

type Connection struct {
	db *sql.DB
}

func NewConnection(databaseURL string) (*Connection, error) {
	db, err := sql.Open("postgres", databaseURL)
	if err != nil {
		return nil, fmt.Errorf("failed to open database connection: %w", err)
	}

	return &Connection{
		db: db,
	}, nil
}

func (c *Connection) Ping(ctx context.Context) error {
	if c.db == nil {
		return fmt.Errorf("database connection not available")
	}

	return c.db.PingContext(ctx)
}

func (c *Connection) IsHealthy(ctx context.Context) bool {
	if c.db == nil {
		return false
	}

	err := c.Ping(ctx)
	if err != nil {
		pls.LogError(ctx, err)
		return false
	}

	return true
}

func (c *Connection) Close() error {
	if c.db == nil {
		return nil
	}
	return c.db.Close()
}