Newer
Older
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
package database
import (
"context"
"database/sql"
sq "github.com/Masterminds/squirrel"
"github.com/rs/zerolog"
)
// NewSQLHelper creates a SQLHelper. It must not outlive the given context and sql executor
func NewSQLHelper(ctx context.Context, sqle SQLExecutor, log zerolog.Logger) SQLHelper {
return SQLHelper{ctx, sqle, log}
}
// SQLHelper is a short lived helper to easily get/select Mapped structures
type SQLHelper struct {
ctx context.Context
sqle SQLExecutor
log zerolog.Logger
}
// Get loads a mapped structure
func (h *SQLHelper) Get(obj interface{}, query sq.Sqlizer) error {
return GetContext(h.ctx, h.sqle, obj, query, &h.log)
}
// GetByPKey loads a mapped structure
func (h *SQLHelper) GetByPKey(obj Mapped, value interface{}) error {
return h.GetBy(obj, obj.PKeyColumn(), value)
}
// GetBy ...
func (h *SQLHelper) GetBy(obj Mapped, column string, value interface{}) error {
return h.GetWhere(obj, sq.Eq{column: value})
}
// GetWhere loads a mapped structure
func (h *SQLHelper) GetWhere(obj Mapped, pred interface{}, args ...interface{}) error {
query := SQ.
Select(obj.Columns(true)...).
From(obj.Table()).
Where(pred, args...)
return h.Get(obj, query)
}
// Select loads a structure list
func (h *SQLHelper) Select(obj interface{}, query sq.Sqlizer) error {
return SelectContext(h.ctx, h.sqle, obj, query, &h.log)
}
// Exec executes a query
func (h *SQLHelper) Exec(query sq.Sqlizer) (sql.Result, error) {
return ExecContext(h.ctx, h.sqle, query, &h.log)
}
// Insert inserts a Mapped into the db
func (h *SQLHelper) Insert(instances ...Mapped) (sql.Result, error) {
query := SQLInsert(instances...)
return h.Exec(query)
}
// Upsert upserts a Mapped into the db
func (h *SQLHelper) Upsert(instances ...Mapped) error {
for _, instance := range instances {
query := SQLUpsert(instance)
if _, err := h.Exec(query); err != nil {
return err
}
}
return nil
}