organizations.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package database
  2. import (
  3. "context"
  4. "github.com/pkg/errors"
  5. "gorm.io/gorm"
  6. "gogs.io/gogs/internal/dbutil"
  7. )
  8. // OrganizationsStore is the storage layer for organizations.
  9. type OrganizationsStore struct {
  10. db *gorm.DB
  11. }
  12. func newOrganizationsStoreStore(db *gorm.DB) *OrganizationsStore {
  13. return &OrganizationsStore{db: db}
  14. }
  15. type ListOrgsOptions struct {
  16. // Filter by the membership with the given user ID.
  17. MemberID int64
  18. // Whether to include private memberships.
  19. IncludePrivateMembers bool
  20. }
  21. // List returns a list of organizations filtered by options.
  22. func (s *OrganizationsStore) List(ctx context.Context, opts ListOrgsOptions) ([]*Organization, error) {
  23. if opts.MemberID <= 0 {
  24. return nil, errors.New("MemberID must be greater than 0")
  25. }
  26. /*
  27. Equivalent SQL for PostgreSQL:
  28. SELECT * FROM "org"
  29. JOIN org_user ON org_user.org_id = org.id
  30. WHERE
  31. org_user.uid = @memberID
  32. [AND org_user.is_public = @includePrivateMembers]
  33. ORDER BY org.id ASC
  34. */
  35. tx := s.db.WithContext(ctx).
  36. Joins(dbutil.Quote("JOIN org_user ON org_user.org_id = %s.id", "user")).
  37. Where("org_user.uid = ?", opts.MemberID).
  38. Order(dbutil.Quote("%s.id ASC", "user"))
  39. if !opts.IncludePrivateMembers {
  40. tx = tx.Where("org_user.is_public = ?", true)
  41. }
  42. var orgs []*Organization
  43. return orgs, tx.Find(&orgs).Error
  44. }
  45. // SearchByName returns a list of organizations whose username or full name
  46. // matches the given keyword case-insensitively. Results are paginated by given
  47. // page and page size, and sorted by the given order (e.g. "id DESC"). A total
  48. // count of all results is also returned. If the order is not given, it's up to
  49. // the database to decide.
  50. func (s *OrganizationsStore) SearchByName(ctx context.Context, keyword string, page, pageSize int, orderBy string) ([]*Organization, int64, error) {
  51. return searchUserByName(ctx, s.db, UserTypeOrganization, keyword, page, pageSize, orderBy)
  52. }
  53. // CountByUser returns the number of organizations the user is a member of.
  54. func (s *OrganizationsStore) CountByUser(ctx context.Context, userID int64) (int64, error) {
  55. var count int64
  56. return count, s.db.WithContext(ctx).Model(&OrgUser{}).Where("uid = ?", userID).Count(&count).Error
  57. }
  58. type Organization = User
  59. func (o *Organization) TableName() string {
  60. return "user"
  61. }