orgs.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 db
  5. import (
  6. "context"
  7. "github.com/pkg/errors"
  8. "gorm.io/gorm"
  9. "gogs.io/gogs/internal/dbutil"
  10. )
  11. // OrgsStore is the persistent interface for organizations.
  12. //
  13. // NOTE: All methods are sorted in alphabetical order.
  14. type OrgsStore interface {
  15. // List returns a list of organizations filtered by options.
  16. List(ctx context.Context, opts ListOrgsOptions) ([]*Organization, error)
  17. }
  18. var Orgs OrgsStore
  19. var _ OrgsStore = (*orgs)(nil)
  20. type orgs struct {
  21. *gorm.DB
  22. }
  23. // NewOrgsStore returns a persistent interface for orgs with given database
  24. // connection.
  25. func NewOrgsStore(db *gorm.DB) OrgsStore {
  26. return &orgs{DB: db}
  27. }
  28. type ListOrgsOptions struct {
  29. // Filter by the membership with the given user ID.
  30. MemberID int64
  31. // Whether to include private memberships.
  32. IncludePrivateMembers bool
  33. }
  34. func (db *orgs) List(ctx context.Context, opts ListOrgsOptions) ([]*Organization, error) {
  35. if opts.MemberID <= 0 {
  36. return nil, errors.New("MemberID must be greater than 0")
  37. }
  38. /*
  39. Equivalent SQL for PostgreSQL:
  40. SELECT * FROM "org"
  41. JOIN org_user ON org_user.org_id = org.id
  42. WHERE
  43. org_user.uid = @memberID
  44. [AND org_user.is_public = @includePrivateMembers]
  45. ORDER BY org.id ASC
  46. */
  47. tx := db.WithContext(ctx).
  48. Joins(dbutil.Quote("JOIN org_user ON org_user.org_id = %s.id", "user")).
  49. Where("org_user.uid = ?", opts.MemberID).
  50. Order(dbutil.Quote("%s.id ASC", "user"))
  51. if !opts.IncludePrivateMembers {
  52. tx = tx.Where("org_user.is_public = ?", true)
  53. }
  54. var orgs []*Organization
  55. return orgs, tx.Find(&orgs).Error
  56. }
  57. type Organization = User
  58. func (o *Organization) TableName() string {
  59. return "user"
  60. }