-
Notifications
You must be signed in to change notification settings - Fork 2
/
driver-sql.go
111 lines (88 loc) · 2.07 KB
/
driver-sql.go
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
package db
import (
"database/sql"
"errors"
"fmt"
"log/slog"
"github.com/chadweimer/gomp/models"
"github.com/jmoiron/sqlx"
)
// UserWithPasswordHash reprents a user including the password hash in the database
type UserWithPasswordHash struct {
models.User
PasswordHash string `json:"-" db:"password_hash"`
}
type sqlDriver struct {
Db *sqlx.DB
app *sqlAppConfigurationDriver
recipes *sqlRecipeDriver
images *sqlRecipeImageDriver
notes *sqlNoteDriver
links *sqlLinkDriver
users *sqlUserDriver
}
func newSQLDriver(db *sqlx.DB, adapter sqlRecipeDriverAdapter) *sqlDriver {
return &sqlDriver{
Db: db,
app: &sqlAppConfigurationDriver{db},
recipes: &sqlRecipeDriver{db, adapter},
images: &sqlRecipeImageDriver{db},
notes: &sqlNoteDriver{db},
links: &sqlLinkDriver{db},
users: &sqlUserDriver{db},
}
}
func (d *sqlDriver) AppConfiguration() AppConfigurationDriver {
return d.app
}
func (d *sqlDriver) Recipes() RecipeDriver {
return d.recipes
}
func (d *sqlDriver) Images() RecipeImageDriver {
return d.images
}
func (d *sqlDriver) Notes() NoteDriver {
return d.notes
}
func (d *sqlDriver) Links() LinkDriver {
return d.links
}
func (d *sqlDriver) Users() UserDriver {
return d.users
}
func (d *sqlDriver) Close() error {
slog.Debug("Closing database connection...")
if err := d.Db.Close(); err != nil {
return fmt.Errorf("failed to close the connection to the database: '%w'", err)
}
return nil
}
func get[T any](db sqlx.Queryer, op func(sqlx.Queryer) (T, error)) (T, error) {
t, err := op(db)
return t, mapSQLErrors(err)
}
func tx(db *sqlx.DB, op func(sqlx.Ext) error) error {
tx, err := db.Beginx()
if err != nil {
return err
}
defer func() {
if recv := recover(); recv != nil {
// Make sure to rollback after a panic...
_ = tx.Rollback()
// ... but let the panicing continue
panic(recv)
}
}()
if err = op(tx); err != nil {
_ = tx.Rollback()
return mapSQLErrors(err)
}
return tx.Commit()
}
func mapSQLErrors(err error) error {
if errors.Is(err, sql.ErrNoRows) {
return ErrNotFound
}
return err
}