organizations.go 2.4 KB

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