forked from stakwork/sphinx-tribes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
784 lines (668 loc) · 21.3 KB
/
db.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
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
package main
import (
"errors"
"fmt"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/jinzhu/gorm"
"github.com/lib/pq"
_ "github.com/lib/pq"
"github.com/rs/xid"
)
type database struct {
db *gorm.DB
}
// DB is the object
var DB database
func initDB() {
dbURL := os.Getenv("DATABASE_URL")
fmt.Printf("db url : %v", dbURL)
if dbURL == "" {
rdsHost := os.Getenv("RDS_HOSTNAME")
rdsPort := os.Getenv("RDS_PORT")
rdsDbName := os.Getenv("RDS_DB_NAME")
rdsUsername := os.Getenv("RDS_USERNAME")
rdsPassword := os.Getenv("RDS_PASSWORD")
dbURL = fmt.Sprintf("postgres://%s:%s@%s:%s/%s", rdsUsername, rdsPassword, rdsHost, rdsPort, rdsDbName)
}
if dbURL == "" {
panic("DB env vars not found")
}
var err error
db, err := gorm.Open("postgres", dbURL)
db.LogMode(true)
if err != nil {
panic(err)
}
DB.db = db
fmt.Println("db connected")
// migrate table changes
db.AutoMigrate(&Person{}, &Channel{}, &LeaderBoard{}, &ConnectionCodes{})
people := DB.getAllPeople()
for _, p := range people {
if p.Uuid == "" {
DB.addUuidToPerson(p.ID, xid.New().String())
}
}
}
var updatables = []string{
"name", "description", "tags", "img",
"owner_alias", "price_to_join", "price_per_message",
"escrow_amount", "escrow_millis",
"unlisted", "private", "deleted",
"app_url", "bots", "feed_url", "feed_type",
"owner_route_hint", "updated", "pin",
"profile_filters",
}
var botupdatables = []string{
"name", "description", "tags", "img",
"owner_alias", "price_per_use",
"unlisted", "deleted",
"owner_route_hint", "updated",
}
var peopleupdatables = []string{
"description", "tags", "img",
"owner_alias",
"unlisted", "deleted",
"owner_route_hint",
"price_to_meet", "updated",
"extras",
}
var channelupdatables = []string{
"name", "deleted"}
// check that update owner_pub_key does in fact throw error
func (db database) createOrEditTribe(m Tribe) (Tribe, error) {
if m.OwnerPubKey == "" {
return Tribe{}, errors.New("no pub key")
}
onConflict := "ON CONFLICT (uuid) DO UPDATE SET"
for i, u := range updatables {
onConflict = onConflict + fmt.Sprintf(" %s=EXCLUDED.%s", u, u)
if i < len(updatables)-1 {
onConflict = onConflict + ","
}
}
if m.Name == "" {
m.Name = "name"
}
if m.Description == "" {
m.Description = "description"
}
if m.Tags == nil {
m.Tags = []string{}
}
if m.Badges == nil {
m.Badges = []string{}
}
if err := db.db.Set("gorm:insert_option", onConflict).Create(&m).Error; err != nil {
fmt.Println(">>>>>>>>> == ", err)
return Tribe{}, err
}
db.db.Exec(`UPDATE tribes SET tsv =
setweight(to_tsvector(name), 'A') ||
setweight(to_tsvector(description), 'B') ||
setweight(array_to_tsvector(tags), 'C')
WHERE uuid = '` + m.UUID + "'")
return m, nil
}
func (db database) createChannel(c Channel) (Channel, error) {
if c.Created == nil {
now := time.Now()
c.Created = &now
}
db.db.Create(&c)
return c, nil
}
// check that update owner_pub_key does in fact throw error
func (db database) createOrEditBot(b Bot) (Bot, error) {
if b.OwnerPubKey == "" {
return Bot{}, errors.New("no pub key")
}
if b.UniqueName == "" {
return Bot{}, errors.New("no unique name")
}
onConflict := "ON CONFLICT (uuid) DO UPDATE SET"
for i, u := range botupdatables {
onConflict = onConflict + fmt.Sprintf(" %s=EXCLUDED.%s", u, u)
if i < len(botupdatables)-1 {
onConflict = onConflict + ","
}
}
if b.Name == "" {
b.Name = "name"
}
if b.Description == "" {
b.Description = "description"
}
if b.Tags == nil {
b.Tags = []string{}
}
if err := db.db.Set("gorm:insert_option", onConflict).Create(&b).Error; err != nil {
fmt.Println(err)
return Bot{}, err
}
db.db.Exec(`UPDATE bots SET tsv =
setweight(to_tsvector(name), 'A') ||
setweight(to_tsvector(description), 'B') ||
setweight(array_to_tsvector(tags), 'C')
WHERE uuid = '` + b.UUID + "'")
return b, nil
}
// check that update owner_pub_key does in fact throw error
func (db database) createOrEditPerson(m Person) (Person, error) {
if m.OwnerPubKey == "" {
return Person{}, errors.New("no pub key")
}
onConflict := "ON CONFLICT (id) DO UPDATE SET"
for i, u := range peopleupdatables {
onConflict = onConflict + fmt.Sprintf(" %s=EXCLUDED.%s", u, u)
if i < len(peopleupdatables)-1 {
onConflict = onConflict + ","
}
}
if m.OwnerAlias == "" {
m.OwnerAlias = "name"
}
if m.Description == "" {
m.Description = "description"
}
if m.Tags == nil {
m.Tags = []string{}
}
if m.Extras == nil {
m.Extras = map[string]interface{}{}
}
if m.GithubIssues == nil {
m.GithubIssues = map[string]interface{}{}
}
if err := db.db.Set("gorm:insert_option", onConflict).Create(&m).Error; err != nil {
fmt.Println(err)
return Person{}, err
}
db.db.Exec(`UPDATE people SET tsv =
setweight(to_tsvector(owner_alias), 'A') ||
setweight(to_tsvector(description), 'B') ||
setweight(array_to_tsvector(tags), 'C')
WHERE id = '` + strconv.Itoa(int(m.ID)) + "'")
return m, nil
}
func (db database) getUnconfirmedTwitter() []Person {
ms := []Person{}
db.db.Raw(`SELECT * FROM people where extras -> 'twitter' IS NOT NULL and twitter_confirmed = 'f';`).Find(&ms)
return ms
}
func (db database) updateTwitterConfirmed(id uint, confirmed bool) {
if id == 0 {
return
}
db.db.Model(&Person{}).Where("id = ?", id).Updates(map[string]interface{}{
"twitter_confirmed": confirmed,
})
}
func (db database) addUuidToPerson(id uint, uuid string) {
if id == 0 {
return
}
db.db.Model(&Person{}).Where("id = ?", id).Updates(map[string]interface{}{
"uuid": uuid,
})
}
func (db database) getUnconfirmedGithub() []Person {
ms := []Person{}
db.db.Raw(`SELECT * FROM people where extras -> 'github' IS NOT NULL and github_confirmed = 'f';`).Find(&ms)
return ms
}
func (db database) updateGithubConfirmed(id uint, confirmed bool) {
if id == 0 {
return
}
db.db.Model(&Person{}).Where("id = ?", id).Updates(map[string]interface{}{
"github_confirmed": confirmed,
})
}
func (db database) updateGithubIssues(id uint, issues map[string]interface{}) {
db.db.Model(&Person{}).Where("id = ?", id).Updates(map[string]interface{}{
"github_issues": issues,
})
}
func (db database) updateTribe(uuid string, u map[string]interface{}) bool {
if uuid == "" {
return false
}
db.db.Model(&Tribe{}).Where("uuid = ?", uuid).Updates(u)
return true
}
func (db database) updateChannel(id uint, u map[string]interface{}) bool {
if id == 0 {
return false
}
db.db.Model(&Channel{}).Where("id= ?", id).Updates(u)
return true
}
func (db database) updatePerson(id uint, u map[string]interface{}) bool {
if id == 0 {
return false
}
db.db.Model(&Person{}).Where("id = ?", id).Updates(u)
return true
}
func (db database) updateTribeUniqueName(uuid string, u string) {
if uuid == "" {
return
}
// fmt.Println(u)
db.db.Model(&Tribe{}).Where("uuid = ?", uuid).Update("unique_name", u)
}
type GithubOpenIssue struct {
Status string `json:"status"`
Assignee string `json:"assignee"`
}
func (db database) getOpenGithubIssues(r *http.Request) (int64, error) {
ms := []GithubOpenIssue{}
// set limit
result := db.db.Raw(
`SELECT COUNT(value)
FROM (
SELECT *
FROM people
WHERE github_issues IS NOT NULL
AND github_issues != 'null'
) p,
jsonb_each(github_issues) t2
WHERE value @> '{"status": "open"}' OR value @> '{"status": ""}'`).Find(&ms)
return result.RowsAffected, result.Error
}
func (db database) getListedTribes(r *http.Request) []Tribe {
ms := []Tribe{}
keys := r.URL.Query()
tags := keys.Get("tags") // this is a string of tags separated by commas
offset, limit, sortBy, direction, search := getPaginationParams(r)
thequery := db.db.Offset(offset).Limit(limit).Order(sortBy+" "+direction).Where("(unlisted = 'f' OR unlisted is null) AND (deleted = 'f' OR deleted is null)").Where("LOWER(name) LIKE ?", "%"+search+"%")
if tags != "" {
// pull out the tags and add them in here
t := strings.Split(tags, ",")
for _, s := range t {
thequery = thequery.Where("'" + s + "'" + " = any (tags)")
}
}
thequery.Find(&ms)
return ms
}
func (db database) getTribesByOwner(pubkey string) []Tribe {
ms := []Tribe{}
db.db.Where("owner_pub_key = ? AND (unlisted = 'f' OR unlisted is null) AND (deleted = 'f' OR deleted is null)", pubkey).Find(&ms)
return ms
}
func (db database) getAllTribesByOwner(pubkey string) []Tribe {
ms := []Tribe{}
db.db.Where("owner_pub_key = ? AND (deleted = 'f' OR deleted is null)", pubkey).Find(&ms)
return ms
}
func (db database) getChannelsByTribe(tribe_uuid string) []Channel {
ms := []Channel{}
db.db.Where("tribe_uuid = ? AND (deleted = 'f' OR deleted is null)", tribe_uuid).Find(&ms)
return ms
}
func (db database) getChannel(id uint) Channel {
ms := Channel{}
db.db.Where("id = ? AND (deleted = 'f' OR deleted is null)", id).Find(&ms)
return ms
}
func (db database) getListedBots(r *http.Request) []Bot {
ms := []Bot{}
offset, limit, sortBy, direction, search := getPaginationParams(r)
// db.db.Where("(unlisted = 'f' OR unlisted is null) AND (deleted = 'f' OR deleted is null)").Find(&ms)
db.db.Offset(offset).Limit(limit).Order(sortBy+" "+direction).Where("(unlisted = 'f' OR unlisted is null) AND (deleted = 'f' OR deleted is null)").Where("LOWER(name) LIKE ?", "%"+search+"%").Find(&ms)
return ms
}
func (db database) getListedPeople(r *http.Request) []Person {
ms := []Person{}
offset, limit, sortBy, direction, search := getPaginationParams(r)
// if search is empty, returns all
db.db.Offset(offset).Limit(limit).Order(sortBy+" "+direction+" NULLS LAST").Where("(unlisted = 'f' OR unlisted is null) AND (deleted = 'f' OR deleted is null)").Where("LOWER(owner_alias) LIKE ?", "%"+search+"%").Find(&ms)
return ms
}
func (db database) getAllPeople() []Person {
ms := []Person{}
// if search is empty, returns all
db.db.Where("(unlisted = 'f' OR unlisted is null) AND (deleted = 'f' OR deleted is null)").Find(&ms)
return ms
}
func (db database) getPeopleBySearch(r *http.Request) []Person {
ms := []Person{}
offset, limit, sortBy, direction, search := getPaginationParams(r)
// if search is empty, returns all
// return if like owner_alias, unique_name, or equals pubkey
db.db.Offset(offset).Limit(limit).Order(sortBy+" "+direction+" NULLS LAST").Where("(unlisted = 'f' OR unlisted is null) AND (deleted = 'f' OR deleted is null)").Where("LOWER(owner_alias) LIKE ?", "%"+search+"%").Or("LOWER(unique_name) LIKE ?", "%"+search+"%").Or("LOWER(owner_pub_key) = ?", search).Find(&ms)
return ms
}
type PeopleExtra struct {
Body string `json:"body"`
Person string `json:"person"`
}
func makeExtrasListQuery(columnName string) string {
// this is safe because columnName is not provided by the user, its hard-coded in db.go
return `SELECT
json_build_object('owner_pubkey', owner_pub_key, 'owner_alias', owner_alias, 'img', img, 'unique_name', unique_name, 'id', id, '` + columnName + `', extras->'` + columnName + `', 'github_issues', github_issues) #>> '{}' as person,
arr.item_object as body
FROM people,
jsonb_array_elements(extras->'` + columnName + `') with ordinality
arr(item_object, position)
WHERE people.deleted != true
AND people.unlisted != true
AND LOWER(arr.item_object->>'title') LIKE ?
AND CASE
WHEN arr.item_object->>'show' = 'false' THEN false
ELSE true
END`
}
func addNewerThanXDaysToExtrasRawQuery(query string, days int) string {
secondsInDay := 86400
newerThan := secondsInDay * days
t := strconv.Itoa(newerThan)
return query + ` AND CAST(arr.item_object->>'created' AS INT) > (extract(epoch from now()) - ` + t + `) `
}
func addNewerThanTimestampToExtrasRawQuery(query string, timestamp int) string {
t := strconv.Itoa(timestamp)
return query + ` AND CAST(arr.item_object->>'created' AS INT) > ` + t
}
func addNotMineToExtrasRawQuery(query string, pubkey string) string {
return query + ` AND people.owner_pub_key != ` + pubkey + ` `
}
func (db database) getListedPosts(r *http.Request) ([]PeopleExtra, error) {
ms := []PeopleExtra{}
// set limit
offset, limit, sortBy, _, search := getPaginationParams(r)
rawQuery := makeExtrasListQuery("post")
// if logged in, dont get mine
ctx := r.Context()
pubKeyFromAuth, _ := ctx.Value(ContextKey).(string)
if pubKeyFromAuth != "" {
rawQuery = addNotMineToExtrasRawQuery(rawQuery, pubKeyFromAuth)
}
// sort by newest
result := db.db.Offset(offset).Limit(limit).Order("arr.item_object->>'"+sortBy+"' DESC").Raw(
rawQuery, "%"+search+"%").Find(&ms)
return ms, result.Error
}
func (db database) getListedWanteds(r *http.Request) ([]PeopleExtra, error) {
ms := []PeopleExtra{}
// set limit
offset, limit, sortBy, _, search := getPaginationParams(r)
rawQuery := makeExtrasListQuery("wanted")
// 3/1/2022 = 1646172712, we do this to disclude early test tickets
rawQuery = addNewerThanTimestampToExtrasRawQuery(rawQuery, 1646172712)
// if logged in, dont get mine
ctx := r.Context()
pubKeyFromAuth, _ := ctx.Value(ContextKey).(string)
if pubKeyFromAuth != "" {
rawQuery = addNotMineToExtrasRawQuery(rawQuery, pubKeyFromAuth)
}
// sort by newest
result := db.db.Offset(offset).Limit(limit).Order("arr.item_object->>'"+sortBy+"' DESC").Raw(
rawQuery, "%"+search+"%").Find(&ms)
return ms, result.Error
}
func (db database) getPeopleForNewTicket(languages []interface{}) ([]Person, error) {
ms := []Person{}
query := "Select owner_pub_key, json_build_object('coding_languages',extras->'coding_languages') as extras from people" +
" where (deleted != true AND unlisted != true) AND " +
"extras->'alert' = 'true' AND ("
for _, lang := range languages {
l, ok := lang.(map[string]interface{})
if !ok {
return ms, errors.New("could not parse coding languages correctly")
}
label, ok2 := l["label"].(string)
if !ok2 {
return ms, errors.New("could not find label in language")
}
query += "extras->'coding_languages' @> '[{\"label\": \"" + label + "\"}]' OR "
}
query = query[:len(query)-4]
query += ");"
err := db.db.Raw(query).Find(&ms).Error
return ms, err
}
func (db database) getListedOffers(r *http.Request) ([]PeopleExtra, error) {
ms := []PeopleExtra{}
// set limit
offset, limit, sortBy, _, search := getPaginationParams(r)
rawQuery := makeExtrasListQuery("offer")
// if logged in, dont get mine
ctx := r.Context()
pubKeyFromAuth, _ := ctx.Value(ContextKey).(string)
if pubKeyFromAuth != "" {
rawQuery = addNotMineToExtrasRawQuery(rawQuery, pubKeyFromAuth)
}
// sort by newest
result := db.db.Offset(offset).Limit(limit).Order("arr.item_object->>'"+sortBy+"' DESC").Raw(
rawQuery, "%"+search+"%").Find(&ms)
return ms, result.Error
}
func (db database) updateBot(uuid string, u map[string]interface{}) bool {
if uuid == "" {
return false
}
db.db.Model(&Bot{}).Where("uuid = ?", uuid).Updates(u)
return true
}
func (db database) getAllTribes() []Tribe {
ms := []Tribe{}
db.db.Where("(deleted = 'f' OR de leted is null)").Find(&ms)
return ms
}
func (db database) getTribesTotal() uint64 {
var count uint64
db.db.Model(&Tribe{}).Where("deleted = 'false' OR deleted is null").Count(&count)
return count
}
func (db database) getTribeByIdAndPubkey(uuid string, pubkey string) Tribe {
m := Tribe{}
//db.db.Where("uuid = ? AND (deleted = 'f' OR deleted is null) AND owner_pubkey = ?", uuid, pubkey).Find(&m)
db.db.Where("uuid = ? AND owner_pub_key = ?", uuid, pubkey).Find(&m)
return m
}
func (db database) getTribe(uuid string) Tribe {
m := Tribe{}
db.db.Where("uuid = ? AND (deleted = 'f' OR deleted is null)", uuid).Find(&m)
return m
}
func (db database) getPerson(id uint) Person {
m := Person{}
db.db.Where("id = ? AND (deleted = 'f' OR deleted is null)", id).Find(&m)
return m
}
func (db database) getPersonByPubkey(pubkey string) Person {
m := Person{}
db.db.Where("owner_pub_key = ? AND (deleted = 'f' OR deleted is null)", pubkey).Find(&m)
return m
}
func (db database) getPersonByUuid(uuid string) Person {
m := Person{}
db.db.Where("uuid = ? AND (deleted = 'f' OR deleted is null)", uuid).Find(&m)
return m
}
func (db database) getPersonByGithubName(github_name string) Person {
m := Person{}
db.db.Raw(`SELECT
json_build_object('owner_pubkey', owner_pub_key, 'owner_alias', owner_alias, 'img', img, 'unique_name', unique_name, 'id', id, 'wanted', extras->'wanted', 'github_issues', github_issues) #>> '{}' as person,
FROM people,
jsonb_array_elements(extras->'github') with ordinality
arr(item_object, position)
WHERE people.deleted != true
AND people.unlisted != true
AND CASE
WHEN arr.item_object->>'value' = ? THEN true
ELSE false
END`, github_name).First(&m)
return m
}
func (db database) getFirstTribeByFeedURL(feedURL string) Tribe {
m := Tribe{}
db.db.Where("feed_url = ? AND (deleted = 'f' OR deleted is null)", feedURL).First(&m)
return m
}
func (db database) getBot(uuid string) Bot {
m := Bot{}
db.db.Where("uuid = ? AND (deleted = 'f' OR deleted is null)", uuid).Find(&m)
return m
}
func (db database) getTribeByUniqueName(un string) Tribe {
m := Tribe{}
db.db.Where("unique_name = ? AND (deleted = 'f' OR deleted is null)", un).Find(&m)
return m
}
func (db database) getBotsByOwner(pubkey string) []Bot {
bs := []Bot{}
db.db.Where("owner_pub_key = ?", pubkey).Find(&bs)
return bs
}
func (db database) getBotByUniqueName(un string) Bot {
m := Bot{}
db.db.Where("unique_name = ? AND (deleted = 'f' OR deleted is null)", un).Find(&m)
return m
}
func (db database) getPersonByUniqueName(un string) Person {
m := Person{}
db.db.Where("unique_name = ? AND (deleted = 'f' OR deleted is null)", un).Find(&m)
return m
}
func (db database) searchTribes(s string) []Tribe {
ms := []Tribe{}
if s == "" {
return ms
}
// set limit
db.db.Raw(
`SELECT uuid, owner_pub_key, name, img, description, ts_rank(tsv, q) as rank
FROM tribes, to_tsquery(?) q
WHERE tsv @@ q
AND (deleted = 'f' OR deleted is null)
ORDER BY rank DESC LIMIT 100;`, s).Find(&ms)
return ms
}
func (db database) searchBots(s string, limit, offset int) []BotRes {
ms := []BotRes{}
if s == "" {
return ms
}
// set limit
limitStr := strconv.Itoa(limit)
offsetStr := strconv.Itoa(offset)
db.db.Raw(
`SELECT uuid, owner_pub_key, name, unique_name, img, description, tags, price_per_use, ts_rank(tsv, q) as rank
FROM bots, to_tsquery(?) q
WHERE tsv @@ q
AND (deleted = 'f' OR deleted is null)
ORDER BY rank DESC
LIMIT ? OFFSET ?;`, s, limitStr, offsetStr).Find(&ms)
return ms
}
func (db database) searchPeople(s string, limit, offset int) []Person {
ms := []Person{}
if s == "" {
return ms
}
// set limit
limitStr := strconv.Itoa(limit)
offsetStr := strconv.Itoa(offset)
db.db.Raw(
`SELECT id, owner_pub_key, unique_name, img, description, tags, ts_rank(tsv, q) as rank
FROM people, to_tsquery(?) q
WHERE tsv @@ q
AND (deleted = 'f' OR deleted is null)
ORDER BY rank DESC
LIMIT ? OFFSET ?;`, s, limitStr, offsetStr).Find(&ms)
return ms
}
func (db database) createLeaderBoard(uuid string, leaderboards []LeaderBoard) ([]LeaderBoard, error) {
m := LeaderBoard{}
db.db.Where("tribe_uuid = ?", uuid).Delete(&m)
for _, leaderboard := range leaderboards {
leaderboard.TribeUuid = uuid
db.db.Create(leaderboard)
}
return leaderboards, nil
}
func (db database) getLeaderBoard(uuid string) []LeaderBoard {
m := []LeaderBoard{}
db.db.Where("tribe_uuid = ?", uuid).Find(&m)
return m
}
func (db database) getLeaderBoardByUuidAndAlias(uuid string, alias string) LeaderBoard {
m := LeaderBoard{}
db.db.Where("tribe_uuid = ? and alias = ?", uuid, alias).Find(&m)
return m
}
func (db database) updateLeaderBoard(uuid string, alias string, u map[string]interface{}) bool {
if uuid == "" {
return false
}
db.db.Model(&LeaderBoard{}).Where("tribe_uuid = ? and alias = ?", uuid, alias).Updates(u)
return true
}
func (db database) countDevelopers() uint64 {
var count uint64
db.db.Model(&Person{}).Where("deleted = 'f' OR deleted is null").Count(&count)
return count
}
func (db database) countBounties() uint64 {
var count struct {
Sum uint64 `db:"sum"`
}
db.db.Raw(`Select sum(jsonb_array_length(extras -> 'wanted')) from people where
people.deleted = 'f' OR people.deleted is null`).Scan(&count)
return count.Sum
}
func (db database) getPeopleListShort(count uint32) *[]PersonInShort {
p := []PersonInShort{}
db.db.Raw(
`SELECT id, owner_pub_key, unique_name, img, uuid, owner_alias
FROM people
WHERE
(deleted = 'f' OR deleted is null)
ORDER BY random()
LIMIT ?;`, count).Find(&p)
return &p
}
func (db database) createConnectionCode(c ConnectionCodes) (ConnectionCodes, error) {
if c.DateCreated == nil {
now := time.Now()
c.DateCreated = &now
}
db.db.Create(&c)
return c, nil
}
func (db database) getConnectionCode() ConnectionCodesShort {
c := ConnectionCodesShort{}
db.db.Raw(`SELECT connection_string, date_created FROM connectioncodes WHERE is_used =? ORDER BY id DESC LIMIT 1`, false).Find(&c)
db.db.Model(&ConnectionCodes{}).Where("connection_string = ?", c.ConnectionString).Updates(map[string]interface{}{
"is_used": true,
})
return c
}
func (db database) getLnUser(lnKey string) uint64 {
var count uint64
db.db.Model(&Person{}).Where("owner_pub_key = ?", lnKey).Count(&count)
return count
}
func (db database) createLnUser(lnKey string) (Person, error) {
now := time.Now()
p := Person{}
if db.getLnUser(lnKey) == 0 {
p.OwnerPubKey = lnKey
p.OwnerAlias = lnKey
p.UniqueName, _ = personUniqueNameFromName(p.OwnerAlias)
p.Created = &now
p.Tags = pq.StringArray{}
p.Uuid = xid.New().String()
p.Extras = map[string]interface{}{}
p.GithubIssues = map[string]interface{}{}
db.db.Create(&p)
}
return p, nil
}