github.com/Azareal/Gosora@v0.0.0-20210729070923-553e66b59003/common/likes.go (about) 1 package common 2 3 import ( 4 "database/sql" 5 6 qgen "github.com/Azareal/Gosora/query_gen" 7 ) 8 9 var Likes LikeStore 10 11 type LikeStore interface { 12 BulkExists(ids []int, sentBy int, targetType string) ([]int, error) 13 BulkExistsFunc(ids []int, sentBy int, targetType string, f func(int) error) error 14 Delete(targetID int, targetType string) error 15 Count() (count int) 16 } 17 18 type DefaultLikeStore struct { 19 count *sql.Stmt 20 delete *sql.Stmt 21 singleExists *sql.Stmt 22 } 23 24 func NewDefaultLikeStore(acc *qgen.Accumulator) (*DefaultLikeStore, error) { 25 return &DefaultLikeStore{ 26 count: acc.Count("likes").Prepare(), 27 delete: acc.Delete("likes").Where("targetItem=? AND targetType=?").Prepare(), 28 singleExists: acc.Select("likes").Columns("targetItem").Where("sentBy=? AND targetType=? AND targetItem=?").Prepare(), 29 }, acc.FirstError() 30 } 31 32 // TODO: Write a test for this 33 func (s *DefaultLikeStore) BulkExists(ids []int, sentBy int, targetType string) (eids []int, e error) { 34 if len(ids) == 0 { 35 return nil, nil 36 } 37 var rows *sql.Rows 38 if len(ids) == 1 { 39 rows, e = s.singleExists.Query(sentBy, targetType, ids[0]) 40 } else { 41 rows, e = qgen.NewAcc().Select("likes").Columns("targetItem").Where("sentBy=? AND targetType=?").In("targetItem", ids).Query(sentBy, targetType) 42 } 43 if e == sql.ErrNoRows { 44 return nil, nil 45 } else if e != nil { 46 return nil, e 47 } 48 defer rows.Close() 49 50 var id int 51 for rows.Next() { 52 if e := rows.Scan(&id); e != nil { 53 return nil, e 54 } 55 eids = append(eids, id) 56 } 57 return eids, rows.Err() 58 } 59 60 // TODO: Write a test for this 61 func (s *DefaultLikeStore) BulkExistsFunc(ids []int, sentBy int, targetType string, f func(id int) error) (e error) { 62 if len(ids) == 0 { 63 return nil 64 } 65 var rows *sql.Rows 66 if len(ids) == 1 { 67 rows, e = s.singleExists.Query(sentBy, targetType, ids[0]) 68 } else { 69 rows, e = qgen.NewAcc().Select("likes").Columns("targetItem").Where("sentBy=? AND targetType=?").In("targetItem", ids).Query(sentBy, targetType) 70 } 71 if e == sql.ErrNoRows { 72 return nil 73 } else if e != nil { 74 return e 75 } 76 defer rows.Close() 77 78 var id int 79 for rows.Next() { 80 if e := rows.Scan(&id); e != nil { 81 return e 82 } 83 if e := f(id); e != nil { 84 return e 85 } 86 } 87 return rows.Err() 88 } 89 90 func (s *DefaultLikeStore) Delete(targetID int, targetType string) error { 91 _, err := s.delete.Exec(targetID, targetType) 92 return err 93 } 94 95 // TODO: Write a test for this 96 // Count returns the total number of likes globally 97 func (s *DefaultLikeStore) Count() (count int) { 98 e := s.count.QueryRow().Scan(&count) 99 if e != nil { 100 LogError(e) 101 } 102 return count 103 }