Jelajahi Sumber

models/org: reduce to 2 SQL executions for GetOrgIDsByUserID

This also addresses #4231. It is now ignoring nonexistent
organizations returned from 'org_user' table.
This was a bug caused in older version that didn't cleanup
'org_user' table when delete an organization.
Unknwon 7 tahun lalu
induk
melakukan
ebd95dd082
4 mengubah file dengan 17 tambahan dan 21 penghapusan
  1. 1 1
      gogs.go
  2. 9 10
      models/org.go
  3. 6 9
      models/user.go
  4. 1 1
      templates/.VERSION

+ 1 - 1
gogs.go

@@ -16,7 +16,7 @@ import (
 	"github.com/gogits/gogs/modules/setting"
 )
 
-const APP_VER = "0.10.4.0302"
+const APP_VER = "0.10.4.0303"
 
 func init() {
 	setting.AppVer = APP_VER

+ 9 - 10
models/org.go

@@ -303,16 +303,15 @@ func GetOwnedOrgsByUserIDDesc(userID int64, desc string) ([]*User, error) {
 	return getOwnedOrgsByUserID(sess.Desc(desc), userID)
 }
 
-// GetOrgUsersByUserID returns all organization-user relations by user ID.
-func GetOrgUsersByUserID(uid int64, all bool) ([]*OrgUser, error) {
-	ous := make([]*OrgUser, 0, 10)
-	sess := x.Where("uid=?", uid)
-	if !all {
-		// Only show public organizations
-		sess.And("is_public=?", true)
-	}
-	err := sess.Find(&ous)
-	return ous, err
+// GetOrgIDsByUserID returns a list of organization IDs that user belongs to.
+// The showPrivate indicates whether to include private memberships.
+func GetOrgIDsByUserID(userID int64, showPrivate bool) ([]int64, error) {
+	orgIDs := make([]int64, 0, 5)
+	sess := x.Table("org_user").Where("uid = ?", userID)
+	if !showPrivate {
+		sess.And("is_public = ?", true)
+	}
+	return orgIDs, sess.Distinct("org_id").Find(&orgIDs)
 }
 
 func getOrgUsersByOrgID(e Engine, orgID int64) ([]*OrgUser, error) {

+ 6 - 9
models/user.go

@@ -448,18 +448,15 @@ func (u *User) GetOwnedOrganizations() (err error) {
 }
 
 // GetOrganizations returns all organizations that user belongs to.
-func (u *User) GetOrganizations(all bool) error {
-	ous, err := GetOrgUsersByUserID(u.ID, all)
+func (u *User) GetOrganizations(showPrivate bool) error {
+	orgIDs, err := GetOrgIDsByUserID(u.ID, showPrivate)
 	if err != nil {
-		return err
+		return fmt.Errorf("GetOrgIDsByUserID: %v", err)
 	}
 
-	u.Orgs = make([]*User, len(ous))
-	for i, ou := range ous {
-		u.Orgs[i], err = GetUserByID(ou.OrgID)
-		if err != nil {
-			return err
-		}
+	u.Orgs = make([]*User, 0, len(orgIDs))
+	if err = x.In("id", orgIDs).Find(&u.Orgs); err != nil {
+		return err
 	}
 	return nil
 }

+ 1 - 1
templates/.VERSION

@@ -1 +1 @@
-0.10.4.0302
+0.10.4.0303