summaryrefslogtreecommitdiff
path: root/internal/database/sql/main.go
blob: 80d5f5cad40ff99716a295fa988aa88427f2ce52 (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package database

import (
	"apjournal/internal/database/migrations"
	"os"
	"time"

	"github.com/jmoiron/sqlx"

	// driver postgres for migrations
	"log/slog"

	"github.com/golang-migrate/migrate"
	_ "github.com/golang-migrate/migrate/database/postgres"
	bindata "github.com/golang-migrate/migrate/source/go_bindata"
	_ "github.com/jackc/pgx/v5/stdlib" // register pgx driver
	"github.com/pkg/errors"
)

var log = slog.New(slog.NewJSONHandler(os.Stdout, nil))

type DB struct {
	Conn *sqlx.DB
	URI  string
}

func (d *DB) CloseAll() error {
	for _, conn := range []*sqlx.DB{d.Conn} {
		if err := closeConn(conn); err != nil {
			return err
		}
	}
	return nil
}

func closeConn(conn *sqlx.DB) error {
	return conn.Close()
}

func Init(DBURI string) (*DB, error) {
	var result DB
	var err error
	result.Conn, err = openDBConnection(DBURI, "pgx")
	if err != nil {
		return nil, err
	}
	result.URI = DBURI

	if err := testConnection(result.Conn); err != nil {
		return nil, err
	}
	return &result, nil
}

func InitWithMigrate(DBURI string, up bool) (*DB, error) {
	var (
		result DB
		err    error
	)
	result.Conn, err = openDBConnection(DBURI, "pgx")
	if err != nil {
		return nil, err
	}
	result.URI = DBURI

	if err = testConnection(result.Conn); err != nil {
		return nil, err
	}
	if err = result.Migrate(DBURI, up); err != nil {
		return nil, err
	}
	return &result, nil
}

func openDBConnection(dbURI, driver string) (*sqlx.DB, error) {
	conn, err := sqlx.Open(driver, dbURI)
	if err != nil {
		return nil, err
	}
	return conn, nil
}

func testConnection(conn *sqlx.DB) error {
	err := conn.Ping()
	if err != nil {
		return errors.Wrap(err, "can't ping database")
	}
	return nil
}

func (db *DB) Migrate(url string, up bool) error {
	source := bindata.Resource(migrations.AssetNames(), migrations.Asset)
	driver, err := bindata.WithInstance(source)
	if err != nil {
		return errors.WithStack(errors.WithMessage(err,
			"unable to instantiate driver from bindata"))
	}
	migration, err := migrate.NewWithSourceInstance("go-bindata",
		driver, url)
	if err != nil {
		return errors.WithStack(errors.WithMessage(err,
			"unable to start migration"))
	}
	if up {
		if err = migration.Up(); err != nil && err.Error() != "no change" {
			return errors.WithStack(errors.WithMessage(err,
				"unable to migrate up"))
		}
	} else {
		if err = migration.Down(); err != nil &&
			err.Error() != "no change" {
			return errors.WithStack(errors.WithMessage(err,
				"unable to migrate down"))
		}
	}
	return nil
}

func (d *DB) PingRoutine(interval time.Duration) {
	ticker := time.NewTicker(interval)
	done := make(chan bool)

	for {
		select {
		case <-done:
			return
		case t := <-ticker.C:
			if err := testConnection(d.Conn); err != nil {
				log.Error("failed to ping postrges db", "error", err, "ping_at", t)
				// reconnect
				if err := closeConn(d.Conn); err != nil {
					log.Error("failed to close db connection", "error", err, "ping_at", t)
				}
				d.Conn, err = openDBConnection(d.URI, "pgx")
				if err != nil {
					log.Error("failed to reconnect", "error", err, "ping_at", t)
				}
			}
		}
	}
}