-
Notifications
You must be signed in to change notification settings - Fork 247
/
persistence_metrics.go
63 lines (51 loc) · 1.62 KB
/
persistence_metrics.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
package protocol
import (
"database/sql"
"fmt"
"strings"
)
const selectTimestampsQuery = "SELECT whisper_timestamp FROM user_messages WHERE %s whisper_timestamp >= ? AND whisper_timestamp <= ?"
const selectCountQuery = "SELECT COUNT(*) FROM user_messages WHERE %s whisper_timestamp >= ? AND whisper_timestamp <= ?"
func querySeveralChats(chatIDs []string) string {
if len(chatIDs) == 0 {
return ""
}
var conditions []string
for _, chatID := range chatIDs {
conditions = append(conditions, fmt.Sprintf("local_chat_id = '%s'", chatID))
}
return fmt.Sprintf("(%s) AND", strings.Join(conditions, " OR "))
}
func (db sqlitePersistence) SelectMessagesTimestampsForChatsByPeriod(chatIDs []string, startTimestamp uint64, endTimestamp uint64) ([]uint64, error) {
query := fmt.Sprintf(selectTimestampsQuery, querySeveralChats(chatIDs))
rows, err := db.db.Query(query, startTimestamp, endTimestamp)
if err != nil {
return []uint64{}, err
}
defer rows.Close()
var timestamps []uint64
for rows.Next() {
var timestamp uint64
err := rows.Scan(×tamp)
if err != nil {
return nil, err
}
timestamps = append(timestamps, timestamp)
}
err = rows.Err()
if err != nil {
return []uint64{}, err
}
return timestamps, nil
}
func (db sqlitePersistence) SelectMessagesCountForChatsByPeriod(chatIDs []string, startTimestamp uint64, endTimestamp uint64) (int, error) {
query := fmt.Sprintf(selectCountQuery, querySeveralChats(chatIDs))
var count int
if err := db.db.QueryRow(query, startTimestamp, endTimestamp).Scan(&count); err != nil {
if err == sql.ErrNoRows {
return 0, nil
}
return 0, err
}
return count, nil
}