-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepocounter.go
More file actions
71 lines (61 loc) · 1.51 KB
/
repocounter.go
File metadata and controls
71 lines (61 loc) · 1.51 KB
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
package database
import (
"strings"
"github.com/jmoiron/sqlx"
)
type Counter interface {
// NumericArgs specifies whether to use numeric ($1, $2) or normal (?, ?) placeholder
NumericArgs(isNumeric bool) Counter
// Query set sql query
Query(query string) Counter
// Replace replace phrase in query string before run
Replace(old string, new string) Counter
// Result get count, returns -1 on error
Result(args ...any) (int64, error)
}
func NewCounter(db *sqlx.DB) Counter {
counter := new(counterDriver)
counter.db = db
counter.numeric = true
return counter
}
type counterDriver struct {
db *sqlx.DB
numeric bool
query string
replacements []string
}
func (counter *counterDriver) sql() string {
if counter.numeric {
return numericArgs(
strings.
NewReplacer(counter.replacements...).
Replace(counter.query),
1,
)
} else {
return strings.
NewReplacer(counter.replacements...).
Replace(counter.query)
}
}
func (counter *counterDriver) NumericArgs(numeric bool) Counter {
counter.numeric = numeric
return counter
}
func (counter *counterDriver) Query(query string) Counter {
counter.query = query
return counter
}
func (counter *counterDriver) Replace(old, new string) Counter {
counter.replacements = append(counter.replacements, old, new)
return counter
}
func (counter *counterDriver) Result(args ...any) (int64, error) {
var count int64
if err := counter.db.Get(&count, counter.sql(), args...); err != nil {
return -1, err
} else {
return count, nil
}
}