diff options
Diffstat (limited to 'models/repo.go')
-rw-r--r-- | models/repo.go | 213 |
1 files changed, 109 insertions, 104 deletions
diff --git a/models/repo.go b/models/repo.go index 575b8acbc8..914001191a 100644 --- a/models/repo.go +++ b/models/repo.go @@ -25,6 +25,7 @@ import ( "strings" "time" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/lfs" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/markup" @@ -251,6 +252,10 @@ type Repository struct { UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"` } +func init() { + db.RegisterModel(new(Repository)) +} + // SanitizedOriginalURL returns a sanitized OriginalURL func (repo *Repository) SanitizedOriginalURL() string { if repo.OriginalURL == "" { @@ -300,7 +305,7 @@ func (repo *Repository) AfterLoad() { // It creates a fake object that contains error details // when error occurs. func (repo *Repository) MustOwner() *User { - return repo.mustOwner(x) + return repo.mustOwner(db.DefaultContext().Engine()) } // FullName returns the repository full name @@ -340,7 +345,7 @@ func (repo *Repository) GetCommitsCountCacheKey(contextName string, isRef bool) return fmt.Sprintf("commits-count-%d-%s-%s", repo.ID, prefix, contextName) } -func (repo *Repository) getUnits(e Engine) (err error) { +func (repo *Repository) getUnits(e db.Engine) (err error) { if repo.Units != nil { return nil } @@ -352,10 +357,10 @@ func (repo *Repository) getUnits(e Engine) (err error) { // CheckUnitUser check whether user could visit the unit of this repository func (repo *Repository) CheckUnitUser(user *User, unitType UnitType) bool { - return repo.checkUnitUser(x, user, unitType) + return repo.checkUnitUser(db.DefaultContext().Engine(), user, unitType) } -func (repo *Repository) checkUnitUser(e Engine, user *User, unitType UnitType) bool { +func (repo *Repository) checkUnitUser(e db.Engine, user *User, unitType UnitType) bool { if user.IsAdmin { return true } @@ -370,7 +375,7 @@ func (repo *Repository) checkUnitUser(e Engine, user *User, unitType UnitType) b // UnitEnabled if this repository has the given unit enabled func (repo *Repository) UnitEnabled(tp UnitType) bool { - if err := repo.getUnits(x); err != nil { + if err := repo.getUnits(db.DefaultContext().Engine()); err != nil { log.Warn("Error loading repository (ID: %d) units: %s", repo.ID, err.Error()) } for _, unit := range repo.Units { @@ -432,10 +437,10 @@ func (repo *Repository) MustGetUnit(tp UnitType) *RepoUnit { // GetUnit returns a RepoUnit object func (repo *Repository) GetUnit(tp UnitType) (*RepoUnit, error) { - return repo.getUnit(x, tp) + return repo.getUnit(db.DefaultContext().Engine(), tp) } -func (repo *Repository) getUnit(e Engine, tp UnitType) (*RepoUnit, error) { +func (repo *Repository) getUnit(e db.Engine, tp UnitType) (*RepoUnit, error) { if err := repo.getUnits(e); err != nil { return nil, err } @@ -447,7 +452,7 @@ func (repo *Repository) getUnit(e Engine, tp UnitType) (*RepoUnit, error) { return nil, ErrUnitTypeNotExist{tp} } -func (repo *Repository) getOwner(e Engine) (err error) { +func (repo *Repository) getOwner(e db.Engine) (err error) { if repo.Owner != nil { return nil } @@ -458,10 +463,10 @@ func (repo *Repository) getOwner(e Engine) (err error) { // GetOwner returns the repository owner func (repo *Repository) GetOwner() error { - return repo.getOwner(x) + return repo.getOwner(db.DefaultContext().Engine()) } -func (repo *Repository) mustOwner(e Engine) *User { +func (repo *Repository) mustOwner(e db.Engine) *User { if err := repo.getOwner(e); err != nil { return &User{ Name: "error", @@ -496,7 +501,7 @@ func (repo *Repository) ComposeMetas() map[string]string { repo.MustOwner() if repo.Owner.IsOrganization() { teams := make([]string, 0, 5) - _ = x.Table("team_repo"). + _ = db.DefaultContext().Engine().Table("team_repo"). Join("INNER", "team", "team.id = team_repo.team_id"). Where("team_repo.repo_id = ?", repo.ID). Select("team.lower_name"). @@ -524,7 +529,7 @@ func (repo *Repository) ComposeDocumentMetas() map[string]string { return repo.DocumentRenderingMetas } -func (repo *Repository) getAssignees(e Engine) (_ []*User, err error) { +func (repo *Repository) getAssignees(e db.Engine) (_ []*User, err error) { if err = repo.getOwner(e); err != nil { return nil, err } @@ -559,10 +564,10 @@ func (repo *Repository) getAssignees(e Engine) (_ []*User, err error) { // GetAssignees returns all users that have write access and can be assigned to issues // of the repository, func (repo *Repository) GetAssignees() (_ []*User, err error) { - return repo.getAssignees(x) + return repo.getAssignees(db.DefaultContext().Engine()) } -func (repo *Repository) getReviewers(e Engine, doerID, posterID int64) ([]*User, error) { +func (repo *Repository) getReviewers(e db.Engine, doerID, posterID int64) ([]*User, error) { // Get the owner of the repository - this often already pre-cached and if so saves complexity for the following queries if err := repo.getOwner(e); err != nil { return nil, err @@ -611,7 +616,7 @@ func (repo *Repository) getReviewers(e Engine, doerID, posterID int64) ([]*User, // all repo watchers and all organization members. // TODO: may be we should have a busy choice for users to block review request to them. func (repo *Repository) GetReviewers(doerID, posterID int64) ([]*User, error) { - return repo.getReviewers(x, doerID, posterID) + return repo.getReviewers(db.DefaultContext().Engine(), doerID, posterID) } // GetReviewerTeams get all teams can be requested to review @@ -657,10 +662,10 @@ func (repo *Repository) LoadPushMirrors() (err error) { // returns an error on failure (NOTE: no error is returned for // non-fork repositories, and BaseRepo will be left untouched) func (repo *Repository) GetBaseRepo() (err error) { - return repo.getBaseRepo(x) + return repo.getBaseRepo(db.DefaultContext().Engine()) } -func (repo *Repository) getBaseRepo(e Engine) (err error) { +func (repo *Repository) getBaseRepo(e db.Engine) (err error) { if !repo.IsFork { return nil } @@ -678,10 +683,10 @@ func (repo *Repository) IsGenerated() bool { // returns an error on failure (NOTE: no error is returned for // non-generated repositories, and TemplateRepo will be left untouched) func (repo *Repository) GetTemplateRepo() (err error) { - return repo.getTemplateRepo(x) + return repo.getTemplateRepo(db.DefaultContext().Engine()) } -func (repo *Repository) getTemplateRepo(e Engine) (err error) { +func (repo *Repository) getTemplateRepo(e db.Engine) (err error) { if !repo.IsGenerated() { return nil } @@ -722,7 +727,7 @@ func (repo *Repository) ComposeCompareURL(oldCommitID, newCommitID string) strin // UpdateDefaultBranch updates the default branch func (repo *Repository) UpdateDefaultBranch() error { - _, err := x.ID(repo.ID).Cols("default_branch").Update(repo) + _, err := db.DefaultContext().Engine().ID(repo.ID).Cols("default_branch").Update(repo) return err } @@ -731,7 +736,7 @@ func (repo *Repository) IsOwnedBy(userID int64) bool { return repo.OwnerID == userID } -func (repo *Repository) updateSize(e Engine) error { +func (repo *Repository) updateSize(e db.Engine) error { size, err := util.GetDirectorySize(repo.RepoPath()) if err != nil { return fmt.Errorf("updateSize: %v", err) @@ -748,8 +753,8 @@ func (repo *Repository) updateSize(e Engine) error { } // UpdateSize updates the repository size, calculating it using util.GetDirectorySize -func (repo *Repository) UpdateSize(ctx DBContext) error { - return repo.updateSize(ctx.e) +func (repo *Repository) UpdateSize(ctx *db.Context) error { + return repo.updateSize(ctx.Engine()) } // CanUserFork returns true if specified user can fork repository. @@ -810,12 +815,12 @@ func (repo *Repository) CanEnableEditor() bool { // GetReaders returns all users that have explicit read access or higher to the repository. func (repo *Repository) GetReaders() (_ []*User, err error) { - return repo.getUsersWithAccessMode(x, AccessModeRead) + return repo.getUsersWithAccessMode(db.DefaultContext().Engine(), AccessModeRead) } // GetWriters returns all users that have write access to the repository. func (repo *Repository) GetWriters() (_ []*User, err error) { - return repo.getUsersWithAccessMode(x, AccessModeWrite) + return repo.getUsersWithAccessMode(db.DefaultContext().Engine(), AccessModeWrite) } // IsReader returns true if user has explicit read access or higher to the repository. @@ -823,11 +828,11 @@ func (repo *Repository) IsReader(userID int64) (bool, error) { if repo.OwnerID == userID { return true, nil } - return x.Where("repo_id = ? AND user_id = ? AND mode >= ?", repo.ID, userID, AccessModeRead).Get(&Access{}) + return db.DefaultContext().Engine().Where("repo_id = ? AND user_id = ? AND mode >= ?", repo.ID, userID, AccessModeRead).Get(&Access{}) } // getUsersWithAccessMode returns users that have at least given access mode to the repository. -func (repo *Repository) getUsersWithAccessMode(e Engine, mode AccessMode) (_ []*User, err error) { +func (repo *Repository) getUsersWithAccessMode(e db.Engine, mode AccessMode) (_ []*User, err error) { if err = repo.getOwner(e); err != nil { return nil, err } @@ -872,10 +877,10 @@ func (repo *Repository) DescriptionHTML() template.HTML { // ReadBy sets repo to be visited by given user. func (repo *Repository) ReadBy(userID int64) error { - return setRepoNotificationStatusReadIfUnread(x, userID, repo.ID) + return setRepoNotificationStatusReadIfUnread(db.DefaultContext().Engine(), userID, repo.ID) } -func isRepositoryExist(e Engine, u *User, repoName string) (bool, error) { +func isRepositoryExist(e db.Engine, u *User, repoName string) (bool, error) { has, err := e.Get(&Repository{ OwnerID: u.ID, LowerName: strings.ToLower(repoName), @@ -889,7 +894,7 @@ func isRepositoryExist(e Engine, u *User, repoName string) (bool, error) { // IsRepositoryExist returns true if the repository with given name under user has already existed. func IsRepositoryExist(u *User, repoName string) (bool, error) { - return isRepositoryExist(x, u, repoName) + return isRepositoryExist(db.DefaultContext().Engine(), u, repoName) } // CloneLink represents different types of clone URLs of repository. @@ -951,7 +956,7 @@ func CheckCreateRepository(doer, u *User, name string, overwriteOrAdopt bool) er return err } - has, err := isRepositoryExist(x, u, name) + has, err := isRepositoryExist(db.DefaultContext().Engine(), u, name) if err != nil { return fmt.Errorf("IsRepositoryExist: %v", err) } else if has { @@ -1040,12 +1045,12 @@ func IsUsableRepoName(name string) error { } // CreateRepository creates a repository for the user/organization. -func CreateRepository(ctx DBContext, doer, u *User, repo *Repository, overwriteOrAdopt bool) (err error) { +func CreateRepository(ctx *db.Context, doer, u *User, repo *Repository, overwriteOrAdopt bool) (err error) { if err = IsUsableRepoName(repo.Name); err != nil { return err } - has, err := isRepositoryExist(ctx.e, u, repo.Name) + has, err := isRepositoryExist(ctx.Engine(), u, repo.Name) if err != nil { return fmt.Errorf("IsRepositoryExist: %v", err) } else if has { @@ -1066,10 +1071,10 @@ func CreateRepository(ctx DBContext, doer, u *User, repo *Repository, overwriteO } } - if _, err = ctx.e.Insert(repo); err != nil { + if _, err = ctx.Engine().Insert(repo); err != nil { return err } - if err = deleteRepoRedirect(ctx.e, u.ID, repo.Name); err != nil { + if err = deleteRepoRedirect(ctx.Engine(), u.ID, repo.Name); err != nil { return err } @@ -1100,46 +1105,46 @@ func CreateRepository(ctx DBContext, doer, u *User, repo *Repository, overwriteO } } - if _, err = ctx.e.Insert(&units); err != nil { + if _, err = ctx.Engine().Insert(&units); err != nil { return err } // Remember visibility preference. u.LastRepoVisibility = repo.IsPrivate - if err = updateUserCols(ctx.e, u, "last_repo_visibility"); err != nil { + if err = updateUserCols(ctx.Engine(), u, "last_repo_visibility"); err != nil { return fmt.Errorf("updateUser: %v", err) } - if _, err = ctx.e.Incr("num_repos").ID(u.ID).Update(new(User)); err != nil { + if _, err = ctx.Engine().Incr("num_repos").ID(u.ID).Update(new(User)); err != nil { return fmt.Errorf("increment user total_repos: %v", err) } u.NumRepos++ // Give access to all members in teams with access to all repositories. if u.IsOrganization() { - if err := u.loadTeams(ctx.e); err != nil { + if err := u.loadTeams(ctx.Engine()); err != nil { return fmt.Errorf("loadTeams: %v", err) } for _, t := range u.Teams { if t.IncludesAllRepositories { - if err := t.addRepository(ctx.e, repo); err != nil { + if err := t.addRepository(ctx.Engine(), repo); err != nil { return fmt.Errorf("addRepository: %v", err) } } } - if isAdmin, err := isUserRepoAdmin(ctx.e, repo, doer); err != nil { + if isAdmin, err := isUserRepoAdmin(ctx.Engine(), repo, doer); err != nil { return fmt.Errorf("isUserRepoAdmin: %v", err) } else if !isAdmin { // Make creator repo admin if it wan't assigned automatically - if err = repo.addCollaborator(ctx.e, doer); err != nil { + if err = repo.addCollaborator(ctx.Engine(), doer); err != nil { return fmt.Errorf("AddCollaborator: %v", err) } - if err = repo.changeCollaborationAccessMode(ctx.e, doer.ID, AccessModeAdmin); err != nil { + if err = repo.changeCollaborationAccessMode(ctx.Engine(), doer.ID, AccessModeAdmin); err != nil { return fmt.Errorf("ChangeCollaborationAccessMode: %v", err) } } - } else if err = repo.recalculateAccesses(ctx.e); err != nil { + } else if err = repo.recalculateAccesses(ctx.Engine()); err != nil { // Organization automatically called this in addRepository method. return fmt.Errorf("recalculateAccesses: %v", err) } @@ -1155,12 +1160,12 @@ func CreateRepository(ctx DBContext, doer, u *User, repo *Repository, overwriteO } if setting.Service.AutoWatchNewRepos { - if err = watchRepo(ctx.e, doer.ID, repo.ID, true); err != nil { + if err = watchRepo(ctx.Engine(), doer.ID, repo.ID, true); err != nil { return fmt.Errorf("watchRepo: %v", err) } } - if err = copyDefaultWebhooksToRepo(ctx.e, repo.ID); err != nil { + if err = copyDefaultWebhooksToRepo(ctx.Engine(), repo.ID); err != nil { return fmt.Errorf("copyDefaultWebhooksToRepo: %v", err) } @@ -1168,7 +1173,7 @@ func CreateRepository(ctx DBContext, doer, u *User, repo *Repository, overwriteO } func countRepositories(userID int64, private bool) int64 { - sess := x.Where("id > 0") + sess := db.DefaultContext().Engine().Where("id > 0") if userID > 0 { sess.And("owner_id = ?", userID) @@ -1204,14 +1209,14 @@ func RepoPath(userName, repoName string) string { } // IncrementRepoForkNum increment repository fork number -func IncrementRepoForkNum(ctx DBContext, repoID int64) error { - _, err := ctx.e.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", repoID) +func IncrementRepoForkNum(ctx *db.Context, repoID int64) error { + _, err := ctx.Engine().Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", repoID) return err } // DecrementRepoForkNum decrement repository fork number -func DecrementRepoForkNum(ctx DBContext, repoID int64) error { - _, err := ctx.e.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repoID) +func DecrementRepoForkNum(ctx *db.Context, repoID int64) error { + _, err := ctx.Engine().Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repoID) return err } @@ -1251,7 +1256,7 @@ func ChangeRepositoryName(doer *User, repo *Repository, newRepoName string) (err } } - sess := x.NewSession() + sess := db.DefaultContext().NewSession() defer sess.Close() if err = sess.Begin(); err != nil { return fmt.Errorf("sess.Begin: %v", err) @@ -1264,7 +1269,7 @@ func ChangeRepositoryName(doer *User, repo *Repository, newRepoName string) (err return sess.Commit() } -func getRepositoriesByForkID(e Engine, forkID int64) ([]*Repository, error) { +func getRepositoriesByForkID(e db.Engine, forkID int64) ([]*Repository, error) { repos := make([]*Repository, 0, 10) return repos, e. Where("fork_id=?", forkID). @@ -1273,10 +1278,10 @@ func getRepositoriesByForkID(e Engine, forkID int64) ([]*Repository, error) { // GetRepositoriesByForkID returns all repositories with given fork ID. func GetRepositoriesByForkID(forkID int64) ([]*Repository, error) { - return getRepositoriesByForkID(x, forkID) + return getRepositoriesByForkID(db.DefaultContext().Engine(), forkID) } -func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err error) { +func updateRepository(e db.Engine, repo *Repository, visibilityChanged bool) (err error) { repo.LowerName = strings.ToLower(repo.Name) if utf8.RuneCountInString(repo.Description) > 255 { @@ -1351,13 +1356,13 @@ func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err e } // UpdateRepositoryCtx updates a repository with db context -func UpdateRepositoryCtx(ctx DBContext, repo *Repository, visibilityChanged bool) error { - return updateRepository(ctx.e, repo, visibilityChanged) +func UpdateRepositoryCtx(ctx *db.Context, repo *Repository, visibilityChanged bool) error { + return updateRepository(ctx.Engine(), repo, visibilityChanged) } // UpdateRepository updates a repository func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) { - sess := x.NewSession() + sess := db.DefaultContext().NewSession() defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -1375,7 +1380,7 @@ func UpdateRepositoryOwnerNames(ownerID int64, ownerName string) error { if ownerID == 0 { return nil } - sess := x.NewSession() + sess := db.DefaultContext().NewSession() defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -1392,13 +1397,13 @@ func UpdateRepositoryOwnerNames(ownerID int64, ownerName string) error { // UpdateRepositoryUpdatedTime updates a repository's updated time func UpdateRepositoryUpdatedTime(repoID int64, updateTime time.Time) error { - _, err := x.Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", updateTime.Unix(), repoID) + _, err := db.DefaultContext().Engine().Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", updateTime.Unix(), repoID) return err } // UpdateRepositoryUnits updates a repository's units func UpdateRepositoryUnits(repo *Repository, units []RepoUnit, deleteUnitTypes []UnitType) (err error) { - sess := x.NewSession() + sess := db.DefaultContext().NewSession() defer sess.Close() if err = sess.Begin(); err != nil { return err @@ -1425,7 +1430,7 @@ func UpdateRepositoryUnits(repo *Repository, units []RepoUnit, deleteUnitTypes [ // DeleteRepository deletes a repository for a user or organization. // make sure if you call this func to close open sessions (sqlite will otherwise get a deadlock) func DeleteRepository(doer *User, uid, repoID int64) error { - sess := x.NewSession() + sess := db.DefaultContext().NewSession() defer sess.Close() if err := sess.Begin(); err != nil { return err @@ -1533,7 +1538,7 @@ func DeleteRepository(doer *User, uid, repoID int64) error { } // Delete issue index - if err := deleteResouceIndex(sess, "issue_index", repoID); err != nil { + if err := db.DeleteResouceIndex(sess, "issue_index", repoID); err != nil { return err } @@ -1641,21 +1646,21 @@ func DeleteRepository(doer *User, uid, repoID int64) error { // Remove repository files. repoPath := repo.RepoPath() - removeAllWithNotice(x, "Delete repository files", repoPath) + removeAllWithNotice(db.DefaultContext().Engine(), "Delete repository files", repoPath) // Remove wiki files if repo.HasWiki() { - removeAllWithNotice(x, "Delete repository wiki", repo.WikiPath()) + removeAllWithNotice(db.DefaultContext().Engine(), "Delete repository wiki", repo.WikiPath()) } // Remove archives for i := range archivePaths { - removeStorageWithNotice(x, storage.RepoArchives, "Delete repo archive file", archivePaths[i]) + removeStorageWithNotice(db.DefaultContext().Engine(), storage.RepoArchives, "Delete repo archive file", archivePaths[i]) } // Remove lfs objects for i := range lfsPaths { - removeStorageWithNotice(x, storage.LFS, "Delete orphaned LFS file", lfsPaths[i]) + removeStorageWithNotice(db.DefaultContext().Engine(), storage.LFS, "Delete orphaned LFS file", lfsPaths[i]) } // Remove issue attachment files. @@ -1684,10 +1689,10 @@ func DeleteRepository(doer *User, uid, repoID int64) error { // GetRepositoryByOwnerAndName returns the repository by given ownername and reponame. func GetRepositoryByOwnerAndName(ownerName, repoName string) (*Repository, error) { - return getRepositoryByOwnerAndName(x, ownerName, repoName) + return getRepositoryByOwnerAndName(db.DefaultContext().Engine(), ownerName, repoName) } -func getRepositoryByOwnerAndName(e Engine, ownerName, repoName string) (*Repository, error) { +func getRepositoryByOwnerAndName(e db.Engine, ownerName, repoName string) (*Repository, error) { var repo Repository has, err := e.Table("repository").Select("repository.*"). Join("INNER", "`user`", "`user`.id = repository.owner_id"). @@ -1708,7 +1713,7 @@ func GetRepositoryByName(ownerID int64, name string) (*Repository, error) { OwnerID: ownerID, LowerName: strings.ToLower(name), } - has, err := x.Get(repo) + has, err := db.DefaultContext().Engine().Get(repo) if err != nil { return nil, err } else if !has { @@ -1717,7 +1722,7 @@ func GetRepositoryByName(ownerID int64, name string) (*Repository, error) { return repo, err } -func getRepositoryByID(e Engine, id int64) (*Repository, error) { +func getRepositoryByID(e db.Engine, id int64) (*Repository, error) { repo := new(Repository) has, err := e.ID(id).Get(repo) if err != nil { @@ -1730,18 +1735,18 @@ func getRepositoryByID(e Engine, id int64) (*Repository, error) { // GetRepositoryByID returns the repository by given id if exists. func GetRepositoryByID(id int64) (*Repository, error) { - return getRepositoryByID(x, id) + return getRepositoryByID(db.DefaultContext().Engine(), id) } // GetRepositoryByIDCtx returns the repository by given id if exists. -func GetRepositoryByIDCtx(ctx DBContext, id int64) (*Repository, error) { - return getRepositoryByID(ctx.e, id) +func GetRepositoryByIDCtx(ctx *db.Context, id int64) (*Repository, error) { + return getRepositoryByID(ctx.Engine(), id) } // GetRepositoriesMapByIDs returns the repositories by given id slice. func GetRepositoriesMapByIDs(ids []int64) (map[int64]*Repository, error) { repos := make(map[int64]*Repository, len(ids)) - return repos, x.In("id", ids).Find(&repos) + return repos, db.DefaultContext().Engine().In("id", ids).Find(&repos) } // GetUserRepositories returns a list of repositories of given user. @@ -1760,7 +1765,7 @@ func GetUserRepositories(opts *SearchRepoOptions) ([]*Repository, int64, error) cond = cond.And(builder.In("lower_name", opts.LowerNames)) } - sess := x.NewSession() + sess := db.DefaultContext().NewSession() defer sess.Close() count, err := sess.Where(cond).Count(new(Repository)) @@ -1776,37 +1781,37 @@ func GetUserRepositories(opts *SearchRepoOptions) ([]*Repository, int64, error) // GetUserMirrorRepositories returns a list of mirror repositories of given user. func GetUserMirrorRepositories(userID int64) ([]*Repository, error) { repos := make([]*Repository, 0, 10) - return repos, x. + return repos, db.DefaultContext().Engine(). Where("owner_id = ?", userID). And("is_mirror = ?", true). Find(&repos) } -func getRepositoryCount(e Engine, u *User) (int64, error) { +func getRepositoryCount(e db.Engine, u *User) (int64, error) { return e.Count(&Repository{OwnerID: u.ID}) } -func getPublicRepositoryCount(e Engine, u *User) (int64, error) { +func getPublicRepositoryCount(e db.Engine, u *User) (int64, error) { return e.Where("is_private = ?", false).Count(&Repository{OwnerID: u.ID}) } -func getPrivateRepositoryCount(e Engine, u *User) (int64, error) { +func getPrivateRepositoryCount(e db.Engine, u *User) (int64, error) { return e.Where("is_private = ?", true).Count(&Repository{OwnerID: u.ID}) } // GetRepositoryCount returns the total number of repositories of user. func GetRepositoryCount(u *User) (int64, error) { - return getRepositoryCount(x, u) + return getRepositoryCount(db.DefaultContext().Engine(), u) } // GetPublicRepositoryCount returns the total number of public repositories of user. func GetPublicRepositoryCount(u *User) (int64, error) { - return getPublicRepositoryCount(x, u) + return getPublicRepositoryCount(db.DefaultContext().Engine(), u) } // GetPrivateRepositoryCount returns the total number of private repositories of user. func GetPrivateRepositoryCount(u *User) (int64, error) { - return getPrivateRepositoryCount(x, u) + return getPrivateRepositoryCount(db.DefaultContext().Engine(), u) } // DeleteOldRepositoryArchives deletes old repository archives. @@ -1815,7 +1820,7 @@ func DeleteOldRepositoryArchives(ctx context.Context, olderThan time.Duration) e for { var archivers []RepoArchiver - err := x.Where("created_unix < ?", time.Now().Add(-olderThan).Unix()). + err := db.DefaultContext().Engine().Where("created_unix < ?", time.Now().Add(-olderThan).Unix()). Asc("created_unix"). Limit(100). Find(&archivers) @@ -1845,7 +1850,7 @@ func deleteOldRepoArchiver(ctx context.Context, archiver *RepoArchiver) error { if err != nil { return err } - _, err = x.ID(archiver.ID).Delete(delRepoArchiver) + _, err = db.DefaultContext().Engine().ID(archiver.ID).Delete(delRepoArchiver) if err != nil { return err } @@ -1861,7 +1866,7 @@ type repoChecker struct { } func repoStatsCheck(ctx context.Context, checker *repoChecker) { - results, err := x.Query(checker.querySQL) + results, err := db.DefaultContext().Engine().Query(checker.querySQL) if err != nil { log.Error("Select %s: %v", checker.desc, err) return @@ -1875,7 +1880,7 @@ func repoStatsCheck(ctx context.Context, checker *repoChecker) { default: } log.Trace("Updating %s: %d", checker.desc, id) - _, err = x.Exec(checker.correctSQL, id, id) + _, err = db.DefaultContext().Engine().Exec(checker.correctSQL, id, id) if err != nil { log.Error("Update %s[%d]: %v", checker.desc, id, err) } @@ -1930,7 +1935,7 @@ func CheckRepoStats(ctx context.Context) error { // ***** START: Repository.NumClosedIssues ***** desc := "repository count 'num_closed_issues'" - results, err := x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_closed_issues!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_closed=? AND is_pull=?)", true, false) + results, err := db.DefaultContext().Engine().Query("SELECT repo.id FROM `repository` repo WHERE repo.num_closed_issues!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_closed=? AND is_pull=?)", true, false) if err != nil { log.Error("Select %s: %v", desc, err) } else { @@ -1943,7 +1948,7 @@ func CheckRepoStats(ctx context.Context) error { default: } log.Trace("Updating %s: %d", desc, id) - _, err = x.Exec("UPDATE `repository` SET num_closed_issues=(SELECT COUNT(*) FROM `issue` WHERE repo_id=? AND is_closed=? AND is_pull=?) WHERE id=?", id, true, false, id) + _, err = db.DefaultContext().Engine().Exec("UPDATE `repository` SET num_closed_issues=(SELECT COUNT(*) FROM `issue` WHERE repo_id=? AND is_closed=? AND is_pull=?) WHERE id=?", id, true, false, id) if err != nil { log.Error("Update %s[%d]: %v", desc, id, err) } @@ -1953,7 +1958,7 @@ func CheckRepoStats(ctx context.Context) error { // ***** START: Repository.NumClosedPulls ***** desc = "repository count 'num_closed_pulls'" - results, err = x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_closed_pulls!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_closed=? AND is_pull=?)", true, true) + results, err = db.DefaultContext().Engine().Query("SELECT repo.id FROM `repository` repo WHERE repo.num_closed_pulls!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_closed=? AND is_pull=?)", true, true) if err != nil { log.Error("Select %s: %v", desc, err) } else { @@ -1966,7 +1971,7 @@ func CheckRepoStats(ctx context.Context) error { default: } log.Trace("Updating %s: %d", desc, id) - _, err = x.Exec("UPDATE `repository` SET num_closed_pulls=(SELECT COUNT(*) FROM `issue` WHERE repo_id=? AND is_closed=? AND is_pull=?) WHERE id=?", id, true, true, id) + _, err = db.DefaultContext().Engine().Exec("UPDATE `repository` SET num_closed_pulls=(SELECT COUNT(*) FROM `issue` WHERE repo_id=? AND is_closed=? AND is_pull=?) WHERE id=?", id, true, true, id) if err != nil { log.Error("Update %s[%d]: %v", desc, id, err) } @@ -1976,7 +1981,7 @@ func CheckRepoStats(ctx context.Context) error { // FIXME: use checker when stop supporting old fork repo format. // ***** START: Repository.NumForks ***** - results, err = x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)") + results, err = db.DefaultContext().Engine().Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)") if err != nil { log.Error("Select repository count 'num_forks': %v", err) } else { @@ -1996,7 +2001,7 @@ func CheckRepoStats(ctx context.Context) error { continue } - rawResult, err := x.Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID) + rawResult, err := db.DefaultContext().Engine().Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID) if err != nil { log.Error("Select count of forks[%d]: %v", repo.ID, err) continue @@ -2016,7 +2021,7 @@ func CheckRepoStats(ctx context.Context) error { // SetArchiveRepoState sets if a repo is archived func (repo *Repository) SetArchiveRepoState(isArchived bool) (err error) { repo.IsArchived = isArchived - _, err = x.Where("id = ?", repo.ID).Cols("is_archived").NoAutoTime().Update(repo) + _, err = db.DefaultContext().Engine().Where("id = ?", repo.ID).Cols("is_archived").NoAutoTime().Update(repo) return } @@ -2030,23 +2035,23 @@ func (repo *Repository) SetArchiveRepoState(isArchived bool) (err error) { // HasForkedRepo checks if given user has already forked a repository with given ID. func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) { repo := new(Repository) - has, _ := x. + has, _ := db.DefaultContext().Engine(). Where("owner_id=? AND fork_id=?", ownerID, repoID). Get(repo) return repo, has } // CopyLFS copies LFS data from one repo to another -func CopyLFS(ctx DBContext, newRepo, oldRepo *Repository) error { +func CopyLFS(ctx *db.Context, newRepo, oldRepo *Repository) error { var lfsObjects []*LFSMetaObject - if err := ctx.e.Where("repository_id=?", oldRepo.ID).Find(&lfsObjects); err != nil { + if err := ctx.Engine().Where("repository_id=?", oldRepo.ID).Find(&lfsObjects); err != nil { return err } for _, v := range lfsObjects { v.ID = 0 v.RepositoryID = newRepo.ID - if _, err := ctx.e.Insert(v); err != nil { + if _, err := ctx.Engine().Insert(v); err != nil { return err } } @@ -2058,7 +2063,7 @@ func CopyLFS(ctx DBContext, newRepo, oldRepo *Repository) error { func (repo *Repository) GetForks(listOptions ListOptions) ([]*Repository, error) { if listOptions.Page == 0 { forks := make([]*Repository, 0, repo.NumForks) - return forks, x.Find(&forks, &Repository{ForkID: repo.ID}) + return forks, db.DefaultContext().Engine().Find(&forks, &Repository{ForkID: repo.ID}) } sess := getPaginatedSession(&listOptions) @@ -2069,7 +2074,7 @@ func (repo *Repository) GetForks(listOptions ListOptions) ([]*Repository, error) // GetUserFork return user forked repository from this repository, if not forked return nil func (repo *Repository) GetUserFork(userID int64) (*Repository, error) { var forkedRepo Repository - has, err := x.Where("fork_id = ?", repo.ID).And("owner_id = ?", userID).Get(&forkedRepo) + has, err := db.DefaultContext().Engine().Where("fork_id = ?", repo.ID).And("owner_id = ?", userID).Get(&forkedRepo) if err != nil { return nil, err } @@ -2105,14 +2110,14 @@ func (repo *Repository) GetTreePathLock(treePath string) (*LFSLock, error) { return nil, nil } -func updateRepositoryCols(e Engine, repo *Repository, cols ...string) error { +func updateRepositoryCols(e db.Engine, repo *Repository, cols ...string) error { _, err := e.ID(repo.ID).Cols(cols...).Update(repo) return err } // UpdateRepositoryCols updates repository's columns func UpdateRepositoryCols(repo *Repository, cols ...string) error { - return updateRepositoryCols(x, repo, cols...) + return updateRepositoryCols(db.DefaultContext().Engine(), repo, cols...) } // GetTrustModel will get the TrustModel for the repo or the default trust model @@ -2130,7 +2135,7 @@ func (repo *Repository) GetTrustModel() TrustModelType { // DoctorUserStarNum recalculate Stars number for all user func DoctorUserStarNum() (err error) { const batchSize = 100 - sess := x.NewSession() + sess := db.DefaultContext().NewSession() defer sess.Close() for start := 0; ; start += batchSize { @@ -2168,7 +2173,7 @@ func IterateRepository(f func(repo *Repository) error) error { batchSize := setting.Database.IterateBufferSize for { repos := make([]*Repository, 0, batchSize) - if err := x.Limit(batchSize, start).Find(&repos); err != nil { + if err := db.DefaultContext().Engine().Limit(batchSize, start).Find(&repos); err != nil { return err } if len(repos) == 0 { |