aboutsummaryrefslogtreecommitdiffstats
path: root/internal/storage/db.go
blob: d83e71dcb438b07449b9f421f863e9ba772f8516 (plain) (blame)
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
55
56
57
58
59
60
61
package storage

import (
	"database/sql"
	"errors"
	"fmt"
	"slices"

	"github.com/eugenetriguba/bolt/internal/configloader"
	_ "github.com/jackc/pgx/v5/stdlib"
)

var supportedDrivers = []string{"postgres"}

var (
	ErrMalformedConnectionString = errors.New(
		"malformed database connection parameters provided",
	)
	ErrUnableToConnect   = errors.New("unable to open connection to database")
	ErrUnsupportedDriver = fmt.Errorf("unsupported driver, supported drivers are %s", supportedDrivers)
)

// DBConnect establishes a connection to the database using the driver
// and connection information. Only "postgres" is supported as the driver.
//
// The following errors may be returned:
//   - ErrMalformedConnectionString: The provided connection parameters are
//     not in a valid format.
//   - ErrUnableToConnect: Unable to make a connection to the database with
//     the provided connection parameters.
//   - ErrUnsupportedDriver: The provided driver is not supported.
func DBConnect(driver string, connectionParams string) (*sql.DB, error) {
	if !slices.Contains(supportedDrivers, driver) {
		return nil, ErrUnsupportedDriver
	}

	db, err := sql.Open("pgx", connectionParams)
	if err != nil {
		return nil, fmt.Errorf("%w: %v", ErrMalformedConnectionString, err)
	}

	// Note: `sql.Open` only validates the connection string we provided is sane.
	// It doesn't actually open up a connection to the database. For that, we ping
	// the database to ensure the connection string is fully valid.
	err = db.Ping()
	if err != nil {
		return nil, fmt.Errorf("%w: %v", ErrUnableToConnect, err)
	}

	return db, nil
}

// DBConnectionString generates a properly formatted connection
// string that can be used to establish a database connection.
// Note that it always creates a connection string with sslmode disabled.
func DBConnectionString(cfg *configloader.ConnectionConfig) string {
	return fmt.Sprintf(
		"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
		cfg.Host, cfg.Port, cfg.User, cfg.Password, cfg.DBName,
	)
}