summaryrefslogtreecommitdiffstats
path: root/internal/storage/query.go
blob: 29a2a4cc53544b1a84684d0c8e1ceedd683ae8a3 (plain)
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package storage

import (
	"context"
	"fmt"
	"strings"

	"google.golang.org/protobuf/proto"

	pb "northwest.io/nostr-grpc/api/nostr/v1"
)

type QueryOptions struct {
	IncludeCanonical bool
	Limit            int32
}

func (s *Storage) QueryEvents(ctx context.Context, filters []*pb.Filter, opts *QueryOptions) ([]*pb.Event, error) {
	if len(filters) == 0 {
		return nil, nil
	}

	if opts == nil {
		opts = &QueryOptions{Limit: 100}
	}

	query, args := buildQuery(filters, opts)

	rows, err := s.db.QueryContext(ctx, query, args...)
	if err != nil {
		return nil, fmt.Errorf("query failed: %w", err)
	}
	defer rows.Close()

	var events []*pb.Event
	for rows.Next() {
		var eventBytes []byte
		var compressedJSON []byte
		var createdAt int64

		if opts.IncludeCanonical {
			if err := rows.Scan(&eventBytes, &compressedJSON, &createdAt); err != nil {
				return nil, fmt.Errorf("scan failed: %w", err)
			}
		} else {
			if err := rows.Scan(&eventBytes, &createdAt); err != nil {
				return nil, fmt.Errorf("scan failed: %w", err)
			}
		}

		event := &pb.Event{}
		if err := proto.Unmarshal(eventBytes, event); err != nil {
			return nil, fmt.Errorf("unmarshal failed: %w", err)
		}

		if opts.IncludeCanonical && compressedJSON != nil {
			canonicalJSON, err := decompressJSON(compressedJSON)
			if err != nil {
				return nil, fmt.Errorf("decompress failed: %w", err)
			}
			event.CanonicalJson = canonicalJSON
		}

		events = append(events, event)
	}

	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("rows iteration failed: %w", err)
	}

	return events, nil
}

func buildQuery(filters []*pb.Filter, opts *QueryOptions) (string, []interface{}) {
	selectFields := "event_data, created_at"
	if opts.IncludeCanonical {
		selectFields = "event_data, canonical_json, created_at"
	}

	var unions []string
	var args []interface{}

	for _, filter := range filters {
		clause, filterArgs := buildWhereClause(filter)
		subQuery := fmt.Sprintf("SELECT %s FROM events WHERE deleted = 0 AND (%s)", selectFields, clause)
		unions = append(unions, subQuery)
		args = append(args, filterArgs...)
	}

	query := strings.Join(unions, " UNION ")
	query += " ORDER BY created_at DESC"

	if opts.Limit > 0 {
		query += fmt.Sprintf(" LIMIT %d", opts.Limit)
	}

	return query, args
}

func buildWhereClause(filter *pb.Filter) (string, []interface{}) {
	var conditions []string
	var args []interface{}

	if len(filter.Ids) > 0 {
		conditions = append(conditions, buildPrefixCondition("id", filter.Ids, &args))
	}

	if len(filter.Authors) > 0 {
		conditions = append(conditions, buildPrefixCondition("pubkey", filter.Authors, &args))
	}

	if len(filter.Kinds) > 0 {
		placeholders := make([]string, len(filter.Kinds))
		for i, kind := range filter.Kinds {
			placeholders[i] = "?"
			args = append(args, kind)
		}
		conditions = append(conditions, fmt.Sprintf("kind IN (%s)", strings.Join(placeholders, ",")))
	}

	if filter.Since != nil && *filter.Since > 0 {
		conditions = append(conditions, "created_at >= ?")
		args = append(args, *filter.Since)
	}

	if filter.Until != nil && *filter.Until > 0 {
		conditions = append(conditions, "created_at <= ?")
		args = append(args, *filter.Until)
	}

	if len(filter.ETags) > 0 {
		conditions = append(conditions, buildTagCondition("e", filter.ETags, &args))
	}

	if len(filter.PTags) > 0 {
		conditions = append(conditions, buildTagCondition("p", filter.PTags, &args))
	}

	for tagName, tagFilter := range filter.TagFilters {
		if len(tagFilter.Values) > 0 {
			conditions = append(conditions, buildTagCondition(tagName, tagFilter.Values, &args))
		}
	}

	if len(conditions) == 0 {
		return "1=1", args
	}

	return strings.Join(conditions, " AND "), args
}

func buildPrefixCondition(column string, values []string, args *[]interface{}) string {
	var orConditions []string

	for _, val := range values {
		if len(val) == 64 {
			orConditions = append(orConditions, column+" = ?")
			*args = append(*args, val)
		} else {
			orConditions = append(orConditions, column+" LIKE ?")
			*args = append(*args, val+"%")
		}
	}

	if len(orConditions) == 1 {
		return orConditions[0]
	}

	return "(" + strings.Join(orConditions, " OR ") + ")"
}

func buildTagCondition(tagName string, values []string, args *[]interface{}) string {
	var orConditions []string

	for _, val := range values {
		orConditions = append(orConditions, "EXISTS (SELECT 1 FROM json_each(tags) WHERE json_extract(value, '$[0]') = ? AND json_extract(value, '$[1]') = ?)")
		*args = append(*args, tagName, val)
	}

	if len(orConditions) == 1 {
		return orConditions[0]
	}

	return "(" + strings.Join(orConditions, " OR ") + ")"
}