/
auditdb_write_store.go
59 lines (50 loc) · 1.09 KB
/
auditdb_write_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
package analytic
import (
"github.com/authgear/authgear-server/pkg/lib/infra/db/auditdb"
)
type AuditDBWriteStore struct {
SQLBuilder *auditdb.SQLBuilder
SQLExecutor *auditdb.WriteSQLExecutor
}
// UpsertCounts upsert counts in batches
func (s *AuditDBWriteStore) UpsertCounts(counts []*Count) error {
batchSize := 100
for i := 0; i < len(counts); i += batchSize {
j := i + batchSize
if j > len(counts) {
j = len(counts)
}
batch := counts[i:j]
err := s.upsertCounts(batch)
if err != nil {
return err
}
}
return nil
}
func (s *AuditDBWriteStore) upsertCounts(counts []*Count) error {
builder := s.SQLBuilder.WithoutAppID().
Insert(s.SQLBuilder.TableName("_audit_analytic_count")).
Columns(
"id",
"app_id",
"type",
"count",
"date",
)
for _, count := range counts {
builder = builder.Values(
count.ID,
count.AppID,
count.Type,
count.Count,
count.Date,
)
}
builder = builder.Suffix("ON CONFLICT (app_id, type, date) DO UPDATE SET count = excluded.count")
_, err := s.SQLExecutor.ExecWith(builder)
if err != nil {
return err
}
return nil
}