org.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2014 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. "fmt"
  7. "xorm.io/builder"
  8. "xorm.io/xorm"
  9. )
  10. // getOwnedOrgsByUserID returns a list of organizations are owned by given user ID.
  11. func getOwnedOrgsByUserID(sess *xorm.Session, userID int64) ([]*User, error) {
  12. orgs := make([]*User, 0, 10)
  13. return orgs, sess.Where("`org_user`.uid=?", userID).And("`org_user`.is_owner=?", true).
  14. Join("INNER", "`org_user`", "`org_user`.org_id=`user`.id").Find(&orgs)
  15. }
  16. // GetOwnedOrganizationsByUserIDDesc returns a list of organizations are owned by
  17. // given user ID, ordered descending by the given condition.
  18. func GetOwnedOrgsByUserIDDesc(userID int64, desc string) ([]*User, error) {
  19. sess := x.NewSession()
  20. return getOwnedOrgsByUserID(sess.Desc(desc), userID)
  21. }
  22. // getOrgUsersByOrgID returns all organization-user relations by organization ID.
  23. func getOrgUsersByOrgID(e Engine, orgID int64, limit int) ([]*OrgUser, error) {
  24. orgUsers := make([]*OrgUser, 0, 10)
  25. sess := e.Where("org_id=?", orgID)
  26. if limit > 0 {
  27. sess = sess.Limit(limit)
  28. }
  29. return orgUsers, sess.Find(&orgUsers)
  30. }
  31. // GetUserMirrorRepositories returns mirror repositories of the organization which the user has access to.
  32. func (u *User) GetUserMirrorRepositories(userID int64) ([]*Repository, error) {
  33. teamIDs, err := u.GetUserTeamIDs(userID)
  34. if err != nil {
  35. return nil, fmt.Errorf("GetUserTeamIDs: %v", err)
  36. }
  37. if len(teamIDs) == 0 {
  38. teamIDs = []int64{-1}
  39. }
  40. var teamRepoIDs []int64
  41. err = x.Table("team_repo").In("team_id", teamIDs).Distinct("repo_id").Find(&teamRepoIDs)
  42. if err != nil {
  43. return nil, fmt.Errorf("get team repository ids: %v", err)
  44. }
  45. if len(teamRepoIDs) == 0 {
  46. // team has no repo but "IN ()" is invalid SQL
  47. teamRepoIDs = []int64{-1} // there is no repo with id=-1
  48. }
  49. repos := make([]*Repository, 0, 10)
  50. if err = x.Where("owner_id = ?", u.ID).
  51. And("is_private = ?", false).
  52. Or(builder.In("id", teamRepoIDs)).
  53. And("is_mirror = ?", true). // Don't move up because it's an independent condition
  54. Desc("updated_unix").
  55. Find(&repos); err != nil {
  56. return nil, fmt.Errorf("get user repositories: %v", err)
  57. }
  58. return repos, nil
  59. }