watches.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2020 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package db
  5. import (
  6. "context"
  7. "github.com/pkg/errors"
  8. "gorm.io/gorm"
  9. )
  10. // WatchesStore is the persistent interface for watches.
  11. //
  12. // NOTE: All methods are sorted in alphabetical order.
  13. type WatchesStore interface {
  14. // ListByRepo returns all watches of the given repository.
  15. ListByRepo(ctx context.Context, repoID int64) ([]*Watch, error)
  16. // Watch marks the user to watch the repository.
  17. Watch(ctx context.Context, userID, repoID int64) error
  18. }
  19. var Watches WatchesStore
  20. var _ WatchesStore = (*watches)(nil)
  21. type watches struct {
  22. *gorm.DB
  23. }
  24. // NewWatchesStore returns a persistent interface for watches with given
  25. // database connection.
  26. func NewWatchesStore(db *gorm.DB) WatchesStore {
  27. return &watches{DB: db}
  28. }
  29. func (db *watches) ListByRepo(ctx context.Context, repoID int64) ([]*Watch, error) {
  30. var watches []*Watch
  31. return watches, db.WithContext(ctx).Where("repo_id = ?", repoID).Find(&watches).Error
  32. }
  33. func (db *watches) updateWatchingCount(tx *gorm.DB, repoID int64) error {
  34. /*
  35. Equivalent SQL for PostgreSQL:
  36. UPDATE repository
  37. SET num_watches = (
  38. SELECT COUNT(*) FROM watch WHERE repo_id = @repoID
  39. )
  40. WHERE id = @repoID
  41. */
  42. return tx.Model(&Repository{}).
  43. Where("id = ?", repoID).
  44. Update(
  45. "num_watches",
  46. tx.Model(&Watch{}).Select("COUNT(*)").Where("repo_id = ?", repoID),
  47. ).
  48. Error
  49. }
  50. func (db *watches) Watch(ctx context.Context, userID, repoID int64) error {
  51. return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  52. w := &Watch{
  53. UserID: userID,
  54. RepoID: repoID,
  55. }
  56. result := tx.FirstOrCreate(w, w)
  57. if result.Error != nil {
  58. return errors.Wrap(result.Error, "upsert")
  59. } else if result.RowsAffected <= 0 {
  60. return nil // Relation already exists
  61. }
  62. return db.updateWatchingCount(tx, repoID)
  63. })
  64. }