/
auditdb_read_store.go
128 lines (112 loc) · 2.48 KB
/
auditdb_read_store.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package analytic
import (
"database/sql"
"errors"
"time"
"github.com/authgear/authgear-server/pkg/lib/infra/db"
"github.com/authgear/authgear-server/pkg/lib/infra/db/auditdb"
)
type AuditDBReadStore struct {
SQLBuilder *auditdb.SQLBuilder
SQLExecutor *auditdb.ReadSQLExecutor
}
func (s *AuditDBReadStore) GetAnalyticCountByType(
appID string,
typ string,
date *time.Time,
) (*Count, error) {
builder := s.selectAnalyticCountQuery(appID).
Where("type = ?", typ).
Where("date = ?", date)
row, err := s.SQLExecutor.QueryRowWith(builder)
if err != nil {
return nil, err
}
count, err := s.scanAnalyticCount(row)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrAnalyticCountNotFound
} else if err != nil {
return nil, err
}
return count, nil
}
// GetAnalyticCountsByType get counts by type and date range
// the provided rangeFrom and rangeTo are inclusive
func (s *AuditDBReadStore) GetAnalyticCountsByType(
appID string,
typ string,
rangeFrom *time.Time,
rangeTo *time.Time,
) ([]*Count, error) {
builder := s.selectAnalyticCountQuery(appID).
Where("type = ?", typ).
Where("date >= ?", rangeFrom).
Where("date <= ?", rangeTo)
rows, err := s.SQLExecutor.QueryWith(builder)
if err != nil {
return nil, err
}
defer rows.Close()
var counts []*Count
for rows.Next() {
count, err := s.scanAnalyticCount(rows)
if err != nil {
return nil, err
}
counts = append(counts, count)
}
return counts, nil
}
func (s *AuditDBReadStore) GetSumOfAnalyticCountsByType(
appID string,
typ string,
rangeFrom *time.Time,
rangeTo *time.Time,
) (int, error) {
builder := s.SQLBuilder.WithAppID(appID).
Select(
"sum(count)",
).
From(s.SQLBuilder.TableName("_audit_analytic_count")).
Where("type = ?", typ).
Where("date >= ?", rangeFrom).
Where("date <= ?", rangeTo)
row, err := s.SQLExecutor.QueryRowWith(builder)
if err != nil {
return 0, err
}
var sum sql.NullInt64
err = row.Scan(&sum)
if err != nil {
return 0, err
}
if sum.Valid {
return int(sum.Int64), nil
}
return 0, nil
}
func (s *AuditDBReadStore) selectAnalyticCountQuery(appID string) db.SelectBuilder {
return s.SQLBuilder.WithAppID(appID).
Select(
"id",
"app_id",
"count",
"date",
"type",
).
From(s.SQLBuilder.TableName("_audit_analytic_count"))
}
func (s *AuditDBReadStore) scanAnalyticCount(scn db.Scanner) (*Count, error) {
c := &Count{}
err := scn.Scan(
&c.ID,
&c.AppID,
&c.Count,
&c.Date,
&c.Type,
)
if err != nil {
return nil, err
}
return c, nil
}