-
Notifications
You must be signed in to change notification settings - Fork 74
/
topic.go
365 lines (338 loc) · 10.2 KB
/
topic.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
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
package models
import (
"context"
"database/sql"
"fmt"
"strings"
"time"
"github.com/godiscourse/godiscourse/api/session"
"github.com/gofrs/uuid"
)
// Topic related CONST
const (
minTitleSize = 3
LIMIT = 50
)
const topicsDDL = `
CREATE TABLE IF NOT EXISTS topics (
topic_id VARCHAR(36) PRIMARY KEY,
title VARCHAR(512) NOT NULL,
body TEXT NOT NULL,
comments_count INTEGER NOT NULL DEFAULT 0,
category_id VARCHAR(36) NOT NULL,
user_id VARCHAR(36) NOT NULL REFERENCES users ON DELETE CASCADE,
score INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
CREATE INDEX ON topics (created_at DESC);
CREATE INDEX ON topics (user_id, created_at DESC);
CREATE INDEX ON topics (category_id, created_at DESC);
CREATE INDEX ON topics (score DESC, created_at DESC);
`
var topicCols = []string{"topic_id", "title", "body", "comments_count", "category_id", "user_id", "score", "created_at", "updated_at"}
func (t *Topic) values() []interface{} {
return []interface{}{t.TopicID, t.Title, t.Body, t.CommentsCount, t.CategoryID, t.UserID, t.Score, t.CreatedAt, t.UpdatedAt}
}
// Topic is what use talking about
type Topic struct {
TopicID string
Title string
Body string
CommentsCount int64
CategoryID string
UserID string
Score int
CreatedAt time.Time
UpdatedAt time.Time
User *User
Category *Category
}
//CreateTopic create a new Topic
func (user *User) CreateTopic(ctx context.Context, title, body, categoryID string) (*Topic, error) {
title, body = strings.TrimSpace(title), strings.TrimSpace(body)
if len(title) < minTitleSize {
return nil, session.BadDataError(ctx)
}
t := time.Now()
topic := &Topic{
TopicID: uuid.Must(uuid.NewV4()).String(),
Title: title,
Body: body,
UserID: user.UserID,
CreatedAt: t,
UpdatedAt: t,
}
err := runInTransaction(ctx, func(tx *sql.Tx) error {
category, err := findCategory(ctx, tx, categoryID)
if err != nil {
return err
}
if category == nil {
return session.BadDataError(ctx)
}
topic.CategoryID = category.CategoryID
category.LastTopicID = sql.NullString{String: topic.TopicID, Valid: true}
count, err := topicsCountByCategory(ctx, tx, category.CategoryID)
if err != nil {
return err
}
category.TopicsCount, category.UpdatedAt = count+1, time.Now()
cols, params := prepareColumnsWithValues(topicCols)
_, err = tx.ExecContext(ctx, fmt.Sprintf("INSERT INTO topics(%s) VALUES (%s)", cols, params), topic.values()...)
if err != nil {
return err
}
ccols, cparams := prepareColumnsWithValues([]string{"last_topic_id", "topics_count", "updated_at"})
cvals := []interface{}{category.LastTopicID, category.TopicsCount, category.UpdatedAt}
_, err = tx.ExecContext(ctx, fmt.Sprintf("UPDATE categories SET (%s)=(%s) WHERE category_id='%s'", ccols, cparams, category.CategoryID), cvals...)
if err != nil {
return err
}
_, err = upsertStatistic(ctx, tx, "topics")
return err
})
if err != nil {
if _, ok := err.(session.Error); ok {
return nil, err
}
return nil, session.TransactionError(ctx, err)
}
return topic, nil
}
// UpdateTopic update a Topic by ID
func (user *User) UpdateTopic(ctx context.Context, id, title, body, categoryID string) (*Topic, error) {
title, body = strings.TrimSpace(title), strings.TrimSpace(body)
if title != "" && len(title) < minTitleSize {
return nil, session.BadDataError(ctx)
}
var topic *Topic
var prevCategoryID string
err := runInTransaction(ctx, func(tx *sql.Tx) error {
var err error
topic, err = findTopic(ctx, tx, id)
if err != nil {
return err
} else if topic == nil {
return nil
} else if topic.UserID != user.UserID && !user.isAdmin() {
return session.AuthorizationError(ctx)
}
if title != "" {
topic.Title = title
}
topic.Body = body
if categoryID != "" && topic.CategoryID != categoryID {
prevCategoryID = topic.CategoryID
category, err := findCategory(ctx, tx, categoryID)
if err != nil {
return err
} else if category == nil {
return session.BadDataError(ctx)
}
topic.CategoryID = category.CategoryID
topic.Category = category
}
cols, params := prepareColumnsWithValues([]string{"title", "body", "category_id"})
vals := []interface{}{topic.Title, topic.Body, topic.CategoryID}
_, err = tx.ExecContext(ctx, fmt.Sprintf("UPDATE topics SET (%s)=(%s) WHERE topic_id='%s'", cols, params, topic.TopicID), vals...)
return err
})
if err != nil {
if _, ok := err.(session.Error); ok {
return nil, err
}
return nil, session.TransactionError(ctx, err)
}
if topic == nil {
return nil, session.NotFoundError(ctx)
}
if prevCategoryID != "" {
go ElevateCategory(ctx, prevCategoryID)
go ElevateCategory(ctx, topic.CategoryID)
}
topic.User = user
return topic, nil
}
//ReadTopic read a topic by ID
func ReadTopic(ctx context.Context, id string) (*Topic, error) {
var topic *Topic
err := runInTransaction(ctx, func(tx *sql.Tx) error {
var err error
topic, err = findTopic(ctx, tx, id)
if err != nil {
return err
}
user, err := findUserByID(ctx, tx, topic.UserID)
if err != nil {
return err
}
category, err := findCategory(ctx, tx, topic.CategoryID)
if err != nil {
return err
}
topic.User = user
topic.Category = category
return nil
})
if err != nil {
return nil, session.TransactionError(ctx, err)
}
return topic, nil
}
func findTopic(ctx context.Context, tx *sql.Tx, id string) (*Topic, error) {
if _, err := uuid.FromString(id); err != nil {
return nil, nil
}
rows, err := tx.QueryContext(ctx, fmt.Sprintf("SELECT %s FROM topics WHERE topic_id=$1", strings.Join(topicCols, ",")), id)
if err != nil {
return nil, err
}
defer rows.Close()
if !rows.Next() {
if err := rows.Err(); err != nil {
return nil, err
}
return nil, nil
}
t, err := topicFromRows(rows)
if err != nil {
return nil, err
}
return t, nil
}
// ReadTopics read all topics, parameters: offset default time.Now()
func ReadTopics(ctx context.Context, offset time.Time) ([]*Topic, error) {
if offset.IsZero() {
offset = time.Now()
}
set, err := readCategorySet(ctx)
if err != nil {
return nil, err
}
var topics []*Topic
rows, err := session.Database(ctx).QueryContext(ctx, fmt.Sprintf("SELECT %s FROM topics WHERE created_at<$1 ORDER BY created_at DESC LIMIT $2", strings.Join(topicCols, ",")), offset, LIMIT)
if err != nil {
return nil, session.TransactionError(ctx, err)
}
defer rows.Close()
userIds := []string{}
for rows.Next() {
topic, err := topicFromRows(rows)
if err != nil {
return nil, session.TransactionError(ctx, err)
}
userIds = append(userIds, topic.UserID)
topic.Category = set[topic.CategoryID]
topics = append(topics, topic)
}
if err := rows.Err(); err != nil {
return nil, session.TransactionError(ctx, err)
}
userSet, err := readUserSet(ctx, userIds)
if err != nil {
return nil, err
}
for i, topic := range topics {
topics[i].User = userSet[topic.UserID]
}
return topics, nil
}
// ReadTopics read user's topics, parameters: offset default time.Now()
func (user *User) ReadTopics(ctx context.Context, offset time.Time) ([]*Topic, error) {
if offset.IsZero() {
offset = time.Now()
}
set, err := readCategorySet(ctx)
if err != nil {
return nil, err
}
var topics []*Topic
rows, err := session.Database(ctx).QueryContext(ctx, fmt.Sprintf("SELECT %s FROM topics WHERE user_id=$1 AND created_at<$2 ORDER BY created_at DESC LIMIT $3", strings.Join(topicCols, ",")), user.UserID, offset, LIMIT)
if err != nil {
return nil, session.TransactionError(ctx, err)
}
defer rows.Close()
for rows.Next() {
topic, err := topicFromRows(rows)
if err != nil {
return nil, session.TransactionError(ctx, err)
}
topic.User = user
topic.Category = set[topic.CategoryID]
topics = append(topics, topic)
}
if err := rows.Err(); err != nil {
return nil, session.TransactionError(ctx, err)
}
return topics, nil
}
// ReadTopics read topics by CategoryID order by created_at DESC
func (category *Category) ReadTopics(ctx context.Context, offset time.Time) ([]*Topic, error) {
if offset.IsZero() {
offset = time.Now()
}
var topics []*Topic
rows, err := session.Database(ctx).QueryContext(ctx, fmt.Sprintf("SELECT %s FROM topics WHERE category_id=$1 AND created_at<$2 ORDER BY created_at DESC LIMIT $3", strings.Join(topicCols, ",")), category.CategoryID, offset, LIMIT)
if err != nil {
return nil, session.TransactionError(ctx, err)
}
defer rows.Close()
userIds := []string{}
for rows.Next() {
topic, err := topicFromRows(rows)
if err != nil {
return nil, session.TransactionError(ctx, err)
}
userIds = append(userIds, topic.UserID)
topic.Category = category
topics = append(topics, topic)
}
if err := rows.Err(); err != nil {
return nil, session.TransactionError(ctx, err)
}
userSet, err := readUserSet(ctx, userIds)
if err != nil {
return nil, err
}
for i, topic := range topics {
topics[i].User = userSet[topic.UserID]
}
return topics, nil
}
func (category *Category) lastTopic(ctx context.Context, tx *sql.Tx) (*Topic, error) {
rows, err := tx.QueryContext(ctx, fmt.Sprintf("SELECT %s FROM topics WHERE category_id=$1 LIMIT 1", strings.Join(topicCols, ",")), category.CategoryID)
if err != nil {
return nil, err
}
defer rows.Close()
if !rows.Next() {
if err := rows.Err(); err != nil {
return nil, err
}
return nil, nil
}
t, err := topicFromRows(rows)
if err != nil {
return nil, err
}
return t, nil
}
func topicsCountByCategory(ctx context.Context, tx *sql.Tx, id string) (int64, error) {
var count int64
err := tx.QueryRowContext(ctx, "SELECT count(*) FROM topics WHERE category_id=$1", id).Scan(&count)
if err != nil {
return 0, session.TransactionError(ctx, err)
}
return count, nil
}
func topicsCount(ctx context.Context, tx *sql.Tx) (int64, error) {
var count int64
err := tx.QueryRowContext(ctx, "SELECT count(*) FROM topics").Scan(&count)
return count, err
}
func topicFromRows(rows *sql.Rows) (*Topic, error) {
var t Topic
err := rows.Scan(&t.TopicID, &t.Title, &t.Body, &t.CommentsCount, &t.CategoryID, &t.UserID, &t.Score, &t.CreatedAt, &t.UpdatedAt)
return &t, err
}