-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathkbarticle.go
More file actions
445 lines (387 loc) · 12.3 KB
/
Copy pathkbarticle.go
File metadata and controls
445 lines (387 loc) · 12.3 KB
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
package database
import (
"context"
"time"
"github.com/jackc/pgtype"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
)
type KBArticle struct {
Id int `json:"id"`
GuildId uint64 `json:"guild_id,string"`
Title string `json:"title"`
Slug string `json:"slug"`
Description *string `json:"description"`
Content *string `json:"content"`
Embed *CustomEmbedWithFields `json:"embed"`
CategoryIds []int `json:"category_ids"`
Keywords []string `json:"keywords"`
Position int `json:"position"`
Published bool `json:"published"`
ShowHelpfulCount bool `json:"show_helpful_count"`
HelpfulCount int `json:"helpful_count"`
NotHelpfulCount int `json:"not_helpful_count"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type KBArticlesTable struct {
*pgxpool.Pool
}
func newKBArticles(db *pgxpool.Pool) *KBArticlesTable {
return &KBArticlesTable{
Pool: db,
}
}
func (t KBArticlesTable) Schema() string {
return `
CREATE TABLE IF NOT EXISTS kb_articles(
"id" SERIAL,
"guild_id" int8 NOT NULL,
"title" varchar(100) NOT NULL,
"slug" varchar(100) NOT NULL,
"description" varchar(255) DEFAULT NULL,
"content" text DEFAULT NULL CONSTRAINT kb_content_length CHECK (length(content) <= 4096),
"embed" JSONB DEFAULT NULL,
"category_ids" int4[] DEFAULT '{}',
"keywords" text[] DEFAULT '{}',
"position" int4 NOT NULL DEFAULT 0,
"published" bool NOT NULL DEFAULT true,
"show_helpful_count" bool NOT NULL DEFAULT false,
"helpful_count" int4 NOT NULL DEFAULT 0,
"not_helpful_count" int4 NOT NULL DEFAULT 0,
"search_vector" tsvector,
"created_at" timestamptz NOT NULL DEFAULT NOW(),
"updated_at" timestamptz NOT NULL DEFAULT NOW(),
PRIMARY KEY("id"),
UNIQUE("guild_id", "slug")
);
CREATE INDEX IF NOT EXISTS kb_articles_guild_id_idx ON kb_articles("guild_id");
CREATE INDEX IF NOT EXISTS kb_articles_keywords_idx ON kb_articles USING GIN("keywords");
CREATE INDEX IF NOT EXISTS kb_articles_search_idx ON kb_articles USING GIN("search_vector");
CREATE OR REPLACE FUNCTION kb_articles_search_vector_update() RETURNS trigger AS $$
BEGIN
NEW.search_vector :=
setweight(to_tsvector('english', coalesce(NEW.title, '')), 'A') ||
setweight(to_tsvector('english', coalesce(NEW.content, '')), 'B') ||
setweight(to_tsvector('english', coalesce(array_to_string(NEW.keywords, ' '), '')), 'C');
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
ALTER TABLE kb_articles ADD COLUMN IF NOT EXISTS "show_helpful_count" bool NOT NULL DEFAULT false;
ALTER TABLE kb_articles ADD COLUMN IF NOT EXISTS "helpful_count" int4 NOT NULL DEFAULT 0;
ALTER TABLE kb_articles ADD COLUMN IF NOT EXISTS "not_helpful_count" int4 NOT NULL DEFAULT 0;
DROP TRIGGER IF EXISTS kb_articles_search_vector_trigger ON kb_articles;
CREATE TRIGGER kb_articles_search_vector_trigger
BEFORE INSERT OR UPDATE ON kb_articles
FOR EACH ROW EXECUTE FUNCTION kb_articles_search_vector_update();
`
}
var kbArticleColumns = `"id", "guild_id", "title", "slug", "description", "content", "embed", "category_ids", "keywords", "position", "published", "show_helpful_count", "helpful_count", "not_helpful_count", "created_at", "updated_at"`
func scanKBArticle(row pgx.Row) (KBArticle, error) {
var article KBArticle
var embedRaw *string
var categoryIds pgtype.Int4Array
var keywords pgtype.TextArray
err := row.Scan(
&article.Id,
&article.GuildId,
&article.Title,
&article.Slug,
&article.Description,
&article.Content,
&embedRaw,
&categoryIds,
&keywords,
&article.Position,
&article.Published,
&article.ShowHelpfulCount,
&article.HelpfulCount,
&article.NotHelpfulCount,
&article.CreatedAt,
&article.UpdatedAt,
)
if err != nil {
return article, err
}
if embedRaw != nil {
if err := json.UnmarshalFromString(*embedRaw, &article.Embed); err != nil {
return article, err
}
}
article.CategoryIds = make([]int, 0)
if categoryIds.Status == pgtype.Present {
for _, el := range categoryIds.Elements {
if el.Status == pgtype.Present {
article.CategoryIds = append(article.CategoryIds, int(el.Int))
}
}
}
article.Keywords = make([]string, 0)
if keywords.Status == pgtype.Present {
for _, el := range keywords.Elements {
if el.Status == pgtype.Present {
article.Keywords = append(article.Keywords, el.String)
}
}
}
return article, nil
}
func (t *KBArticlesTable) GetByGuild(ctx context.Context, guildId uint64) ([]KBArticle, error) {
query := `
SELECT ` + kbArticleColumns + `
FROM kb_articles
WHERE "guild_id" = $1
ORDER BY "position" ASC, "id" ASC;
`
rows, err := t.Query(ctx, query, guildId)
if err != nil {
return nil, err
}
defer rows.Close()
var articles []KBArticle
for rows.Next() {
article, err := scanKBArticle(rows)
if err != nil {
return nil, err
}
articles = append(articles, article)
}
return articles, nil
}
func (t *KBArticlesTable) Get(ctx context.Context, id int) (KBArticle, bool, error) {
query := `
SELECT ` + kbArticleColumns + `
FROM kb_articles
WHERE "id" = $1;
`
article, err := scanKBArticle(t.QueryRow(ctx, query, id))
if err != nil {
if err == pgx.ErrNoRows {
return KBArticle{}, false, nil
}
return KBArticle{}, false, err
}
return article, true, nil
}
func (t *KBArticlesTable) GetBySlug(ctx context.Context, guildId uint64, slug string) (KBArticle, bool, error) {
query := `
SELECT ` + kbArticleColumns + `
FROM kb_articles
WHERE "guild_id" = $1 AND "slug" = $2 AND "published" = true;
`
article, err := scanKBArticle(t.QueryRow(ctx, query, guildId, slug))
if err != nil {
if err == pgx.ErrNoRows {
return KBArticle{}, false, nil
}
return KBArticle{}, false, err
}
return article, true, nil
}
func (t *KBArticlesTable) GetByCategory(ctx context.Context, guildId uint64, categoryId int) ([]KBArticle, error) {
query := `
SELECT ` + kbArticleColumns + `
FROM kb_articles
WHERE "guild_id" = $1 AND $2 = ANY("category_ids") AND "published" = true
ORDER BY "position" ASC, "id" ASC;
`
rows, err := t.Query(ctx, query, guildId, categoryId)
if err != nil {
return nil, err
}
defer rows.Close()
var articles []KBArticle
for rows.Next() {
article, err := scanKBArticle(rows)
if err != nil {
return nil, err
}
articles = append(articles, article)
}
return articles, nil
}
func (t *KBArticlesTable) Search(ctx context.Context, guildId uint64, query string, limit int) ([]KBArticle, error) {
// Use full-text search with ts_rank for relevance, plus ILIKE fallback for partial matches.
// Title matches (weight A) rank highest, then content (B), then keywords (C).
q := `
SELECT ` + kbArticleColumns + `
FROM kb_articles
WHERE "guild_id" = $1 AND "published" = true
AND (
("search_vector" IS NOT NULL AND "search_vector" @@ websearch_to_tsquery('english', $2))
OR "title" ILIKE '%' || $2 || '%'
OR "content" ILIKE '%' || $2 || '%'
OR EXISTS (SELECT 1 FROM unnest("keywords") kw WHERE kw ILIKE '%' || $2 || '%')
)
ORDER BY
ts_rank(coalesce("search_vector", ''::tsvector), websearch_to_tsquery('english', $2)) DESC,
CASE WHEN "title" ILIKE $2 || '%' THEN 0 ELSE 1 END,
"position" ASC
LIMIT $3;
`
rows, err := t.Query(ctx, q, guildId, query, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var articles []KBArticle
for rows.Next() {
article, err := scanKBArticle(rows)
if err != nil {
return nil, err
}
articles = append(articles, article)
}
return articles, nil
}
func (t *KBArticlesTable) SearchContaining(ctx context.Context, guildId uint64, substring string, limit int) ([]KBArticleSummary, error) {
// Full-text search for autocomplete, with ILIKE fallback for partial/short queries
query := `
SELECT "id", "title"
FROM kb_articles
WHERE "guild_id" = $1 AND "published" = true
AND (
("search_vector" IS NOT NULL AND "search_vector" @@ websearch_to_tsquery('english', $2))
OR "title" ILIKE '%' || $2 || '%'
)
ORDER BY
ts_rank(coalesce("search_vector", ''::tsvector), websearch_to_tsquery('english', $2)) DESC,
CASE WHEN "title" ILIKE $2 || '%' THEN 0 ELSE 1 END
LIMIT $3;
`
rows, err := t.Query(ctx, query, guildId, substring, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var results []KBArticleSummary
for rows.Next() {
var s KBArticleSummary
if err := rows.Scan(&s.Id, &s.Title); err != nil {
return nil, err
}
results = append(results, s)
}
return results, nil
}
// KBArticleSummary is a lightweight projection returned by autocomplete searches.
type KBArticleSummary struct {
Id int `json:"id"`
Title string `json:"title"`
}
func (t *KBArticlesTable) Create(ctx context.Context, article KBArticle) (int, error) {
query := `
INSERT INTO kb_articles("guild_id", "title", "slug", "description", "content", "embed", "category_ids", "keywords", "position", "published", "show_helpful_count")
VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
RETURNING "id";
`
var embedRaw *string
if article.Embed != nil {
tmp, err := json.MarshalToString(article.Embed)
if err != nil {
return 0, err
}
embedRaw = &tmp
}
categoryIds := toInt4Array(article.CategoryIds)
keywords := toTextArray(article.Keywords)
var id int
err := t.QueryRow(ctx, query,
article.GuildId,
article.Title,
article.Slug,
article.Description,
article.Content,
embedRaw,
categoryIds,
keywords,
article.Position,
article.Published,
article.ShowHelpfulCount,
).Scan(&id)
return id, err
}
func (t *KBArticlesTable) Update(ctx context.Context, article KBArticle) error {
query := `
UPDATE kb_articles
SET "title" = $2, "slug" = $3, "description" = $4, "content" = $5, "embed" = $6, "category_ids" = $7, "keywords" = $8, "position" = $9, "published" = $10, "show_helpful_count" = $11, "updated_at" = NOW()
WHERE "id" = $1 AND "guild_id" = $12;
`
var embedRaw *string
if article.Embed != nil {
tmp, err := json.MarshalToString(article.Embed)
if err != nil {
return err
}
embedRaw = &tmp
}
categoryIds := toInt4Array(article.CategoryIds)
keywords := toTextArray(article.Keywords)
_, err := t.Exec(ctx, query,
article.Id,
article.Title,
article.Slug,
article.Description,
article.Content,
embedRaw,
categoryIds,
keywords,
article.Position,
article.Published,
article.ShowHelpfulCount,
article.GuildId,
)
return err
}
// IncrementFeedback records one web vote. Kept out of Update so that saving an
// article cannot overwrite the tally.
func (t *KBArticlesTable) IncrementFeedback(ctx context.Context, guildId uint64, articleId int, helpful bool) error {
query := `
UPDATE kb_articles
SET "helpful_count" = "helpful_count" + CASE WHEN $3 THEN 1 ELSE 0 END,
"not_helpful_count" = "not_helpful_count" + CASE WHEN $3 THEN 0 ELSE 1 END
WHERE "id" = $2 AND "guild_id" = $1;
`
_, err := t.Exec(ctx, query, guildId, articleId, helpful)
return err
}
func (t *KBArticlesTable) SetPositions(ctx context.Context, guildId uint64, ordered []int) error {
if len(ordered) == 0 {
return nil
}
query := `
UPDATE kb_articles
SET "position" = data.position, "updated_at" = "updated_at"
FROM (SELECT unnest($2::int[]) AS id, generate_subscripts($2::int[], 1) - 1 AS position) AS data
WHERE kb_articles."id" = data.id AND kb_articles."guild_id" = $1;
`
_, err := t.Exec(ctx, query, guildId, toInt4Array(ordered))
return err
}
func (t *KBArticlesTable) Delete(ctx context.Context, guildId uint64, articleId int) error {
query := `DELETE FROM kb_articles WHERE "guild_id" = $1 AND "id" = $2;`
_, err := t.Exec(ctx, query, guildId, articleId)
return err
}
func (t *KBArticlesTable) GetCountByGuild(ctx context.Context, guildId uint64) (int, error) {
query := `SELECT COUNT(*) FROM kb_articles WHERE "guild_id" = $1;`
var count int
err := t.QueryRow(ctx, query, guildId).Scan(&count)
return count, err
}
func toInt4Array(ints []int) pgtype.Int4Array {
if len(ints) == 0 {
return pgtype.Int4Array{
Status: pgtype.Present,
}
}
elements := make([]pgtype.Int4, len(ints))
for i, v := range ints {
elements[i] = pgtype.Int4{Int: int32(v), Status: pgtype.Present}
}
return pgtype.Int4Array{
Elements: elements,
Dimensions: []pgtype.ArrayDimension{{Length: int32(len(ints)), LowerBound: 1}},
Status: pgtype.Present,
}
}