DBContext is just a Context (#17100)

* DBContext is just a Context

This PR removes some of the specialness from the DBContext and makes it context
This allows us to simplify the GetEngine code to wrap around any context in future
and means that we can change our loadRepo(e Engine) functions to simply take contexts.

Signed-off-by: Andrew Thornton <art27@cantab.net>

* fix unit tests

Signed-off-by: Andrew Thornton <art27@cantab.net>

* another place that needs to set the initial context

Signed-off-by: Andrew Thornton <art27@cantab.net>

* avoid race

Signed-off-by: Andrew Thornton <art27@cantab.net>

* change attachment error

Signed-off-by: Andrew Thornton <art27@cantab.net>
This commit is contained in:
zeripath 2021-09-23 16:45:36 +01:00 committed by GitHub
parent b22be7f594
commit 9302eba971
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
129 changed files with 1112 additions and 1022 deletions

View File

@ -116,7 +116,7 @@ func (repoAccess) TableName() string {
// GetRepositoryAccesses finds all repositories with their access mode where a user has access but does not own. // GetRepositoryAccesses finds all repositories with their access mode where a user has access but does not own.
func (user *User) GetRepositoryAccesses() (map[*Repository]AccessMode, error) { func (user *User) GetRepositoryAccesses() (map[*Repository]AccessMode, error) {
rows, err := db.DefaultContext().Engine(). rows, err := db.GetEngine(db.DefaultContext).
Join("INNER", "repository", "repository.id = access.repo_id"). Join("INNER", "repository", "repository.id = access.repo_id").
Where("access.user_id = ?", user.ID). Where("access.user_id = ?", user.ID).
And("repository.owner_id <> ?", user.ID). And("repository.owner_id <> ?", user.ID).
@ -151,7 +151,7 @@ func (user *User) GetRepositoryAccesses() (map[*Repository]AccessMode, error) {
// GetAccessibleRepositories finds repositories which the user has access but does not own. // GetAccessibleRepositories finds repositories which the user has access but does not own.
// If limit is smaller than 1 means returns all found results. // If limit is smaller than 1 means returns all found results.
func (user *User) GetAccessibleRepositories(limit int) (repos []*Repository, _ error) { func (user *User) GetAccessibleRepositories(limit int) (repos []*Repository, _ error) {
sess := db.DefaultContext().Engine(). sess := db.GetEngine(db.DefaultContext).
Where("owner_id !=? ", user.ID). Where("owner_id !=? ", user.ID).
Desc("updated_unix") Desc("updated_unix")
if limit > 0 { if limit > 0 {
@ -342,5 +342,5 @@ func (repo *Repository) recalculateAccesses(e db.Engine) error {
// RecalculateAccesses recalculates all accesses for repository. // RecalculateAccesses recalculates all accesses for repository.
func (repo *Repository) RecalculateAccesses() error { func (repo *Repository) RecalculateAccesses() error {
return repo.recalculateAccesses(db.DefaultContext().Engine()) return repo.recalculateAccesses(db.GetEngine(db.DefaultContext))
} }

View File

@ -127,12 +127,12 @@ func TestRepository_RecalculateAccesses(t *testing.T) {
repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository)
assert.NoError(t, repo1.GetOwner()) assert.NoError(t, repo1.GetOwner())
_, err := db.DefaultContext().Engine().Delete(&Collaboration{UserID: 2, RepoID: 3}) _, err := db.GetEngine(db.DefaultContext).Delete(&Collaboration{UserID: 2, RepoID: 3})
assert.NoError(t, err) assert.NoError(t, err)
assert.NoError(t, repo1.RecalculateAccesses()) assert.NoError(t, repo1.RecalculateAccesses())
access := &Access{UserID: 2, RepoID: 3} access := &Access{UserID: 2, RepoID: 3}
has, err := db.DefaultContext().Engine().Get(access) has, err := db.GetEngine(db.DefaultContext).Get(access)
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, has) assert.True(t, has)
assert.Equal(t, AccessModeOwner, access.Mode) assert.Equal(t, AccessModeOwner, access.Mode)
@ -144,11 +144,11 @@ func TestRepository_RecalculateAccesses2(t *testing.T) {
repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository)
assert.NoError(t, repo1.GetOwner()) assert.NoError(t, repo1.GetOwner())
_, err := db.DefaultContext().Engine().Delete(&Collaboration{UserID: 4, RepoID: 4}) _, err := db.GetEngine(db.DefaultContext).Delete(&Collaboration{UserID: 4, RepoID: 4})
assert.NoError(t, err) assert.NoError(t, err)
assert.NoError(t, repo1.RecalculateAccesses()) assert.NoError(t, repo1.RecalculateAccesses())
has, err := db.DefaultContext().Engine().Get(&Access{UserID: 4, RepoID: 4}) has, err := db.GetEngine(db.DefaultContext).Get(&Access{UserID: 4, RepoID: 4})
assert.NoError(t, err) assert.NoError(t, err)
assert.False(t, has) assert.False(t, has)
} }
@ -158,7 +158,7 @@ func TestRepository_RecalculateAccesses3(t *testing.T) {
team5 := db.AssertExistsAndLoadBean(t, &Team{ID: 5}).(*Team) team5 := db.AssertExistsAndLoadBean(t, &Team{ID: 5}).(*Team)
user29 := db.AssertExistsAndLoadBean(t, &User{ID: 29}).(*User) user29 := db.AssertExistsAndLoadBean(t, &User{ID: 29}).(*User)
has, err := db.DefaultContext().Engine().Get(&Access{UserID: 29, RepoID: 23}) has, err := db.GetEngine(db.DefaultContext).Get(&Access{UserID: 29, RepoID: 23})
assert.NoError(t, err) assert.NoError(t, err)
assert.False(t, has) assert.False(t, has)
@ -166,7 +166,7 @@ func TestRepository_RecalculateAccesses3(t *testing.T) {
// even though repo 23 is public // even though repo 23 is public
assert.NoError(t, AddTeamMember(team5, user29.ID)) assert.NoError(t, AddTeamMember(team5, user29.ID))
has, err = db.DefaultContext().Engine().Get(&Access{UserID: 29, RepoID: 23}) has, err = db.GetEngine(db.DefaultContext).Get(&Access{UserID: 29, RepoID: 23})
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, has) assert.True(t, has)
} }

View File

@ -208,7 +208,7 @@ func GetRepositoryFromMatch(ownerName, repoName string) (*Repository, error) {
// GetCommentLink returns link to action comment. // GetCommentLink returns link to action comment.
func (a *Action) GetCommentLink() string { func (a *Action) GetCommentLink() string {
return a.getCommentLink(db.DefaultContext().Engine()) return a.getCommentLink(db.GetEngine(db.DefaultContext))
} }
func (a *Action) getCommentLink(e db.Engine) string { func (a *Action) getCommentLink(e db.Engine) string {
@ -317,7 +317,7 @@ func GetFeeds(opts GetFeedsOptions) ([]*Action, error) {
actions := make([]*Action, 0, setting.UI.FeedPagingNum) actions := make([]*Action, 0, setting.UI.FeedPagingNum)
if err := db.DefaultContext().Engine().Limit(setting.UI.FeedPagingNum).Desc("created_unix").Where(cond).Find(&actions); err != nil { if err := db.GetEngine(db.DefaultContext).Limit(setting.UI.FeedPagingNum).Desc("created_unix").Where(cond).Find(&actions); err != nil {
return nil, fmt.Errorf("Find: %v", err) return nil, fmt.Errorf("Find: %v", err)
} }
@ -408,6 +408,6 @@ func DeleteOldActions(olderThan time.Duration) (err error) {
return nil return nil
} }
_, err = db.DefaultContext().Engine().Where("created_unix < ?", time.Now().Add(-olderThan).Unix()).Delete(&Action{}) _, err = db.GetEngine(db.DefaultContext).Where("created_unix < ?", time.Now().Add(-olderThan).Unix()).Delete(&Action{})
return return
} }

View File

@ -45,7 +45,7 @@ func (actions ActionList) loadUsers(e db.Engine) ([]*User, error) {
// LoadUsers loads actions' all users // LoadUsers loads actions' all users
func (actions ActionList) LoadUsers() ([]*User, error) { func (actions ActionList) LoadUsers() ([]*User, error) {
return actions.loadUsers(db.DefaultContext().Engine()) return actions.loadUsers(db.GetEngine(db.DefaultContext))
} }
func (actions ActionList) getRepoIDs() []int64 { func (actions ActionList) getRepoIDs() []int64 {
@ -80,7 +80,7 @@ func (actions ActionList) loadRepositories(e db.Engine) ([]*Repository, error) {
// LoadRepositories loads actions' all repositories // LoadRepositories loads actions' all repositories
func (actions ActionList) LoadRepositories() ([]*Repository, error) { func (actions ActionList) LoadRepositories() ([]*Repository, error) {
return actions.loadRepositories(db.DefaultContext().Engine()) return actions.loadRepositories(db.GetEngine(db.DefaultContext))
} }
// loadAttributes loads all attributes // loadAttributes loads all attributes
@ -98,5 +98,5 @@ func (actions ActionList) loadAttributes(e db.Engine) (err error) {
// LoadAttributes loads attributes of the actions // LoadAttributes loads attributes of the actions
func (actions ActionList) LoadAttributes() error { func (actions ActionList) LoadAttributes() error {
return actions.loadAttributes(db.DefaultContext().Engine()) return actions.loadAttributes(db.GetEngine(db.DefaultContext))
} }

View File

@ -44,7 +44,7 @@ func (n *Notice) TrStr() string {
// CreateNotice creates new system notice. // CreateNotice creates new system notice.
func CreateNotice(tp NoticeType, desc string, args ...interface{}) error { func CreateNotice(tp NoticeType, desc string, args ...interface{}) error {
return createNotice(db.DefaultContext().Engine(), tp, desc, args...) return createNotice(db.GetEngine(db.DefaultContext), tp, desc, args...)
} }
func createNotice(e db.Engine, tp NoticeType, desc string, args ...interface{}) error { func createNotice(e db.Engine, tp NoticeType, desc string, args ...interface{}) error {
@ -61,19 +61,19 @@ func createNotice(e db.Engine, tp NoticeType, desc string, args ...interface{})
// CreateRepositoryNotice creates new system notice with type NoticeRepository. // CreateRepositoryNotice creates new system notice with type NoticeRepository.
func CreateRepositoryNotice(desc string, args ...interface{}) error { func CreateRepositoryNotice(desc string, args ...interface{}) error {
return createNotice(db.DefaultContext().Engine(), NoticeRepository, desc, args...) return createNotice(db.GetEngine(db.DefaultContext), NoticeRepository, desc, args...)
} }
// RemoveAllWithNotice removes all directories in given path and // RemoveAllWithNotice removes all directories in given path and
// creates a system notice when error occurs. // creates a system notice when error occurs.
func RemoveAllWithNotice(title, path string) { func RemoveAllWithNotice(title, path string) {
removeAllWithNotice(db.DefaultContext().Engine(), title, path) removeAllWithNotice(db.GetEngine(db.DefaultContext), title, path)
} }
// RemoveStorageWithNotice removes a file from the storage and // RemoveStorageWithNotice removes a file from the storage and
// creates a system notice when error occurs. // creates a system notice when error occurs.
func RemoveStorageWithNotice(bucket storage.ObjectStorage, title, path string) { func RemoveStorageWithNotice(bucket storage.ObjectStorage, title, path string) {
removeStorageWithNotice(db.DefaultContext().Engine(), bucket, title, path) removeStorageWithNotice(db.GetEngine(db.DefaultContext), bucket, title, path)
} }
func removeStorageWithNotice(e db.Engine, bucket storage.ObjectStorage, title, path string) { func removeStorageWithNotice(e db.Engine, bucket storage.ObjectStorage, title, path string) {
@ -98,14 +98,14 @@ func removeAllWithNotice(e db.Engine, title, path string) {
// CountNotices returns number of notices. // CountNotices returns number of notices.
func CountNotices() int64 { func CountNotices() int64 {
count, _ := db.DefaultContext().Engine().Count(new(Notice)) count, _ := db.GetEngine(db.DefaultContext).Count(new(Notice))
return count return count
} }
// Notices returns notices in given page. // Notices returns notices in given page.
func Notices(page, pageSize int) ([]*Notice, error) { func Notices(page, pageSize int) ([]*Notice, error) {
notices := make([]*Notice, 0, pageSize) notices := make([]*Notice, 0, pageSize)
return notices, db.DefaultContext().Engine(). return notices, db.GetEngine(db.DefaultContext).
Limit(pageSize, (page-1)*pageSize). Limit(pageSize, (page-1)*pageSize).
Desc("id"). Desc("id").
Find(&notices) Find(&notices)
@ -113,18 +113,18 @@ func Notices(page, pageSize int) ([]*Notice, error) {
// DeleteNotice deletes a system notice by given ID. // DeleteNotice deletes a system notice by given ID.
func DeleteNotice(id int64) error { func DeleteNotice(id int64) error {
_, err := db.DefaultContext().Engine().ID(id).Delete(new(Notice)) _, err := db.GetEngine(db.DefaultContext).ID(id).Delete(new(Notice))
return err return err
} }
// DeleteNotices deletes all notices with ID from start to end (inclusive). // DeleteNotices deletes all notices with ID from start to end (inclusive).
func DeleteNotices(start, end int64) error { func DeleteNotices(start, end int64) error {
if start == 0 && end == 0 { if start == 0 && end == 0 {
_, err := db.DefaultContext().Engine().Exec("DELETE FROM notice") _, err := db.GetEngine(db.DefaultContext).Exec("DELETE FROM notice")
return err return err
} }
sess := db.DefaultContext().Engine().Where("id >= ?", start) sess := db.GetEngine(db.DefaultContext).Where("id >= ?", start)
if end > 0 { if end > 0 {
sess.And("id <= ?", end) sess.And("id <= ?", end)
} }
@ -137,7 +137,7 @@ func DeleteNoticesByIDs(ids []int64) error {
if len(ids) == 0 { if len(ids) == 0 {
return nil return nil
} }
_, err := db.DefaultContext().Engine(). _, err := db.GetEngine(db.DefaultContext).
In("id", ids). In("id", ids).
Delete(new(Notice)) Delete(new(Notice))
return err return err
@ -146,7 +146,7 @@ func DeleteNoticesByIDs(ids []int64) error {
// GetAdminUser returns the first administrator // GetAdminUser returns the first administrator
func GetAdminUser() (*User, error) { func GetAdminUser() (*User, error) {
var admin User var admin User
has, err := db.DefaultContext().Engine().Where("is_admin=?", true).Get(&admin) has, err := db.GetEngine(db.DefaultContext).Where("is_admin=?", true).Get(&admin)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {

View File

@ -5,6 +5,7 @@
package models package models
import ( import (
"context"
"fmt" "fmt"
"path" "path"
@ -38,7 +39,7 @@ func init() {
// IncreaseDownloadCount is update download count + 1 // IncreaseDownloadCount is update download count + 1
func (a *Attachment) IncreaseDownloadCount() error { func (a *Attachment) IncreaseDownloadCount() error {
// Update download count. // Update download count.
if _, err := db.DefaultContext().Engine().Exec("UPDATE `attachment` SET download_count=download_count+1 WHERE id=?", a.ID); err != nil { if _, err := db.GetEngine(db.DefaultContext).Exec("UPDATE `attachment` SET download_count=download_count+1 WHERE id=?", a.ID); err != nil {
return fmt.Errorf("increase attachment count: %v", err) return fmt.Errorf("increase attachment count: %v", err)
} }
@ -86,7 +87,7 @@ func (a *Attachment) LinkedRepository() (*Repository, UnitType, error) {
// GetAttachmentByID returns attachment by given id // GetAttachmentByID returns attachment by given id
func GetAttachmentByID(id int64) (*Attachment, error) { func GetAttachmentByID(id int64) (*Attachment, error) {
return getAttachmentByID(db.DefaultContext().Engine(), id) return getAttachmentByID(db.GetEngine(db.DefaultContext), id)
} }
func getAttachmentByID(e db.Engine, id int64) (*Attachment, error) { func getAttachmentByID(e db.Engine, id int64) (*Attachment, error) {
@ -111,8 +112,8 @@ func getAttachmentByUUID(e db.Engine, uuid string) (*Attachment, error) {
} }
// GetAttachmentsByUUIDs returns attachment by given UUID list. // GetAttachmentsByUUIDs returns attachment by given UUID list.
func GetAttachmentsByUUIDs(ctx *db.Context, uuids []string) ([]*Attachment, error) { func GetAttachmentsByUUIDs(ctx context.Context, uuids []string) ([]*Attachment, error) {
return getAttachmentsByUUIDs(ctx.Engine(), uuids) return getAttachmentsByUUIDs(db.GetEngine(ctx), uuids)
} }
func getAttachmentsByUUIDs(e db.Engine, uuids []string) ([]*Attachment, error) { func getAttachmentsByUUIDs(e db.Engine, uuids []string) ([]*Attachment, error) {
@ -127,17 +128,17 @@ func getAttachmentsByUUIDs(e db.Engine, uuids []string) ([]*Attachment, error) {
// GetAttachmentByUUID returns attachment by given UUID. // GetAttachmentByUUID returns attachment by given UUID.
func GetAttachmentByUUID(uuid string) (*Attachment, error) { func GetAttachmentByUUID(uuid string) (*Attachment, error) {
return getAttachmentByUUID(db.DefaultContext().Engine(), uuid) return getAttachmentByUUID(db.GetEngine(db.DefaultContext), uuid)
} }
// ExistAttachmentsByUUID returns true if attachment is exist by given UUID // ExistAttachmentsByUUID returns true if attachment is exist by given UUID
func ExistAttachmentsByUUID(uuid string) (bool, error) { func ExistAttachmentsByUUID(uuid string) (bool, error) {
return db.DefaultContext().Engine().Where("`uuid`=?", uuid).Exist(new(Attachment)) return db.GetEngine(db.DefaultContext).Where("`uuid`=?", uuid).Exist(new(Attachment))
} }
// GetAttachmentByReleaseIDFileName returns attachment by given releaseId and fileName. // GetAttachmentByReleaseIDFileName returns attachment by given releaseId and fileName.
func GetAttachmentByReleaseIDFileName(releaseID int64, fileName string) (*Attachment, error) { func GetAttachmentByReleaseIDFileName(releaseID int64, fileName string) (*Attachment, error) {
return getAttachmentByReleaseIDFileName(db.DefaultContext().Engine(), releaseID, fileName) return getAttachmentByReleaseIDFileName(db.GetEngine(db.DefaultContext), releaseID, fileName)
} }
func getAttachmentsByIssueID(e db.Engine, issueID int64) ([]*Attachment, error) { func getAttachmentsByIssueID(e db.Engine, issueID int64) ([]*Attachment, error) {
@ -147,12 +148,12 @@ func getAttachmentsByIssueID(e db.Engine, issueID int64) ([]*Attachment, error)
// GetAttachmentsByIssueID returns all attachments of an issue. // GetAttachmentsByIssueID returns all attachments of an issue.
func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) { func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
return getAttachmentsByIssueID(db.DefaultContext().Engine(), issueID) return getAttachmentsByIssueID(db.GetEngine(db.DefaultContext), issueID)
} }
// GetAttachmentsByCommentID returns all attachments if comment by given ID. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) { func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) {
return getAttachmentsByCommentID(db.DefaultContext().Engine(), commentID) return getAttachmentsByCommentID(db.GetEngine(db.DefaultContext), commentID)
} }
func getAttachmentsByCommentID(e db.Engine, commentID int64) ([]*Attachment, error) { func getAttachmentsByCommentID(e db.Engine, commentID int64) ([]*Attachment, error) {
@ -174,12 +175,12 @@ func getAttachmentByReleaseIDFileName(e db.Engine, releaseID int64, fileName str
// DeleteAttachment deletes the given attachment and optionally the associated file. // DeleteAttachment deletes the given attachment and optionally the associated file.
func DeleteAttachment(a *Attachment, remove bool) error { func DeleteAttachment(a *Attachment, remove bool) error {
_, err := DeleteAttachments(db.DefaultContext(), []*Attachment{a}, remove) _, err := DeleteAttachments(db.DefaultContext, []*Attachment{a}, remove)
return err return err
} }
// DeleteAttachments deletes the given attachments and optionally the associated files. // DeleteAttachments deletes the given attachments and optionally the associated files.
func DeleteAttachments(ctx *db.Context, attachments []*Attachment, remove bool) (int, error) { func DeleteAttachments(ctx context.Context, attachments []*Attachment, remove bool) (int, error) {
if len(attachments) == 0 { if len(attachments) == 0 {
return 0, nil return 0, nil
} }
@ -189,7 +190,7 @@ func DeleteAttachments(ctx *db.Context, attachments []*Attachment, remove bool)
ids = append(ids, a.ID) ids = append(ids, a.ID)
} }
cnt, err := ctx.Engine().In("id", ids).NoAutoCondition().Delete(attachments[0]) cnt, err := db.GetEngine(ctx).In("id", ids).NoAutoCondition().Delete(attachments[0])
if err != nil { if err != nil {
return 0, err return 0, err
} }
@ -211,7 +212,7 @@ func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) {
return 0, err return 0, err
} }
return DeleteAttachments(db.DefaultContext(), attachments, remove) return DeleteAttachments(db.DefaultContext, attachments, remove)
} }
// DeleteAttachmentsByComment deletes all attachments associated with the given comment. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
@ -221,20 +222,20 @@ func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) {
return 0, err return 0, err
} }
return DeleteAttachments(db.DefaultContext(), attachments, remove) return DeleteAttachments(db.DefaultContext, attachments, remove)
} }
// UpdateAttachment updates the given attachment in database // UpdateAttachment updates the given attachment in database
func UpdateAttachment(atta *Attachment) error { func UpdateAttachment(atta *Attachment) error {
return updateAttachment(db.DefaultContext().Engine(), atta) return updateAttachment(db.GetEngine(db.DefaultContext), atta)
} }
// UpdateAttachmentByUUID Updates attachment via uuid // UpdateAttachmentByUUID Updates attachment via uuid
func UpdateAttachmentByUUID(ctx *db.Context, attach *Attachment, cols ...string) error { func UpdateAttachmentByUUID(ctx context.Context, attach *Attachment, cols ...string) error {
if attach.UUID == "" { if attach.UUID == "" {
return fmt.Errorf("Attachement uuid should not blank") return fmt.Errorf("attachment uuid should be not blank")
} }
_, err := ctx.Engine().Where("uuid=?", attach.UUID).Cols(cols...).Update(attach) _, err := db.GetEngine(ctx).Where("uuid=?", attach.UUID).Cols(cols...).Update(attach)
return err return err
} }
@ -252,7 +253,7 @@ func updateAttachment(e db.Engine, atta *Attachment) error {
// DeleteAttachmentsByRelease deletes all attachments associated with the given release. // DeleteAttachmentsByRelease deletes all attachments associated with the given release.
func DeleteAttachmentsByRelease(releaseID int64) error { func DeleteAttachmentsByRelease(releaseID int64) error {
_, err := db.DefaultContext().Engine().Where("release_id = ?", releaseID).Delete(&Attachment{}) _, err := db.GetEngine(db.DefaultContext).Where("release_id = ?", releaseID).Delete(&Attachment{})
return err return err
} }
@ -262,7 +263,7 @@ func IterateAttachment(f func(attach *Attachment) error) error {
const batchSize = 100 const batchSize = 100
for { for {
attachments := make([]*Attachment, 0, batchSize) attachments := make([]*Attachment, 0, batchSize)
if err := db.DefaultContext().Engine().Limit(batchSize, start).Find(&attachments); err != nil { if err := db.GetEngine(db.DefaultContext).Limit(batchSize, start).Find(&attachments); err != nil {
return err return err
} }
if len(attachments) == 0 { if len(attachments) == 0 {
@ -280,13 +281,13 @@ func IterateAttachment(f func(attach *Attachment) error) error {
// CountOrphanedAttachments returns the number of bad attachments // CountOrphanedAttachments returns the number of bad attachments
func CountOrphanedAttachments() (int64, error) { func CountOrphanedAttachments() (int64, error) {
return db.DefaultContext().Engine().Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))"). return db.GetEngine(db.DefaultContext).Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))").
Count(new(Attachment)) Count(new(Attachment))
} }
// DeleteOrphanedAttachments delete all bad attachments // DeleteOrphanedAttachments delete all bad attachments
func DeleteOrphanedAttachments() error { func DeleteOrphanedAttachments() error {
_, err := db.DefaultContext().Engine().Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))"). _, err := db.GetEngine(db.DefaultContext).Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))").
Delete(new(Attachment)) Delete(new(Attachment))
return err return err
} }

View File

@ -92,7 +92,7 @@ func TestUpdateAttachment(t *testing.T) {
func TestGetAttachmentsByUUIDs(t *testing.T) { func TestGetAttachmentsByUUIDs(t *testing.T) {
assert.NoError(t, db.PrepareTestDatabase()) assert.NoError(t, db.PrepareTestDatabase())
attachList, err := GetAttachmentsByUUIDs(db.DefaultContext(), []string{"a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a17", "not-existing-uuid"}) attachList, err := GetAttachmentsByUUIDs(db.DefaultContext, []string{"a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a17", "not-existing-uuid"})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, attachList, 2) assert.Len(t, attachList, 2)
assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attachList[0].UUID) assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attachList[0].UUID)

View File

@ -5,6 +5,7 @@
package models package models
import ( import (
"context"
"crypto/md5" "crypto/md5"
"fmt" "fmt"
"net/url" "net/url"
@ -64,7 +65,7 @@ func GetEmailForHash(md5Sum string) (string, error) {
Hash: strings.ToLower(strings.TrimSpace(md5Sum)), Hash: strings.ToLower(strings.TrimSpace(md5Sum)),
} }
_, err := db.DefaultContext().Engine().Get(&emailHash) _, err := db.GetEngine(db.DefaultContext).Get(&emailHash)
return emailHash.Email, err return emailHash.Email, err
}) })
} }
@ -95,13 +96,13 @@ func HashedAvatarLink(email string, size int) string {
Hash: sum, Hash: sum,
} }
// OK we're going to open a session just because I think that that might hide away any problems with postgres reporting errors // OK we're going to open a session just because I think that that might hide away any problems with postgres reporting errors
if err := db.WithTx(func(ctx *db.Context) error { if err := db.WithTx(func(ctx context.Context) error {
has, err := ctx.Engine().Where("email = ? AND hash = ?", emailHash.Email, emailHash.Hash).Get(new(EmailHash)) has, err := db.GetEngine(ctx).Where("email = ? AND hash = ?", emailHash.Email, emailHash.Hash).Get(new(EmailHash))
if has || err != nil { if has || err != nil {
// Seriously we don't care about any DB problems just return the lowerEmail - we expect the transaction to fail most of the time // Seriously we don't care about any DB problems just return the lowerEmail - we expect the transaction to fail most of the time
return nil return nil
} }
_, _ = ctx.Engine().Insert(emailHash) _, _ = db.GetEngine(ctx).Insert(emailHash)
return nil return nil
}); err != nil { }); err != nil {
// Seriously we don't care about any DB problems just return the lowerEmail - we expect the transaction to fail most of the time // Seriously we don't care about any DB problems just return the lowerEmail - we expect the transaction to fail most of the time

View File

@ -122,7 +122,7 @@ func (protectBranch *ProtectedBranch) IsUserMergeWhitelisted(userID int64, permi
// IsUserOfficialReviewer check if user is official reviewer for the branch (counts towards required approvals) // IsUserOfficialReviewer check if user is official reviewer for the branch (counts towards required approvals)
func (protectBranch *ProtectedBranch) IsUserOfficialReviewer(user *User) (bool, error) { func (protectBranch *ProtectedBranch) IsUserOfficialReviewer(user *User) (bool, error) {
return protectBranch.isUserOfficialReviewer(db.DefaultContext().Engine(), user) return protectBranch.isUserOfficialReviewer(db.GetEngine(db.DefaultContext), user)
} }
func (protectBranch *ProtectedBranch) isUserOfficialReviewer(e db.Engine, user *User) (bool, error) { func (protectBranch *ProtectedBranch) isUserOfficialReviewer(e db.Engine, user *User) (bool, error) {
@ -162,7 +162,7 @@ func (protectBranch *ProtectedBranch) HasEnoughApprovals(pr *PullRequest) bool {
// GetGrantedApprovalsCount returns the number of granted approvals for pr. A granted approval must be authored by a user in an approval whitelist. // GetGrantedApprovalsCount returns the number of granted approvals for pr. A granted approval must be authored by a user in an approval whitelist.
func (protectBranch *ProtectedBranch) GetGrantedApprovalsCount(pr *PullRequest) int64 { func (protectBranch *ProtectedBranch) GetGrantedApprovalsCount(pr *PullRequest) int64 {
sess := db.DefaultContext().Engine().Where("issue_id = ?", pr.IssueID). sess := db.GetEngine(db.DefaultContext).Where("issue_id = ?", pr.IssueID).
And("type = ?", ReviewTypeApprove). And("type = ?", ReviewTypeApprove).
And("official = ?", true). And("official = ?", true).
And("dismissed = ?", false) And("dismissed = ?", false)
@ -183,7 +183,7 @@ func (protectBranch *ProtectedBranch) MergeBlockedByRejectedReview(pr *PullReque
if !protectBranch.BlockOnRejectedReviews { if !protectBranch.BlockOnRejectedReviews {
return false return false
} }
rejectExist, err := db.DefaultContext().Engine().Where("issue_id = ?", pr.IssueID). rejectExist, err := db.GetEngine(db.DefaultContext).Where("issue_id = ?", pr.IssueID).
And("type = ?", ReviewTypeReject). And("type = ?", ReviewTypeReject).
And("official = ?", true). And("official = ?", true).
And("dismissed = ?", false). And("dismissed = ?", false).
@ -202,7 +202,7 @@ func (protectBranch *ProtectedBranch) MergeBlockedByOfficialReviewRequests(pr *P
if !protectBranch.BlockOnOfficialReviewRequests { if !protectBranch.BlockOnOfficialReviewRequests {
return false return false
} }
has, err := db.DefaultContext().Engine().Where("issue_id = ?", pr.IssueID). has, err := db.GetEngine(db.DefaultContext).Where("issue_id = ?", pr.IssueID).
And("type = ?", ReviewTypeRequest). And("type = ?", ReviewTypeRequest).
And("official = ?", true). And("official = ?", true).
Exist(new(Review)) Exist(new(Review))
@ -300,7 +300,7 @@ func (protectBranch *ProtectedBranch) IsUnprotectedFile(patterns []glob.Glob, pa
// GetProtectedBranchBy getting protected branch by ID/Name // GetProtectedBranchBy getting protected branch by ID/Name
func GetProtectedBranchBy(repoID int64, branchName string) (*ProtectedBranch, error) { func GetProtectedBranchBy(repoID int64, branchName string) (*ProtectedBranch, error) {
return getProtectedBranchBy(db.DefaultContext().Engine(), repoID, branchName) return getProtectedBranchBy(db.GetEngine(db.DefaultContext), repoID, branchName)
} }
func getProtectedBranchBy(e db.Engine, repoID int64, branchName string) (*ProtectedBranch, error) { func getProtectedBranchBy(e db.Engine, repoID int64, branchName string) (*ProtectedBranch, error) {
@ -375,13 +375,13 @@ func UpdateProtectBranch(repo *Repository, protectBranch *ProtectedBranch, opts
// Make sure protectBranch.ID is not 0 for whitelists // Make sure protectBranch.ID is not 0 for whitelists
if protectBranch.ID == 0 { if protectBranch.ID == 0 {
if _, err = db.DefaultContext().Engine().Insert(protectBranch); err != nil { if _, err = db.GetEngine(db.DefaultContext).Insert(protectBranch); err != nil {
return fmt.Errorf("Insert: %v", err) return fmt.Errorf("Insert: %v", err)
} }
return nil return nil
} }
if _, err = db.DefaultContext().Engine().ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil { if _, err = db.GetEngine(db.DefaultContext).ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
return fmt.Errorf("Update: %v", err) return fmt.Errorf("Update: %v", err)
} }
@ -391,7 +391,7 @@ func UpdateProtectBranch(repo *Repository, protectBranch *ProtectedBranch, opts
// GetProtectedBranches get all protected branches // GetProtectedBranches get all protected branches
func (repo *Repository) GetProtectedBranches() ([]*ProtectedBranch, error) { func (repo *Repository) GetProtectedBranches() ([]*ProtectedBranch, error) {
protectedBranches := make([]*ProtectedBranch, 0) protectedBranches := make([]*ProtectedBranch, 0)
return protectedBranches, db.DefaultContext().Engine().Find(&protectedBranches, &ProtectedBranch{RepoID: repo.ID}) return protectedBranches, db.GetEngine(db.DefaultContext).Find(&protectedBranches, &ProtectedBranch{RepoID: repo.ID})
} }
// GetBranchProtection get the branch protection of a branch // GetBranchProtection get the branch protection of a branch
@ -406,7 +406,7 @@ func (repo *Repository) IsProtectedBranch(branchName string) (bool, error) {
BranchName: branchName, BranchName: branchName,
} }
has, err := db.DefaultContext().Engine().Exist(protectedBranch) has, err := db.GetEngine(db.DefaultContext).Exist(protectedBranch)
if err != nil { if err != nil {
return true, err return true, err
} }
@ -493,7 +493,7 @@ func (repo *Repository) DeleteProtectedBranch(id int64) (err error) {
ID: id, ID: id,
} }
if affected, err := db.DefaultContext().Engine().Delete(protectedBranch); err != nil { if affected, err := db.GetEngine(db.DefaultContext).Delete(protectedBranch); err != nil {
return err return err
} else if affected != 1 { } else if affected != 1 {
return fmt.Errorf("delete protected branch ID(%v) failed", id) return fmt.Errorf("delete protected branch ID(%v) failed", id)
@ -522,20 +522,20 @@ func (repo *Repository) AddDeletedBranch(branchName, commit string, deletedByID
DeletedByID: deletedByID, DeletedByID: deletedByID,
} }
_, err := db.DefaultContext().Engine().InsertOne(deletedBranch) _, err := db.GetEngine(db.DefaultContext).InsertOne(deletedBranch)
return err return err
} }
// GetDeletedBranches returns all the deleted branches // GetDeletedBranches returns all the deleted branches
func (repo *Repository) GetDeletedBranches() ([]*DeletedBranch, error) { func (repo *Repository) GetDeletedBranches() ([]*DeletedBranch, error) {
deletedBranches := make([]*DeletedBranch, 0) deletedBranches := make([]*DeletedBranch, 0)
return deletedBranches, db.DefaultContext().Engine().Where("repo_id = ?", repo.ID).Desc("deleted_unix").Find(&deletedBranches) return deletedBranches, db.GetEngine(db.DefaultContext).Where("repo_id = ?", repo.ID).Desc("deleted_unix").Find(&deletedBranches)
} }
// GetDeletedBranchByID get a deleted branch by its ID // GetDeletedBranchByID get a deleted branch by its ID
func (repo *Repository) GetDeletedBranchByID(id int64) (*DeletedBranch, error) { func (repo *Repository) GetDeletedBranchByID(id int64) (*DeletedBranch, error) {
deletedBranch := &DeletedBranch{} deletedBranch := &DeletedBranch{}
has, err := db.DefaultContext().Engine().ID(id).Get(deletedBranch) has, err := db.GetEngine(db.DefaultContext).ID(id).Get(deletedBranch)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -552,7 +552,7 @@ func (repo *Repository) RemoveDeletedBranch(id int64) (err error) {
ID: id, ID: id,
} }
if affected, err := db.DefaultContext().Engine().Delete(deletedBranch); err != nil { if affected, err := db.GetEngine(db.DefaultContext).Delete(deletedBranch); err != nil {
return err return err
} else if affected != 1 { } else if affected != 1 {
return fmt.Errorf("remove deleted branch ID(%v) failed", id) return fmt.Errorf("remove deleted branch ID(%v) failed", id)
@ -573,7 +573,7 @@ func (deletedBranch *DeletedBranch) LoadUser() {
// RemoveDeletedBranch removes all deleted branches // RemoveDeletedBranch removes all deleted branches
func RemoveDeletedBranch(repoID int64, branch string) error { func RemoveDeletedBranch(repoID int64, branch string) error {
_, err := db.DefaultContext().Engine().Where("repo_id=? AND name=?", repoID, branch).Delete(new(DeletedBranch)) _, err := db.GetEngine(db.DefaultContext).Where("repo_id=? AND name=?", repoID, branch).Delete(new(DeletedBranch))
return err return err
} }
@ -583,7 +583,7 @@ func RemoveOldDeletedBranches(ctx context.Context, olderThan time.Duration) {
log.Trace("Doing: DeletedBranchesCleanup") log.Trace("Doing: DeletedBranchesCleanup")
deleteBefore := time.Now().Add(-olderThan) deleteBefore := time.Now().Add(-olderThan)
_, err := db.DefaultContext().Engine().Where("deleted_unix < ?", deleteBefore.Unix()).Delete(new(DeletedBranch)) _, err := db.GetEngine(db.DefaultContext).Where("deleted_unix < ?", deleteBefore.Unix()).Delete(new(DeletedBranch))
if err != nil { if err != nil {
log.Error("DeletedBranchesCleanup: %v", err) log.Error("DeletedBranchesCleanup: %v", err)
} }

View File

@ -136,7 +136,7 @@ func (status *CommitStatus) loadAttributes(e db.Engine) (err error) {
// APIURL returns the absolute APIURL to this commit-status. // APIURL returns the absolute APIURL to this commit-status.
func (status *CommitStatus) APIURL() string { func (status *CommitStatus) APIURL() string {
_ = status.loadAttributes(db.DefaultContext().Engine()) _ = status.loadAttributes(db.GetEngine(db.DefaultContext))
return fmt.Sprintf("%sapi/v1/repos/%s/statuses/%s", return fmt.Sprintf("%sapi/v1/repos/%s/statuses/%s",
setting.AppURL, status.Repo.FullName(), status.SHA) setting.AppURL, status.Repo.FullName(), status.SHA)
} }
@ -193,7 +193,7 @@ func GetCommitStatuses(repo *Repository, sha string, opts *CommitStatusOptions)
} }
func listCommitStatusesStatement(repo *Repository, sha string, opts *CommitStatusOptions) *xorm.Session { func listCommitStatusesStatement(repo *Repository, sha string, opts *CommitStatusOptions) *xorm.Session {
sess := db.DefaultContext().Engine().Where("repo_id = ?", repo.ID).And("sha = ?", sha) sess := db.GetEngine(db.DefaultContext).Where("repo_id = ?", repo.ID).And("sha = ?", sha)
switch opts.State { switch opts.State {
case "pending", "success", "error", "failure", "warning": case "pending", "success", "error", "failure", "warning":
sess.And("state = ?", opts.State) sess.And("state = ?", opts.State)
@ -228,7 +228,7 @@ type CommitStatusIndex struct {
// GetLatestCommitStatus returns all statuses with a unique context for a given commit. // GetLatestCommitStatus returns all statuses with a unique context for a given commit.
func GetLatestCommitStatus(repoID int64, sha string, listOptions ListOptions) ([]*CommitStatus, error) { func GetLatestCommitStatus(repoID int64, sha string, listOptions ListOptions) ([]*CommitStatus, error) {
return getLatestCommitStatus(db.DefaultContext().Engine(), repoID, sha, listOptions) return getLatestCommitStatus(db.GetEngine(db.DefaultContext), repoID, sha, listOptions)
} }
func getLatestCommitStatus(e db.Engine, repoID int64, sha string, listOptions ListOptions) ([]*CommitStatus, error) { func getLatestCommitStatus(e db.Engine, repoID int64, sha string, listOptions ListOptions) ([]*CommitStatus, error) {
@ -255,7 +255,7 @@ func getLatestCommitStatus(e db.Engine, repoID int64, sha string, listOptions Li
func FindRepoRecentCommitStatusContexts(repoID int64, before time.Duration) ([]string, error) { func FindRepoRecentCommitStatusContexts(repoID int64, before time.Duration) ([]string, error) {
start := timeutil.TimeStampNow().AddDuration(-before) start := timeutil.TimeStampNow().AddDuration(-before)
ids := make([]int64, 0, 10) ids := make([]int64, 0, 10)
if err := db.DefaultContext().Engine().Table("commit_status"). if err := db.GetEngine(db.DefaultContext).Table("commit_status").
Where("repo_id = ?", repoID). Where("repo_id = ?", repoID).
And("updated_unix >= ?", start). And("updated_unix >= ?", start).
Select("max( id ) as id"). Select("max( id ) as id").
@ -268,7 +268,7 @@ func FindRepoRecentCommitStatusContexts(repoID int64, before time.Duration) ([]s
if len(ids) == 0 { if len(ids) == 0 {
return contexts, nil return contexts, nil
} }
return contexts, db.DefaultContext().Engine().Select("context").Table("commit_status").In("id", ids).Find(&contexts) return contexts, db.GetEngine(db.DefaultContext).Select("context").Table("commit_status").In("id", ids).Find(&contexts)
} }
// NewCommitStatusOptions holds options for creating a CommitStatus // NewCommitStatusOptions holds options for creating a CommitStatus
@ -314,7 +314,7 @@ func NewCommitStatus(opts NewCommitStatusOptions) error {
opts.CommitStatus.ContextHash = hashCommitStatusContext(opts.CommitStatus.Context) opts.CommitStatus.ContextHash = hashCommitStatusContext(opts.CommitStatus.Context)
// Insert new CommitStatus // Insert new CommitStatus
if _, err = ctx.Engine().Insert(opts.CommitStatus); err != nil { if _, err = db.GetEngine(ctx).Insert(opts.CommitStatus); err != nil {
return fmt.Errorf("Insert CommitStatus[%s, %s]: %v", repoPath, opts.SHA, err) return fmt.Errorf("Insert CommitStatus[%s, %s]: %v", repoPath, opts.SHA, err)
} }

View File

@ -41,7 +41,7 @@ func CheckConsistencyFor(t *testing.T, beansToCheck ...interface{}) {
ptrToSliceValue := reflect.New(sliceType) ptrToSliceValue := reflect.New(sliceType)
ptrToSliceValue.Elem().Set(sliceValue) ptrToSliceValue.Elem().Set(sliceValue)
assert.NoError(t, db.DefaultContext().Engine().Table(bean).Find(ptrToSliceValue.Interface())) assert.NoError(t, db.GetEngine(db.DefaultContext).Table(bean).Find(ptrToSliceValue.Interface()))
sliceValue = ptrToSliceValue.Elem() sliceValue = ptrToSliceValue.Elem()
for i := 0; i < sliceValue.Len(); i++ { for i := 0; i < sliceValue.Len(); i++ {
@ -66,7 +66,7 @@ func getCount(t *testing.T, e db.Engine, bean interface{}) int64 {
// assertCount test the count of database entries matching bean // assertCount test the count of database entries matching bean
func assertCount(t *testing.T, bean interface{}, expected int) { func assertCount(t *testing.T, bean interface{}, expected int) {
assert.EqualValues(t, expected, getCount(t, db.DefaultContext().Engine(), bean), assert.EqualValues(t, expected, getCount(t, db.GetEngine(db.DefaultContext), bean),
"Failed consistency test, the counted bean (of type %T) was %+v", bean, bean) "Failed consistency test, the counted bean (of type %T) was %+v", bean, bean)
} }
@ -92,33 +92,33 @@ func (repo *Repository) checkForConsistency(t *testing.T) {
db.AssertExistsAndLoadBean(t, &Repository{ID: repo.ForkID}) db.AssertExistsAndLoadBean(t, &Repository{ID: repo.ForkID})
} }
actual := getCount(t, db.DefaultContext().Engine().Where("Mode<>?", RepoWatchModeDont), &Watch{RepoID: repo.ID}) actual := getCount(t, db.GetEngine(db.DefaultContext).Where("Mode<>?", RepoWatchModeDont), &Watch{RepoID: repo.ID})
assert.EqualValues(t, repo.NumWatches, actual, assert.EqualValues(t, repo.NumWatches, actual,
"Unexpected number of watches for repo %+v", repo) "Unexpected number of watches for repo %+v", repo)
actual = getCount(t, db.DefaultContext().Engine().Where("is_pull=?", false), &Issue{RepoID: repo.ID}) actual = getCount(t, db.GetEngine(db.DefaultContext).Where("is_pull=?", false), &Issue{RepoID: repo.ID})
assert.EqualValues(t, repo.NumIssues, actual, assert.EqualValues(t, repo.NumIssues, actual,
"Unexpected number of issues for repo %+v", repo) "Unexpected number of issues for repo %+v", repo)
actual = getCount(t, db.DefaultContext().Engine().Where("is_pull=? AND is_closed=?", false, true), &Issue{RepoID: repo.ID}) actual = getCount(t, db.GetEngine(db.DefaultContext).Where("is_pull=? AND is_closed=?", false, true), &Issue{RepoID: repo.ID})
assert.EqualValues(t, repo.NumClosedIssues, actual, assert.EqualValues(t, repo.NumClosedIssues, actual,
"Unexpected number of closed issues for repo %+v", repo) "Unexpected number of closed issues for repo %+v", repo)
actual = getCount(t, db.DefaultContext().Engine().Where("is_pull=?", true), &Issue{RepoID: repo.ID}) actual = getCount(t, db.GetEngine(db.DefaultContext).Where("is_pull=?", true), &Issue{RepoID: repo.ID})
assert.EqualValues(t, repo.NumPulls, actual, assert.EqualValues(t, repo.NumPulls, actual,
"Unexpected number of pulls for repo %+v", repo) "Unexpected number of pulls for repo %+v", repo)
actual = getCount(t, db.DefaultContext().Engine().Where("is_pull=? AND is_closed=?", true, true), &Issue{RepoID: repo.ID}) actual = getCount(t, db.GetEngine(db.DefaultContext).Where("is_pull=? AND is_closed=?", true, true), &Issue{RepoID: repo.ID})
assert.EqualValues(t, repo.NumClosedPulls, actual, assert.EqualValues(t, repo.NumClosedPulls, actual,
"Unexpected number of closed pulls for repo %+v", repo) "Unexpected number of closed pulls for repo %+v", repo)
actual = getCount(t, db.DefaultContext().Engine().Where("is_closed=?", true), &Milestone{RepoID: repo.ID}) actual = getCount(t, db.GetEngine(db.DefaultContext).Where("is_closed=?", true), &Milestone{RepoID: repo.ID})
assert.EqualValues(t, repo.NumClosedMilestones, actual, assert.EqualValues(t, repo.NumClosedMilestones, actual,
"Unexpected number of closed milestones for repo %+v", repo) "Unexpected number of closed milestones for repo %+v", repo)
} }
func (issue *Issue) checkForConsistency(t *testing.T) { func (issue *Issue) checkForConsistency(t *testing.T) {
actual := getCount(t, db.DefaultContext().Engine().Where("type=?", CommentTypeComment), &Comment{IssueID: issue.ID}) actual := getCount(t, db.GetEngine(db.DefaultContext).Where("type=?", CommentTypeComment), &Comment{IssueID: issue.ID})
assert.EqualValues(t, issue.NumComments, actual, assert.EqualValues(t, issue.NumComments, actual,
"Unexpected number of comments for issue %+v", issue) "Unexpected number of comments for issue %+v", issue)
if issue.IsPull { if issue.IsPull {
@ -136,7 +136,7 @@ func (pr *PullRequest) checkForConsistency(t *testing.T) {
func (milestone *Milestone) checkForConsistency(t *testing.T) { func (milestone *Milestone) checkForConsistency(t *testing.T) {
assertCount(t, &Issue{MilestoneID: milestone.ID}, milestone.NumIssues) assertCount(t, &Issue{MilestoneID: milestone.ID}, milestone.NumIssues)
actual := getCount(t, db.DefaultContext().Engine().Where("is_closed=?", true), &Issue{MilestoneID: milestone.ID}) actual := getCount(t, db.GetEngine(db.DefaultContext).Where("is_closed=?", true), &Issue{MilestoneID: milestone.ID})
assert.EqualValues(t, milestone.NumClosedIssues, actual, assert.EqualValues(t, milestone.NumClosedIssues, actual,
"Unexpected number of closed issues for milestone %+v", milestone) "Unexpected number of closed issues for milestone %+v", milestone)
@ -149,7 +149,7 @@ func (milestone *Milestone) checkForConsistency(t *testing.T) {
func (label *Label) checkForConsistency(t *testing.T) { func (label *Label) checkForConsistency(t *testing.T) {
issueLabels := make([]*IssueLabel, 0, 10) issueLabels := make([]*IssueLabel, 0, 10)
assert.NoError(t, db.DefaultContext().Engine().Find(&issueLabels, &IssueLabel{LabelID: label.ID})) assert.NoError(t, db.GetEngine(db.DefaultContext).Find(&issueLabels, &IssueLabel{LabelID: label.ID}))
assert.EqualValues(t, label.NumIssues, len(issueLabels), assert.EqualValues(t, label.NumIssues, len(issueLabels),
"Unexpected number of issue for label %+v", label) "Unexpected number of issue for label %+v", label)
@ -160,7 +160,7 @@ func (label *Label) checkForConsistency(t *testing.T) {
expected := int64(0) expected := int64(0)
if len(issueIDs) > 0 { if len(issueIDs) > 0 {
expected = getCount(t, db.DefaultContext().Engine().In("id", issueIDs).Where("is_closed=?", true), &Issue{}) expected = getCount(t, db.GetEngine(db.DefaultContext).In("id", issueIDs).Where("is_closed=?", true), &Issue{})
} }
assert.EqualValues(t, expected, label.NumClosedIssues, assert.EqualValues(t, expected, label.NumClosedIssues,
"Unexpected number of closed issues for label %+v", label) "Unexpected number of closed issues for label %+v", label)
@ -178,12 +178,12 @@ func (action *Action) checkForConsistency(t *testing.T) {
// CountOrphanedLabels return count of labels witch are broken and not accessible via ui anymore // CountOrphanedLabels return count of labels witch are broken and not accessible via ui anymore
func CountOrphanedLabels() (int64, error) { func CountOrphanedLabels() (int64, error) {
noref, err := db.DefaultContext().Engine().Table("label").Where("repo_id=? AND org_id=?", 0, 0).Count("label.id") noref, err := db.GetEngine(db.DefaultContext).Table("label").Where("repo_id=? AND org_id=?", 0, 0).Count("label.id")
if err != nil { if err != nil {
return 0, err return 0, err
} }
norepo, err := db.DefaultContext().Engine().Table("label"). norepo, err := db.GetEngine(db.DefaultContext).Table("label").
Where(builder.And( Where(builder.And(
builder.Gt{"repo_id": 0}, builder.Gt{"repo_id": 0},
builder.NotIn("repo_id", builder.Select("id").From("repository")), builder.NotIn("repo_id", builder.Select("id").From("repository")),
@ -193,7 +193,7 @@ func CountOrphanedLabels() (int64, error) {
return 0, err return 0, err
} }
noorg, err := db.DefaultContext().Engine().Table("label"). noorg, err := db.GetEngine(db.DefaultContext).Table("label").
Where(builder.And( Where(builder.And(
builder.Gt{"org_id": 0}, builder.Gt{"org_id": 0},
builder.NotIn("org_id", builder.Select("id").From("user")), builder.NotIn("org_id", builder.Select("id").From("user")),
@ -209,12 +209,12 @@ func CountOrphanedLabels() (int64, error) {
// DeleteOrphanedLabels delete labels witch are broken and not accessible via ui anymore // DeleteOrphanedLabels delete labels witch are broken and not accessible via ui anymore
func DeleteOrphanedLabels() error { func DeleteOrphanedLabels() error {
// delete labels with no reference // delete labels with no reference
if _, err := db.DefaultContext().Engine().Table("label").Where("repo_id=? AND org_id=?", 0, 0).Delete(new(Label)); err != nil { if _, err := db.GetEngine(db.DefaultContext).Table("label").Where("repo_id=? AND org_id=?", 0, 0).Delete(new(Label)); err != nil {
return err return err
} }
// delete labels with none existing repos // delete labels with none existing repos
if _, err := db.DefaultContext().Engine(). if _, err := db.GetEngine(db.DefaultContext).
Where(builder.And( Where(builder.And(
builder.Gt{"repo_id": 0}, builder.Gt{"repo_id": 0},
builder.NotIn("repo_id", builder.Select("id").From("repository")), builder.NotIn("repo_id", builder.Select("id").From("repository")),
@ -224,7 +224,7 @@ func DeleteOrphanedLabels() error {
} }
// delete labels with none existing orgs // delete labels with none existing orgs
if _, err := db.DefaultContext().Engine(). if _, err := db.GetEngine(db.DefaultContext).
Where(builder.And( Where(builder.And(
builder.Gt{"org_id": 0}, builder.Gt{"org_id": 0},
builder.NotIn("org_id", builder.Select("id").From("user")), builder.NotIn("org_id", builder.Select("id").From("user")),
@ -238,14 +238,14 @@ func DeleteOrphanedLabels() error {
// CountOrphanedIssueLabels return count of IssueLabels witch have no label behind anymore // CountOrphanedIssueLabels return count of IssueLabels witch have no label behind anymore
func CountOrphanedIssueLabels() (int64, error) { func CountOrphanedIssueLabels() (int64, error) {
return db.DefaultContext().Engine().Table("issue_label"). return db.GetEngine(db.DefaultContext).Table("issue_label").
NotIn("label_id", builder.Select("id").From("label")). NotIn("label_id", builder.Select("id").From("label")).
Count() Count()
} }
// DeleteOrphanedIssueLabels delete IssueLabels witch have no label behind anymore // DeleteOrphanedIssueLabels delete IssueLabels witch have no label behind anymore
func DeleteOrphanedIssueLabels() error { func DeleteOrphanedIssueLabels() error {
_, err := db.DefaultContext().Engine(). _, err := db.GetEngine(db.DefaultContext).
NotIn("label_id", builder.Select("id").From("label")). NotIn("label_id", builder.Select("id").From("label")).
Delete(IssueLabel{}) Delete(IssueLabel{})
@ -254,7 +254,7 @@ func DeleteOrphanedIssueLabels() error {
// CountOrphanedIssues count issues without a repo // CountOrphanedIssues count issues without a repo
func CountOrphanedIssues() (int64, error) { func CountOrphanedIssues() (int64, error) {
return db.DefaultContext().Engine().Table("issue"). return db.GetEngine(db.DefaultContext).Table("issue").
Join("LEFT", "repository", "issue.repo_id=repository.id"). Join("LEFT", "repository", "issue.repo_id=repository.id").
Where(builder.IsNull{"repository.id"}). Where(builder.IsNull{"repository.id"}).
Count("id") Count("id")
@ -270,7 +270,7 @@ func DeleteOrphanedIssues() error {
var ids []int64 var ids []int64
if err := ctx.Engine().Table("issue").Distinct("issue.repo_id"). if err := db.GetEngine(ctx).Table("issue").Distinct("issue.repo_id").
Join("LEFT", "repository", "issue.repo_id=repository.id"). Join("LEFT", "repository", "issue.repo_id=repository.id").
Where(builder.IsNull{"repository.id"}).GroupBy("issue.repo_id"). Where(builder.IsNull{"repository.id"}).GroupBy("issue.repo_id").
Find(&ids); err != nil { Find(&ids); err != nil {
@ -279,7 +279,7 @@ func DeleteOrphanedIssues() error {
var attachmentPaths []string var attachmentPaths []string
for i := range ids { for i := range ids {
paths, err := deleteIssuesByRepoID(ctx.Engine(), ids[i]) paths, err := deleteIssuesByRepoID(db.GetEngine(ctx), ids[i])
if err != nil { if err != nil {
return err return err
} }
@ -293,14 +293,14 @@ func DeleteOrphanedIssues() error {
// Remove issue attachment files. // Remove issue attachment files.
for i := range attachmentPaths { for i := range attachmentPaths {
removeAllWithNotice(db.DefaultContext().Engine(), "Delete issue attachment", attachmentPaths[i]) removeAllWithNotice(db.GetEngine(db.DefaultContext), "Delete issue attachment", attachmentPaths[i])
} }
return nil return nil
} }
// CountOrphanedObjects count subjects with have no existing refobject anymore // CountOrphanedObjects count subjects with have no existing refobject anymore
func CountOrphanedObjects(subject, refobject, joinCond string) (int64, error) { func CountOrphanedObjects(subject, refobject, joinCond string) (int64, error) {
return db.DefaultContext().Engine().Table("`"+subject+"`"). return db.GetEngine(db.DefaultContext).Table("`"+subject+"`").
Join("LEFT", refobject, joinCond). Join("LEFT", refobject, joinCond).
Where(builder.IsNull{"`" + refobject + "`.id"}). Where(builder.IsNull{"`" + refobject + "`.id"}).
Count("id") Count("id")
@ -316,45 +316,45 @@ func DeleteOrphanedObjects(subject, refobject, joinCond string) error {
if err != nil { if err != nil {
return err return err
} }
_, err = db.DefaultContext().Engine().Exec(append([]interface{}{sql}, args...)...) _, err = db.GetEngine(db.DefaultContext).Exec(append([]interface{}{sql}, args...)...)
return err return err
} }
// CountNullArchivedRepository counts the number of repositories with is_archived is null // CountNullArchivedRepository counts the number of repositories with is_archived is null
func CountNullArchivedRepository() (int64, error) { func CountNullArchivedRepository() (int64, error) {
return db.DefaultContext().Engine().Where(builder.IsNull{"is_archived"}).Count(new(Repository)) return db.GetEngine(db.DefaultContext).Where(builder.IsNull{"is_archived"}).Count(new(Repository))
} }
// FixNullArchivedRepository sets is_archived to false where it is null // FixNullArchivedRepository sets is_archived to false where it is null
func FixNullArchivedRepository() (int64, error) { func FixNullArchivedRepository() (int64, error) {
return db.DefaultContext().Engine().Where(builder.IsNull{"is_archived"}).Cols("is_archived").NoAutoTime().Update(&Repository{ return db.GetEngine(db.DefaultContext).Where(builder.IsNull{"is_archived"}).Cols("is_archived").NoAutoTime().Update(&Repository{
IsArchived: false, IsArchived: false,
}) })
} }
// CountWrongUserType count OrgUser who have wrong type // CountWrongUserType count OrgUser who have wrong type
func CountWrongUserType() (int64, error) { func CountWrongUserType() (int64, error) {
return db.DefaultContext().Engine().Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Count(new(User)) return db.GetEngine(db.DefaultContext).Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Count(new(User))
} }
// FixWrongUserType fix OrgUser who have wrong type // FixWrongUserType fix OrgUser who have wrong type
func FixWrongUserType() (int64, error) { func FixWrongUserType() (int64, error) {
return db.DefaultContext().Engine().Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Cols("type").NoAutoTime().Update(&User{Type: 1}) return db.GetEngine(db.DefaultContext).Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Cols("type").NoAutoTime().Update(&User{Type: 1})
} }
// CountCommentTypeLabelWithEmptyLabel count label comments with empty label // CountCommentTypeLabelWithEmptyLabel count label comments with empty label
func CountCommentTypeLabelWithEmptyLabel() (int64, error) { func CountCommentTypeLabelWithEmptyLabel() (int64, error) {
return db.DefaultContext().Engine().Where(builder.Eq{"type": CommentTypeLabel, "label_id": 0}).Count(new(Comment)) return db.GetEngine(db.DefaultContext).Where(builder.Eq{"type": CommentTypeLabel, "label_id": 0}).Count(new(Comment))
} }
// FixCommentTypeLabelWithEmptyLabel count label comments with empty label // FixCommentTypeLabelWithEmptyLabel count label comments with empty label
func FixCommentTypeLabelWithEmptyLabel() (int64, error) { func FixCommentTypeLabelWithEmptyLabel() (int64, error) {
return db.DefaultContext().Engine().Where(builder.Eq{"type": CommentTypeLabel, "label_id": 0}).Delete(new(Comment)) return db.GetEngine(db.DefaultContext).Where(builder.Eq{"type": CommentTypeLabel, "label_id": 0}).Delete(new(Comment))
} }
// CountCommentTypeLabelWithOutsideLabels count label comments with outside label // CountCommentTypeLabelWithOutsideLabels count label comments with outside label
func CountCommentTypeLabelWithOutsideLabels() (int64, error) { func CountCommentTypeLabelWithOutsideLabels() (int64, error) {
return db.DefaultContext().Engine().Where("comment.type = ? AND ((label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id))", CommentTypeLabel). return db.GetEngine(db.DefaultContext).Where("comment.type = ? AND ((label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id))", CommentTypeLabel).
Table("comment"). Table("comment").
Join("inner", "label", "label.id = comment.label_id"). Join("inner", "label", "label.id = comment.label_id").
Join("inner", "issue", "issue.id = comment.issue_id "). Join("inner", "issue", "issue.id = comment.issue_id ").
@ -364,7 +364,7 @@ func CountCommentTypeLabelWithOutsideLabels() (int64, error) {
// FixCommentTypeLabelWithOutsideLabels count label comments with outside label // FixCommentTypeLabelWithOutsideLabels count label comments with outside label
func FixCommentTypeLabelWithOutsideLabels() (int64, error) { func FixCommentTypeLabelWithOutsideLabels() (int64, error) {
res, err := db.DefaultContext().Engine().Exec(`DELETE FROM comment WHERE comment.id IN ( res, err := db.GetEngine(db.DefaultContext).Exec(`DELETE FROM comment WHERE comment.id IN (
SELECT il_too.id FROM ( SELECT il_too.id FROM (
SELECT com.id SELECT com.id
FROM comment AS com FROM comment AS com
@ -383,7 +383,7 @@ func FixCommentTypeLabelWithOutsideLabels() (int64, error) {
// CountIssueLabelWithOutsideLabels count label comments with outside label // CountIssueLabelWithOutsideLabels count label comments with outside label
func CountIssueLabelWithOutsideLabels() (int64, error) { func CountIssueLabelWithOutsideLabels() (int64, error) {
return db.DefaultContext().Engine().Where(builder.Expr("(label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id)")). return db.GetEngine(db.DefaultContext).Where(builder.Expr("(label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id)")).
Table("issue_label"). Table("issue_label").
Join("inner", "label", "issue_label.label_id = label.id "). Join("inner", "label", "issue_label.label_id = label.id ").
Join("inner", "issue", "issue.id = issue_label.issue_id "). Join("inner", "issue", "issue.id = issue_label.issue_id ").
@ -393,7 +393,7 @@ func CountIssueLabelWithOutsideLabels() (int64, error) {
// FixIssueLabelWithOutsideLabels fix label comments with outside label // FixIssueLabelWithOutsideLabels fix label comments with outside label
func FixIssueLabelWithOutsideLabels() (int64, error) { func FixIssueLabelWithOutsideLabels() (int64, error) {
res, err := db.DefaultContext().Engine().Exec(`DELETE FROM issue_label WHERE issue_label.id IN ( res, err := db.GetEngine(db.DefaultContext).Exec(`DELETE FROM issue_label WHERE issue_label.id IN (
SELECT il_too.id FROM ( SELECT il_too.id FROM (
SELECT il_too_too.id SELECT il_too_too.id
FROM issue_label AS il_too_too FROM issue_label AS il_too_too

View File

@ -14,10 +14,10 @@ import (
func TestDeleteOrphanedObjects(t *testing.T) { func TestDeleteOrphanedObjects(t *testing.T) {
assert.NoError(t, db.PrepareTestDatabase()) assert.NoError(t, db.PrepareTestDatabase())
countBefore, err := db.DefaultContext().Engine().Count(&PullRequest{}) countBefore, err := db.GetEngine(db.DefaultContext).Count(&PullRequest{})
assert.NoError(t, err) assert.NoError(t, err)
_, err = db.DefaultContext().Engine().Insert(&PullRequest{IssueID: 1000}, &PullRequest{IssueID: 1001}, &PullRequest{IssueID: 1003}) _, err = db.GetEngine(db.DefaultContext).Insert(&PullRequest{IssueID: 1000}, &PullRequest{IssueID: 1001}, &PullRequest{IssueID: 1003})
assert.NoError(t, err) assert.NoError(t, err)
orphaned, err := CountOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id") orphaned, err := CountOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id")
@ -27,7 +27,7 @@ func TestDeleteOrphanedObjects(t *testing.T) {
err = DeleteOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id") err = DeleteOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id")
assert.NoError(t, err) assert.NoError(t, err)
countAfter, err := db.DefaultContext().Engine().Count(&PullRequest{}) countAfter, err := db.GetEngine(db.DefaultContext).Count(&PullRequest{})
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, countBefore, countAfter) assert.EqualValues(t, countBefore, countAfter)
} }

View File

@ -5,14 +5,29 @@
package db package db
import ( import (
"context"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"xorm.io/builder" "xorm.io/builder"
"xorm.io/xorm" "xorm.io/xorm"
) )
// DefaultContext is the default context to run xorm queries in
// will be overwritten by Init with HammerContext
var DefaultContext context.Context
// contextKey is a value for use with context.WithValue.
type contextKey struct {
name string
}
// EnginedContextKey is a context key. It is used with context.Value() to get the current Engined for the context
var EnginedContextKey = &contextKey{"engined"}
// Context represents a db context // Context represents a db context
type Context struct { type Context struct {
context.Context
e Engine e Engine
} }
@ -30,9 +45,48 @@ func (ctx *Context) NewSession() *xorm.Session {
return nil return nil
} }
// DefaultContext represents a Context with default Engine // Value shadows Value for context.Context but allows us to get ourselves and an Engined object
func DefaultContext() *Context { func (ctx *Context) Value(key interface{}) interface{} {
return &Context{x} if key == EnginedContextKey {
return ctx
}
return ctx.Context.Value(key)
}
// Engined structs provide an Engine
type Engined interface {
Engine() Engine
NewSession() *xorm.Session
}
// GetEngine will get a db Engine from this context or return an Engine restricted to this context
func GetEngine(ctx context.Context) Engine {
if engined, ok := ctx.(Engined); ok {
return engined.Engine()
}
enginedInterface := ctx.Value(EnginedContextKey)
if enginedInterface != nil {
return enginedInterface.(Engined).Engine()
}
return x.Context(ctx)
}
// NewSession will get a db Session from this context or return a session restricted to this context
func NewSession(ctx context.Context) *xorm.Session {
if engined, ok := ctx.(Engined); ok {
return engined.NewSession()
}
enginedInterface := ctx.Value(EnginedContextKey)
if enginedInterface != nil {
sess := enginedInterface.(Engined).NewSession()
if sess != nil {
return sess.Context(ctx)
}
return nil
}
return x.NewSession().Context(ctx)
} }
// Committer represents an interface to Commit or Close the Context // Committer represents an interface to Commit or Close the Context
@ -49,23 +103,32 @@ func TxContext() (*Context, Committer, error) {
return nil, nil, err return nil, nil, err
} }
return &Context{sess}, sess, nil return &Context{
Context: DefaultContext,
e: sess,
}, sess, nil
} }
// WithContext represents executing database operations // WithContext represents executing database operations
func WithContext(f func(ctx *Context) error) error { func WithContext(f func(ctx *Context) error) error {
return f(&Context{x}) return f(&Context{
Context: DefaultContext,
e: x,
})
} }
// WithTx represents executing database operations on a transaction // WithTx represents executing database operations on a transaction
func WithTx(f func(ctx *Context) error) error { func WithTx(f func(ctx context.Context) error) error {
sess := x.NewSession() sess := x.NewSession()
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
} }
if err := f(&Context{sess}); err != nil { if err := f(&Context{
Context: DefaultContext,
e: sess,
}); err != nil {
return err return err
} }
@ -73,14 +136,14 @@ func WithTx(f func(ctx *Context) error) error {
} }
// Iterate iterates the databases and doing something // Iterate iterates the databases and doing something
func Iterate(ctx *Context, tableBean interface{}, cond builder.Cond, fun func(idx int, bean interface{}) error) error { func Iterate(ctx context.Context, tableBean interface{}, cond builder.Cond, fun func(idx int, bean interface{}) error) error {
return ctx.e.Where(cond). return GetEngine(ctx).Where(cond).
BufferSize(setting.Database.IterateBufferSize). BufferSize(setting.Database.IterateBufferSize).
Iterate(tableBean, fun) Iterate(tableBean, fun)
} }
// Insert inserts records into database // Insert inserts records into database
func Insert(ctx *Context, beans ...interface{}) error { func Insert(ctx context.Context, beans ...interface{}) error {
_, err := ctx.e.Insert(beans...) _, err := GetEngine(ctx).Insert(beans...)
return err return err
} }

View File

@ -169,6 +169,11 @@ func NewEngine(ctx context.Context, migrateFunc func(*xorm.Engine) error) (err e
return err return err
} }
DefaultContext = &Context{
Context: ctx,
e: x,
}
x.SetDefaultContext(ctx) x.SetDefaultContext(ctx)
if err = x.Ping(); err != nil { if err = x.Ping(); err != nil {

View File

@ -5,6 +5,7 @@
package db package db
import ( import (
"context"
"fmt" "fmt"
"math" "math"
"net/url" "net/url"
@ -117,6 +118,11 @@ func CreateTestEngine(fixturesDir string) error {
x.ShowSQL(true) x.ShowSQL(true)
} }
DefaultContext = &Context{
Context: context.Background(),
e: x,
}
return InitFixtures(fixturesDir) return InitFixtures(fixturesDir)
} }

View File

@ -25,7 +25,7 @@ func TestDumpDatabase(t *testing.T) {
ID int64 `xorm:"pk autoincr"` ID int64 `xorm:"pk autoincr"`
Version int64 Version int64
} }
assert.NoError(t, db.DefaultContext().Engine().Sync2(new(Version))) assert.NoError(t, db.GetEngine(db.DefaultContext).Sync2(new(Version)))
for _, dbName := range setting.SupportedDatabases { for _, dbName := range setting.SupportedDatabases {
dbType := setting.GetDBTypeByName(dbName) dbType := setting.GetDBTypeByName(dbName)

View File

@ -41,13 +41,13 @@ func init() {
// GetExternalLogin checks if a externalID in loginSourceID scope already exists // GetExternalLogin checks if a externalID in loginSourceID scope already exists
func GetExternalLogin(externalLoginUser *ExternalLoginUser) (bool, error) { func GetExternalLogin(externalLoginUser *ExternalLoginUser) (bool, error) {
return db.DefaultContext().Engine().Get(externalLoginUser) return db.GetEngine(db.DefaultContext).Get(externalLoginUser)
} }
// ListAccountLinks returns a map with the ExternalLoginUser and its LoginSource // ListAccountLinks returns a map with the ExternalLoginUser and its LoginSource
func ListAccountLinks(user *User) ([]*ExternalLoginUser, error) { func ListAccountLinks(user *User) ([]*ExternalLoginUser, error) {
externalAccounts := make([]*ExternalLoginUser, 0, 5) externalAccounts := make([]*ExternalLoginUser, 0, 5)
err := db.DefaultContext().Engine().Where("user_id=?", user.ID). err := db.GetEngine(db.DefaultContext).Where("user_id=?", user.ID).
Desc("login_source_id"). Desc("login_source_id").
Find(&externalAccounts) Find(&externalAccounts)
if err != nil { if err != nil {
@ -59,7 +59,7 @@ func ListAccountLinks(user *User) ([]*ExternalLoginUser, error) {
// LinkExternalToUser link the external user to the user // LinkExternalToUser link the external user to the user
func LinkExternalToUser(user *User, externalLoginUser *ExternalLoginUser) error { func LinkExternalToUser(user *User, externalLoginUser *ExternalLoginUser) error {
has, err := db.DefaultContext().Engine().Where("external_id=? AND login_source_id=?", externalLoginUser.ExternalID, externalLoginUser.LoginSourceID). has, err := db.GetEngine(db.DefaultContext).Where("external_id=? AND login_source_id=?", externalLoginUser.ExternalID, externalLoginUser.LoginSourceID).
NoAutoCondition(). NoAutoCondition().
Exist(externalLoginUser) Exist(externalLoginUser)
if err != nil { if err != nil {
@ -68,13 +68,13 @@ func LinkExternalToUser(user *User, externalLoginUser *ExternalLoginUser) error
return ErrExternalLoginUserAlreadyExist{externalLoginUser.ExternalID, user.ID, externalLoginUser.LoginSourceID} return ErrExternalLoginUserAlreadyExist{externalLoginUser.ExternalID, user.ID, externalLoginUser.LoginSourceID}
} }
_, err = db.DefaultContext().Engine().Insert(externalLoginUser) _, err = db.GetEngine(db.DefaultContext).Insert(externalLoginUser)
return err return err
} }
// RemoveAccountLink will remove all external login sources for the given user // RemoveAccountLink will remove all external login sources for the given user
func RemoveAccountLink(user *User, loginSourceID int64) (int64, error) { func RemoveAccountLink(user *User, loginSourceID int64) (int64, error) {
deleted, err := db.DefaultContext().Engine().Delete(&ExternalLoginUser{UserID: user.ID, LoginSourceID: loginSourceID}) deleted, err := db.GetEngine(db.DefaultContext).Delete(&ExternalLoginUser{UserID: user.ID, LoginSourceID: loginSourceID})
if err != nil { if err != nil {
return deleted, err return deleted, err
} }
@ -93,7 +93,7 @@ func removeAllAccountLinks(e db.Engine, user *User) error {
// GetUserIDByExternalUserID get user id according to provider and userID // GetUserIDByExternalUserID get user id according to provider and userID
func GetUserIDByExternalUserID(provider, userID string) (int64, error) { func GetUserIDByExternalUserID(provider, userID string) (int64, error) {
var id int64 var id int64
_, err := db.DefaultContext().Engine().Table("external_login_user"). _, err := db.GetEngine(db.DefaultContext).Table("external_login_user").
Select("user_id"). Select("user_id").
Where("provider=?", provider). Where("provider=?", provider).
And("external_id=?", userID). And("external_id=?", userID).
@ -130,7 +130,7 @@ func UpdateExternalUser(user *User, gothUser goth.User) error {
ExpiresAt: gothUser.ExpiresAt, ExpiresAt: gothUser.ExpiresAt,
} }
has, err := db.DefaultContext().Engine().Where("external_id=? AND login_source_id=?", gothUser.UserID, loginSource.ID). has, err := db.GetEngine(db.DefaultContext).Where("external_id=? AND login_source_id=?", gothUser.UserID, loginSource.ID).
NoAutoCondition(). NoAutoCondition().
Exist(externalLoginUser) Exist(externalLoginUser)
if err != nil { if err != nil {
@ -139,7 +139,7 @@ func UpdateExternalUser(user *User, gothUser goth.User) error {
return ErrExternalLoginUserNotExist{user.ID, loginSource.ID} return ErrExternalLoginUserNotExist{user.ID, loginSource.ID}
} }
_, err = db.DefaultContext().Engine().Where("external_id=? AND login_source_id=?", gothUser.UserID, loginSource.ID).AllCols().Update(externalLoginUser) _, err = db.GetEngine(db.DefaultContext).Where("external_id=? AND login_source_id=?", gothUser.UserID, loginSource.ID).AllCols().Update(externalLoginUser)
return err return err
} }
@ -161,7 +161,7 @@ func (opts FindExternalUserOptions) toConds() builder.Cond {
// FindExternalUsersByProvider represents external users via provider // FindExternalUsersByProvider represents external users via provider
func FindExternalUsersByProvider(opts FindExternalUserOptions) ([]ExternalLoginUser, error) { func FindExternalUsersByProvider(opts FindExternalUserOptions) ([]ExternalLoginUser, error) {
var users []ExternalLoginUser var users []ExternalLoginUser
err := db.DefaultContext().Engine().Where(opts.toConds()). err := db.GetEngine(db.DefaultContext).Where(opts.toConds()).
Limit(opts.Limit, opts.Start). Limit(opts.Limit, opts.Start).
OrderBy("login_source_id ASC, external_id ASC"). OrderBy("login_source_id ASC, external_id ASC").
Find(&users) Find(&users)

View File

@ -15,7 +15,7 @@ import (
// for the access table, as recalculated using repo.RecalculateAccesses() // for the access table, as recalculated using repo.RecalculateAccesses()
func GetYamlFixturesAccess() (string, error) { func GetYamlFixturesAccess() (string, error) {
repos := make([]*Repository, 0, 50) repos := make([]*Repository, 0, 50)
if err := db.DefaultContext().Engine().Find(&repos); err != nil { if err := db.GetEngine(db.DefaultContext).Find(&repos); err != nil {
return "", err return "", err
} }
@ -29,7 +29,7 @@ func GetYamlFixturesAccess() (string, error) {
var b strings.Builder var b strings.Builder
accesses := make([]*Access, 0, 200) accesses := make([]*Access, 0, 200)
if err := db.DefaultContext().Engine().OrderBy("user_id, repo_id").Find(&accesses); err != nil { if err := db.GetEngine(db.DefaultContext).OrderBy("user_id, repo_id").Find(&accesses); err != nil {
return "", err return "", err
} }

View File

@ -63,7 +63,7 @@ func (key *GPGKey) AfterLoad(session *xorm.Session) {
// ListGPGKeys returns a list of public keys belongs to given user. // ListGPGKeys returns a list of public keys belongs to given user.
func ListGPGKeys(uid int64, listOptions ListOptions) ([]*GPGKey, error) { func ListGPGKeys(uid int64, listOptions ListOptions) ([]*GPGKey, error) {
return listGPGKeys(db.DefaultContext().Engine(), uid, listOptions) return listGPGKeys(db.GetEngine(db.DefaultContext), uid, listOptions)
} }
func listGPGKeys(e db.Engine, uid int64, listOptions ListOptions) ([]*GPGKey, error) { func listGPGKeys(e db.Engine, uid int64, listOptions ListOptions) ([]*GPGKey, error) {
@ -78,13 +78,13 @@ func listGPGKeys(e db.Engine, uid int64, listOptions ListOptions) ([]*GPGKey, er
// CountUserGPGKeys return number of gpg keys a user own // CountUserGPGKeys return number of gpg keys a user own
func CountUserGPGKeys(userID int64) (int64, error) { func CountUserGPGKeys(userID int64) (int64, error) {
return db.DefaultContext().Engine().Where("owner_id=? AND primary_key_id=''", userID).Count(&GPGKey{}) return db.GetEngine(db.DefaultContext).Where("owner_id=? AND primary_key_id=''", userID).Count(&GPGKey{})
} }
// GetGPGKeyByID returns public key by given ID. // GetGPGKeyByID returns public key by given ID.
func GetGPGKeyByID(keyID int64) (*GPGKey, error) { func GetGPGKeyByID(keyID int64) (*GPGKey, error) {
key := new(GPGKey) key := new(GPGKey)
has, err := db.DefaultContext().Engine().ID(keyID).Get(key) has, err := db.GetEngine(db.DefaultContext).ID(keyID).Get(key)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -96,7 +96,7 @@ func GetGPGKeyByID(keyID int64) (*GPGKey, error) {
// GetGPGKeysByKeyID returns public key by given ID. // GetGPGKeysByKeyID returns public key by given ID.
func GetGPGKeysByKeyID(keyID string) ([]*GPGKey, error) { func GetGPGKeysByKeyID(keyID string) ([]*GPGKey, error) {
keys := make([]*GPGKey, 0, 1) keys := make([]*GPGKey, 0, 1)
return keys, db.DefaultContext().Engine().Where("key_id=?", keyID).Find(&keys) return keys, db.GetEngine(db.DefaultContext).Where("key_id=?", keyID).Find(&keys)
} }
// GPGKeyToEntity retrieve the imported key and the traducted entity // GPGKeyToEntity retrieve the imported key and the traducted entity
@ -233,7 +233,7 @@ func DeleteGPGKey(doer *User, id int64) (err error) {
} }
defer committer.Close() defer committer.Close()
if _, err = deleteGPGKey(ctx.Engine(), key.KeyID); err != nil { if _, err = deleteGPGKey(db.GetEngine(ctx), key.KeyID); err != nil {
return err return err
} }

View File

@ -103,7 +103,7 @@ func AddGPGKey(ownerID int64, content, token, signature string) ([]*GPGKey, erro
for _, ekey := range ekeys { for _, ekey := range ekeys {
// Key ID cannot be duplicated. // Key ID cannot be duplicated.
has, err := ctx.Engine().Where("key_id=?", ekey.PrimaryKey.KeyIdString()). has, err := db.GetEngine(ctx).Where("key_id=?", ekey.PrimaryKey.KeyIdString()).
Get(new(GPGKey)) Get(new(GPGKey))
if err != nil { if err != nil {
return nil, err return nil, err
@ -118,7 +118,7 @@ func AddGPGKey(ownerID int64, content, token, signature string) ([]*GPGKey, erro
return nil, err return nil, err
} }
if err = addGPGKey(ctx.Engine(), key, content); err != nil { if err = addGPGKey(db.GetEngine(ctx), key, content); err != nil {
return nil, err return nil, err
} }
keys = append(keys, key) keys = append(keys, key)

View File

@ -34,7 +34,7 @@ func init() {
// GetGPGImportByKeyID returns the import public armored key by given KeyID. // GetGPGImportByKeyID returns the import public armored key by given KeyID.
func GetGPGImportByKeyID(keyID string) (*GPGKeyImport, error) { func GetGPGImportByKeyID(keyID string) (*GPGKeyImport, error) {
key := new(GPGKeyImport) key := new(GPGKeyImport)
has, err := db.DefaultContext().Engine().ID(keyID).Get(key) has, err := db.GetEngine(db.DefaultContext).ID(keyID).Get(key)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {

View File

@ -38,7 +38,7 @@ func VerifyGPGKey(ownerID int64, keyID, token, signature string) (string, error)
key := new(GPGKey) key := new(GPGKey)
has, err := ctx.Engine().Where("owner_id = ? AND key_id = ?", ownerID, keyID).Get(key) has, err := db.GetEngine(ctx).Where("owner_id = ? AND key_id = ?", ownerID, keyID).Get(key)
if err != nil { if err != nil {
return "", err return "", err
} else if !has { } else if !has {
@ -92,7 +92,7 @@ func VerifyGPGKey(ownerID int64, keyID, token, signature string) (string, error)
} }
key.Verified = true key.Verified = true
if _, err := ctx.Engine().ID(key.ID).SetExpr("verified", true).Update(new(GPGKey)); err != nil { if _, err := db.GetEngine(ctx).ID(key.ID).SetExpr("verified", true).Update(new(GPGKey)); err != nil {
return "", err return "", err
} }

View File

@ -6,6 +6,7 @@
package models package models
import ( import (
"context"
"fmt" "fmt"
"regexp" "regexp"
"sort" "sort"
@ -113,7 +114,7 @@ func (issue *Issue) IsOverdue() bool {
// LoadRepo loads issue's repository // LoadRepo loads issue's repository
func (issue *Issue) LoadRepo() error { func (issue *Issue) LoadRepo() error {
return issue.loadRepo(db.DefaultContext().Engine()) return issue.loadRepo(db.GetEngine(db.DefaultContext))
} }
func (issue *Issue) loadRepo(e db.Engine) (err error) { func (issue *Issue) loadRepo(e db.Engine) (err error) {
@ -128,7 +129,7 @@ func (issue *Issue) loadRepo(e db.Engine) (err error) {
// IsTimetrackerEnabled returns true if the repo enables timetracking // IsTimetrackerEnabled returns true if the repo enables timetracking
func (issue *Issue) IsTimetrackerEnabled() bool { func (issue *Issue) IsTimetrackerEnabled() bool {
return issue.isTimetrackerEnabled(db.DefaultContext().Engine()) return issue.isTimetrackerEnabled(db.GetEngine(db.DefaultContext))
} }
func (issue *Issue) isTimetrackerEnabled(e db.Engine) bool { func (issue *Issue) isTimetrackerEnabled(e db.Engine) bool {
@ -145,7 +146,7 @@ func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
return nil, fmt.Errorf("Issue is not a pull request") return nil, fmt.Errorf("Issue is not a pull request")
} }
pr, err = getPullRequestByIssueID(db.DefaultContext().Engine(), issue.ID) pr, err = getPullRequestByIssueID(db.GetEngine(db.DefaultContext), issue.ID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -155,7 +156,7 @@ func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
// LoadLabels loads labels // LoadLabels loads labels
func (issue *Issue) LoadLabels() error { func (issue *Issue) LoadLabels() error {
return issue.loadLabels(db.DefaultContext().Engine()) return issue.loadLabels(db.GetEngine(db.DefaultContext))
} }
func (issue *Issue) loadLabels(e db.Engine) (err error) { func (issue *Issue) loadLabels(e db.Engine) (err error) {
@ -170,7 +171,7 @@ func (issue *Issue) loadLabels(e db.Engine) (err error) {
// LoadPoster loads poster // LoadPoster loads poster
func (issue *Issue) LoadPoster() error { func (issue *Issue) LoadPoster() error {
return issue.loadPoster(db.DefaultContext().Engine()) return issue.loadPoster(db.GetEngine(db.DefaultContext))
} }
func (issue *Issue) loadPoster(e db.Engine) (err error) { func (issue *Issue) loadPoster(e db.Engine) (err error) {
@ -205,7 +206,7 @@ func (issue *Issue) loadPullRequest(e db.Engine) (err error) {
// LoadPullRequest loads pull request info // LoadPullRequest loads pull request info
func (issue *Issue) LoadPullRequest() error { func (issue *Issue) LoadPullRequest() error {
return issue.loadPullRequest(db.DefaultContext().Engine()) return issue.loadPullRequest(db.GetEngine(db.DefaultContext))
} }
func (issue *Issue) loadComments(e db.Engine) (err error) { func (issue *Issue) loadComments(e db.Engine) (err error) {
@ -214,7 +215,7 @@ func (issue *Issue) loadComments(e db.Engine) (err error) {
// LoadDiscussComments loads discuss comments // LoadDiscussComments loads discuss comments
func (issue *Issue) LoadDiscussComments() error { func (issue *Issue) LoadDiscussComments() error {
return issue.loadCommentsByType(db.DefaultContext().Engine(), CommentTypeComment) return issue.loadCommentsByType(db.GetEngine(db.DefaultContext), CommentTypeComment)
} }
func (issue *Issue) loadCommentsByType(e db.Engine, tp CommentType) (err error) { func (issue *Issue) loadCommentsByType(e db.Engine, tp CommentType) (err error) {
@ -327,18 +328,18 @@ func (issue *Issue) loadAttributes(e db.Engine) (err error) {
// LoadAttributes loads the attribute of this issue. // LoadAttributes loads the attribute of this issue.
func (issue *Issue) LoadAttributes() error { func (issue *Issue) LoadAttributes() error {
return issue.loadAttributes(db.DefaultContext().Engine()) return issue.loadAttributes(db.GetEngine(db.DefaultContext))
} }
// LoadMilestone load milestone of this issue. // LoadMilestone load milestone of this issue.
func (issue *Issue) LoadMilestone() error { func (issue *Issue) LoadMilestone() error {
return issue.loadMilestone(db.DefaultContext().Engine()) return issue.loadMilestone(db.GetEngine(db.DefaultContext))
} }
// GetIsRead load the `IsRead` field of the issue // GetIsRead load the `IsRead` field of the issue
func (issue *Issue) GetIsRead(userID int64) error { func (issue *Issue) GetIsRead(userID int64) error {
issueUser := &IssueUser{IssueID: issue.ID, UID: userID} issueUser := &IssueUser{IssueID: issue.ID, UID: userID}
if has, err := db.DefaultContext().Engine().Get(issueUser); err != nil { if has, err := db.GetEngine(db.DefaultContext).Get(issueUser); err != nil {
return err return err
} else if !has { } else if !has {
issue.IsRead = false issue.IsRead = false
@ -411,7 +412,7 @@ func (issue *Issue) hasLabel(e db.Engine, labelID int64) bool {
// HasLabel returns true if issue has been labeled by given ID. // HasLabel returns true if issue has been labeled by given ID.
func (issue *Issue) HasLabel(labelID int64) bool { func (issue *Issue) HasLabel(labelID int64) bool {
return issue.hasLabel(db.DefaultContext().Engine(), labelID) return issue.hasLabel(db.GetEngine(db.DefaultContext), labelID)
} }
// ReplyReference returns tokenized address to use for email reply headers // ReplyReference returns tokenized address to use for email reply headers
@ -473,13 +474,13 @@ func (issue *Issue) ClearLabels(doer *User) (err error) {
} }
defer committer.Close() defer committer.Close()
if err := issue.loadRepo(ctx.Engine()); err != nil { if err := issue.loadRepo(db.GetEngine(ctx)); err != nil {
return err return err
} else if err = issue.loadPullRequest(ctx.Engine()); err != nil { } else if err = issue.loadPullRequest(db.GetEngine(ctx)); err != nil {
return err return err
} }
perm, err := getUserRepoPermission(ctx.Engine(), issue.Repo, doer) perm, err := getUserRepoPermission(db.GetEngine(ctx), issue.Repo, doer)
if err != nil { if err != nil {
return err return err
} }
@ -487,7 +488,7 @@ func (issue *Issue) ClearLabels(doer *User) (err error) {
return ErrRepoLabelNotExist{} return ErrRepoLabelNotExist{}
} }
if err = issue.clearLabels(ctx.Engine(), doer); err != nil { if err = issue.clearLabels(db.GetEngine(ctx), doer); err != nil {
return err return err
} }
@ -521,11 +522,11 @@ func (issue *Issue) ReplaceLabels(labels []*Label, doer *User) (err error) {
} }
defer committer.Close() defer committer.Close()
if err = issue.loadRepo(ctx.Engine()); err != nil { if err = issue.loadRepo(db.GetEngine(ctx)); err != nil {
return err return err
} }
if err = issue.loadLabels(ctx.Engine()); err != nil { if err = issue.loadLabels(db.GetEngine(ctx)); err != nil {
return err return err
} }
@ -561,19 +562,19 @@ func (issue *Issue) ReplaceLabels(labels []*Label, doer *User) (err error) {
toRemove = append(toRemove, issue.Labels[removeIndex:]...) toRemove = append(toRemove, issue.Labels[removeIndex:]...)
if len(toAdd) > 0 { if len(toAdd) > 0 {
if err = issue.addLabels(ctx.Engine(), toAdd, doer); err != nil { if err = issue.addLabels(db.GetEngine(ctx), toAdd, doer); err != nil {
return fmt.Errorf("addLabels: %v", err) return fmt.Errorf("addLabels: %v", err)
} }
} }
for _, l := range toRemove { for _, l := range toRemove {
if err = issue.removeLabel(ctx.Engine(), doer, l); err != nil { if err = issue.removeLabel(db.GetEngine(ctx), doer, l); err != nil {
return fmt.Errorf("removeLabel: %v", err) return fmt.Errorf("removeLabel: %v", err)
} }
} }
issue.Labels = nil issue.Labels = nil
if err = issue.loadLabels(ctx.Engine()); err != nil { if err = issue.loadLabels(db.GetEngine(ctx)); err != nil {
return err return err
} }
@ -586,7 +587,7 @@ func (issue *Issue) ReadBy(userID int64) error {
return err return err
} }
return setIssueNotificationStatusReadIfUnread(db.DefaultContext().Engine(), userID, issue.ID) return setIssueNotificationStatusReadIfUnread(db.GetEngine(db.DefaultContext), userID, issue.ID)
} }
func updateIssueCols(e db.Engine, issue *Issue, cols ...string) error { func updateIssueCols(e db.Engine, issue *Issue, cols ...string) error {
@ -688,14 +689,14 @@ func (issue *Issue) ChangeStatus(doer *User, isClosed bool) (*Comment, error) {
} }
defer committer.Close() defer committer.Close()
if err := issue.loadRepo(ctx.Engine()); err != nil { if err := issue.loadRepo(db.GetEngine(ctx)); err != nil {
return nil, err return nil, err
} }
if err := issue.loadPoster(ctx.Engine()); err != nil { if err := issue.loadPoster(db.GetEngine(ctx)); err != nil {
return nil, err return nil, err
} }
comment, err := issue.changeStatus(ctx.Engine(), doer, isClosed, false) comment, err := issue.changeStatus(db.GetEngine(ctx), doer, isClosed, false)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -715,11 +716,11 @@ func (issue *Issue) ChangeTitle(doer *User, oldTitle string) (err error) {
} }
defer committer.Close() defer committer.Close()
if err = updateIssueCols(ctx.Engine(), issue, "name"); err != nil { if err = updateIssueCols(db.GetEngine(ctx), issue, "name"); err != nil {
return fmt.Errorf("updateIssueCols: %v", err) return fmt.Errorf("updateIssueCols: %v", err)
} }
if err = issue.loadRepo(ctx.Engine()); err != nil { if err = issue.loadRepo(db.GetEngine(ctx)); err != nil {
return fmt.Errorf("loadRepo: %v", err) return fmt.Errorf("loadRepo: %v", err)
} }
@ -731,10 +732,10 @@ func (issue *Issue) ChangeTitle(doer *User, oldTitle string) (err error) {
OldTitle: oldTitle, OldTitle: oldTitle,
NewTitle: issue.Title, NewTitle: issue.Title,
} }
if _, err = createComment(ctx.Engine(), opts); err != nil { if _, err = createComment(db.GetEngine(ctx), opts); err != nil {
return fmt.Errorf("createComment: %v", err) return fmt.Errorf("createComment: %v", err)
} }
if err = issue.addCrossReferences(ctx.Engine(), doer, true); err != nil { if err = issue.addCrossReferences(db.GetEngine(ctx), doer, true); err != nil {
return err return err
} }
@ -749,7 +750,7 @@ func (issue *Issue) ChangeRef(doer *User, oldRef string) (err error) {
} }
defer committer.Close() defer committer.Close()
if err = updateIssueCols(ctx.Engine(), issue, "ref"); err != nil { if err = updateIssueCols(db.GetEngine(ctx), issue, "ref"); err != nil {
return fmt.Errorf("updateIssueCols: %v", err) return fmt.Errorf("updateIssueCols: %v", err)
} }
@ -758,7 +759,7 @@ func (issue *Issue) ChangeRef(doer *User, oldRef string) (err error) {
// AddDeletePRBranchComment adds delete branch comment for pull request issue // AddDeletePRBranchComment adds delete branch comment for pull request issue
func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branchName string) error { func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branchName string) error {
issue, err := getIssueByID(db.DefaultContext().Engine(), issueID) issue, err := getIssueByID(db.GetEngine(db.DefaultContext), issueID)
if err != nil { if err != nil {
return err return err
} }
@ -774,7 +775,7 @@ func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branc
Issue: issue, Issue: issue,
OldRef: branchName, OldRef: branchName,
} }
if _, err = createComment(ctx.Engine(), opts); err != nil { if _, err = createComment(db.GetEngine(ctx), opts); err != nil {
return err return err
} }
@ -788,13 +789,13 @@ func (issue *Issue) UpdateAttachments(uuids []string) (err error) {
return err return err
} }
defer committer.Close() defer committer.Close()
attachments, err := getAttachmentsByUUIDs(ctx.Engine(), uuids) attachments, err := getAttachmentsByUUIDs(db.GetEngine(ctx), uuids)
if err != nil { if err != nil {
return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", uuids, err) return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", uuids, err)
} }
for i := 0; i < len(attachments); i++ { for i := 0; i < len(attachments); i++ {
attachments[i].IssueID = issue.ID attachments[i].IssueID = issue.ID
if err := updateAttachment(ctx.Engine(), attachments[i]); err != nil { if err := updateAttachment(db.GetEngine(ctx), attachments[i]); err != nil {
return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err) return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
} }
} }
@ -811,11 +812,11 @@ func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
} }
defer committer.Close() defer committer.Close()
if err = updateIssueCols(ctx.Engine(), issue, "content"); err != nil { if err = updateIssueCols(db.GetEngine(ctx), issue, "content"); err != nil {
return fmt.Errorf("UpdateIssueCols: %v", err) return fmt.Errorf("UpdateIssueCols: %v", err)
} }
if err = issue.addCrossReferences(ctx.Engine(), doer, true); err != nil { if err = issue.addCrossReferences(db.GetEngine(ctx), doer, true); err != nil {
return err return err
} }
@ -854,7 +855,7 @@ func (issue *Issue) GetLastEventLabel() string {
// GetLastComment return last comment for the current issue. // GetLastComment return last comment for the current issue.
func (issue *Issue) GetLastComment() (*Comment, error) { func (issue *Issue) GetLastComment() (*Comment, error) {
var c Comment var c Comment
exist, err := db.DefaultContext().Engine().Where("type = ?", CommentTypeComment). exist, err := db.GetEngine(db.DefaultContext).Where("type = ?", CommentTypeComment).
And("issue_id = ?", issue.ID).Desc("id").Get(&c) And("issue_id = ?", issue.ID).Desc("id").Get(&c)
if err != nil { if err != nil {
return nil, err return nil, err
@ -996,16 +997,16 @@ func RecalculateIssueIndexForRepo(repoID int64) error {
} }
defer committer.Close() defer committer.Close()
if err := db.UpsertResourceIndex(ctx.Engine(), "issue_index", repoID); err != nil { if err := db.UpsertResourceIndex(db.GetEngine(ctx), "issue_index", repoID); err != nil {
return err return err
} }
var max int64 var max int64
if _, err := ctx.Engine().Select(" MAX(`index`)").Table("issue").Where("repo_id=?", repoID).Get(&max); err != nil { if _, err := db.GetEngine(ctx).Select(" MAX(`index`)").Table("issue").Where("repo_id=?", repoID).Get(&max); err != nil {
return err return err
} }
if _, err := ctx.Engine().Exec("UPDATE `issue_index` SET max_index=? WHERE group_id=?", max, repoID); err != nil { if _, err := db.GetEngine(ctx).Exec("UPDATE `issue_index` SET max_index=? WHERE group_id=?", max, repoID); err != nil {
return err return err
} }
@ -1027,7 +1028,7 @@ func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string)
} }
defer committer.Close() defer committer.Close()
if err = newIssue(ctx.Engine(), issue.Poster, NewIssueOptions{ if err = newIssue(db.GetEngine(ctx), issue.Poster, NewIssueOptions{
Repo: repo, Repo: repo,
Issue: issue, Issue: issue,
LabelIDs: labelIDs, LabelIDs: labelIDs,
@ -1055,7 +1056,7 @@ func GetIssueByIndex(repoID, index int64) (*Issue, error) {
RepoID: repoID, RepoID: repoID,
Index: index, Index: index,
} }
has, err := db.DefaultContext().Engine().Get(issue) has, err := db.GetEngine(db.DefaultContext).Get(issue)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -1086,16 +1087,16 @@ func getIssueByID(e db.Engine, id int64) (*Issue, error) {
// GetIssueWithAttrsByID returns an issue with attributes by given ID. // GetIssueWithAttrsByID returns an issue with attributes by given ID.
func GetIssueWithAttrsByID(id int64) (*Issue, error) { func GetIssueWithAttrsByID(id int64) (*Issue, error) {
issue, err := getIssueByID(db.DefaultContext().Engine(), id) issue, err := getIssueByID(db.GetEngine(db.DefaultContext), id)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return issue, issue.loadAttributes(db.DefaultContext().Engine()) return issue, issue.loadAttributes(db.GetEngine(db.DefaultContext))
} }
// GetIssueByID returns an issue by given ID. // GetIssueByID returns an issue by given ID.
func GetIssueByID(id int64) (*Issue, error) { func GetIssueByID(id int64) (*Issue, error) {
return getIssueByID(db.DefaultContext().Engine(), id) return getIssueByID(db.GetEngine(db.DefaultContext), id)
} }
func getIssuesByIDs(e db.Engine, issueIDs []int64) ([]*Issue, error) { func getIssuesByIDs(e db.Engine, issueIDs []int64) ([]*Issue, error) {
@ -1111,12 +1112,12 @@ func getIssueIDsByRepoID(e db.Engine, repoID int64) ([]int64, error) {
// GetIssueIDsByRepoID returns all issue ids by repo id // GetIssueIDsByRepoID returns all issue ids by repo id
func GetIssueIDsByRepoID(repoID int64) ([]int64, error) { func GetIssueIDsByRepoID(repoID int64) ([]int64, error) {
return getIssueIDsByRepoID(db.DefaultContext().Engine(), repoID) return getIssueIDsByRepoID(db.GetEngine(db.DefaultContext), repoID)
} }
// GetIssuesByIDs return issues with the given IDs. // GetIssuesByIDs return issues with the given IDs.
func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) { func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) {
return getIssuesByIDs(db.DefaultContext().Engine(), issueIDs) return getIssuesByIDs(db.GetEngine(db.DefaultContext), issueIDs)
} }
// IssuesOptions represents options of an issue. // IssuesOptions represents options of an issue.
@ -1316,7 +1317,7 @@ func applyReviewRequestedCondition(sess *xorm.Session, reviewRequestedID int64)
// CountIssuesByRepo map from repoID to number of issues matching the options // CountIssuesByRepo map from repoID to number of issues matching the options
func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) { func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
sess.Join("INNER", "repository", "`issue`.repo_id = `repository`.id") sess.Join("INNER", "repository", "`issue`.repo_id = `repository`.id")
@ -1344,7 +1345,7 @@ func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
// GetRepoIDsForIssuesOptions find all repo ids for the given options // GetRepoIDsForIssuesOptions find all repo ids for the given options
func GetRepoIDsForIssuesOptions(opts *IssuesOptions, user *User) ([]int64, error) { func GetRepoIDsForIssuesOptions(opts *IssuesOptions, user *User) ([]int64, error) {
repoIDs := make([]int64, 0, 5) repoIDs := make([]int64, 0, 5)
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
sess.Join("INNER", "repository", "`issue`.repo_id = `repository`.id") sess.Join("INNER", "repository", "`issue`.repo_id = `repository`.id")
@ -1364,7 +1365,7 @@ func GetRepoIDsForIssuesOptions(opts *IssuesOptions, user *User) ([]int64, error
// Issues returns a list of issues by given conditions. // Issues returns a list of issues by given conditions.
func Issues(opts *IssuesOptions) ([]*Issue, error) { func Issues(opts *IssuesOptions) ([]*Issue, error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
sess.Join("INNER", "repository", "`issue`.repo_id = `repository`.id") sess.Join("INNER", "repository", "`issue`.repo_id = `repository`.id")
@ -1386,7 +1387,7 @@ func Issues(opts *IssuesOptions) ([]*Issue, error) {
// CountIssues number return of issues by given conditions. // CountIssues number return of issues by given conditions.
func CountIssues(opts *IssuesOptions) (int64, error) { func CountIssues(opts *IssuesOptions) (int64, error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
countsSlice := make([]*struct { countsSlice := make([]*struct {
@ -1411,7 +1412,7 @@ func CountIssues(opts *IssuesOptions) (int64, error) {
// User permissions must be verified elsewhere if required. // User permissions must be verified elsewhere if required.
func GetParticipantsIDsByIssueID(issueID int64) ([]int64, error) { func GetParticipantsIDsByIssueID(issueID int64) ([]int64, error) {
userIDs := make([]int64, 0, 5) userIDs := make([]int64, 0, 5)
return userIDs, db.DefaultContext().Engine().Table("comment"). return userIDs, db.GetEngine(db.DefaultContext).Table("comment").
Cols("poster_id"). Cols("poster_id").
Where("issue_id = ?", issueID). Where("issue_id = ?", issueID).
And("type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview). And("type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
@ -1421,7 +1422,7 @@ func GetParticipantsIDsByIssueID(issueID int64) ([]int64, error) {
// IsUserParticipantsOfIssue return true if user is participants of an issue // IsUserParticipantsOfIssue return true if user is participants of an issue
func IsUserParticipantsOfIssue(user *User, issue *Issue) bool { func IsUserParticipantsOfIssue(user *User, issue *Issue) bool {
userIDs, err := issue.getParticipantIDsByIssue(db.DefaultContext().Engine()) userIDs, err := issue.getParticipantIDsByIssue(db.GetEngine(db.DefaultContext))
if err != nil { if err != nil {
log.Error(err.Error()) log.Error(err.Error())
return false return false
@ -1430,7 +1431,7 @@ func IsUserParticipantsOfIssue(user *User, issue *Issue) bool {
} }
// UpdateIssueMentions updates issue-user relations for mentioned users. // UpdateIssueMentions updates issue-user relations for mentioned users.
func UpdateIssueMentions(ctx *db.Context, issueID int64, mentions []*User) error { func UpdateIssueMentions(ctx context.Context, issueID int64, mentions []*User) error {
if len(mentions) == 0 { if len(mentions) == 0 {
return nil return nil
} }
@ -1529,7 +1530,7 @@ func getIssueStatsChunk(opts *IssueStatsOptions, issueIDs []int64) (*IssueStats,
stats := &IssueStats{} stats := &IssueStats{}
countSession := func(opts *IssueStatsOptions) *xorm.Session { countSession := func(opts *IssueStatsOptions) *xorm.Session {
sess := db.DefaultContext().Engine(). sess := db.GetEngine(db.DefaultContext).
Where("issue.repo_id = ?", opts.RepoID) Where("issue.repo_id = ?", opts.RepoID)
if len(opts.IssueIDs) > 0 { if len(opts.IssueIDs) > 0 {
@ -1623,7 +1624,7 @@ func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) {
} }
sess := func(cond builder.Cond) *xorm.Session { sess := func(cond builder.Cond) *xorm.Session {
s := db.DefaultContext().Engine().Where(cond) s := db.GetEngine(db.DefaultContext).Where(cond)
if len(opts.LabelIDs) > 0 { if len(opts.LabelIDs) > 0 {
s.Join("INNER", "issue_label", "issue_label.issue_id = issue.id"). s.Join("INNER", "issue_label", "issue_label.issue_id = issue.id").
In("issue_label.label_id", opts.LabelIDs) In("issue_label.label_id", opts.LabelIDs)
@ -1735,7 +1736,7 @@ func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) {
// GetRepoIssueStats returns number of open and closed repository issues by given filter mode. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen, numClosed int64) { func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen, numClosed int64) {
countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session { countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
sess := db.DefaultContext().Engine(). sess := db.GetEngine(db.DefaultContext).
Where("is_closed = ?", isClosed). Where("is_closed = ?", isClosed).
And("is_pull = ?", isPull). And("is_pull = ?", isPull).
And("repo_id = ?", repoID) And("repo_id = ?", repoID)
@ -1787,7 +1788,7 @@ func SearchIssueIDsByKeyword(kw string, repoIDs []int64, limit, start int) (int6
ID int64 ID int64
UpdatedUnix int64 UpdatedUnix int64
}, 0, limit) }, 0, limit)
err := db.DefaultContext().Engine().Distinct("id", "updated_unix").Table("issue").Where(cond). err := db.GetEngine(db.DefaultContext).Distinct("id", "updated_unix").Table("issue").Where(cond).
OrderBy("`updated_unix` DESC").Limit(limit, start). OrderBy("`updated_unix` DESC").Limit(limit, start).
Find(&res) Find(&res)
if err != nil { if err != nil {
@ -1797,7 +1798,7 @@ func SearchIssueIDsByKeyword(kw string, repoIDs []int64, limit, start int) (int6
ids = append(ids, r.ID) ids = append(ids, r.ID)
} }
total, err := db.DefaultContext().Engine().Distinct("id").Table("issue").Where(cond).Count() total, err := db.GetEngine(db.DefaultContext).Distinct("id").Table("issue").Where(cond).Count()
if err != nil { if err != nil {
return 0, nil, err return 0, nil, err
} }
@ -1809,7 +1810,7 @@ func SearchIssueIDsByKeyword(kw string, repoIDs []int64, limit, start int) (int6
// If the issue status is changed a statusChangeComment is returned // If the issue status is changed a statusChangeComment is returned
// similarly if the title is changed the titleChanged bool is set to true // similarly if the title is changed the titleChanged bool is set to true
func UpdateIssueByAPI(issue *Issue, doer *User) (statusChangeComment *Comment, titleChanged bool, err error) { func UpdateIssueByAPI(issue *Issue, doer *User) (statusChangeComment *Comment, titleChanged bool, err error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return nil, false, err return nil, false, err
@ -1868,7 +1869,7 @@ func UpdateIssueDeadline(issue *Issue, deadlineUnix timeutil.TimeStamp, doer *Us
return nil return nil
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -1941,12 +1942,12 @@ func (issue *Issue) getBlockingDependencies(e db.Engine) (issueDeps []*Dependenc
// BlockedByDependencies finds all Dependencies an issue is blocked by // BlockedByDependencies finds all Dependencies an issue is blocked by
func (issue *Issue) BlockedByDependencies() ([]*DependencyInfo, error) { func (issue *Issue) BlockedByDependencies() ([]*DependencyInfo, error) {
return issue.getBlockedByDependencies(db.DefaultContext().Engine()) return issue.getBlockedByDependencies(db.GetEngine(db.DefaultContext))
} }
// BlockingDependencies returns all blocking dependencies, aka all other issues a given issue blocks // BlockingDependencies returns all blocking dependencies, aka all other issues a given issue blocks
func (issue *Issue) BlockingDependencies() ([]*DependencyInfo, error) { func (issue *Issue) BlockingDependencies() ([]*DependencyInfo, error) {
return issue.getBlockingDependencies(db.DefaultContext().Engine()) return issue.getBlockingDependencies(db.GetEngine(db.DefaultContext))
} }
func (issue *Issue) updateClosedNum(e db.Engine) (err error) { func (issue *Issue) updateClosedNum(e db.Engine) (err error) {
@ -1969,7 +1970,7 @@ func (issue *Issue) updateClosedNum(e db.Engine) (err error) {
} }
// FindAndUpdateIssueMentions finds users mentioned in the given content string, and saves them in the database. // FindAndUpdateIssueMentions finds users mentioned in the given content string, and saves them in the database.
func (issue *Issue) FindAndUpdateIssueMentions(ctx *db.Context, doer *User, content string) (mentions []*User, err error) { func (issue *Issue) FindAndUpdateIssueMentions(ctx context.Context, doer *User, content string) (mentions []*User, err error) {
rawMentions := references.FindAllMentionsMarkdown(content) rawMentions := references.FindAllMentionsMarkdown(content)
mentions, err = issue.ResolveMentionsByVisibility(ctx, doer, rawMentions) mentions, err = issue.ResolveMentionsByVisibility(ctx, doer, rawMentions)
if err != nil { if err != nil {
@ -1983,18 +1984,18 @@ func (issue *Issue) FindAndUpdateIssueMentions(ctx *db.Context, doer *User, cont
// ResolveMentionsByVisibility returns the users mentioned in an issue, removing those that // ResolveMentionsByVisibility returns the users mentioned in an issue, removing those that
// don't have access to reading it. Teams are expanded into their users, but organizations are ignored. // don't have access to reading it. Teams are expanded into their users, but organizations are ignored.
func (issue *Issue) ResolveMentionsByVisibility(ctx *db.Context, doer *User, mentions []string) (users []*User, err error) { func (issue *Issue) ResolveMentionsByVisibility(ctx context.Context, doer *User, mentions []string) (users []*User, err error) {
if len(mentions) == 0 { if len(mentions) == 0 {
return return
} }
if err = issue.loadRepo(ctx.Engine()); err != nil { if err = issue.loadRepo(db.GetEngine(ctx)); err != nil {
return return
} }
resolved := make(map[string]bool, 10) resolved := make(map[string]bool, 10)
var mentionTeams []string var mentionTeams []string
if err := issue.Repo.getOwner(ctx.Engine()); err != nil { if err := issue.Repo.getOwner(db.GetEngine(ctx)); err != nil {
return nil, err return nil, err
} }
@ -2023,7 +2024,7 @@ func (issue *Issue) ResolveMentionsByVisibility(ctx *db.Context, doer *User, men
if issue.Repo.Owner.IsOrganization() && len(mentionTeams) > 0 { if issue.Repo.Owner.IsOrganization() && len(mentionTeams) > 0 {
teams := make([]*Team, 0, len(mentionTeams)) teams := make([]*Team, 0, len(mentionTeams))
if err := ctx.Engine(). if err := db.GetEngine(ctx).
Join("INNER", "team_repo", "team_repo.team_id = team.id"). Join("INNER", "team_repo", "team_repo.team_id = team.id").
Where("team_repo.repo_id=?", issue.Repo.ID). Where("team_repo.repo_id=?", issue.Repo.ID).
In("team.lower_name", mentionTeams). In("team.lower_name", mentionTeams).
@ -2042,7 +2043,7 @@ func (issue *Issue) ResolveMentionsByVisibility(ctx *db.Context, doer *User, men
resolved[issue.Repo.Owner.LowerName+"/"+team.LowerName] = true resolved[issue.Repo.Owner.LowerName+"/"+team.LowerName] = true
continue continue
} }
has, err := ctx.Engine().Get(&TeamUnit{OrgID: issue.Repo.Owner.ID, TeamID: team.ID, Type: unittype}) has, err := db.GetEngine(ctx).Get(&TeamUnit{OrgID: issue.Repo.Owner.ID, TeamID: team.ID, Type: unittype})
if err != nil { if err != nil {
return nil, fmt.Errorf("get team units (%d): %v", team.ID, err) return nil, fmt.Errorf("get team units (%d): %v", team.ID, err)
} }
@ -2053,7 +2054,7 @@ func (issue *Issue) ResolveMentionsByVisibility(ctx *db.Context, doer *User, men
} }
if len(checked) != 0 { if len(checked) != 0 {
teamusers := make([]*User, 0, 20) teamusers := make([]*User, 0, 20)
if err := ctx.Engine(). if err := db.GetEngine(ctx).
Join("INNER", "team_user", "team_user.uid = `user`.id"). Join("INNER", "team_user", "team_user.uid = `user`.id").
In("`team_user`.team_id", checked). In("`team_user`.team_id", checked).
And("`user`.is_active = ?", true). And("`user`.is_active = ?", true).
@ -2090,7 +2091,7 @@ func (issue *Issue) ResolveMentionsByVisibility(ctx *db.Context, doer *User, men
} }
unchecked := make([]*User, 0, len(mentionUsers)) unchecked := make([]*User, 0, len(mentionUsers))
if err := ctx.Engine(). if err := db.GetEngine(ctx).
Where("`user`.is_active = ?", true). Where("`user`.is_active = ?", true).
And("`user`.prohibit_login = ?", false). And("`user`.prohibit_login = ?", false).
In("`user`.lower_name", mentionUsers). In("`user`.lower_name", mentionUsers).
@ -2102,7 +2103,7 @@ func (issue *Issue) ResolveMentionsByVisibility(ctx *db.Context, doer *User, men
continue continue
} }
// Normal users must have read access to the referencing issue // Normal users must have read access to the referencing issue
perm, err := getUserRepoPermission(ctx.Engine(), issue.Repo, user) perm, err := getUserRepoPermission(db.GetEngine(ctx), issue.Repo, user)
if err != nil { if err != nil {
return nil, fmt.Errorf("getUserRepoPermission [%d]: %v", user.ID, err) return nil, fmt.Errorf("getUserRepoPermission [%d]: %v", user.ID, err)
} }
@ -2117,7 +2118,7 @@ func (issue *Issue) ResolveMentionsByVisibility(ctx *db.Context, doer *User, men
// UpdateIssuesMigrationsByType updates all migrated repositories' issues from gitServiceType to replace originalAuthorID to posterID // UpdateIssuesMigrationsByType updates all migrated repositories' issues from gitServiceType to replace originalAuthorID to posterID
func UpdateIssuesMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error { func UpdateIssuesMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error {
_, err := db.DefaultContext().Engine().Table("issue"). _, err := db.GetEngine(db.DefaultContext).Table("issue").
Where("repo_id IN (SELECT id FROM repository WHERE original_service_type = ?)", gitServiceType). Where("repo_id IN (SELECT id FROM repository WHERE original_service_type = ?)", gitServiceType).
And("original_author_id = ?", originalAuthorID). And("original_author_id = ?", originalAuthorID).
Update(map[string]interface{}{ Update(map[string]interface{}{
@ -2130,7 +2131,7 @@ func UpdateIssuesMigrationsByType(gitServiceType structs.GitServiceType, origina
// UpdateReactionsMigrationsByType updates all migrated repositories' reactions from gitServiceType to replace originalAuthorID to posterID // UpdateReactionsMigrationsByType updates all migrated repositories' reactions from gitServiceType to replace originalAuthorID to posterID
func UpdateReactionsMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, userID int64) error { func UpdateReactionsMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, userID int64) error {
_, err := db.DefaultContext().Engine().Table("reaction"). _, err := db.GetEngine(db.DefaultContext).Table("reaction").
Where("original_author_id = ?", originalAuthorID). Where("original_author_id = ?", originalAuthorID).
And(migratedIssueCond(gitServiceType)). And(migratedIssueCond(gitServiceType)).
Update(map[string]interface{}{ Update(map[string]interface{}{

View File

@ -26,7 +26,7 @@ func init() {
// LoadAssignees load assignees of this issue. // LoadAssignees load assignees of this issue.
func (issue *Issue) LoadAssignees() error { func (issue *Issue) LoadAssignees() error {
return issue.loadAssignees(db.DefaultContext().Engine()) return issue.loadAssignees(db.GetEngine(db.DefaultContext))
} }
// This loads all assignees of an issue // This loads all assignees of an issue
@ -56,7 +56,7 @@ func (issue *Issue) loadAssignees(e db.Engine) (err error) {
// User permissions must be verified elsewhere if required. // User permissions must be verified elsewhere if required.
func GetAssigneeIDsByIssue(issueID int64) ([]int64, error) { func GetAssigneeIDsByIssue(issueID int64) ([]int64, error) {
userIDs := make([]int64, 0, 5) userIDs := make([]int64, 0, 5)
return userIDs, db.DefaultContext().Engine().Table("issue_assignees"). return userIDs, db.GetEngine(db.DefaultContext).Table("issue_assignees").
Cols("assignee_id"). Cols("assignee_id").
Where("issue_id = ?", issueID). Where("issue_id = ?", issueID).
Distinct("assignee_id"). Distinct("assignee_id").
@ -65,7 +65,7 @@ func GetAssigneeIDsByIssue(issueID int64) ([]int64, error) {
// GetAssigneesByIssue returns everyone assigned to that issue // GetAssigneesByIssue returns everyone assigned to that issue
func GetAssigneesByIssue(issue *Issue) (assignees []*User, err error) { func GetAssigneesByIssue(issue *Issue) (assignees []*User, err error) {
return getAssigneesByIssue(db.DefaultContext().Engine(), issue) return getAssigneesByIssue(db.GetEngine(db.DefaultContext), issue)
} }
func getAssigneesByIssue(e db.Engine, issue *Issue) (assignees []*User, err error) { func getAssigneesByIssue(e db.Engine, issue *Issue) (assignees []*User, err error) {
@ -79,7 +79,7 @@ func getAssigneesByIssue(e db.Engine, issue *Issue) (assignees []*User, err erro
// IsUserAssignedToIssue returns true when the user is assigned to the issue // IsUserAssignedToIssue returns true when the user is assigned to the issue
func IsUserAssignedToIssue(issue *Issue, user *User) (isAssigned bool, err error) { func IsUserAssignedToIssue(issue *Issue, user *User) (isAssigned bool, err error) {
return isUserAssignedToIssue(db.DefaultContext().Engine(), issue, user) return isUserAssignedToIssue(db.GetEngine(db.DefaultContext), issue, user)
} }
func isUserAssignedToIssue(e db.Engine, issue *Issue, user *User) (isAssigned bool, err error) { func isUserAssignedToIssue(e db.Engine, issue *Issue, user *User) (isAssigned bool, err error) {
@ -94,7 +94,7 @@ func clearAssigneeByUserID(sess db.Engine, userID int64) (err error) {
// ToggleAssignee changes a user between assigned and not assigned for this issue, and make issue comment for it. // ToggleAssignee changes a user between assigned and not assigned for this issue, and make issue comment for it.
func (issue *Issue) ToggleAssignee(doer *User, assigneeID int64) (removed bool, comment *Comment, err error) { func (issue *Issue) ToggleAssignee(doer *User, assigneeID int64) (removed bool, comment *Comment, err error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {

View File

@ -210,7 +210,7 @@ type PushActionContent struct {
// LoadIssue loads issue from database // LoadIssue loads issue from database
func (c *Comment) LoadIssue() (err error) { func (c *Comment) LoadIssue() (err error) {
return c.loadIssue(db.DefaultContext().Engine()) return c.loadIssue(db.GetEngine(db.DefaultContext))
} }
func (c *Comment) loadIssue(e db.Engine) (err error) { func (c *Comment) loadIssue(e db.Engine) (err error) {
@ -284,7 +284,7 @@ func (c *Comment) HTMLURL() string {
log.Error("LoadIssue(%d): %v", c.IssueID, err) log.Error("LoadIssue(%d): %v", c.IssueID, err)
return "" return ""
} }
err = c.Issue.loadRepo(db.DefaultContext().Engine()) err = c.Issue.loadRepo(db.GetEngine(db.DefaultContext))
if err != nil { // Silently dropping errors :unamused: if err != nil { // Silently dropping errors :unamused:
log.Error("loadRepo(%d): %v", c.Issue.RepoID, err) log.Error("loadRepo(%d): %v", c.Issue.RepoID, err)
return "" return ""
@ -313,7 +313,7 @@ func (c *Comment) APIURL() string {
log.Error("LoadIssue(%d): %v", c.IssueID, err) log.Error("LoadIssue(%d): %v", c.IssueID, err)
return "" return ""
} }
err = c.Issue.loadRepo(db.DefaultContext().Engine()) err = c.Issue.loadRepo(db.GetEngine(db.DefaultContext))
if err != nil { // Silently dropping errors :unamused: if err != nil { // Silently dropping errors :unamused:
log.Error("loadRepo(%d): %v", c.Issue.RepoID, err) log.Error("loadRepo(%d): %v", c.Issue.RepoID, err)
return "" return ""
@ -334,7 +334,7 @@ func (c *Comment) IssueURL() string {
return "" return ""
} }
err = c.Issue.loadRepo(db.DefaultContext().Engine()) err = c.Issue.loadRepo(db.GetEngine(db.DefaultContext))
if err != nil { // Silently dropping errors :unamused: if err != nil { // Silently dropping errors :unamused:
log.Error("loadRepo(%d): %v", c.Issue.RepoID, err) log.Error("loadRepo(%d): %v", c.Issue.RepoID, err)
return "" return ""
@ -350,7 +350,7 @@ func (c *Comment) PRURL() string {
return "" return ""
} }
err = c.Issue.loadRepo(db.DefaultContext().Engine()) err = c.Issue.loadRepo(db.GetEngine(db.DefaultContext))
if err != nil { // Silently dropping errors :unamused: if err != nil { // Silently dropping errors :unamused:
log.Error("loadRepo(%d): %v", c.Issue.RepoID, err) log.Error("loadRepo(%d): %v", c.Issue.RepoID, err)
return "" return ""
@ -380,7 +380,7 @@ func (c *Comment) EventTag() string {
// LoadLabel if comment.Type is CommentTypeLabel, then load Label // LoadLabel if comment.Type is CommentTypeLabel, then load Label
func (c *Comment) LoadLabel() error { func (c *Comment) LoadLabel() error {
var label Label var label Label
has, err := db.DefaultContext().Engine().ID(c.LabelID).Get(&label) has, err := db.GetEngine(db.DefaultContext).ID(c.LabelID).Get(&label)
if err != nil { if err != nil {
return err return err
} else if has { } else if has {
@ -397,7 +397,7 @@ func (c *Comment) LoadLabel() error {
func (c *Comment) LoadProject() error { func (c *Comment) LoadProject() error {
if c.OldProjectID > 0 { if c.OldProjectID > 0 {
var oldProject Project var oldProject Project
has, err := db.DefaultContext().Engine().ID(c.OldProjectID).Get(&oldProject) has, err := db.GetEngine(db.DefaultContext).ID(c.OldProjectID).Get(&oldProject)
if err != nil { if err != nil {
return err return err
} else if has { } else if has {
@ -407,7 +407,7 @@ func (c *Comment) LoadProject() error {
if c.ProjectID > 0 { if c.ProjectID > 0 {
var project Project var project Project
has, err := db.DefaultContext().Engine().ID(c.ProjectID).Get(&project) has, err := db.GetEngine(db.DefaultContext).ID(c.ProjectID).Get(&project)
if err != nil { if err != nil {
return err return err
} else if has { } else if has {
@ -422,7 +422,7 @@ func (c *Comment) LoadProject() error {
func (c *Comment) LoadMilestone() error { func (c *Comment) LoadMilestone() error {
if c.OldMilestoneID > 0 { if c.OldMilestoneID > 0 {
var oldMilestone Milestone var oldMilestone Milestone
has, err := db.DefaultContext().Engine().ID(c.OldMilestoneID).Get(&oldMilestone) has, err := db.GetEngine(db.DefaultContext).ID(c.OldMilestoneID).Get(&oldMilestone)
if err != nil { if err != nil {
return err return err
} else if has { } else if has {
@ -432,7 +432,7 @@ func (c *Comment) LoadMilestone() error {
if c.MilestoneID > 0 { if c.MilestoneID > 0 {
var milestone Milestone var milestone Milestone
has, err := db.DefaultContext().Engine().ID(c.MilestoneID).Get(&milestone) has, err := db.GetEngine(db.DefaultContext).ID(c.MilestoneID).Get(&milestone)
if err != nil { if err != nil {
return err return err
} else if has { } else if has {
@ -444,7 +444,7 @@ func (c *Comment) LoadMilestone() error {
// LoadPoster loads comment poster // LoadPoster loads comment poster
func (c *Comment) LoadPoster() error { func (c *Comment) LoadPoster() error {
return c.loadPoster(db.DefaultContext().Engine()) return c.loadPoster(db.GetEngine(db.DefaultContext))
} }
// LoadAttachments loads attachments // LoadAttachments loads attachments
@ -454,7 +454,7 @@ func (c *Comment) LoadAttachments() error {
} }
var err error var err error
c.Attachments, err = getAttachmentsByCommentID(db.DefaultContext().Engine(), c.ID) c.Attachments, err = getAttachmentsByCommentID(db.GetEngine(db.DefaultContext), c.ID)
if err != nil { if err != nil {
log.Error("getAttachmentsByCommentID[%d]: %v", c.ID, err) log.Error("getAttachmentsByCommentID[%d]: %v", c.ID, err)
} }
@ -463,7 +463,7 @@ func (c *Comment) LoadAttachments() error {
// UpdateAttachments update attachments by UUIDs for the comment // UpdateAttachments update attachments by UUIDs for the comment
func (c *Comment) UpdateAttachments(uuids []string) error { func (c *Comment) UpdateAttachments(uuids []string) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -487,7 +487,7 @@ func (c *Comment) LoadAssigneeUserAndTeam() error {
var err error var err error
if c.AssigneeID > 0 && c.Assignee == nil { if c.AssigneeID > 0 && c.Assignee == nil {
c.Assignee, err = getUserByID(db.DefaultContext().Engine(), c.AssigneeID) c.Assignee, err = getUserByID(db.GetEngine(db.DefaultContext), c.AssigneeID)
if err != nil { if err != nil {
if !IsErrUserNotExist(err) { if !IsErrUserNotExist(err) {
return err return err
@ -522,7 +522,7 @@ func (c *Comment) LoadResolveDoer() (err error) {
if c.ResolveDoerID == 0 || c.Type != CommentTypeCode { if c.ResolveDoerID == 0 || c.Type != CommentTypeCode {
return nil return nil
} }
c.ResolveDoer, err = getUserByID(db.DefaultContext().Engine(), c.ResolveDoerID) c.ResolveDoer, err = getUserByID(db.GetEngine(db.DefaultContext), c.ResolveDoerID)
if err != nil { if err != nil {
if IsErrUserNotExist(err) { if IsErrUserNotExist(err) {
c.ResolveDoer = NewGhostUser() c.ResolveDoer = NewGhostUser()
@ -542,7 +542,7 @@ func (c *Comment) LoadDepIssueDetails() (err error) {
if c.DependentIssueID <= 0 || c.DependentIssue != nil { if c.DependentIssueID <= 0 || c.DependentIssue != nil {
return nil return nil
} }
c.DependentIssue, err = getIssueByID(db.DefaultContext().Engine(), c.DependentIssueID) c.DependentIssue, err = getIssueByID(db.GetEngine(db.DefaultContext), c.DependentIssueID)
return err return err
} }
@ -576,7 +576,7 @@ func (c *Comment) loadReactions(e db.Engine, repo *Repository) (err error) {
// LoadReactions loads comment reactions // LoadReactions loads comment reactions
func (c *Comment) LoadReactions(repo *Repository) error { func (c *Comment) LoadReactions(repo *Repository) error {
return c.loadReactions(db.DefaultContext().Engine(), repo) return c.loadReactions(db.GetEngine(db.DefaultContext), repo)
} }
func (c *Comment) loadReview(e db.Engine) (err error) { func (c *Comment) loadReview(e db.Engine) (err error) {
@ -591,7 +591,7 @@ func (c *Comment) loadReview(e db.Engine) (err error) {
// LoadReview loads the associated review // LoadReview loads the associated review
func (c *Comment) LoadReview() error { func (c *Comment) LoadReview() error {
return c.loadReview(db.DefaultContext().Engine()) return c.loadReview(db.GetEngine(db.DefaultContext))
} }
var notEnoughLines = regexp.MustCompile(`fatal: file .* has only \d+ lines?`) var notEnoughLines = regexp.MustCompile(`fatal: file .* has only \d+ lines?`)
@ -642,7 +642,7 @@ func (c *Comment) CodeCommentURL() string {
log.Error("LoadIssue(%d): %v", c.IssueID, err) log.Error("LoadIssue(%d): %v", c.IssueID, err)
return "" return ""
} }
err = c.Issue.loadRepo(db.DefaultContext().Engine()) err = c.Issue.loadRepo(db.GetEngine(db.DefaultContext))
if err != nil { // Silently dropping errors :unamused: if err != nil { // Silently dropping errors :unamused:
log.Error("loadRepo(%d): %v", c.Issue.RepoID, err) log.Error("loadRepo(%d): %v", c.Issue.RepoID, err)
return "" return ""
@ -899,7 +899,7 @@ type CreateCommentOptions struct {
// CreateComment creates comment of issue or commit. // CreateComment creates comment of issue or commit.
func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) { func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return nil, err return nil, err
@ -924,7 +924,7 @@ func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commi
} }
// Check if same reference from same commit has already existed. // Check if same reference from same commit has already existed.
has, err := db.DefaultContext().Engine().Get(&Comment{ has, err := db.GetEngine(db.DefaultContext).Get(&Comment{
Type: CommentTypeCommitRef, Type: CommentTypeCommitRef,
IssueID: issue.ID, IssueID: issue.ID,
CommitSHA: commitSHA, CommitSHA: commitSHA,
@ -948,7 +948,7 @@ func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commi
// GetCommentByID returns the comment by given ID. // GetCommentByID returns the comment by given ID.
func GetCommentByID(id int64) (*Comment, error) { func GetCommentByID(id int64) (*Comment, error) {
return getCommentByID(db.DefaultContext().Engine(), id) return getCommentByID(db.GetEngine(db.DefaultContext), id)
} }
func getCommentByID(e db.Engine, id int64) (*Comment, error) { func getCommentByID(e db.Engine, id int64) (*Comment, error) {
@ -1025,12 +1025,12 @@ func findComments(e db.Engine, opts *FindCommentsOptions) ([]*Comment, error) {
// FindComments returns all comments according options // FindComments returns all comments according options
func FindComments(opts *FindCommentsOptions) ([]*Comment, error) { func FindComments(opts *FindCommentsOptions) ([]*Comment, error) {
return findComments(db.DefaultContext().Engine(), opts) return findComments(db.GetEngine(db.DefaultContext), opts)
} }
// CountComments count all comments according options by ignoring pagination // CountComments count all comments according options by ignoring pagination
func CountComments(opts *FindCommentsOptions) (int64, error) { func CountComments(opts *FindCommentsOptions) (int64, error) {
sess := db.DefaultContext().Engine().Where(opts.toConds()) sess := db.GetEngine(db.DefaultContext).Where(opts.toConds())
if opts.RepoID > 0 { if opts.RepoID > 0 {
sess.Join("INNER", "issue", "issue.id = comment.issue_id") sess.Join("INNER", "issue", "issue.id = comment.issue_id")
} }
@ -1039,7 +1039,7 @@ func CountComments(opts *FindCommentsOptions) (int64, error) {
// UpdateComment updates information of comment. // UpdateComment updates information of comment.
func UpdateComment(c *Comment, doer *User) error { func UpdateComment(c *Comment, doer *User) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -1063,7 +1063,7 @@ func UpdateComment(c *Comment, doer *User) error {
// DeleteComment deletes the comment // DeleteComment deletes the comment
func DeleteComment(comment *Comment) error { func DeleteComment(comment *Comment) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -1207,17 +1207,17 @@ func FetchCodeCommentsByLine(issue *Issue, currentUser *User, treePath string, l
TreePath: treePath, TreePath: treePath,
Line: line, Line: line,
} }
return findCodeComments(db.DefaultContext().Engine(), opts, issue, currentUser, nil) return findCodeComments(db.GetEngine(db.DefaultContext), opts, issue, currentUser, nil)
} }
// FetchCodeComments will return a 2d-map: ["Path"]["Line"] = Comments at line // FetchCodeComments will return a 2d-map: ["Path"]["Line"] = Comments at line
func FetchCodeComments(issue *Issue, currentUser *User) (CodeComments, error) { func FetchCodeComments(issue *Issue, currentUser *User) (CodeComments, error) {
return fetchCodeComments(db.DefaultContext().Engine(), issue, currentUser) return fetchCodeComments(db.GetEngine(db.DefaultContext), issue, currentUser)
} }
// UpdateCommentsMigrationsByType updates comments' migrations information via given git service type and original id and poster id // UpdateCommentsMigrationsByType updates comments' migrations information via given git service type and original id and poster id
func UpdateCommentsMigrationsByType(tp structs.GitServiceType, originalAuthorID string, posterID int64) error { func UpdateCommentsMigrationsByType(tp structs.GitServiceType, originalAuthorID string, posterID int64) error {
_, err := db.DefaultContext().Engine().Table("comment"). _, err := db.GetEngine(db.DefaultContext).Table("comment").
Where(builder.In("issue_id", Where(builder.In("issue_id",
builder.Select("issue.id"). builder.Select("issue.id").
From("issue"). From("issue").

View File

@ -526,20 +526,20 @@ func (comments CommentList) loadAttributes(e db.Engine) (err error) {
// LoadAttributes loads attributes of the comments, except for attachments and // LoadAttributes loads attributes of the comments, except for attachments and
// comments // comments
func (comments CommentList) LoadAttributes() error { func (comments CommentList) LoadAttributes() error {
return comments.loadAttributes(db.DefaultContext().Engine()) return comments.loadAttributes(db.GetEngine(db.DefaultContext))
} }
// LoadAttachments loads attachments // LoadAttachments loads attachments
func (comments CommentList) LoadAttachments() error { func (comments CommentList) LoadAttachments() error {
return comments.loadAttachments(db.DefaultContext().Engine()) return comments.loadAttachments(db.GetEngine(db.DefaultContext))
} }
// LoadPosters loads posters // LoadPosters loads posters
func (comments CommentList) LoadPosters() error { func (comments CommentList) LoadPosters() error {
return comments.loadPosters(db.DefaultContext().Engine()) return comments.loadPosters(db.GetEngine(db.DefaultContext))
} }
// LoadIssues loads issues of comments // LoadIssues loads issues of comments
func (comments CommentList) LoadIssues() error { func (comments CommentList) LoadIssues() error {
return comments.loadIssues(db.DefaultContext().Engine()) return comments.loadIssues(db.GetEngine(db.DefaultContext))
} }

View File

@ -36,7 +36,7 @@ const (
// CreateIssueDependency creates a new dependency for an issue // CreateIssueDependency creates a new dependency for an issue
func CreateIssueDependency(user *User, issue, dep *Issue) error { func CreateIssueDependency(user *User, issue, dep *Issue) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -77,7 +77,7 @@ func CreateIssueDependency(user *User, issue, dep *Issue) error {
// RemoveIssueDependency removes a dependency from an issue // RemoveIssueDependency removes a dependency from an issue
func RemoveIssueDependency(user *User, issue, dep *Issue, depType DependencyType) (err error) { func RemoveIssueDependency(user *User, issue, dep *Issue, depType DependencyType) (err error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -118,7 +118,7 @@ func issueDepExists(e db.Engine, issueID, depID int64) (bool, error) {
// IssueNoDependenciesLeft checks if issue can be closed // IssueNoDependenciesLeft checks if issue can be closed
func IssueNoDependenciesLeft(issue *Issue) (bool, error) { func IssueNoDependenciesLeft(issue *Issue) (bool, error) {
return issueNoDependenciesLeft(db.DefaultContext().Engine(), issue) return issueNoDependenciesLeft(db.GetEngine(db.DefaultContext), issue)
} }
func issueNoDependenciesLeft(e db.Engine, issue *Issue) (bool, error) { func issueNoDependenciesLeft(e db.Engine, issue *Issue) (bool, error) {
@ -135,7 +135,7 @@ func issueNoDependenciesLeft(e db.Engine, issue *Issue) (bool, error) {
// IsDependenciesEnabled returns if dependencies are enabled and returns the default setting if not set. // IsDependenciesEnabled returns if dependencies are enabled and returns the default setting if not set.
func (repo *Repository) IsDependenciesEnabled() bool { func (repo *Repository) IsDependenciesEnabled() bool {
return repo.isDependenciesEnabled(db.DefaultContext().Engine()) return repo.isDependenciesEnabled(db.GetEngine(db.DefaultContext))
} }
func (repo *Repository) isDependenciesEnabled(e db.Engine) bool { func (repo *Repository) isDependenciesEnabled(e db.Engine) bool {

View File

@ -6,6 +6,7 @@
package models package models
import ( import (
"context"
"fmt" "fmt"
"html/template" "html/template"
"math" "math"
@ -242,8 +243,8 @@ func initializeLabels(e db.Engine, id int64, labelTemplate string, isOrg bool) e
} }
// InitializeLabels adds a label set to a repository using a template // InitializeLabels adds a label set to a repository using a template
func InitializeLabels(ctx *db.Context, repoID int64, labelTemplate string, isOrg bool) error { func InitializeLabels(ctx context.Context, repoID int64, labelTemplate string, isOrg bool) error {
return initializeLabels(ctx.Engine(), repoID, labelTemplate, isOrg) return initializeLabels(db.GetEngine(ctx), repoID, labelTemplate, isOrg)
} }
func newLabel(e db.Engine, label *Label) error { func newLabel(e db.Engine, label *Label) error {
@ -256,7 +257,7 @@ func NewLabel(label *Label) error {
if !LabelColorPattern.MatchString(label.Color) { if !LabelColorPattern.MatchString(label.Color) {
return fmt.Errorf("bad color code: %s", label.Color) return fmt.Errorf("bad color code: %s", label.Color)
} }
return newLabel(db.DefaultContext().Engine(), label) return newLabel(db.GetEngine(db.DefaultContext), label)
} }
// NewLabels creates new labels // NewLabels creates new labels
@ -271,7 +272,7 @@ func NewLabels(labels ...*Label) error {
if !LabelColorPattern.MatchString(label.Color) { if !LabelColorPattern.MatchString(label.Color) {
return fmt.Errorf("bad color code: %s", label.Color) return fmt.Errorf("bad color code: %s", label.Color)
} }
if err := newLabel(ctx.Engine(), label); err != nil { if err := newLabel(db.GetEngine(ctx), label); err != nil {
return err return err
} }
} }
@ -283,7 +284,7 @@ func UpdateLabel(l *Label) error {
if !LabelColorPattern.MatchString(l.Color) { if !LabelColorPattern.MatchString(l.Color) {
return fmt.Errorf("bad color code: %s", l.Color) return fmt.Errorf("bad color code: %s", l.Color)
} }
return updateLabelCols(db.DefaultContext().Engine(), l, "name", "description", "color") return updateLabelCols(db.GetEngine(db.DefaultContext), l, "name", "description", "color")
} }
// DeleteLabel delete a label // DeleteLabel delete a label
@ -296,7 +297,7 @@ func DeleteLabel(id, labelID int64) error {
return err return err
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -343,13 +344,13 @@ func getLabelByID(e db.Engine, labelID int64) (*Label, error) {
// GetLabelByID returns a label by given ID. // GetLabelByID returns a label by given ID.
func GetLabelByID(id int64) (*Label, error) { func GetLabelByID(id int64) (*Label, error) {
return getLabelByID(db.DefaultContext().Engine(), id) return getLabelByID(db.GetEngine(db.DefaultContext), id)
} }
// GetLabelsByIDs returns a list of labels by IDs // GetLabelsByIDs returns a list of labels by IDs
func GetLabelsByIDs(labelIDs []int64) ([]*Label, error) { func GetLabelsByIDs(labelIDs []int64) ([]*Label, error) {
labels := make([]*Label, 0, len(labelIDs)) labels := make([]*Label, 0, len(labelIDs))
return labels, db.DefaultContext().Engine().Table("label"). return labels, db.GetEngine(db.DefaultContext).Table("label").
In("id", labelIDs). In("id", labelIDs).
Asc("name"). Asc("name").
Cols("id", "repo_id", "org_id"). Cols("id", "repo_id", "org_id").
@ -403,7 +404,7 @@ func getLabelInRepoByID(e db.Engine, repoID, labelID int64) (*Label, error) {
// GetLabelInRepoByName returns a label by name in given repository. // GetLabelInRepoByName returns a label by name in given repository.
func GetLabelInRepoByName(repoID int64, labelName string) (*Label, error) { func GetLabelInRepoByName(repoID int64, labelName string) (*Label, error) {
return getLabelInRepoByName(db.DefaultContext().Engine(), repoID, labelName) return getLabelInRepoByName(db.GetEngine(db.DefaultContext), repoID, labelName)
} }
// GetLabelIDsInRepoByNames returns a list of labelIDs by names in a given // GetLabelIDsInRepoByNames returns a list of labelIDs by names in a given
@ -411,7 +412,7 @@ func GetLabelInRepoByName(repoID int64, labelName string) (*Label, error) {
// it silently ignores label names that do not belong to the repository. // it silently ignores label names that do not belong to the repository.
func GetLabelIDsInRepoByNames(repoID int64, labelNames []string) ([]int64, error) { func GetLabelIDsInRepoByNames(repoID int64, labelNames []string) ([]int64, error) {
labelIDs := make([]int64, 0, len(labelNames)) labelIDs := make([]int64, 0, len(labelNames))
return labelIDs, db.DefaultContext().Engine().Table("label"). return labelIDs, db.GetEngine(db.DefaultContext).Table("label").
Where("repo_id = ?", repoID). Where("repo_id = ?", repoID).
In("name", labelNames). In("name", labelNames).
Asc("name"). Asc("name").
@ -432,14 +433,14 @@ func BuildLabelNamesIssueIDsCondition(labelNames []string) *builder.Builder {
// GetLabelInRepoByID returns a label by ID in given repository. // GetLabelInRepoByID returns a label by ID in given repository.
func GetLabelInRepoByID(repoID, labelID int64) (*Label, error) { func GetLabelInRepoByID(repoID, labelID int64) (*Label, error) {
return getLabelInRepoByID(db.DefaultContext().Engine(), repoID, labelID) return getLabelInRepoByID(db.GetEngine(db.DefaultContext), repoID, labelID)
} }
// GetLabelsInRepoByIDs returns a list of labels by IDs in given repository, // GetLabelsInRepoByIDs returns a list of labels by IDs in given repository,
// it silently ignores label IDs that do not belong to the repository. // it silently ignores label IDs that do not belong to the repository.
func GetLabelsInRepoByIDs(repoID int64, labelIDs []int64) ([]*Label, error) { func GetLabelsInRepoByIDs(repoID int64, labelIDs []int64) ([]*Label, error) {
labels := make([]*Label, 0, len(labelIDs)) labels := make([]*Label, 0, len(labelIDs))
return labels, db.DefaultContext().Engine(). return labels, db.GetEngine(db.DefaultContext).
Where("repo_id = ?", repoID). Where("repo_id = ?", repoID).
In("id", labelIDs). In("id", labelIDs).
Asc("name"). Asc("name").
@ -473,12 +474,12 @@ func getLabelsByRepoID(e db.Engine, repoID int64, sortType string, listOptions L
// GetLabelsByRepoID returns all labels that belong to given repository by ID. // GetLabelsByRepoID returns all labels that belong to given repository by ID.
func GetLabelsByRepoID(repoID int64, sortType string, listOptions ListOptions) ([]*Label, error) { func GetLabelsByRepoID(repoID int64, sortType string, listOptions ListOptions) ([]*Label, error) {
return getLabelsByRepoID(db.DefaultContext().Engine(), repoID, sortType, listOptions) return getLabelsByRepoID(db.GetEngine(db.DefaultContext), repoID, sortType, listOptions)
} }
// CountLabelsByRepoID count number of all labels that belong to given repository by ID. // CountLabelsByRepoID count number of all labels that belong to given repository by ID.
func CountLabelsByRepoID(repoID int64) (int64, error) { func CountLabelsByRepoID(repoID int64) (int64, error) {
return db.DefaultContext().Engine().Where("repo_id = ?", repoID).Count(&Label{}) return db.GetEngine(db.DefaultContext).Where("repo_id = ?", repoID).Count(&Label{})
} }
// ________ // ________
@ -528,7 +529,7 @@ func getLabelInOrgByID(e db.Engine, orgID, labelID int64) (*Label, error) {
// GetLabelInOrgByName returns a label by name in given organization. // GetLabelInOrgByName returns a label by name in given organization.
func GetLabelInOrgByName(orgID int64, labelName string) (*Label, error) { func GetLabelInOrgByName(orgID int64, labelName string) (*Label, error) {
return getLabelInOrgByName(db.DefaultContext().Engine(), orgID, labelName) return getLabelInOrgByName(db.GetEngine(db.DefaultContext), orgID, labelName)
} }
// GetLabelIDsInOrgByNames returns a list of labelIDs by names in a given // GetLabelIDsInOrgByNames returns a list of labelIDs by names in a given
@ -539,7 +540,7 @@ func GetLabelIDsInOrgByNames(orgID int64, labelNames []string) ([]int64, error)
} }
labelIDs := make([]int64, 0, len(labelNames)) labelIDs := make([]int64, 0, len(labelNames))
return labelIDs, db.DefaultContext().Engine().Table("label"). return labelIDs, db.GetEngine(db.DefaultContext).Table("label").
Where("org_id = ?", orgID). Where("org_id = ?", orgID).
In("name", labelNames). In("name", labelNames).
Asc("name"). Asc("name").
@ -549,14 +550,14 @@ func GetLabelIDsInOrgByNames(orgID int64, labelNames []string) ([]int64, error)
// GetLabelInOrgByID returns a label by ID in given organization. // GetLabelInOrgByID returns a label by ID in given organization.
func GetLabelInOrgByID(orgID, labelID int64) (*Label, error) { func GetLabelInOrgByID(orgID, labelID int64) (*Label, error) {
return getLabelInOrgByID(db.DefaultContext().Engine(), orgID, labelID) return getLabelInOrgByID(db.GetEngine(db.DefaultContext), orgID, labelID)
} }
// GetLabelsInOrgByIDs returns a list of labels by IDs in given organization, // GetLabelsInOrgByIDs returns a list of labels by IDs in given organization,
// it silently ignores label IDs that do not belong to the organization. // it silently ignores label IDs that do not belong to the organization.
func GetLabelsInOrgByIDs(orgID int64, labelIDs []int64) ([]*Label, error) { func GetLabelsInOrgByIDs(orgID int64, labelIDs []int64) ([]*Label, error) {
labels := make([]*Label, 0, len(labelIDs)) labels := make([]*Label, 0, len(labelIDs))
return labels, db.DefaultContext().Engine(). return labels, db.GetEngine(db.DefaultContext).
Where("org_id = ?", orgID). Where("org_id = ?", orgID).
In("id", labelIDs). In("id", labelIDs).
Asc("name"). Asc("name").
@ -590,12 +591,12 @@ func getLabelsByOrgID(e db.Engine, orgID int64, sortType string, listOptions Lis
// GetLabelsByOrgID returns all labels that belong to given organization by ID. // GetLabelsByOrgID returns all labels that belong to given organization by ID.
func GetLabelsByOrgID(orgID int64, sortType string, listOptions ListOptions) ([]*Label, error) { func GetLabelsByOrgID(orgID int64, sortType string, listOptions ListOptions) ([]*Label, error) {
return getLabelsByOrgID(db.DefaultContext().Engine(), orgID, sortType, listOptions) return getLabelsByOrgID(db.GetEngine(db.DefaultContext), orgID, sortType, listOptions)
} }
// CountLabelsByOrgID count all labels that belong to given organization by ID. // CountLabelsByOrgID count all labels that belong to given organization by ID.
func CountLabelsByOrgID(orgID int64) (int64, error) { func CountLabelsByOrgID(orgID int64) (int64, error) {
return db.DefaultContext().Engine().Where("org_id = ?", orgID).Count(&Label{}) return db.GetEngine(db.DefaultContext).Where("org_id = ?", orgID).Count(&Label{})
} }
// .___ // .___
@ -615,7 +616,7 @@ func getLabelsByIssueID(e db.Engine, issueID int64) ([]*Label, error) {
// GetLabelsByIssueID returns all labels that belong to given issue by ID. // GetLabelsByIssueID returns all labels that belong to given issue by ID.
func GetLabelsByIssueID(issueID int64) ([]*Label, error) { func GetLabelsByIssueID(issueID int64) ([]*Label, error) {
return getLabelsByIssueID(db.DefaultContext().Engine(), issueID) return getLabelsByIssueID(db.GetEngine(db.DefaultContext), issueID)
} }
func updateLabelCols(e db.Engine, l *Label, cols ...string) error { func updateLabelCols(e db.Engine, l *Label, cols ...string) error {
@ -657,7 +658,7 @@ func hasIssueLabel(e db.Engine, issueID, labelID int64) bool {
// HasIssueLabel returns true if issue has been labeled. // HasIssueLabel returns true if issue has been labeled.
func HasIssueLabel(issueID, labelID int64) bool { func HasIssueLabel(issueID, labelID int64) bool {
return hasIssueLabel(db.DefaultContext().Engine(), issueID, labelID) return hasIssueLabel(db.GetEngine(db.DefaultContext), issueID, labelID)
} }
// newIssueLabel this function creates a new label it does not check if the label is valid for the issue // newIssueLabel this function creates a new label it does not check if the label is valid for the issue
@ -695,7 +696,7 @@ func NewIssueLabel(issue *Issue, label *Label, doer *User) (err error) {
return nil return nil
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -750,12 +751,12 @@ func NewIssueLabels(issue *Issue, labels []*Label, doer *User) (err error) {
} }
defer committer.Close() defer committer.Close()
if err = newIssueLabels(ctx.Engine(), issue, labels, doer); err != nil { if err = newIssueLabels(db.GetEngine(ctx), issue, labels, doer); err != nil {
return err return err
} }
issue.Labels = nil issue.Labels = nil
if err = issue.loadLabels(ctx.Engine()); err != nil { if err = issue.loadLabels(db.GetEngine(ctx)); err != nil {
return err return err
} }
@ -792,7 +793,7 @@ func deleteIssueLabel(e db.Engine, issue *Issue, label *Label, doer *User) (err
// DeleteIssueLabel deletes issue-label relation. // DeleteIssueLabel deletes issue-label relation.
func DeleteIssueLabel(issue *Issue, label *Label, doer *User) (err error) { func DeleteIssueLabel(issue *Issue, label *Label, doer *User) (err error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err

View File

@ -63,7 +63,7 @@ func (issues IssueList) loadRepositories(e db.Engine) ([]*Repository, error) {
// LoadRepositories loads issues' all repositories // LoadRepositories loads issues' all repositories
func (issues IssueList) LoadRepositories() ([]*Repository, error) { func (issues IssueList) LoadRepositories() ([]*Repository, error) {
return issues.loadRepositories(db.DefaultContext().Engine()) return issues.loadRepositories(db.GetEngine(db.DefaultContext))
} }
func (issues IssueList) getPosterIDs() []int64 { func (issues IssueList) getPosterIDs() []int64 {
@ -502,33 +502,33 @@ func (issues IssueList) loadAttributes(e db.Engine) error {
// LoadAttributes loads attributes of the issues, except for attachments and // LoadAttributes loads attributes of the issues, except for attachments and
// comments // comments
func (issues IssueList) LoadAttributes() error { func (issues IssueList) LoadAttributes() error {
return issues.loadAttributes(db.DefaultContext().Engine()) return issues.loadAttributes(db.GetEngine(db.DefaultContext))
} }
// LoadAttachments loads attachments // LoadAttachments loads attachments
func (issues IssueList) LoadAttachments() error { func (issues IssueList) LoadAttachments() error {
return issues.loadAttachments(db.DefaultContext().Engine()) return issues.loadAttachments(db.GetEngine(db.DefaultContext))
} }
// LoadComments loads comments // LoadComments loads comments
func (issues IssueList) LoadComments() error { func (issues IssueList) LoadComments() error {
return issues.loadComments(db.DefaultContext().Engine(), builder.NewCond()) return issues.loadComments(db.GetEngine(db.DefaultContext), builder.NewCond())
} }
// LoadDiscussComments loads discuss comments // LoadDiscussComments loads discuss comments
func (issues IssueList) LoadDiscussComments() error { func (issues IssueList) LoadDiscussComments() error {
return issues.loadComments(db.DefaultContext().Engine(), builder.Eq{"comment.type": CommentTypeComment}) return issues.loadComments(db.GetEngine(db.DefaultContext), builder.Eq{"comment.type": CommentTypeComment})
} }
// LoadPullRequests loads pull requests // LoadPullRequests loads pull requests
func (issues IssueList) LoadPullRequests() error { func (issues IssueList) LoadPullRequests() error {
return issues.loadPullRequests(db.DefaultContext().Engine()) return issues.loadPullRequests(db.GetEngine(db.DefaultContext))
} }
// GetApprovalCounts returns a map of issue ID to slice of approval counts // GetApprovalCounts returns a map of issue ID to slice of approval counts
// FIXME: only returns official counts due to double counting of non-official approvals // FIXME: only returns official counts due to double counting of non-official approvals
func (issues IssueList) GetApprovalCounts() (map[int64][]*ReviewCount, error) { func (issues IssueList) GetApprovalCounts() (map[int64][]*ReviewCount, error) {
return issues.getApprovalCounts(db.DefaultContext().Engine()) return issues.getApprovalCounts(db.GetEngine(db.DefaultContext))
} }
func (issues IssueList) getApprovalCounts(e db.Engine) (map[int64][]*ReviewCount, error) { func (issues IssueList) getApprovalCounts(e db.Engine) (map[int64][]*ReviewCount, error) {

View File

@ -37,7 +37,7 @@ func updateIssueLock(opts *IssueLockOptions, lock bool) error {
commentType = CommentTypeUnlock commentType = CommentTypeUnlock
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err

View File

@ -85,7 +85,7 @@ func (m *Milestone) State() api.StateType {
// NewMilestone creates new milestone of repository. // NewMilestone creates new milestone of repository.
func NewMilestone(m *Milestone) (err error) { func NewMilestone(m *Milestone) (err error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -116,13 +116,13 @@ func getMilestoneByRepoID(e db.Engine, repoID, id int64) (*Milestone, error) {
// GetMilestoneByRepoID returns the milestone in a repository. // GetMilestoneByRepoID returns the milestone in a repository.
func GetMilestoneByRepoID(repoID, id int64) (*Milestone, error) { func GetMilestoneByRepoID(repoID, id int64) (*Milestone, error) {
return getMilestoneByRepoID(db.DefaultContext().Engine(), repoID, id) return getMilestoneByRepoID(db.GetEngine(db.DefaultContext), repoID, id)
} }
// GetMilestoneByRepoIDANDName return a milestone if one exist by name and repo // GetMilestoneByRepoIDANDName return a milestone if one exist by name and repo
func GetMilestoneByRepoIDANDName(repoID int64, name string) (*Milestone, error) { func GetMilestoneByRepoIDANDName(repoID int64, name string) (*Milestone, error) {
var mile Milestone var mile Milestone
has, err := db.DefaultContext().Engine().Where("repo_id=? AND name=?", repoID, name).Get(&mile) has, err := db.GetEngine(db.DefaultContext).Where("repo_id=? AND name=?", repoID, name).Get(&mile)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -134,7 +134,7 @@ func GetMilestoneByRepoIDANDName(repoID int64, name string) (*Milestone, error)
// GetMilestoneByID returns the milestone via id . // GetMilestoneByID returns the milestone via id .
func GetMilestoneByID(id int64) (*Milestone, error) { func GetMilestoneByID(id int64) (*Milestone, error) {
return getMilestoneByID(db.DefaultContext().Engine(), id) return getMilestoneByID(db.GetEngine(db.DefaultContext), id)
} }
func getMilestoneByID(e db.Engine, id int64) (*Milestone, error) { func getMilestoneByID(e db.Engine, id int64) (*Milestone, error) {
@ -150,7 +150,7 @@ func getMilestoneByID(e db.Engine, id int64) (*Milestone, error) {
// UpdateMilestone updates information of given milestone. // UpdateMilestone updates information of given milestone.
func UpdateMilestone(m *Milestone, oldIsClosed bool) error { func UpdateMilestone(m *Milestone, oldIsClosed bool) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -207,7 +207,7 @@ func updateMilestoneCounters(e db.Engine, id int64) error {
// ChangeMilestoneStatusByRepoIDAndID changes a milestone open/closed status if the milestone ID is in the repo. // ChangeMilestoneStatusByRepoIDAndID changes a milestone open/closed status if the milestone ID is in the repo.
func ChangeMilestoneStatusByRepoIDAndID(repoID, milestoneID int64, isClosed bool) error { func ChangeMilestoneStatusByRepoIDAndID(repoID, milestoneID int64, isClosed bool) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -234,7 +234,7 @@ func ChangeMilestoneStatusByRepoIDAndID(repoID, milestoneID int64, isClosed bool
// ChangeMilestoneStatus changes the milestone open/closed status. // ChangeMilestoneStatus changes the milestone open/closed status.
func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) { func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -303,7 +303,7 @@ func changeMilestoneAssign(e *xorm.Session, doer *User, issue *Issue, oldMilesto
// ChangeMilestoneAssign changes assignment of milestone for issue. // ChangeMilestoneAssign changes assignment of milestone for issue.
func ChangeMilestoneAssign(issue *Issue, doer *User, oldMilestoneID int64) (err error) { func ChangeMilestoneAssign(issue *Issue, doer *User, oldMilestoneID int64) (err error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -334,7 +334,7 @@ func DeleteMilestoneByRepoID(repoID, id int64) error {
return err return err
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -410,7 +410,7 @@ func (opts GetMilestonesOption) toCond() builder.Cond {
// GetMilestones returns milestones filtered by GetMilestonesOption's // GetMilestones returns milestones filtered by GetMilestonesOption's
func GetMilestones(opts GetMilestonesOption) (MilestoneList, int64, error) { func GetMilestones(opts GetMilestonesOption) (MilestoneList, int64, error) {
sess := db.DefaultContext().Engine().Where(opts.toCond()) sess := db.GetEngine(db.DefaultContext).Where(opts.toCond())
if opts.Page != 0 { if opts.Page != 0 {
sess = setSessionPagination(sess, &opts) sess = setSessionPagination(sess, &opts)
@ -441,7 +441,7 @@ func GetMilestones(opts GetMilestonesOption) (MilestoneList, int64, error) {
// SearchMilestones search milestones // SearchMilestones search milestones
func SearchMilestones(repoCond builder.Cond, page int, isClosed bool, sortType string, keyword string) (MilestoneList, error) { func SearchMilestones(repoCond builder.Cond, page int, isClosed bool, sortType string, keyword string) (MilestoneList, error) {
miles := make([]*Milestone, 0, setting.UI.IssuePagingNum) miles := make([]*Milestone, 0, setting.UI.IssuePagingNum)
sess := db.DefaultContext().Engine().Where("is_closed = ?", isClosed) sess := db.GetEngine(db.DefaultContext).Where("is_closed = ?", isClosed)
if len(keyword) > 0 { if len(keyword) > 0 {
sess = sess.And(builder.Like{"UPPER(name)", strings.ToUpper(keyword)}) sess = sess.And(builder.Like{"UPPER(name)", strings.ToUpper(keyword)})
} }
@ -502,7 +502,7 @@ func GetMilestonesStatsByRepoCond(repoCond builder.Cond) (*MilestonesStats, erro
var err error var err error
stats := &MilestonesStats{} stats := &MilestonesStats{}
sess := db.DefaultContext().Engine().Where("is_closed = ?", false) sess := db.GetEngine(db.DefaultContext).Where("is_closed = ?", false)
if repoCond.IsValid() { if repoCond.IsValid() {
sess.And(builder.In("repo_id", builder.Select("id").From("repository").Where(repoCond))) sess.And(builder.In("repo_id", builder.Select("id").From("repository").Where(repoCond)))
} }
@ -511,7 +511,7 @@ func GetMilestonesStatsByRepoCond(repoCond builder.Cond) (*MilestonesStats, erro
return nil, err return nil, err
} }
sess = db.DefaultContext().Engine().Where("is_closed = ?", true) sess = db.GetEngine(db.DefaultContext).Where("is_closed = ?", true)
if repoCond.IsValid() { if repoCond.IsValid() {
sess.And(builder.In("repo_id", builder.Select("id").From("repository").Where(repoCond))) sess.And(builder.In("repo_id", builder.Select("id").From("repository").Where(repoCond)))
} }
@ -528,7 +528,7 @@ func GetMilestonesStatsByRepoCondAndKw(repoCond builder.Cond, keyword string) (*
var err error var err error
stats := &MilestonesStats{} stats := &MilestonesStats{}
sess := db.DefaultContext().Engine().Where("is_closed = ?", false) sess := db.GetEngine(db.DefaultContext).Where("is_closed = ?", false)
if len(keyword) > 0 { if len(keyword) > 0 {
sess = sess.And(builder.Like{"UPPER(name)", strings.ToUpper(keyword)}) sess = sess.And(builder.Like{"UPPER(name)", strings.ToUpper(keyword)})
} }
@ -540,7 +540,7 @@ func GetMilestonesStatsByRepoCondAndKw(repoCond builder.Cond, keyword string) (*
return nil, err return nil, err
} }
sess = db.DefaultContext().Engine().Where("is_closed = ?", true) sess = db.GetEngine(db.DefaultContext).Where("is_closed = ?", true)
if len(keyword) > 0 { if len(keyword) > 0 {
sess = sess.And(builder.Like{"UPPER(name)", strings.ToUpper(keyword)}) sess = sess.And(builder.Like{"UPPER(name)", strings.ToUpper(keyword)})
} }
@ -569,12 +569,12 @@ func countRepoClosedMilestones(e db.Engine, repoID int64) (int64, error) {
// CountRepoClosedMilestones returns number of closed milestones in given repository. // CountRepoClosedMilestones returns number of closed milestones in given repository.
func CountRepoClosedMilestones(repoID int64) (int64, error) { func CountRepoClosedMilestones(repoID int64) (int64, error) {
return countRepoClosedMilestones(db.DefaultContext().Engine(), repoID) return countRepoClosedMilestones(db.GetEngine(db.DefaultContext), repoID)
} }
// CountMilestonesByRepoCond map from repo conditions to number of milestones matching the options` // CountMilestonesByRepoCond map from repo conditions to number of milestones matching the options`
func CountMilestonesByRepoCond(repoCond builder.Cond, isClosed bool) (map[int64]int64, error) { func CountMilestonesByRepoCond(repoCond builder.Cond, isClosed bool) (map[int64]int64, error) {
sess := db.DefaultContext().Engine().Where("is_closed = ?", isClosed) sess := db.GetEngine(db.DefaultContext).Where("is_closed = ?", isClosed)
if repoCond.IsValid() { if repoCond.IsValid() {
sess.In("repo_id", builder.Select("id").From("repository").Where(repoCond)) sess.In("repo_id", builder.Select("id").From("repository").Where(repoCond))
} }
@ -599,7 +599,7 @@ func CountMilestonesByRepoCond(repoCond builder.Cond, isClosed bool) (map[int64]
// CountMilestonesByRepoCondAndKw map from repo conditions and the keyword of milestones' name to number of milestones matching the options` // CountMilestonesByRepoCondAndKw map from repo conditions and the keyword of milestones' name to number of milestones matching the options`
func CountMilestonesByRepoCondAndKw(repoCond builder.Cond, keyword string, isClosed bool) (map[int64]int64, error) { func CountMilestonesByRepoCondAndKw(repoCond builder.Cond, keyword string, isClosed bool) (map[int64]int64, error) {
sess := db.DefaultContext().Engine().Where("is_closed = ?", isClosed) sess := db.GetEngine(db.DefaultContext).Where("is_closed = ?", isClosed)
if len(keyword) > 0 { if len(keyword) > 0 {
sess = sess.And(builder.Like{"UPPER(name)", strings.ToUpper(keyword)}) sess = sess.And(builder.Like{"UPPER(name)", strings.ToUpper(keyword)})
} }
@ -707,10 +707,10 @@ func (m *Milestone) loadTotalTrackedTime(e db.Engine) error {
// LoadTotalTrackedTimes loads for every milestone in the list the TotalTrackedTime by a batch request // LoadTotalTrackedTimes loads for every milestone in the list the TotalTrackedTime by a batch request
func (milestones MilestoneList) LoadTotalTrackedTimes() error { func (milestones MilestoneList) LoadTotalTrackedTimes() error {
return milestones.loadTotalTrackedTimes(db.DefaultContext().Engine()) return milestones.loadTotalTrackedTimes(db.GetEngine(db.DefaultContext))
} }
// LoadTotalTrackedTime loads the tracked time for the milestone // LoadTotalTrackedTime loads the tracked time for the milestone
func (m *Milestone) LoadTotalTrackedTime() error { func (m *Milestone) LoadTotalTrackedTime() error {
return m.loadTotalTrackedTime(db.DefaultContext().Engine()) return m.loadTotalTrackedTime(db.GetEngine(db.DefaultContext))
} }

View File

@ -173,7 +173,7 @@ func TestCountRepoMilestones(t *testing.T) {
assert.NoError(t, db.PrepareTestDatabase()) assert.NoError(t, db.PrepareTestDatabase())
test := func(repoID int64) { test := func(repoID int64) {
repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository)
count, err := countRepoMilestones(db.DefaultContext().Engine(), repoID) count, err := countRepoMilestones(db.GetEngine(db.DefaultContext), repoID)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, repo.NumMilestones, count) assert.EqualValues(t, repo.NumMilestones, count)
} }
@ -181,7 +181,7 @@ func TestCountRepoMilestones(t *testing.T) {
test(2) test(2)
test(3) test(3)
count, err := countRepoMilestones(db.DefaultContext().Engine(), db.NonexistentID) count, err := countRepoMilestones(db.GetEngine(db.DefaultContext), db.NonexistentID)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, 0, count) assert.EqualValues(t, 0, count)
} }
@ -223,16 +223,16 @@ func TestUpdateMilestoneCounters(t *testing.T) {
issue.IsClosed = true issue.IsClosed = true
issue.ClosedUnix = timeutil.TimeStampNow() issue.ClosedUnix = timeutil.TimeStampNow()
_, err := db.DefaultContext().Engine().ID(issue.ID).Cols("is_closed", "closed_unix").Update(issue) _, err := db.GetEngine(db.DefaultContext).ID(issue.ID).Cols("is_closed", "closed_unix").Update(issue)
assert.NoError(t, err) assert.NoError(t, err)
assert.NoError(t, updateMilestoneCounters(db.DefaultContext().Engine(), issue.MilestoneID)) assert.NoError(t, updateMilestoneCounters(db.GetEngine(db.DefaultContext), issue.MilestoneID))
CheckConsistencyFor(t, &Milestone{}) CheckConsistencyFor(t, &Milestone{})
issue.IsClosed = false issue.IsClosed = false
issue.ClosedUnix = 0 issue.ClosedUnix = 0
_, err = db.DefaultContext().Engine().ID(issue.ID).Cols("is_closed", "closed_unix").Update(issue) _, err = db.GetEngine(db.DefaultContext).ID(issue.ID).Cols("is_closed", "closed_unix").Update(issue)
assert.NoError(t, err) assert.NoError(t, err)
assert.NoError(t, updateMilestoneCounters(db.DefaultContext().Engine(), issue.MilestoneID)) assert.NoError(t, updateMilestoneCounters(db.GetEngine(db.DefaultContext), issue.MilestoneID))
CheckConsistencyFor(t, &Milestone{}) CheckConsistencyFor(t, &Milestone{})
} }

View File

@ -71,7 +71,7 @@ func (opts *FindReactionsOptions) toConds() builder.Cond {
// FindCommentReactions returns a ReactionList of all reactions from an comment // FindCommentReactions returns a ReactionList of all reactions from an comment
func FindCommentReactions(comment *Comment) (ReactionList, error) { func FindCommentReactions(comment *Comment) (ReactionList, error) {
return findReactions(db.DefaultContext().Engine(), FindReactionsOptions{ return findReactions(db.GetEngine(db.DefaultContext), FindReactionsOptions{
IssueID: comment.IssueID, IssueID: comment.IssueID,
CommentID: comment.ID, CommentID: comment.ID,
}) })
@ -79,7 +79,7 @@ func FindCommentReactions(comment *Comment) (ReactionList, error) {
// FindIssueReactions returns a ReactionList of all reactions from an issue // FindIssueReactions returns a ReactionList of all reactions from an issue
func FindIssueReactions(issue *Issue, listOptions ListOptions) (ReactionList, error) { func FindIssueReactions(issue *Issue, listOptions ListOptions) (ReactionList, error) {
return findReactions(db.DefaultContext().Engine(), FindReactionsOptions{ return findReactions(db.GetEngine(db.DefaultContext), FindReactionsOptions{
ListOptions: listOptions, ListOptions: listOptions,
IssueID: issue.ID, IssueID: issue.ID,
CommentID: -1, CommentID: -1,
@ -148,7 +148,7 @@ func CreateReaction(opts *ReactionOptions) (*Reaction, error) {
return nil, ErrForbiddenIssueReaction{opts.Type} return nil, ErrForbiddenIssueReaction{opts.Type}
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return nil, err return nil, err
@ -203,7 +203,7 @@ func deleteReaction(e db.Engine, opts *ReactionOptions) error {
// DeleteReaction deletes reaction for issue or comment. // DeleteReaction deletes reaction for issue or comment.
func DeleteReaction(opts *ReactionOptions) error { func DeleteReaction(opts *ReactionOptions) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -240,7 +240,7 @@ func (r *Reaction) LoadUser() (*User, error) {
if r.User != nil { if r.User != nil {
return r.User, nil return r.User, nil
} }
user, err := getUserByID(db.DefaultContext().Engine(), r.UserID) user, err := getUserByID(db.GetEngine(db.DefaultContext), r.UserID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -314,7 +314,7 @@ func (list ReactionList) loadUsers(e db.Engine, repo *Repository) ([]*User, erro
// LoadUsers loads reactions' all users // LoadUsers loads reactions' all users
func (list ReactionList) LoadUsers(repo *Repository) ([]*User, error) { func (list ReactionList) LoadUsers(repo *Repository) ([]*User, error) {
return list.loadUsers(db.DefaultContext().Engine(), repo) return list.loadUsers(db.GetEngine(db.DefaultContext), repo)
} }
// GetFirstUsers returns first reacted user display names separated by comma // GetFirstUsers returns first reacted user display names separated by comma

View File

@ -93,7 +93,7 @@ func TestIssueReactionCount(t *testing.T) {
addReaction(t, user4, issue, nil, "heart") addReaction(t, user4, issue, nil, "heart")
addReaction(t, ghost, issue, nil, "-1") addReaction(t, ghost, issue, nil, "-1")
err := issue.loadReactions(db.DefaultContext().Engine()) err := issue.loadReactions(db.GetEngine(db.DefaultContext))
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, issue.Reactions, 7) assert.Len(t, issue.Reactions, 7)

View File

@ -48,7 +48,7 @@ func getStopwatch(e db.Engine, userID, issueID int64) (sw *Stopwatch, exists boo
// GetUserStopwatches return list of all stopwatches of a user // GetUserStopwatches return list of all stopwatches of a user
func GetUserStopwatches(userID int64, listOptions ListOptions) ([]*Stopwatch, error) { func GetUserStopwatches(userID int64, listOptions ListOptions) ([]*Stopwatch, error) {
sws := make([]*Stopwatch, 0, 8) sws := make([]*Stopwatch, 0, 8)
sess := db.DefaultContext().Engine().Where("stopwatch.user_id = ?", userID) sess := db.GetEngine(db.DefaultContext).Where("stopwatch.user_id = ?", userID)
if listOptions.Page != 0 { if listOptions.Page != 0 {
sess = setSessionPagination(sess, &listOptions) sess = setSessionPagination(sess, &listOptions)
} }
@ -62,18 +62,18 @@ func GetUserStopwatches(userID int64, listOptions ListOptions) ([]*Stopwatch, er
// CountUserStopwatches return count of all stopwatches of a user // CountUserStopwatches return count of all stopwatches of a user
func CountUserStopwatches(userID int64) (int64, error) { func CountUserStopwatches(userID int64) (int64, error) {
return db.DefaultContext().Engine().Where("user_id = ?", userID).Count(&Stopwatch{}) return db.GetEngine(db.DefaultContext).Where("user_id = ?", userID).Count(&Stopwatch{})
} }
// StopwatchExists returns true if the stopwatch exists // StopwatchExists returns true if the stopwatch exists
func StopwatchExists(userID, issueID int64) bool { func StopwatchExists(userID, issueID int64) bool {
_, exists, _ := getStopwatch(db.DefaultContext().Engine(), userID, issueID) _, exists, _ := getStopwatch(db.GetEngine(db.DefaultContext), userID, issueID)
return exists return exists
} }
// HasUserStopwatch returns true if the user has a stopwatch // HasUserStopwatch returns true if the user has a stopwatch
func HasUserStopwatch(userID int64) (exists bool, sw *Stopwatch, err error) { func HasUserStopwatch(userID int64) (exists bool, sw *Stopwatch, err error) {
return hasUserStopwatch(db.DefaultContext().Engine(), userID) return hasUserStopwatch(db.GetEngine(db.DefaultContext), userID)
} }
func hasUserStopwatch(e db.Engine, userID int64) (exists bool, sw *Stopwatch, err error) { func hasUserStopwatch(e db.Engine, userID int64) (exists bool, sw *Stopwatch, err error) {
@ -86,7 +86,7 @@ func hasUserStopwatch(e db.Engine, userID int64) (exists bool, sw *Stopwatch, er
// CreateOrStopIssueStopwatch will create or remove a stopwatch and will log it into issue's timeline. // CreateOrStopIssueStopwatch will create or remove a stopwatch and will log it into issue's timeline.
func CreateOrStopIssueStopwatch(user *User, issue *Issue) error { func CreateOrStopIssueStopwatch(user *User, issue *Issue) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -175,7 +175,7 @@ func createOrStopIssueStopwatch(e *xorm.Session, user *User, issue *Issue) error
// CancelStopwatch removes the given stopwatch and logs it into issue's timeline. // CancelStopwatch removes the given stopwatch and logs it into issue's timeline.
func CancelStopwatch(user *User, issue *Issue) error { func CancelStopwatch(user *User, issue *Issue) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err

View File

@ -77,7 +77,7 @@ func TestGetParticipantIDsByIssue(t *testing.T) {
checkParticipants := func(issueID int64, userIDs []int) { checkParticipants := func(issueID int64, userIDs []int) {
issue, err := GetIssueByID(issueID) issue, err := GetIssueByID(issueID)
assert.NoError(t, err) assert.NoError(t, err)
participants, err := issue.getParticipantIDsByIssue(db.DefaultContext().Engine()) participants, err := issue.getParticipantIDsByIssue(db.GetEngine(db.DefaultContext))
if assert.NoError(t, err) { if assert.NoError(t, err) {
participantsIDs := make([]int, len(participants)) participantsIDs := make([]int, len(participants))
for i, uid := range participants { for i, uid := range participants {
@ -125,7 +125,7 @@ func TestUpdateIssueCols(t *testing.T) {
issue.Content = "This should have no effect" issue.Content = "This should have no effect"
now := time.Now().Unix() now := time.Now().Unix()
assert.NoError(t, updateIssueCols(db.DefaultContext().Engine(), issue, "name")) assert.NoError(t, updateIssueCols(db.GetEngine(db.DefaultContext), issue, "name"))
then := time.Now().Unix() then := time.Now().Unix()
updatedIssue := db.AssertExistsAndLoadBean(t, &Issue{ID: issue.ID}).(*Issue) updatedIssue := db.AssertExistsAndLoadBean(t, &Issue{ID: issue.ID}).(*Issue)
@ -290,7 +290,7 @@ func TestIssue_loadTotalTimes(t *testing.T) {
assert.NoError(t, db.PrepareTestDatabase()) assert.NoError(t, db.PrepareTestDatabase())
ms, err := GetIssueByID(2) ms, err := GetIssueByID(2)
assert.NoError(t, err) assert.NoError(t, err)
assert.NoError(t, ms.loadTotalTimes(db.DefaultContext().Engine())) assert.NoError(t, ms.loadTotalTimes(db.GetEngine(db.DefaultContext)))
assert.Equal(t, int64(3682), ms.TotalTrackedTime) assert.Equal(t, int64(3682), ms.TotalTrackedTime)
} }
@ -363,7 +363,7 @@ func testInsertIssue(t *testing.T, title, content string, expectIndex int64) *Is
err := NewIssue(repo, &issue, nil, nil) err := NewIssue(repo, &issue, nil, nil)
assert.NoError(t, err) assert.NoError(t, err)
has, err := db.DefaultContext().Engine().ID(issue.ID).Get(&newIssue) has, err := db.GetEngine(db.DefaultContext).ID(issue.ID).Get(&newIssue)
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, has) assert.True(t, has)
assert.EqualValues(t, issue.Title, newIssue.Title) assert.EqualValues(t, issue.Title, newIssue.Title)
@ -380,11 +380,11 @@ func TestIssue_InsertIssue(t *testing.T) {
// there are 5 issues and max index is 5 on repository 1, so this one should 6 // there are 5 issues and max index is 5 on repository 1, so this one should 6
issue := testInsertIssue(t, "my issue1", "special issue's comments?", 6) issue := testInsertIssue(t, "my issue1", "special issue's comments?", 6)
_, err := db.DefaultContext().Engine().ID(issue.ID).Delete(new(Issue)) _, err := db.GetEngine(db.DefaultContext).ID(issue.ID).Delete(new(Issue))
assert.NoError(t, err) assert.NoError(t, err)
issue = testInsertIssue(t, `my issue2, this is my son's love \n \r \ `, "special issue's '' comments?", 7) issue = testInsertIssue(t, `my issue2, this is my son's love \n \r \ `, "special issue's '' comments?", 7)
_, err = db.DefaultContext().Engine().ID(issue.ID).Delete(new(Issue)) _, err = db.GetEngine(db.DefaultContext).ID(issue.ID).Delete(new(Issue))
assert.NoError(t, err) assert.NoError(t, err)
} }
@ -397,7 +397,7 @@ func TestIssue_ResolveMentions(t *testing.T) {
r := db.AssertExistsAndLoadBean(t, &Repository{OwnerID: o.ID, LowerName: repo}).(*Repository) r := db.AssertExistsAndLoadBean(t, &Repository{OwnerID: o.ID, LowerName: repo}).(*Repository)
issue := &Issue{RepoID: r.ID} issue := &Issue{RepoID: r.ID}
d := db.AssertExistsAndLoadBean(t, &User{LowerName: doer}).(*User) d := db.AssertExistsAndLoadBean(t, &User{LowerName: doer}).(*User)
resolved, err := issue.ResolveMentionsByVisibility(db.DefaultContext(), d, mentions) resolved, err := issue.ResolveMentionsByVisibility(db.DefaultContext, d, mentions)
assert.NoError(t, err) assert.NoError(t, err)
ids := make([]int64, len(resolved)) ids := make([]int64, len(resolved))
for i, user := range resolved { for i, user := range resolved {

View File

@ -40,7 +40,7 @@ func (t *TrackedTime) AfterLoad() {
// LoadAttributes load Issue, User // LoadAttributes load Issue, User
func (t *TrackedTime) LoadAttributes() (err error) { func (t *TrackedTime) LoadAttributes() (err error) {
return t.loadAttributes(db.DefaultContext().Engine()) return t.loadAttributes(db.GetEngine(db.DefaultContext))
} }
func (t *TrackedTime) loadAttributes(e db.Engine) (err error) { func (t *TrackedTime) loadAttributes(e db.Engine) (err error) {
@ -131,12 +131,12 @@ func getTrackedTimes(e db.Engine, options *FindTrackedTimesOptions) (trackedTime
// GetTrackedTimes returns all tracked times that fit to the given options. // GetTrackedTimes returns all tracked times that fit to the given options.
func GetTrackedTimes(opts *FindTrackedTimesOptions) (TrackedTimeList, error) { func GetTrackedTimes(opts *FindTrackedTimesOptions) (TrackedTimeList, error) {
return getTrackedTimes(db.DefaultContext().Engine(), opts) return getTrackedTimes(db.GetEngine(db.DefaultContext), opts)
} }
// CountTrackedTimes returns count of tracked times that fit to the given options. // CountTrackedTimes returns count of tracked times that fit to the given options.
func CountTrackedTimes(opts *FindTrackedTimesOptions) (int64, error) { func CountTrackedTimes(opts *FindTrackedTimesOptions) (int64, error) {
sess := db.DefaultContext().Engine().Where(opts.toCond()) sess := db.GetEngine(db.DefaultContext).Where(opts.toCond())
if opts.RepositoryID > 0 || opts.MilestoneID > 0 { if opts.RepositoryID > 0 || opts.MilestoneID > 0 {
sess = sess.Join("INNER", "issue", "issue.id = tracked_time.issue_id") sess = sess.Join("INNER", "issue", "issue.id = tracked_time.issue_id")
} }
@ -149,12 +149,12 @@ func getTrackedSeconds(e db.Engine, opts FindTrackedTimesOptions) (trackedSecond
// GetTrackedSeconds return sum of seconds // GetTrackedSeconds return sum of seconds
func GetTrackedSeconds(opts FindTrackedTimesOptions) (int64, error) { func GetTrackedSeconds(opts FindTrackedTimesOptions) (int64, error) {
return getTrackedSeconds(db.DefaultContext().Engine(), opts) return getTrackedSeconds(db.GetEngine(db.DefaultContext), opts)
} }
// AddTime will add the given time (in seconds) to the issue // AddTime will add the given time (in seconds) to the issue
func AddTime(user *User, issue *Issue, amount int64, created time.Time) (*TrackedTime, error) { func AddTime(user *User, issue *Issue, amount int64, created time.Time) (*TrackedTime, error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
@ -230,7 +230,7 @@ func TotalTimes(options *FindTrackedTimesOptions) (map[*User]string, error) {
// DeleteIssueUserTimes deletes times for issue // DeleteIssueUserTimes deletes times for issue
func DeleteIssueUserTimes(issue *Issue, user *User) error { func DeleteIssueUserTimes(issue *Issue, user *User) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
@ -268,7 +268,7 @@ func DeleteIssueUserTimes(issue *Issue, user *User) error {
// DeleteTime delete a specific Time // DeleteTime delete a specific Time
func DeleteTime(t *TrackedTime) error { func DeleteTime(t *TrackedTime) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
@ -318,7 +318,7 @@ func deleteTime(e db.Engine, t *TrackedTime) error {
// GetTrackedTimeByID returns raw TrackedTime without loading attributes by id // GetTrackedTimeByID returns raw TrackedTime without loading attributes by id
func GetTrackedTimeByID(id int64) (*TrackedTime, error) { func GetTrackedTimeByID(id int64) (*TrackedTime, error) {
time := new(TrackedTime) time := new(TrackedTime)
has, err := db.DefaultContext().Engine().ID(id).Get(time) has, err := db.GetEngine(db.DefaultContext).ID(id).Get(time)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {

View File

@ -5,6 +5,7 @@
package models package models
import ( import (
"context"
"fmt" "fmt"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
@ -57,27 +58,27 @@ func newIssueUsers(e db.Engine, repo *Repository, issue *Issue) error {
// UpdateIssueUserByRead updates issue-user relation for reading. // UpdateIssueUserByRead updates issue-user relation for reading.
func UpdateIssueUserByRead(uid, issueID int64) error { func UpdateIssueUserByRead(uid, issueID int64) error {
_, err := db.DefaultContext().Engine().Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID) _, err := db.GetEngine(db.DefaultContext).Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID)
return err return err
} }
// UpdateIssueUsersByMentions updates issue-user pairs by mentioning. // UpdateIssueUsersByMentions updates issue-user pairs by mentioning.
func UpdateIssueUsersByMentions(ctx *db.Context, issueID int64, uids []int64) error { func UpdateIssueUsersByMentions(ctx context.Context, issueID int64, uids []int64) error {
for _, uid := range uids { for _, uid := range uids {
iu := &IssueUser{ iu := &IssueUser{
UID: uid, UID: uid,
IssueID: issueID, IssueID: issueID,
} }
has, err := ctx.Engine().Get(iu) has, err := db.GetEngine(ctx).Get(iu)
if err != nil { if err != nil {
return err return err
} }
iu.IsMentioned = true iu.IsMentioned = true
if has { if has {
_, err = ctx.Engine().ID(iu.ID).Cols("is_mentioned").Update(iu) _, err = db.GetEngine(ctx).ID(iu.ID).Cols("is_mentioned").Update(iu)
} else { } else {
_, err = ctx.Engine().Insert(iu) _, err = db.GetEngine(ctx).Insert(iu)
} }
if err != nil { if err != nil {
return err return err

View File

@ -26,7 +26,7 @@ func Test_newIssueUsers(t *testing.T) {
// artificially insert new issue // artificially insert new issue
db.AssertSuccessfulInsert(t, newIssue) db.AssertSuccessfulInsert(t, newIssue)
assert.NoError(t, newIssueUsers(db.DefaultContext().Engine(), repo, newIssue)) assert.NoError(t, newIssueUsers(db.GetEngine(db.DefaultContext), repo, newIssue))
// issue_user table should now have entries for new issue // issue_user table should now have entries for new issue
db.AssertExistsAndLoadBean(t, &IssueUser{IssueID: newIssue.ID, UID: newIssue.PosterID}) db.AssertExistsAndLoadBean(t, &IssueUser{IssueID: newIssue.ID, UID: newIssue.PosterID})
@ -51,7 +51,7 @@ func TestUpdateIssueUsersByMentions(t *testing.T) {
issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue)
uids := []int64{2, 5} uids := []int64{2, 5}
assert.NoError(t, UpdateIssueUsersByMentions(db.DefaultContext(), issue.ID, uids)) assert.NoError(t, UpdateIssueUsersByMentions(db.DefaultContext, issue.ID, uids))
for _, uid := range uids { for _, uid := range uids {
db.AssertExistsAndLoadBean(t, &IssueUser{IssueID: issue.ID, UID: uid}, "is_mentioned=1") db.AssertExistsAndLoadBean(t, &IssueUser{IssueID: issue.ID, UID: uid}, "is_mentioned=1")
} }

View File

@ -28,7 +28,7 @@ type IssueWatchList []*IssueWatch
// CreateOrUpdateIssueWatch set watching for a user and issue // CreateOrUpdateIssueWatch set watching for a user and issue
func CreateOrUpdateIssueWatch(userID, issueID int64, isWatching bool) error { func CreateOrUpdateIssueWatch(userID, issueID int64, isWatching bool) error {
iw, exists, err := getIssueWatch(db.DefaultContext().Engine(), userID, issueID) iw, exists, err := getIssueWatch(db.GetEngine(db.DefaultContext), userID, issueID)
if err != nil { if err != nil {
return err return err
} }
@ -40,13 +40,13 @@ func CreateOrUpdateIssueWatch(userID, issueID int64, isWatching bool) error {
IsWatching: isWatching, IsWatching: isWatching,
} }
if _, err := db.DefaultContext().Engine().Insert(iw); err != nil { if _, err := db.GetEngine(db.DefaultContext).Insert(iw); err != nil {
return err return err
} }
} else { } else {
iw.IsWatching = isWatching iw.IsWatching = isWatching
if _, err := db.DefaultContext().Engine().ID(iw.ID).Cols("is_watching", "updated_unix").Update(iw); err != nil { if _, err := db.GetEngine(db.DefaultContext).ID(iw.ID).Cols("is_watching", "updated_unix").Update(iw); err != nil {
return err return err
} }
} }
@ -56,7 +56,7 @@ func CreateOrUpdateIssueWatch(userID, issueID int64, isWatching bool) error {
// GetIssueWatch returns all IssueWatch objects from db by user and issue // GetIssueWatch returns all IssueWatch objects from db by user and issue
// the current Web-UI need iw object for watchers AND explicit non-watchers // the current Web-UI need iw object for watchers AND explicit non-watchers
func GetIssueWatch(userID, issueID int64) (iw *IssueWatch, exists bool, err error) { func GetIssueWatch(userID, issueID int64) (iw *IssueWatch, exists bool, err error) {
return getIssueWatch(db.DefaultContext().Engine(), userID, issueID) return getIssueWatch(db.GetEngine(db.DefaultContext), userID, issueID)
} }
// Return watcher AND explicit non-watcher if entry in db exist // Return watcher AND explicit non-watcher if entry in db exist
@ -72,14 +72,14 @@ func getIssueWatch(e db.Engine, userID, issueID int64) (iw *IssueWatch, exists b
// CheckIssueWatch check if an user is watching an issue // CheckIssueWatch check if an user is watching an issue
// it takes participants and repo watch into account // it takes participants and repo watch into account
func CheckIssueWatch(user *User, issue *Issue) (bool, error) { func CheckIssueWatch(user *User, issue *Issue) (bool, error) {
iw, exist, err := getIssueWatch(db.DefaultContext().Engine(), user.ID, issue.ID) iw, exist, err := getIssueWatch(db.GetEngine(db.DefaultContext), user.ID, issue.ID)
if err != nil { if err != nil {
return false, err return false, err
} }
if exist { if exist {
return iw.IsWatching, nil return iw.IsWatching, nil
} }
w, err := getWatch(db.DefaultContext().Engine(), user.ID, issue.RepoID) w, err := getWatch(db.GetEngine(db.DefaultContext), user.ID, issue.RepoID)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -90,7 +90,7 @@ func CheckIssueWatch(user *User, issue *Issue) (bool, error) {
// but avoids joining with `user` for performance reasons // but avoids joining with `user` for performance reasons
// User permissions must be verified elsewhere if required // User permissions must be verified elsewhere if required
func GetIssueWatchersIDs(issueID int64, watching bool) ([]int64, error) { func GetIssueWatchersIDs(issueID int64, watching bool) ([]int64, error) {
return getIssueWatchersIDs(db.DefaultContext().Engine(), issueID, watching) return getIssueWatchersIDs(db.GetEngine(db.DefaultContext), issueID, watching)
} }
func getIssueWatchersIDs(e db.Engine, issueID int64, watching bool) ([]int64, error) { func getIssueWatchersIDs(e db.Engine, issueID int64, watching bool) ([]int64, error) {
@ -104,7 +104,7 @@ func getIssueWatchersIDs(e db.Engine, issueID int64, watching bool) ([]int64, er
// GetIssueWatchers returns watchers/unwatchers of a given issue // GetIssueWatchers returns watchers/unwatchers of a given issue
func GetIssueWatchers(issueID int64, listOptions ListOptions) (IssueWatchList, error) { func GetIssueWatchers(issueID int64, listOptions ListOptions) (IssueWatchList, error) {
return getIssueWatchers(db.DefaultContext().Engine(), issueID, listOptions) return getIssueWatchers(db.GetEngine(db.DefaultContext), issueID, listOptions)
} }
func getIssueWatchers(e db.Engine, issueID int64, listOptions ListOptions) (IssueWatchList, error) { func getIssueWatchers(e db.Engine, issueID int64, listOptions ListOptions) (IssueWatchList, error) {

View File

@ -277,7 +277,7 @@ func (comment *Comment) LoadRefIssue() (err error) {
} }
comment.RefIssue, err = GetIssueByID(comment.RefIssueID) comment.RefIssue, err = GetIssueByID(comment.RefIssueID)
if err == nil { if err == nil {
err = comment.RefIssue.loadRepo(db.DefaultContext().Engine()) err = comment.RefIssue.loadRepo(db.GetEngine(db.DefaultContext))
} }
return return
} }
@ -337,7 +337,7 @@ func (comment *Comment) RefIssueIdent() string {
// ResolveCrossReferences will return the list of references to close/reopen by this PR // ResolveCrossReferences will return the list of references to close/reopen by this PR
func (pr *PullRequest) ResolveCrossReferences() ([]*Comment, error) { func (pr *PullRequest) ResolveCrossReferences() ([]*Comment, error) {
unfiltered := make([]*Comment, 0, 5) unfiltered := make([]*Comment, 0, 5)
if err := db.DefaultContext().Engine(). if err := db.GetEngine(db.DefaultContext).
Where("ref_repo_id = ? AND ref_issue_id = ?", pr.Issue.RepoID, pr.Issue.ID). Where("ref_repo_id = ? AND ref_issue_id = ?", pr.Issue.RepoID, pr.Issue.ID).
In("ref_action", []references.XRefAction{references.XRefActionCloses, references.XRefActionReopens}). In("ref_action", []references.XRefAction{references.XRefActionCloses, references.XRefActionReopens}).
OrderBy("id"). OrderBy("id").

View File

@ -139,7 +139,7 @@ func testCreateIssue(t *testing.T, repo, doer int64, title, content string, ispu
Index: idx, Index: idx,
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
assert.NoError(t, sess.Begin()) assert.NoError(t, sess.Begin())
@ -170,7 +170,7 @@ func testCreateComment(t *testing.T, repo, doer, issue int64, content string) *C
i := db.AssertExistsAndLoadBean(t, &Issue{ID: issue}).(*Issue) i := db.AssertExistsAndLoadBean(t, &Issue{ID: issue}).(*Issue)
c := &Comment{Type: CommentTypeComment, PosterID: doer, Poster: d, IssueID: issue, Issue: i, Content: content} c := &Comment{Type: CommentTypeComment, PosterID: doer, Poster: d, IssueID: issue, Issue: i, Content: content}
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
assert.NoError(t, sess.Begin()) assert.NoError(t, sess.Begin())
_, err := sess.Insert(c) _, err := sess.Insert(c)

View File

@ -44,7 +44,7 @@ var ErrLFSObjectNotExist = errors.New("LFS Meta object does not exist")
func NewLFSMetaObject(m *LFSMetaObject) (*LFSMetaObject, error) { func NewLFSMetaObject(m *LFSMetaObject) (*LFSMetaObject, error) {
var err error var err error
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return nil, err return nil, err
@ -76,7 +76,7 @@ func (repo *Repository) GetLFSMetaObjectByOid(oid string) (*LFSMetaObject, error
} }
m := &LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}, RepositoryID: repo.ID} m := &LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}, RepositoryID: repo.ID}
has, err := db.DefaultContext().Engine().Get(m) has, err := db.GetEngine(db.DefaultContext).Get(m)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -92,7 +92,7 @@ func (repo *Repository) RemoveLFSMetaObjectByOid(oid string) (int64, error) {
return 0, ErrLFSObjectNotExist return 0, ErrLFSObjectNotExist
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return -1, err return -1, err
@ -113,7 +113,7 @@ func (repo *Repository) RemoveLFSMetaObjectByOid(oid string) (int64, error) {
// GetLFSMetaObjects returns all LFSMetaObjects associated with a repository // GetLFSMetaObjects returns all LFSMetaObjects associated with a repository
func (repo *Repository) GetLFSMetaObjects(page, pageSize int) ([]*LFSMetaObject, error) { func (repo *Repository) GetLFSMetaObjects(page, pageSize int) ([]*LFSMetaObject, error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if page >= 0 && pageSize > 0 { if page >= 0 && pageSize > 0 {
@ -129,23 +129,23 @@ func (repo *Repository) GetLFSMetaObjects(page, pageSize int) ([]*LFSMetaObject,
// CountLFSMetaObjects returns a count of all LFSMetaObjects associated with a repository // CountLFSMetaObjects returns a count of all LFSMetaObjects associated with a repository
func (repo *Repository) CountLFSMetaObjects() (int64, error) { func (repo *Repository) CountLFSMetaObjects() (int64, error) {
return db.DefaultContext().Engine().Count(&LFSMetaObject{RepositoryID: repo.ID}) return db.GetEngine(db.DefaultContext).Count(&LFSMetaObject{RepositoryID: repo.ID})
} }
// LFSObjectAccessible checks if a provided Oid is accessible to the user // LFSObjectAccessible checks if a provided Oid is accessible to the user
func LFSObjectAccessible(user *User, oid string) (bool, error) { func LFSObjectAccessible(user *User, oid string) (bool, error) {
if user.IsAdmin { if user.IsAdmin {
count, err := db.DefaultContext().Engine().Count(&LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}}) count, err := db.GetEngine(db.DefaultContext).Count(&LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}})
return count > 0, err return count > 0, err
} }
cond := accessibleRepositoryCondition(user) cond := accessibleRepositoryCondition(user)
count, err := db.DefaultContext().Engine().Where(cond).Join("INNER", "repository", "`lfs_meta_object`.repository_id = `repository`.id").Count(&LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}}) count, err := db.GetEngine(db.DefaultContext).Where(cond).Join("INNER", "repository", "`lfs_meta_object`.repository_id = `repository`.id").Count(&LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}})
return count > 0, err return count > 0, err
} }
// LFSAutoAssociate auto associates accessible LFSMetaObjects // LFSAutoAssociate auto associates accessible LFSMetaObjects
func LFSAutoAssociate(metas []*LFSMetaObject, user *User, repoID int64) error { func LFSAutoAssociate(metas []*LFSMetaObject, user *User, repoID int64) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -184,7 +184,7 @@ func IterateLFS(f func(mo *LFSMetaObject) error) error {
const batchSize = 100 const batchSize = 100
for { for {
mos := make([]*LFSMetaObject, 0, batchSize) mos := make([]*LFSMetaObject, 0, batchSize)
if err := db.DefaultContext().Engine().Limit(batchSize, start).Find(&mos); err != nil { if err := db.GetEngine(db.DefaultContext).Limit(batchSize, start).Find(&mos); err != nil {
return err return err
} }
if len(mos) == 0 { if len(mos) == 0 {

View File

@ -72,7 +72,7 @@ func CreateLFSLock(lock *LFSLock) (*LFSLock, error) {
return nil, err return nil, err
} }
_, err = db.DefaultContext().Engine().InsertOne(lock) _, err = db.GetEngine(db.DefaultContext).InsertOne(lock)
return lock, err return lock, err
} }
@ -80,7 +80,7 @@ func CreateLFSLock(lock *LFSLock) (*LFSLock, error) {
func GetLFSLock(repo *Repository, path string) (*LFSLock, error) { func GetLFSLock(repo *Repository, path string) (*LFSLock, error) {
path = cleanPath(path) path = cleanPath(path)
rel := &LFSLock{RepoID: repo.ID} rel := &LFSLock{RepoID: repo.ID}
has, err := db.DefaultContext().Engine().Where("lower(path) = ?", strings.ToLower(path)).Get(rel) has, err := db.GetEngine(db.DefaultContext).Where("lower(path) = ?", strings.ToLower(path)).Get(rel)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -93,7 +93,7 @@ func GetLFSLock(repo *Repository, path string) (*LFSLock, error) {
// GetLFSLockByID returns release by given id. // GetLFSLockByID returns release by given id.
func GetLFSLockByID(id int64) (*LFSLock, error) { func GetLFSLockByID(id int64) (*LFSLock, error) {
lock := new(LFSLock) lock := new(LFSLock)
has, err := db.DefaultContext().Engine().ID(id).Get(lock) has, err := db.GetEngine(db.DefaultContext).ID(id).Get(lock)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -104,7 +104,7 @@ func GetLFSLockByID(id int64) (*LFSLock, error) {
// GetLFSLockByRepoID returns a list of locks of repository. // GetLFSLockByRepoID returns a list of locks of repository.
func GetLFSLockByRepoID(repoID int64, page, pageSize int) ([]*LFSLock, error) { func GetLFSLockByRepoID(repoID int64, page, pageSize int) ([]*LFSLock, error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if page >= 0 && pageSize > 0 { if page >= 0 && pageSize > 0 {
@ -120,7 +120,7 @@ func GetLFSLockByRepoID(repoID int64, page, pageSize int) ([]*LFSLock, error) {
// CountLFSLockByRepoID returns a count of all LFSLocks associated with a repository. // CountLFSLockByRepoID returns a count of all LFSLocks associated with a repository.
func CountLFSLockByRepoID(repoID int64) (int64, error) { func CountLFSLockByRepoID(repoID int64) (int64, error) {
return db.DefaultContext().Engine().Count(&LFSLock{RepoID: repoID}) return db.GetEngine(db.DefaultContext).Count(&LFSLock{RepoID: repoID})
} }
// DeleteLFSLockByID deletes a lock by given ID. // DeleteLFSLockByID deletes a lock by given ID.
@ -139,7 +139,7 @@ func DeleteLFSLockByID(id int64, u *User, force bool) (*LFSLock, error) {
return nil, fmt.Errorf("user doesn't own lock and force flag is not set") return nil, fmt.Errorf("user doesn't own lock and force flag is not set")
} }
_, err = db.DefaultContext().Engine().ID(id).Delete(new(LFSLock)) _, err = db.GetEngine(db.DefaultContext).ID(id).Delete(new(LFSLock))
return lock, err return lock, err
} }

View File

@ -21,7 +21,7 @@ type Paginator interface {
func getPaginatedSession(p Paginator) *xorm.Session { func getPaginatedSession(p Paginator) *xorm.Session {
skip, take := p.GetSkipTake() skip, take := p.GetSkipTake()
return db.DefaultContext().Engine().Limit(take, skip) return db.GetEngine(db.DefaultContext).Limit(take, skip)
} }
// setSessionPagination sets pagination for a database session // setSessionPagination sets pagination for a database session

View File

@ -208,7 +208,7 @@ func (source *LoginSource) SkipVerify() bool {
// CreateLoginSource inserts a LoginSource in the DB if not already // CreateLoginSource inserts a LoginSource in the DB if not already
// existing with the given name. // existing with the given name.
func CreateLoginSource(source *LoginSource) error { func CreateLoginSource(source *LoginSource) error {
has, err := db.DefaultContext().Engine().Where("name=?", source.Name).Exist(new(LoginSource)) has, err := db.GetEngine(db.DefaultContext).Where("name=?", source.Name).Exist(new(LoginSource))
if err != nil { if err != nil {
return err return err
} else if has { } else if has {
@ -219,7 +219,7 @@ func CreateLoginSource(source *LoginSource) error {
source.IsSyncEnabled = false source.IsSyncEnabled = false
} }
_, err = db.DefaultContext().Engine().Insert(source) _, err = db.GetEngine(db.DefaultContext).Insert(source)
if err != nil { if err != nil {
return err return err
} }
@ -240,7 +240,7 @@ func CreateLoginSource(source *LoginSource) error {
err = registerableSource.RegisterSource() err = registerableSource.RegisterSource()
if err != nil { if err != nil {
// remove the LoginSource in case of errors while registering configuration // remove the LoginSource in case of errors while registering configuration
if _, err := db.DefaultContext().Engine().Delete(source); err != nil { if _, err := db.GetEngine(db.DefaultContext).Delete(source); err != nil {
log.Error("CreateLoginSource: Error while wrapOpenIDConnectInitializeError: %v", err) log.Error("CreateLoginSource: Error while wrapOpenIDConnectInitializeError: %v", err)
} }
} }
@ -250,13 +250,13 @@ func CreateLoginSource(source *LoginSource) error {
// LoginSources returns a slice of all login sources found in DB. // LoginSources returns a slice of all login sources found in DB.
func LoginSources() ([]*LoginSource, error) { func LoginSources() ([]*LoginSource, error) {
auths := make([]*LoginSource, 0, 6) auths := make([]*LoginSource, 0, 6)
return auths, db.DefaultContext().Engine().Find(&auths) return auths, db.GetEngine(db.DefaultContext).Find(&auths)
} }
// LoginSourcesByType returns all sources of the specified type // LoginSourcesByType returns all sources of the specified type
func LoginSourcesByType(loginType LoginType) ([]*LoginSource, error) { func LoginSourcesByType(loginType LoginType) ([]*LoginSource, error) {
sources := make([]*LoginSource, 0, 1) sources := make([]*LoginSource, 0, 1)
if err := db.DefaultContext().Engine().Where("type = ?", loginType).Find(&sources); err != nil { if err := db.GetEngine(db.DefaultContext).Where("type = ?", loginType).Find(&sources); err != nil {
return nil, err return nil, err
} }
return sources, nil return sources, nil
@ -265,7 +265,7 @@ func LoginSourcesByType(loginType LoginType) ([]*LoginSource, error) {
// AllActiveLoginSources returns all active sources // AllActiveLoginSources returns all active sources
func AllActiveLoginSources() ([]*LoginSource, error) { func AllActiveLoginSources() ([]*LoginSource, error) {
sources := make([]*LoginSource, 0, 5) sources := make([]*LoginSource, 0, 5)
if err := db.DefaultContext().Engine().Where("is_active = ?", true).Find(&sources); err != nil { if err := db.GetEngine(db.DefaultContext).Where("is_active = ?", true).Find(&sources); err != nil {
return nil, err return nil, err
} }
return sources, nil return sources, nil
@ -274,7 +274,7 @@ func AllActiveLoginSources() ([]*LoginSource, error) {
// ActiveLoginSources returns all active sources of the specified type // ActiveLoginSources returns all active sources of the specified type
func ActiveLoginSources(loginType LoginType) ([]*LoginSource, error) { func ActiveLoginSources(loginType LoginType) ([]*LoginSource, error) {
sources := make([]*LoginSource, 0, 1) sources := make([]*LoginSource, 0, 1)
if err := db.DefaultContext().Engine().Where("is_active = ? and type = ?", true, loginType).Find(&sources); err != nil { if err := db.GetEngine(db.DefaultContext).Where("is_active = ? and type = ?", true, loginType).Find(&sources); err != nil {
return nil, err return nil, err
} }
return sources, nil return sources, nil
@ -305,7 +305,7 @@ func GetLoginSourceByID(id int64) (*LoginSource, error) {
return source, nil return source, nil
} }
has, err := db.DefaultContext().Engine().ID(id).Get(source) has, err := db.GetEngine(db.DefaultContext).ID(id).Get(source)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -325,7 +325,7 @@ func UpdateSource(source *LoginSource) error {
} }
} }
_, err := db.DefaultContext().Engine().ID(source.ID).AllCols().Update(source) _, err := db.GetEngine(db.DefaultContext).ID(source.ID).AllCols().Update(source)
if err != nil { if err != nil {
return err return err
} }
@ -346,7 +346,7 @@ func UpdateSource(source *LoginSource) error {
err = registerableSource.RegisterSource() err = registerableSource.RegisterSource()
if err != nil { if err != nil {
// restore original values since we cannot update the provider it self // restore original values since we cannot update the provider it self
if _, err := db.DefaultContext().Engine().ID(source.ID).AllCols().Update(originalLoginSource); err != nil { if _, err := db.GetEngine(db.DefaultContext).ID(source.ID).AllCols().Update(originalLoginSource); err != nil {
log.Error("UpdateSource: Error while wrapOpenIDConnectInitializeError: %v", err) log.Error("UpdateSource: Error while wrapOpenIDConnectInitializeError: %v", err)
} }
} }
@ -355,14 +355,14 @@ func UpdateSource(source *LoginSource) error {
// DeleteSource deletes a LoginSource record in DB. // DeleteSource deletes a LoginSource record in DB.
func DeleteSource(source *LoginSource) error { func DeleteSource(source *LoginSource) error {
count, err := db.DefaultContext().Engine().Count(&User{LoginSource: source.ID}) count, err := db.GetEngine(db.DefaultContext).Count(&User{LoginSource: source.ID})
if err != nil { if err != nil {
return err return err
} else if count > 0 { } else if count > 0 {
return ErrLoginSourceInUse{source.ID} return ErrLoginSourceInUse{source.ID}
} }
count, err = db.DefaultContext().Engine().Count(&ExternalLoginUser{LoginSourceID: source.ID}) count, err = db.GetEngine(db.DefaultContext).Count(&ExternalLoginUser{LoginSourceID: source.ID})
if err != nil { if err != nil {
return err return err
} else if count > 0 { } else if count > 0 {
@ -375,12 +375,12 @@ func DeleteSource(source *LoginSource) error {
} }
} }
_, err = db.DefaultContext().Engine().ID(source.ID).Delete(new(LoginSource)) _, err = db.GetEngine(db.DefaultContext).ID(source.ID).Delete(new(LoginSource))
return err return err
} }
// CountLoginSources returns number of login sources. // CountLoginSources returns number of login sources.
func CountLoginSources() int64 { func CountLoginSources() int64 {
count, _ := db.DefaultContext().Engine().Count(new(LoginSource)) count, _ := db.GetEngine(db.DefaultContext).Count(new(LoginSource))
return count return count
} }

View File

@ -18,7 +18,7 @@ func InsertMilestones(ms ...*Milestone) (err error) {
return nil return nil
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -39,7 +39,7 @@ func InsertMilestones(ms ...*Milestone) (err error) {
// InsertIssues insert issues to database // InsertIssues insert issues to database
func InsertIssues(issues ...*Issue) error { func InsertIssues(issues ...*Issue) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -144,7 +144,7 @@ func InsertIssueComments(comments []*Comment) error {
issueIDs[comment.IssueID] = true issueIDs[comment.IssueID] = true
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -175,7 +175,7 @@ func InsertIssueComments(comments []*Comment) error {
// InsertPullRequests inserted pull requests // InsertPullRequests inserted pull requests
func InsertPullRequests(prs ...*PullRequest) error { func InsertPullRequests(prs ...*PullRequest) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -195,7 +195,7 @@ func InsertPullRequests(prs ...*PullRequest) error {
// InsertReleases migrates release // InsertReleases migrates release
func InsertReleases(rels ...*Release) error { func InsertReleases(rels ...*Release) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -233,7 +233,7 @@ func migratedIssueCond(tp structs.GitServiceType) builder.Cond {
// UpdateReviewsMigrationsByType updates reviews' migrations information via given git service type and original id and poster id // UpdateReviewsMigrationsByType updates reviews' migrations information via given git service type and original id and poster id
func UpdateReviewsMigrationsByType(tp structs.GitServiceType, originalAuthorID string, posterID int64) error { func UpdateReviewsMigrationsByType(tp structs.GitServiceType, originalAuthorID string, posterID int64) error {
_, err := db.DefaultContext().Engine().Table("review"). _, err := db.GetEngine(db.DefaultContext).Table("review").
Where("original_author_id = ?", originalAuthorID). Where("original_author_id = ?", originalAuthorID).
And(migratedIssueCond(tp)). And(migratedIssueCond(tp)).
Update(map[string]interface{}{ Update(map[string]interface{}{

View File

@ -127,17 +127,17 @@ func getNotifications(e db.Engine, options *FindNotificationOptions) (nl Notific
// GetNotifications returns all notifications that fit to the given options. // GetNotifications returns all notifications that fit to the given options.
func GetNotifications(opts *FindNotificationOptions) (NotificationList, error) { func GetNotifications(opts *FindNotificationOptions) (NotificationList, error) {
return getNotifications(db.DefaultContext().Engine(), opts) return getNotifications(db.GetEngine(db.DefaultContext), opts)
} }
// CountNotifications count all notifications that fit to the given options and ignore pagination. // CountNotifications count all notifications that fit to the given options and ignore pagination.
func CountNotifications(opts *FindNotificationOptions) (int64, error) { func CountNotifications(opts *FindNotificationOptions) (int64, error) {
return db.DefaultContext().Engine().Where(opts.ToCond()).Count(&Notification{}) return db.GetEngine(db.DefaultContext).Where(opts.ToCond()).Count(&Notification{})
} }
// CreateRepoTransferNotification creates notification for the user a repository was transferred to // CreateRepoTransferNotification creates notification for the user a repository was transferred to
func CreateRepoTransferNotification(doer, newOwner *User, repo *Repository) error { func CreateRepoTransferNotification(doer, newOwner *User, repo *Repository) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -179,7 +179,7 @@ func CreateRepoTransferNotification(doer, newOwner *User, repo *Repository) erro
// for each watcher, or updates it if already exists // for each watcher, or updates it if already exists
// receiverID > 0 just send to reciver, else send to all watcher // receiverID > 0 just send to reciver, else send to all watcher
func CreateOrUpdateIssueNotifications(issueID, commentID, notificationAuthorID, receiverID int64) error { func CreateOrUpdateIssueNotifications(issueID, commentID, notificationAuthorID, receiverID int64) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -352,7 +352,7 @@ func getIssueNotification(e db.Engine, userID, issueID int64) (*Notification, er
// NotificationsForUser returns notifications for a given user and status // NotificationsForUser returns notifications for a given user and status
func NotificationsForUser(user *User, statuses []NotificationStatus, page, perPage int) (NotificationList, error) { func NotificationsForUser(user *User, statuses []NotificationStatus, page, perPage int) (NotificationList, error) {
return notificationsForUser(db.DefaultContext().Engine(), user, statuses, page, perPage) return notificationsForUser(db.GetEngine(db.DefaultContext), user, statuses, page, perPage)
} }
func notificationsForUser(e db.Engine, user *User, statuses []NotificationStatus, page, perPage int) (notifications []*Notification, err error) { func notificationsForUser(e db.Engine, user *User, statuses []NotificationStatus, page, perPage int) (notifications []*Notification, err error) {
@ -375,7 +375,7 @@ func notificationsForUser(e db.Engine, user *User, statuses []NotificationStatus
// CountUnread count unread notifications for a user // CountUnread count unread notifications for a user
func CountUnread(user *User) int64 { func CountUnread(user *User) int64 {
return countUnread(db.DefaultContext().Engine(), user.ID) return countUnread(db.GetEngine(db.DefaultContext), user.ID)
} }
func countUnread(e db.Engine, userID int64) int64 { func countUnread(e db.Engine, userID int64) int64 {
@ -389,7 +389,7 @@ func countUnread(e db.Engine, userID int64) int64 {
// LoadAttributes load Repo Issue User and Comment if not loaded // LoadAttributes load Repo Issue User and Comment if not loaded
func (n *Notification) LoadAttributes() (err error) { func (n *Notification) LoadAttributes() (err error) {
return n.loadAttributes(db.DefaultContext().Engine()) return n.loadAttributes(db.GetEngine(db.DefaultContext))
} }
func (n *Notification) loadAttributes(e db.Engine) (err error) { func (n *Notification) loadAttributes(e db.Engine) (err error) {
@ -451,12 +451,12 @@ func (n *Notification) loadUser(e db.Engine) (err error) {
// GetRepo returns the repo of the notification // GetRepo returns the repo of the notification
func (n *Notification) GetRepo() (*Repository, error) { func (n *Notification) GetRepo() (*Repository, error) {
return n.Repository, n.loadRepo(db.DefaultContext().Engine()) return n.Repository, n.loadRepo(db.GetEngine(db.DefaultContext))
} }
// GetIssue returns the issue of the notification // GetIssue returns the issue of the notification
func (n *Notification) GetIssue() (*Issue, error) { func (n *Notification) GetIssue() (*Issue, error) {
return n.Issue, n.loadIssue(db.DefaultContext().Engine()) return n.Issue, n.loadIssue(db.GetEngine(db.DefaultContext))
} }
// HTMLURL formats a URL-string to the notification // HTMLURL formats a URL-string to the notification
@ -521,7 +521,7 @@ func (nl NotificationList) LoadRepos() (RepositoryList, []int, error) {
if left < limit { if left < limit {
limit = left limit = left
} }
rows, err := db.DefaultContext().Engine(). rows, err := db.GetEngine(db.DefaultContext).
In("id", repoIDs[:limit]). In("id", repoIDs[:limit]).
Rows(new(Repository)) Rows(new(Repository))
if err != nil { if err != nil {
@ -597,7 +597,7 @@ func (nl NotificationList) LoadIssues() ([]int, error) {
if left < limit { if left < limit {
limit = left limit = left
} }
rows, err := db.DefaultContext().Engine(). rows, err := db.GetEngine(db.DefaultContext).
In("id", issueIDs[:limit]). In("id", issueIDs[:limit]).
Rows(new(Issue)) Rows(new(Issue))
if err != nil { if err != nil {
@ -683,7 +683,7 @@ func (nl NotificationList) LoadComments() ([]int, error) {
if left < limit { if left < limit {
limit = left limit = left
} }
rows, err := db.DefaultContext().Engine(). rows, err := db.GetEngine(db.DefaultContext).
In("id", commentIDs[:limit]). In("id", commentIDs[:limit]).
Rows(new(Comment)) Rows(new(Comment))
if err != nil { if err != nil {
@ -723,7 +723,7 @@ func (nl NotificationList) LoadComments() ([]int, error) {
// GetNotificationCount returns the notification count for user // GetNotificationCount returns the notification count for user
func GetNotificationCount(user *User, status NotificationStatus) (int64, error) { func GetNotificationCount(user *User, status NotificationStatus) (int64, error) {
return getNotificationCount(db.DefaultContext().Engine(), user, status) return getNotificationCount(db.GetEngine(db.DefaultContext), user, status)
} }
func getNotificationCount(e db.Engine, user *User, status NotificationStatus) (count int64, err error) { func getNotificationCount(e db.Engine, user *User, status NotificationStatus) (count int64, err error) {
@ -746,7 +746,7 @@ func GetUIDsAndNotificationCounts(since, until timeutil.TimeStamp) ([]UserIDCoun
`WHERE user_id IN (SELECT user_id FROM notification WHERE updated_unix >= ? AND ` + `WHERE user_id IN (SELECT user_id FROM notification WHERE updated_unix >= ? AND ` +
`updated_unix < ?) AND status = ? GROUP BY user_id` `updated_unix < ?) AND status = ? GROUP BY user_id`
var res []UserIDCount var res []UserIDCount
return res, db.DefaultContext().Engine().SQL(sql, since, until, NotificationStatusUnread).Find(&res) return res, db.GetEngine(db.DefaultContext).SQL(sql, since, until, NotificationStatusUnread).Find(&res)
} }
func setIssueNotificationStatusReadIfUnread(e db.Engine, userID, issueID int64) error { func setIssueNotificationStatusReadIfUnread(e db.Engine, userID, issueID int64) error {
@ -778,7 +778,7 @@ func setRepoNotificationStatusReadIfUnread(e db.Engine, userID, repoID int64) er
// SetNotificationStatus change the notification status // SetNotificationStatus change the notification status
func SetNotificationStatus(notificationID int64, user *User, status NotificationStatus) (*Notification, error) { func SetNotificationStatus(notificationID int64, user *User, status NotificationStatus) (*Notification, error) {
notification, err := getNotificationByID(db.DefaultContext().Engine(), notificationID) notification, err := getNotificationByID(db.GetEngine(db.DefaultContext), notificationID)
if err != nil { if err != nil {
return notification, err return notification, err
} }
@ -789,13 +789,13 @@ func SetNotificationStatus(notificationID int64, user *User, status Notification
notification.Status = status notification.Status = status
_, err = db.DefaultContext().Engine().ID(notificationID).Update(notification) _, err = db.GetEngine(db.DefaultContext).ID(notificationID).Update(notification)
return notification, err return notification, err
} }
// GetNotificationByID return notification by ID // GetNotificationByID return notification by ID
func GetNotificationByID(notificationID int64) (*Notification, error) { func GetNotificationByID(notificationID int64) (*Notification, error) {
return getNotificationByID(db.DefaultContext().Engine(), notificationID) return getNotificationByID(db.GetEngine(db.DefaultContext), notificationID)
} }
func getNotificationByID(e db.Engine, notificationID int64) (*Notification, error) { func getNotificationByID(e db.Engine, notificationID int64) (*Notification, error) {
@ -817,7 +817,7 @@ func getNotificationByID(e db.Engine, notificationID int64) (*Notification, erro
// UpdateNotificationStatuses updates the statuses of all of a user's notifications that are of the currentStatus type to the desiredStatus // UpdateNotificationStatuses updates the statuses of all of a user's notifications that are of the currentStatus type to the desiredStatus
func UpdateNotificationStatuses(user *User, currentStatus, desiredStatus NotificationStatus) error { func UpdateNotificationStatuses(user *User, currentStatus, desiredStatus NotificationStatus) error {
n := &Notification{Status: desiredStatus, UpdatedBy: user.ID} n := &Notification{Status: desiredStatus, UpdatedBy: user.ID}
_, err := db.DefaultContext().Engine(). _, err := db.GetEngine(db.DefaultContext).
Where("user_id = ? AND status = ?", user.ID, currentStatus). Where("user_id = ? AND status = ?", user.ID, currentStatus).
Cols("status", "updated_by", "updated_unix"). Cols("status", "updated_by", "updated_unix").
Update(n) Update(n)

View File

@ -9,7 +9,7 @@ import "code.gitea.io/gitea/models/db"
// GetActiveOAuth2ProviderLoginSources returns all actived LoginOAuth2 sources // GetActiveOAuth2ProviderLoginSources returns all actived LoginOAuth2 sources
func GetActiveOAuth2ProviderLoginSources() ([]*LoginSource, error) { func GetActiveOAuth2ProviderLoginSources() ([]*LoginSource, error) {
sources := make([]*LoginSource, 0, 1) sources := make([]*LoginSource, 0, 1)
if err := db.DefaultContext().Engine().Where("is_active = ? and type = ?", true, LoginOAuth2).Find(&sources); err != nil { if err := db.GetEngine(db.DefaultContext).Where("is_active = ? and type = ?", true, LoginOAuth2).Find(&sources); err != nil {
return nil, err return nil, err
} }
return sources, nil return sources, nil
@ -18,7 +18,7 @@ func GetActiveOAuth2ProviderLoginSources() ([]*LoginSource, error) {
// GetActiveOAuth2LoginSourceByName returns a OAuth2 LoginSource based on the given name // GetActiveOAuth2LoginSourceByName returns a OAuth2 LoginSource based on the given name
func GetActiveOAuth2LoginSourceByName(name string) (*LoginSource, error) { func GetActiveOAuth2LoginSourceByName(name string) (*LoginSource, error) {
loginSource := new(LoginSource) loginSource := new(LoginSource)
has, err := db.DefaultContext().Engine().Where("name = ? and type = ? and is_active = ?", name, LoginOAuth2, true).Get(loginSource) has, err := db.GetEngine(db.DefaultContext).Where("name = ? and type = ? and is_active = ?", name, LoginOAuth2, true).Get(loginSource)
if !has || err != nil { if !has || err != nil {
return nil, err return nil, err
} }

View File

@ -81,7 +81,7 @@ func (app *OAuth2Application) GenerateClientSecret() (string, error) {
return "", err return "", err
} }
app.ClientSecret = string(hashedSecret) app.ClientSecret = string(hashedSecret)
if _, err := db.DefaultContext().Engine().ID(app.ID).Cols("client_secret").Update(app); err != nil { if _, err := db.GetEngine(db.DefaultContext).ID(app.ID).Cols("client_secret").Update(app); err != nil {
return "", err return "", err
} }
return clientSecret, nil return clientSecret, nil
@ -94,7 +94,7 @@ func (app *OAuth2Application) ValidateClientSecret(secret []byte) bool {
// GetGrantByUserID returns a OAuth2Grant by its user and application ID // GetGrantByUserID returns a OAuth2Grant by its user and application ID
func (app *OAuth2Application) GetGrantByUserID(userID int64) (*OAuth2Grant, error) { func (app *OAuth2Application) GetGrantByUserID(userID int64) (*OAuth2Grant, error) {
return app.getGrantByUserID(db.DefaultContext().Engine(), userID) return app.getGrantByUserID(db.GetEngine(db.DefaultContext), userID)
} }
func (app *OAuth2Application) getGrantByUserID(e db.Engine, userID int64) (grant *OAuth2Grant, err error) { func (app *OAuth2Application) getGrantByUserID(e db.Engine, userID int64) (grant *OAuth2Grant, err error) {
@ -109,7 +109,7 @@ func (app *OAuth2Application) getGrantByUserID(e db.Engine, userID int64) (grant
// CreateGrant generates a grant for an user // CreateGrant generates a grant for an user
func (app *OAuth2Application) CreateGrant(userID int64, scope string) (*OAuth2Grant, error) { func (app *OAuth2Application) CreateGrant(userID int64, scope string) (*OAuth2Grant, error) {
return app.createGrant(db.DefaultContext().Engine(), userID, scope) return app.createGrant(db.GetEngine(db.DefaultContext), userID, scope)
} }
func (app *OAuth2Application) createGrant(e db.Engine, userID int64, scope string) (*OAuth2Grant, error) { func (app *OAuth2Application) createGrant(e db.Engine, userID int64, scope string) (*OAuth2Grant, error) {
@ -127,7 +127,7 @@ func (app *OAuth2Application) createGrant(e db.Engine, userID int64, scope strin
// GetOAuth2ApplicationByClientID returns the oauth2 application with the given client_id. Returns an error if not found. // GetOAuth2ApplicationByClientID returns the oauth2 application with the given client_id. Returns an error if not found.
func GetOAuth2ApplicationByClientID(clientID string) (app *OAuth2Application, err error) { func GetOAuth2ApplicationByClientID(clientID string) (app *OAuth2Application, err error) {
return getOAuth2ApplicationByClientID(db.DefaultContext().Engine(), clientID) return getOAuth2ApplicationByClientID(db.GetEngine(db.DefaultContext), clientID)
} }
func getOAuth2ApplicationByClientID(e db.Engine, clientID string) (app *OAuth2Application, err error) { func getOAuth2ApplicationByClientID(e db.Engine, clientID string) (app *OAuth2Application, err error) {
@ -141,7 +141,7 @@ func getOAuth2ApplicationByClientID(e db.Engine, clientID string) (app *OAuth2Ap
// GetOAuth2ApplicationByID returns the oauth2 application with the given id. Returns an error if not found. // GetOAuth2ApplicationByID returns the oauth2 application with the given id. Returns an error if not found.
func GetOAuth2ApplicationByID(id int64) (app *OAuth2Application, err error) { func GetOAuth2ApplicationByID(id int64) (app *OAuth2Application, err error) {
return getOAuth2ApplicationByID(db.DefaultContext().Engine(), id) return getOAuth2ApplicationByID(db.GetEngine(db.DefaultContext), id)
} }
func getOAuth2ApplicationByID(e db.Engine, id int64) (app *OAuth2Application, err error) { func getOAuth2ApplicationByID(e db.Engine, id int64) (app *OAuth2Application, err error) {
@ -158,7 +158,7 @@ func getOAuth2ApplicationByID(e db.Engine, id int64) (app *OAuth2Application, er
// GetOAuth2ApplicationsByUserID returns all oauth2 applications owned by the user // GetOAuth2ApplicationsByUserID returns all oauth2 applications owned by the user
func GetOAuth2ApplicationsByUserID(userID int64) (apps []*OAuth2Application, err error) { func GetOAuth2ApplicationsByUserID(userID int64) (apps []*OAuth2Application, err error) {
return getOAuth2ApplicationsByUserID(db.DefaultContext().Engine(), userID) return getOAuth2ApplicationsByUserID(db.GetEngine(db.DefaultContext), userID)
} }
func getOAuth2ApplicationsByUserID(e db.Engine, userID int64) (apps []*OAuth2Application, err error) { func getOAuth2ApplicationsByUserID(e db.Engine, userID int64) (apps []*OAuth2Application, err error) {
@ -176,7 +176,7 @@ type CreateOAuth2ApplicationOptions struct {
// CreateOAuth2Application inserts a new oauth2 application // CreateOAuth2Application inserts a new oauth2 application
func CreateOAuth2Application(opts CreateOAuth2ApplicationOptions) (*OAuth2Application, error) { func CreateOAuth2Application(opts CreateOAuth2ApplicationOptions) (*OAuth2Application, error) {
return createOAuth2Application(db.DefaultContext().Engine(), opts) return createOAuth2Application(db.GetEngine(db.DefaultContext), opts)
} }
func createOAuth2Application(e db.Engine, opts CreateOAuth2ApplicationOptions) (*OAuth2Application, error) { func createOAuth2Application(e db.Engine, opts CreateOAuth2ApplicationOptions) (*OAuth2Application, error) {
@ -203,7 +203,7 @@ type UpdateOAuth2ApplicationOptions struct {
// UpdateOAuth2Application updates an oauth2 application // UpdateOAuth2Application updates an oauth2 application
func UpdateOAuth2Application(opts UpdateOAuth2ApplicationOptions) (*OAuth2Application, error) { func UpdateOAuth2Application(opts UpdateOAuth2ApplicationOptions) (*OAuth2Application, error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return nil, err return nil, err
} }
@ -264,7 +264,7 @@ func deleteOAuth2Application(sess *xorm.Session, id, userid int64) error {
// DeleteOAuth2Application deletes the application with the given id and the grants and auth codes related to it. It checks if the userid was the creator of the app. // DeleteOAuth2Application deletes the application with the given id and the grants and auth codes related to it. It checks if the userid was the creator of the app.
func DeleteOAuth2Application(id, userid int64) error { func DeleteOAuth2Application(id, userid int64) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -277,7 +277,7 @@ func DeleteOAuth2Application(id, userid int64) error {
// ListOAuth2Applications returns a list of oauth2 applications belongs to given user. // ListOAuth2Applications returns a list of oauth2 applications belongs to given user.
func ListOAuth2Applications(uid int64, listOptions ListOptions) ([]*OAuth2Application, int64, error) { func ListOAuth2Applications(uid int64, listOptions ListOptions) ([]*OAuth2Application, int64, error) {
sess := db.DefaultContext().Engine(). sess := db.GetEngine(db.DefaultContext).
Where("uid=?", uid). Where("uid=?", uid).
Desc("id") Desc("id")
@ -329,7 +329,7 @@ func (code *OAuth2AuthorizationCode) GenerateRedirectURI(state string) (redirect
// Invalidate deletes the auth code from the database to invalidate this code // Invalidate deletes the auth code from the database to invalidate this code
func (code *OAuth2AuthorizationCode) Invalidate() error { func (code *OAuth2AuthorizationCode) Invalidate() error {
return code.invalidate(db.DefaultContext().Engine()) return code.invalidate(db.GetEngine(db.DefaultContext))
} }
func (code *OAuth2AuthorizationCode) invalidate(e db.Engine) error { func (code *OAuth2AuthorizationCode) invalidate(e db.Engine) error {
@ -361,7 +361,7 @@ func (code *OAuth2AuthorizationCode) validateCodeChallenge(verifier string) bool
// GetOAuth2AuthorizationByCode returns an authorization by its code // GetOAuth2AuthorizationByCode returns an authorization by its code
func GetOAuth2AuthorizationByCode(code string) (*OAuth2AuthorizationCode, error) { func GetOAuth2AuthorizationByCode(code string) (*OAuth2AuthorizationCode, error) {
return getOAuth2AuthorizationByCode(db.DefaultContext().Engine(), code) return getOAuth2AuthorizationByCode(db.GetEngine(db.DefaultContext), code)
} }
func getOAuth2AuthorizationByCode(e db.Engine, code string) (auth *OAuth2AuthorizationCode, err error) { func getOAuth2AuthorizationByCode(e db.Engine, code string) (auth *OAuth2AuthorizationCode, err error) {
@ -402,7 +402,7 @@ func (grant *OAuth2Grant) TableName() string {
// GenerateNewAuthorizationCode generates a new authorization code for a grant and saves it to the database // GenerateNewAuthorizationCode generates a new authorization code for a grant and saves it to the database
func (grant *OAuth2Grant) GenerateNewAuthorizationCode(redirectURI, codeChallenge, codeChallengeMethod string) (*OAuth2AuthorizationCode, error) { func (grant *OAuth2Grant) GenerateNewAuthorizationCode(redirectURI, codeChallenge, codeChallengeMethod string) (*OAuth2AuthorizationCode, error) {
return grant.generateNewAuthorizationCode(db.DefaultContext().Engine(), redirectURI, codeChallenge, codeChallengeMethod) return grant.generateNewAuthorizationCode(db.GetEngine(db.DefaultContext), redirectURI, codeChallenge, codeChallengeMethod)
} }
func (grant *OAuth2Grant) generateNewAuthorizationCode(e db.Engine, redirectURI, codeChallenge, codeChallengeMethod string) (code *OAuth2AuthorizationCode, err error) { func (grant *OAuth2Grant) generateNewAuthorizationCode(e db.Engine, redirectURI, codeChallenge, codeChallengeMethod string) (code *OAuth2AuthorizationCode, err error) {
@ -426,7 +426,7 @@ func (grant *OAuth2Grant) generateNewAuthorizationCode(e db.Engine, redirectURI,
// IncreaseCounter increases the counter and updates the grant // IncreaseCounter increases the counter and updates the grant
func (grant *OAuth2Grant) IncreaseCounter() error { func (grant *OAuth2Grant) IncreaseCounter() error {
return grant.increaseCount(db.DefaultContext().Engine()) return grant.increaseCount(db.GetEngine(db.DefaultContext))
} }
func (grant *OAuth2Grant) increaseCount(e db.Engine) error { func (grant *OAuth2Grant) increaseCount(e db.Engine) error {
@ -454,7 +454,7 @@ func (grant *OAuth2Grant) ScopeContains(scope string) bool {
// SetNonce updates the current nonce value of a grant // SetNonce updates the current nonce value of a grant
func (grant *OAuth2Grant) SetNonce(nonce string) error { func (grant *OAuth2Grant) SetNonce(nonce string) error {
return grant.setNonce(db.DefaultContext().Engine(), nonce) return grant.setNonce(db.GetEngine(db.DefaultContext), nonce)
} }
func (grant *OAuth2Grant) setNonce(e db.Engine, nonce string) error { func (grant *OAuth2Grant) setNonce(e db.Engine, nonce string) error {
@ -468,7 +468,7 @@ func (grant *OAuth2Grant) setNonce(e db.Engine, nonce string) error {
// GetOAuth2GrantByID returns the grant with the given ID // GetOAuth2GrantByID returns the grant with the given ID
func GetOAuth2GrantByID(id int64) (*OAuth2Grant, error) { func GetOAuth2GrantByID(id int64) (*OAuth2Grant, error) {
return getOAuth2GrantByID(db.DefaultContext().Engine(), id) return getOAuth2GrantByID(db.GetEngine(db.DefaultContext), id)
} }
func getOAuth2GrantByID(e db.Engine, id int64) (grant *OAuth2Grant, err error) { func getOAuth2GrantByID(e db.Engine, id int64) (grant *OAuth2Grant, err error) {
@ -483,7 +483,7 @@ func getOAuth2GrantByID(e db.Engine, id int64) (grant *OAuth2Grant, err error) {
// GetOAuth2GrantsByUserID lists all grants of a certain user // GetOAuth2GrantsByUserID lists all grants of a certain user
func GetOAuth2GrantsByUserID(uid int64) ([]*OAuth2Grant, error) { func GetOAuth2GrantsByUserID(uid int64) ([]*OAuth2Grant, error) {
return getOAuth2GrantsByUserID(db.DefaultContext().Engine(), uid) return getOAuth2GrantsByUserID(db.GetEngine(db.DefaultContext), uid)
} }
func getOAuth2GrantsByUserID(e db.Engine, uid int64) ([]*OAuth2Grant, error) { func getOAuth2GrantsByUserID(e db.Engine, uid int64) ([]*OAuth2Grant, error) {
@ -515,7 +515,7 @@ func getOAuth2GrantsByUserID(e db.Engine, uid int64) ([]*OAuth2Grant, error) {
// RevokeOAuth2Grant deletes the grant with grantID and userID // RevokeOAuth2Grant deletes the grant with grantID and userID
func RevokeOAuth2Grant(grantID, userID int64) error { func RevokeOAuth2Grant(grantID, userID int64) error {
return revokeOAuth2Grant(db.DefaultContext().Engine(), grantID, userID) return revokeOAuth2Grant(db.GetEngine(db.DefaultContext), grantID, userID)
} }
func revokeOAuth2Grant(e db.Engine, grantID, userID int64) error { func revokeOAuth2Grant(e db.Engine, grantID, userID int64) error {

View File

@ -41,7 +41,7 @@ func (org *User) getTeam(e db.Engine, name string) (*Team, error) {
// GetTeam returns named team of organization. // GetTeam returns named team of organization.
func (org *User) GetTeam(name string) (*Team, error) { func (org *User) GetTeam(name string) (*Team, error) {
return org.getTeam(db.DefaultContext().Engine(), name) return org.getTeam(db.GetEngine(db.DefaultContext), name)
} }
func (org *User) getOwnerTeam(e db.Engine) (*Team, error) { func (org *User) getOwnerTeam(e db.Engine) (*Team, error) {
@ -50,7 +50,7 @@ func (org *User) getOwnerTeam(e db.Engine) (*Team, error) {
// GetOwnerTeam returns owner team of organization. // GetOwnerTeam returns owner team of organization.
func (org *User) GetOwnerTeam() (*Team, error) { func (org *User) GetOwnerTeam() (*Team, error) {
return org.getOwnerTeam(db.DefaultContext().Engine()) return org.getOwnerTeam(db.GetEngine(db.DefaultContext))
} }
func (org *User) loadTeams(e db.Engine) error { func (org *User) loadTeams(e db.Engine) error {
@ -65,7 +65,7 @@ func (org *User) loadTeams(e db.Engine) error {
// LoadTeams load teams if not loaded. // LoadTeams load teams if not loaded.
func (org *User) LoadTeams() error { func (org *User) LoadTeams() error {
return org.loadTeams(db.DefaultContext().Engine()) return org.loadTeams(db.GetEngine(db.DefaultContext))
} }
// GetMembers returns all members of organization. // GetMembers returns all members of organization.
@ -85,7 +85,7 @@ type FindOrgMembersOpts struct {
// CountOrgMembers counts the organization's members // CountOrgMembers counts the organization's members
func CountOrgMembers(opts *FindOrgMembersOpts) (int64, error) { func CountOrgMembers(opts *FindOrgMembersOpts) (int64, error) {
sess := db.DefaultContext().Engine().Where("org_id=?", opts.OrgID) sess := db.GetEngine(db.DefaultContext).Where("org_id=?", opts.OrgID)
if opts.PublicOnly { if opts.PublicOnly {
sess.And("is_public = ?", true) sess.And("is_public = ?", true)
} }
@ -129,7 +129,7 @@ func (org *User) removeOrgRepo(e db.Engine, repoID int64) error {
// RemoveOrgRepo removes all team-repository relations of organization. // RemoveOrgRepo removes all team-repository relations of organization.
func (org *User) RemoveOrgRepo(repoID int64) error { func (org *User) RemoveOrgRepo(repoID int64) error {
return org.removeOrgRepo(db.DefaultContext().Engine(), repoID) return org.removeOrgRepo(db.GetEngine(db.DefaultContext), repoID)
} }
// CreateOrganization creates record of a new organization. // CreateOrganization creates record of a new organization.
@ -162,7 +162,7 @@ func CreateOrganization(org, owner *User) (err error) {
org.NumMembers = 1 org.NumMembers = 1
org.Type = UserTypeOrganization org.Type = UserTypeOrganization
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -238,7 +238,7 @@ func GetOrgByName(name string) (*User, error) {
LowerName: strings.ToLower(name), LowerName: strings.ToLower(name),
Type: UserTypeOrganization, Type: UserTypeOrganization,
} }
has, err := db.DefaultContext().Engine().Get(u) has, err := db.GetEngine(db.DefaultContext).Get(u)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -249,7 +249,7 @@ func GetOrgByName(name string) (*User, error) {
// CountOrganizations returns number of organizations. // CountOrganizations returns number of organizations.
func CountOrganizations() int64 { func CountOrganizations() int64 {
count, _ := db.DefaultContext().Engine(). count, _ := db.GetEngine(db.DefaultContext).
Where("type=1"). Where("type=1").
Count(new(User)) Count(new(User))
return count return count
@ -261,7 +261,7 @@ func DeleteOrganization(org *User) (err error) {
return fmt.Errorf("%s is a user not an organization", org.Name) return fmt.Errorf("%s is a user not an organization", org.Name)
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
@ -353,12 +353,12 @@ func isOrganizationOwner(e db.Engine, orgID, uid int64) (bool, error) {
// IsOrganizationOwner returns true if given user is in the owner team. // IsOrganizationOwner returns true if given user is in the owner team.
func IsOrganizationOwner(orgID, uid int64) (bool, error) { func IsOrganizationOwner(orgID, uid int64) (bool, error) {
return isOrganizationOwner(db.DefaultContext().Engine(), orgID, uid) return isOrganizationOwner(db.GetEngine(db.DefaultContext), orgID, uid)
} }
// IsOrganizationMember returns true if given user is member of organization. // IsOrganizationMember returns true if given user is member of organization.
func IsOrganizationMember(orgID, uid int64) (bool, error) { func IsOrganizationMember(orgID, uid int64) (bool, error) {
return isOrganizationMember(db.DefaultContext().Engine(), orgID, uid) return isOrganizationMember(db.GetEngine(db.DefaultContext), orgID, uid)
} }
func isOrganizationMember(e db.Engine, orgID, uid int64) (bool, error) { func isOrganizationMember(e db.Engine, orgID, uid int64) (bool, error) {
@ -371,7 +371,7 @@ func isOrganizationMember(e db.Engine, orgID, uid int64) (bool, error) {
// IsPublicMembership returns true if given user public his/her membership. // IsPublicMembership returns true if given user public his/her membership.
func IsPublicMembership(orgID, uid int64) (bool, error) { func IsPublicMembership(orgID, uid int64) (bool, error) {
return db.DefaultContext().Engine(). return db.GetEngine(db.DefaultContext).
Where("uid=?", uid). Where("uid=?", uid).
And("org_id=?", orgID). And("org_id=?", orgID).
And("is_public=?", true). And("is_public=?", true).
@ -384,7 +384,7 @@ func CanCreateOrgRepo(orgID, uid int64) (bool, error) {
if owner, err := IsOrganizationOwner(orgID, uid); owner || err != nil { if owner, err := IsOrganizationOwner(orgID, uid); owner || err != nil {
return owner, err return owner, err
} }
return db.DefaultContext().Engine(). return db.GetEngine(db.DefaultContext).
Where(builder.Eq{"team.can_create_org_repo": true}). Where(builder.Eq{"team.can_create_org_repo": true}).
Join("INNER", "team_user", "team_user.team_id = team.id"). Join("INNER", "team_user", "team_user.team_id = team.id").
And("team_user.uid = ?", uid). And("team_user.uid = ?", uid).
@ -394,12 +394,12 @@ func CanCreateOrgRepo(orgID, uid int64) (bool, error) {
// GetUsersWhoCanCreateOrgRepo returns users which are able to create repo in organization // GetUsersWhoCanCreateOrgRepo returns users which are able to create repo in organization
func GetUsersWhoCanCreateOrgRepo(orgID int64) ([]*User, error) { func GetUsersWhoCanCreateOrgRepo(orgID int64) ([]*User, error) {
return getUsersWhoCanCreateOrgRepo(db.DefaultContext().Engine(), orgID) return getUsersWhoCanCreateOrgRepo(db.GetEngine(db.DefaultContext), orgID)
} }
func getUsersWhoCanCreateOrgRepo(e db.Engine, orgID int64) ([]*User, error) { func getUsersWhoCanCreateOrgRepo(e db.Engine, orgID int64) ([]*User, error) {
users := make([]*User, 0, 10) users := make([]*User, 0, 10)
return users, db.DefaultContext().Engine(). return users, db.GetEngine(db.DefaultContext).
Join("INNER", "`team_user`", "`team_user`.uid=`user`.id"). Join("INNER", "`team_user`", "`team_user`.uid=`user`.id").
Join("INNER", "`team`", "`team`.id=`team_user`.team_id"). Join("INNER", "`team`", "`team`.id=`team_user`.team_id").
Where(builder.Eq{"team.can_create_org_repo": true}.Or(builder.Eq{"team.authorize": AccessModeOwner})). Where(builder.Eq{"team.can_create_org_repo": true}.Or(builder.Eq{"team.authorize": AccessModeOwner})).
@ -421,7 +421,7 @@ func getOrgsByUserID(sess *xorm.Session, userID int64, showAll bool) ([]*User, e
// GetOrgsByUserID returns a list of organizations that the given user ID // GetOrgsByUserID returns a list of organizations that the given user ID
// has joined. // has joined.
func GetOrgsByUserID(userID int64, showAll bool) ([]*User, error) { func GetOrgsByUserID(userID int64, showAll bool) ([]*User, error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
return getOrgsByUserID(sess, userID, showAll) return getOrgsByUserID(sess, userID, showAll)
} }
@ -431,7 +431,7 @@ type MinimalOrg = User
// GetUserOrgsList returns one user's all orgs list // GetUserOrgsList returns one user's all orgs list
func GetUserOrgsList(user *User) ([]*MinimalOrg, error) { func GetUserOrgsList(user *User) ([]*MinimalOrg, error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
schema, err := db.TableInfo(new(User)) schema, err := db.TableInfo(new(User))
@ -502,7 +502,7 @@ func getOwnedOrgsByUserID(sess *xorm.Session, userID int64) ([]*User, error) {
// HasOrgOrUserVisible tells if the given user can see the given org or user // HasOrgOrUserVisible tells if the given user can see the given org or user
func HasOrgOrUserVisible(org, user *User) bool { func HasOrgOrUserVisible(org, user *User) bool {
return hasOrgOrUserVisible(db.DefaultContext().Engine(), org, user) return hasOrgOrUserVisible(db.GetEngine(db.DefaultContext), org, user)
} }
func hasOrgOrUserVisible(e db.Engine, orgOrUser, user *User) bool { func hasOrgOrUserVisible(e db.Engine, orgOrUser, user *User) bool {
@ -537,7 +537,7 @@ func HasOrgsVisible(orgs []*User, user *User) bool {
// GetOwnedOrgsByUserID returns a list of organizations are owned by given user ID. // GetOwnedOrgsByUserID returns a list of organizations are owned by given user ID.
func GetOwnedOrgsByUserID(userID int64) ([]*User, error) { func GetOwnedOrgsByUserID(userID int64) ([]*User, error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
return getOwnedOrgsByUserID(sess, userID) return getOwnedOrgsByUserID(sess, userID)
} }
@ -545,7 +545,7 @@ func GetOwnedOrgsByUserID(userID int64) ([]*User, error) {
// GetOwnedOrgsByUserIDDesc returns a list of organizations are owned by // GetOwnedOrgsByUserIDDesc returns a list of organizations are owned by
// given user ID, ordered descending by the given condition. // given user ID, ordered descending by the given condition.
func GetOwnedOrgsByUserIDDesc(userID int64, desc string) ([]*User, error) { func GetOwnedOrgsByUserIDDesc(userID int64, desc string) ([]*User, error) {
return getOwnedOrgsByUserID(db.DefaultContext().Engine().Desc(desc), userID) return getOwnedOrgsByUserID(db.GetEngine(db.DefaultContext).Desc(desc), userID)
} }
// GetOrgsCanCreateRepoByUserID returns a list of organizations where given user ID // GetOrgsCanCreateRepoByUserID returns a list of organizations where given user ID
@ -553,7 +553,7 @@ func GetOwnedOrgsByUserIDDesc(userID int64, desc string) ([]*User, error) {
func GetOrgsCanCreateRepoByUserID(userID int64) ([]*User, error) { func GetOrgsCanCreateRepoByUserID(userID int64) ([]*User, error) {
orgs := make([]*User, 0, 10) orgs := make([]*User, 0, 10)
return orgs, db.DefaultContext().Engine().Where(builder.In("id", builder.Select("`user`.id").From("`user`"). return orgs, db.GetEngine(db.DefaultContext).Where(builder.In("id", builder.Select("`user`.id").From("`user`").
Join("INNER", "`team_user`", "`team_user`.org_id = `user`.id"). Join("INNER", "`team_user`", "`team_user`.org_id = `user`.id").
Join("INNER", "`team`", "`team`.id = `team_user`.team_id"). Join("INNER", "`team`", "`team`.id = `team_user`.team_id").
Where(builder.Eq{"`team_user`.uid": userID}). Where(builder.Eq{"`team_user`.uid": userID}).
@ -565,7 +565,7 @@ func GetOrgsCanCreateRepoByUserID(userID int64) ([]*User, error) {
// GetOrgUsersByUserID returns all organization-user relations by user ID. // GetOrgUsersByUserID returns all organization-user relations by user ID.
func GetOrgUsersByUserID(uid int64, opts *SearchOrganizationsOptions) ([]*OrgUser, error) { func GetOrgUsersByUserID(uid int64, opts *SearchOrganizationsOptions) ([]*OrgUser, error) {
ous := make([]*OrgUser, 0, 10) ous := make([]*OrgUser, 0, 10)
sess := db.DefaultContext().Engine(). sess := db.GetEngine(db.DefaultContext).
Join("LEFT", "`user`", "`org_user`.org_id=`user`.id"). Join("LEFT", "`user`", "`org_user`.org_id=`user`.id").
Where("`org_user`.uid=?", uid) Where("`org_user`.uid=?", uid)
if !opts.All { if !opts.All {
@ -585,7 +585,7 @@ func GetOrgUsersByUserID(uid int64, opts *SearchOrganizationsOptions) ([]*OrgUse
// GetOrgUsersByOrgID returns all organization-user relations by organization ID. // GetOrgUsersByOrgID returns all organization-user relations by organization ID.
func GetOrgUsersByOrgID(opts *FindOrgMembersOpts) ([]*OrgUser, error) { func GetOrgUsersByOrgID(opts *FindOrgMembersOpts) ([]*OrgUser, error) {
return getOrgUsersByOrgID(db.DefaultContext().Engine(), opts) return getOrgUsersByOrgID(db.GetEngine(db.DefaultContext), opts)
} }
func getOrgUsersByOrgID(e db.Engine, opts *FindOrgMembersOpts) ([]*OrgUser, error) { func getOrgUsersByOrgID(e db.Engine, opts *FindOrgMembersOpts) ([]*OrgUser, error) {
@ -607,7 +607,7 @@ func getOrgUsersByOrgID(e db.Engine, opts *FindOrgMembersOpts) ([]*OrgUser, erro
// ChangeOrgUserStatus changes public or private membership status. // ChangeOrgUserStatus changes public or private membership status.
func ChangeOrgUserStatus(orgID, uid int64, public bool) error { func ChangeOrgUserStatus(orgID, uid int64, public bool) error {
ou := new(OrgUser) ou := new(OrgUser)
has, err := db.DefaultContext().Engine(). has, err := db.GetEngine(db.DefaultContext).
Where("uid=?", uid). Where("uid=?", uid).
And("org_id=?", orgID). And("org_id=?", orgID).
Get(ou) Get(ou)
@ -618,7 +618,7 @@ func ChangeOrgUserStatus(orgID, uid int64, public bool) error {
} }
ou.IsPublic = public ou.IsPublic = public
_, err = db.DefaultContext().Engine().ID(ou.ID).Cols("is_public").Update(ou) _, err = db.GetEngine(db.DefaultContext).ID(ou.ID).Cols("is_public").Update(ou)
return err return err
} }
@ -629,7 +629,7 @@ func AddOrgUser(orgID, uid int64) error {
return err return err
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -738,7 +738,7 @@ func removeOrgUser(sess *xorm.Session, orgID, userID int64) error {
// RemoveOrgUser removes user from given organization. // RemoveOrgUser removes user from given organization.
func RemoveOrgUser(orgID, userID int64) error { func RemoveOrgUser(orgID, userID int64) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -805,13 +805,13 @@ func (org *User) TeamsWithAccessToRepo(repoID int64, mode AccessMode) ([]*Team,
// GetUserTeamIDs returns of all team IDs of the organization that user is member of. // GetUserTeamIDs returns of all team IDs of the organization that user is member of.
func (org *User) GetUserTeamIDs(userID int64) ([]int64, error) { func (org *User) GetUserTeamIDs(userID int64) ([]int64, error) {
return org.getUserTeamIDs(db.DefaultContext().Engine(), userID) return org.getUserTeamIDs(db.GetEngine(db.DefaultContext), userID)
} }
// GetUserTeams returns all teams that belong to user, // GetUserTeams returns all teams that belong to user,
// and that the user has joined. // and that the user has joined.
func (org *User) GetUserTeams(userID int64) ([]*Team, error) { func (org *User) GetUserTeams(userID int64) ([]*Team, error) {
return org.getUserTeams(db.DefaultContext().Engine(), userID) return org.getUserTeams(db.GetEngine(db.DefaultContext), userID)
} }
// AccessibleReposEnvironment operations involving the repositories that are // AccessibleReposEnvironment operations involving the repositories that are
@ -838,7 +838,7 @@ type accessibleReposEnv struct {
// AccessibleReposEnv builds an AccessibleReposEnvironment for the repositories in `org` // AccessibleReposEnv builds an AccessibleReposEnvironment for the repositories in `org`
// that are accessible to the specified user. // that are accessible to the specified user.
func (org *User) AccessibleReposEnv(userID int64) (AccessibleReposEnvironment, error) { func (org *User) AccessibleReposEnv(userID int64) (AccessibleReposEnvironment, error) {
return org.accessibleReposEnv(db.DefaultContext().Engine(), userID) return org.accessibleReposEnv(db.GetEngine(db.DefaultContext), userID)
} }
func (org *User) accessibleReposEnv(e db.Engine, userID int64) (AccessibleReposEnvironment, error) { func (org *User) accessibleReposEnv(e db.Engine, userID int64) (AccessibleReposEnvironment, error) {
@ -871,7 +871,7 @@ func (org *User) AccessibleTeamReposEnv(team *Team) AccessibleReposEnvironment {
return &accessibleReposEnv{ return &accessibleReposEnv{
org: org, org: org,
team: team, team: team,
e: db.DefaultContext().Engine(), e: db.GetEngine(db.DefaultContext),
orderBy: SearchOrderByRecentUpdated, orderBy: SearchOrderByRecentUpdated,
} }
} }

View File

@ -82,7 +82,7 @@ func SearchTeam(opts *SearchTeamOptions) ([]*Team, int64, error) {
cond = cond.And(builder.Eq{"org_id": opts.OrgID}) cond = cond.And(builder.Eq{"org_id": opts.OrgID})
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
count, err := sess. count, err := sess.
@ -120,7 +120,7 @@ func (t *Team) ColorFormat(s fmt.State) {
// GetUnits return a list of available units for a team // GetUnits return a list of available units for a team
func (t *Team) GetUnits() error { func (t *Team) GetUnits() error {
return t.getUnits(db.DefaultContext().Engine()) return t.getUnits(db.GetEngine(db.DefaultContext))
} }
func (t *Team) getUnits(e db.Engine) (err error) { func (t *Team) getUnits(e db.Engine) (err error) {
@ -173,7 +173,7 @@ func (t *Team) getRepositories(e db.Engine) error {
// GetRepositories returns paginated repositories in team of organization. // GetRepositories returns paginated repositories in team of organization.
func (t *Team) GetRepositories(opts *SearchTeamOptions) error { func (t *Team) GetRepositories(opts *SearchTeamOptions) error {
if opts.Page == 0 { if opts.Page == 0 {
return t.getRepositories(db.DefaultContext().Engine()) return t.getRepositories(db.GetEngine(db.DefaultContext))
} }
return t.getRepositories(getPaginatedSession(opts)) return t.getRepositories(getPaginatedSession(opts))
@ -187,7 +187,7 @@ func (t *Team) getMembers(e db.Engine) (err error) {
// GetMembers returns paginated members in team of organization. // GetMembers returns paginated members in team of organization.
func (t *Team) GetMembers(opts *SearchMembersOptions) (err error) { func (t *Team) GetMembers(opts *SearchMembersOptions) (err error) {
if opts.Page == 0 { if opts.Page == 0 {
return t.getMembers(db.DefaultContext().Engine()) return t.getMembers(db.GetEngine(db.DefaultContext))
} }
return t.getMembers(getPaginatedSession(opts)) return t.getMembers(getPaginatedSession(opts))
@ -210,7 +210,7 @@ func (t *Team) hasRepository(e db.Engine, repoID int64) bool {
// HasRepository returns true if given repository belong to team. // HasRepository returns true if given repository belong to team.
func (t *Team) HasRepository(repoID int64) bool { func (t *Team) HasRepository(repoID int64) bool {
return t.hasRepository(db.DefaultContext().Engine(), repoID) return t.hasRepository(db.GetEngine(db.DefaultContext), repoID)
} }
func (t *Team) addRepository(e db.Engine, repo *Repository) (err error) { func (t *Team) addRepository(e db.Engine, repo *Repository) (err error) {
@ -264,7 +264,7 @@ func (t *Team) addAllRepositories(e db.Engine) error {
// AddAllRepositories adds all repositories to the team // AddAllRepositories adds all repositories to the team
func (t *Team) AddAllRepositories() (err error) { func (t *Team) AddAllRepositories() (err error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -285,7 +285,7 @@ func (t *Team) AddRepository(repo *Repository) (err error) {
return nil return nil
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -304,7 +304,7 @@ func (t *Team) RemoveAllRepositories() (err error) {
return nil return nil
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -421,7 +421,7 @@ func (t *Team) RemoveRepository(repoID int64) error {
return err return err
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -436,7 +436,7 @@ func (t *Team) RemoveRepository(repoID int64) error {
// UnitEnabled returns if the team has the given unit type enabled // UnitEnabled returns if the team has the given unit type enabled
func (t *Team) UnitEnabled(tp UnitType) bool { func (t *Team) UnitEnabled(tp UnitType) bool {
return t.unitEnabled(db.DefaultContext().Engine(), tp) return t.unitEnabled(db.GetEngine(db.DefaultContext), tp)
} }
func (t *Team) unitEnabled(e db.Engine, tp UnitType) bool { func (t *Team) unitEnabled(e db.Engine, tp UnitType) bool {
@ -473,7 +473,7 @@ func NewTeam(t *Team) (err error) {
return err return err
} }
has, err := db.DefaultContext().Engine().ID(t.OrgID).Get(new(User)) has, err := db.GetEngine(db.DefaultContext).ID(t.OrgID).Get(new(User))
if err != nil { if err != nil {
return err return err
} }
@ -482,7 +482,7 @@ func NewTeam(t *Team) (err error) {
} }
t.LowerName = strings.ToLower(t.Name) t.LowerName = strings.ToLower(t.Name)
has, err = db.DefaultContext().Engine(). has, err = db.GetEngine(db.DefaultContext).
Where("org_id=?", t.OrgID). Where("org_id=?", t.OrgID).
And("lower_name=?", t.LowerName). And("lower_name=?", t.LowerName).
Get(new(Team)) Get(new(Team))
@ -493,7 +493,7 @@ func NewTeam(t *Team) (err error) {
return ErrTeamAlreadyExist{t.OrgID, t.LowerName} return ErrTeamAlreadyExist{t.OrgID, t.LowerName}
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -556,7 +556,7 @@ func getTeam(e db.Engine, orgID int64, name string) (*Team, error) {
// GetTeam returns team by given team name and organization. // GetTeam returns team by given team name and organization.
func GetTeam(orgID int64, name string) (*Team, error) { func GetTeam(orgID int64, name string) (*Team, error) {
return getTeam(db.DefaultContext().Engine(), orgID, name) return getTeam(db.GetEngine(db.DefaultContext), orgID, name)
} }
// GetTeamIDsByNames returns a slice of team ids corresponds to names. // GetTeamIDsByNames returns a slice of team ids corresponds to names.
@ -594,7 +594,7 @@ func getTeamByID(e db.Engine, teamID int64) (*Team, error) {
// GetTeamByID returns team by given ID. // GetTeamByID returns team by given ID.
func GetTeamByID(teamID int64) (*Team, error) { func GetTeamByID(teamID int64) (*Team, error) {
return getTeamByID(db.DefaultContext().Engine(), teamID) return getTeamByID(db.GetEngine(db.DefaultContext), teamID)
} }
// GetTeamNamesByID returns team's lower name from a list of team ids. // GetTeamNamesByID returns team's lower name from a list of team ids.
@ -604,7 +604,7 @@ func GetTeamNamesByID(teamIDs []int64) ([]string, error) {
} }
var teamNames []string var teamNames []string
err := db.DefaultContext().Engine().Table("team"). err := db.GetEngine(db.DefaultContext).Table("team").
Select("lower_name"). Select("lower_name").
In("id", teamIDs). In("id", teamIDs).
Asc("name"). Asc("name").
@ -623,7 +623,7 @@ func UpdateTeam(t *Team, authChanged, includeAllChanged bool) (err error) {
t.Description = t.Description[:255] t.Description = t.Description[:255]
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -697,7 +697,7 @@ func DeleteTeam(t *Team) error {
return err return err
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -764,7 +764,7 @@ func isTeamMember(e db.Engine, orgID, teamID, userID int64) (bool, error) {
// IsTeamMember returns true if given user is a member of team. // IsTeamMember returns true if given user is a member of team.
func IsTeamMember(orgID, teamID, userID int64) (bool, error) { func IsTeamMember(orgID, teamID, userID int64) (bool, error) {
return isTeamMember(db.DefaultContext().Engine(), orgID, teamID, userID) return isTeamMember(db.GetEngine(db.DefaultContext), orgID, teamID, userID)
} }
func getTeamUsersByTeamID(e db.Engine, teamID int64) ([]*TeamUser, error) { func getTeamUsersByTeamID(e db.Engine, teamID int64) ([]*TeamUser, error) {
@ -795,7 +795,7 @@ func getTeamMembers(e db.Engine, teamID int64) (_ []*User, err error) {
// GetTeamMembers returns all members in given team of organization. // GetTeamMembers returns all members in given team of organization.
func GetTeamMembers(teamID int64) ([]*User, error) { func GetTeamMembers(teamID int64) ([]*User, error) {
return getTeamMembers(db.DefaultContext().Engine(), teamID) return getTeamMembers(db.GetEngine(db.DefaultContext), teamID)
} }
func getUserOrgTeams(e db.Engine, orgID, userID int64) (teams []*Team, err error) { func getUserOrgTeams(e db.Engine, orgID, userID int64) (teams []*Team, err error) {
@ -818,7 +818,7 @@ func getUserRepoTeams(e db.Engine, orgID, userID, repoID int64) (teams []*Team,
// GetUserOrgTeams returns all teams that user belongs to in given organization. // GetUserOrgTeams returns all teams that user belongs to in given organization.
func GetUserOrgTeams(orgID, userID int64) ([]*Team, error) { func GetUserOrgTeams(orgID, userID int64) ([]*Team, error) {
return getUserOrgTeams(db.DefaultContext().Engine(), orgID, userID) return getUserOrgTeams(db.GetEngine(db.DefaultContext), orgID, userID)
} }
// AddTeamMember adds new membership of given team to given organization, // AddTeamMember adds new membership of given team to given organization,
@ -838,7 +838,7 @@ func AddTeamMember(team *Team, userID int64) error {
return err return err
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -933,7 +933,7 @@ func removeTeamMember(e *xorm.Session, team *Team, userID int64) error {
// RemoveTeamMember removes member from given team of given organization. // RemoveTeamMember removes member from given team of given organization.
func RemoveTeamMember(team *Team, userID int64) error { func RemoveTeamMember(team *Team, userID int64) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -946,7 +946,7 @@ func RemoveTeamMember(team *Team, userID int64) error {
// IsUserInTeams returns if a user in some teams // IsUserInTeams returns if a user in some teams
func IsUserInTeams(userID int64, teamIDs []int64) (bool, error) { func IsUserInTeams(userID int64, teamIDs []int64) (bool, error) {
return isUserInTeams(db.DefaultContext().Engine(), userID, teamIDs) return isUserInTeams(db.GetEngine(db.DefaultContext), userID, teamIDs)
} }
func isUserInTeams(e db.Engine, userID int64, teamIDs []int64) (bool, error) { func isUserInTeams(e db.Engine, userID int64, teamIDs []int64) (bool, error) {
@ -956,7 +956,7 @@ func isUserInTeams(e db.Engine, userID int64, teamIDs []int64) (bool, error) {
// UsersInTeamsCount counts the number of users which are in userIDs and teamIDs // UsersInTeamsCount counts the number of users which are in userIDs and teamIDs
func UsersInTeamsCount(userIDs, teamIDs []int64) (int64, error) { func UsersInTeamsCount(userIDs, teamIDs []int64) (int64, error) {
var ids []int64 var ids []int64
if err := db.DefaultContext().Engine().In("uid", userIDs).In("team_id", teamIDs). if err := db.GetEngine(db.DefaultContext).In("uid", userIDs).In("team_id", teamIDs).
Table("team_user"). Table("team_user").
Cols("uid").GroupBy("uid").Find(&ids); err != nil { Cols("uid").GroupBy("uid").Find(&ids); err != nil {
return 0, err return 0, err
@ -990,7 +990,7 @@ func hasTeamRepo(e db.Engine, orgID, teamID, repoID int64) bool {
// HasTeamRepo returns true if given repository belongs to team. // HasTeamRepo returns true if given repository belongs to team.
func HasTeamRepo(orgID, teamID, repoID int64) bool { func HasTeamRepo(orgID, teamID, repoID int64) bool {
return hasTeamRepo(db.DefaultContext().Engine(), orgID, teamID, repoID) return hasTeamRepo(db.GetEngine(db.DefaultContext), orgID, teamID, repoID)
} }
func addTeamRepo(e db.Engine, orgID, teamID, repoID int64) error { func addTeamRepo(e db.Engine, orgID, teamID, repoID int64) error {
@ -1013,7 +1013,7 @@ func removeTeamRepo(e db.Engine, teamID, repoID int64) error {
// GetTeamsWithAccessToRepo returns all teams in an organization that have given access level to the repository. // GetTeamsWithAccessToRepo returns all teams in an organization that have given access level to the repository.
func GetTeamsWithAccessToRepo(orgID, repoID int64, mode AccessMode) ([]*Team, error) { func GetTeamsWithAccessToRepo(orgID, repoID int64, mode AccessMode) ([]*Team, error) {
teams := make([]*Team, 0, 5) teams := make([]*Team, 0, 5)
return teams, db.DefaultContext().Engine().Where("team.authorize >= ?", mode). return teams, db.GetEngine(db.DefaultContext).Where("team.authorize >= ?", mode).
Join("INNER", "team_repo", "team_repo.team_id = team.id"). Join("INNER", "team_repo", "team_repo.team_id = team.id").
And("team_repo.org_id = ?", orgID). And("team_repo.org_id = ?", orgID).
And("team_repo.repo_id = ?", repoID). And("team_repo.repo_id = ?", repoID).
@ -1046,7 +1046,7 @@ func getUnitsByTeamID(e db.Engine, teamID int64) (units []*TeamUnit, err error)
// UpdateTeamUnits updates a teams's units // UpdateTeamUnits updates a teams's units
func UpdateTeamUnits(team *Team, units []TeamUnit) (err error) { func UpdateTeamUnits(team *Team, units []TeamUnit) (err error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err

View File

@ -255,7 +255,7 @@ func TestGetOrgByName(t *testing.T) {
func TestCountOrganizations(t *testing.T) { func TestCountOrganizations(t *testing.T) {
assert.NoError(t, db.PrepareTestDatabase()) assert.NoError(t, db.PrepareTestDatabase())
expected, err := db.DefaultContext().Engine().Where("type=?", UserTypeOrganization).Count(&User{}) expected, err := db.GetEngine(db.DefaultContext).Where("type=?", UserTypeOrganization).Count(&User{})
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, expected, CountOrganizations()) assert.Equal(t, expected, CountOrganizations())
} }

View File

@ -90,7 +90,7 @@ type ProjectSearchOptions struct {
// GetProjects returns a list of all projects that have been created in the repository // GetProjects returns a list of all projects that have been created in the repository
func GetProjects(opts ProjectSearchOptions) ([]*Project, int64, error) { func GetProjects(opts ProjectSearchOptions) ([]*Project, int64, error) {
return getProjects(db.DefaultContext().Engine(), opts) return getProjects(db.GetEngine(db.DefaultContext), opts)
} }
func getProjects(e db.Engine, opts ProjectSearchOptions) ([]*Project, int64, error) { func getProjects(e db.Engine, opts ProjectSearchOptions) ([]*Project, int64, error) {
@ -143,7 +143,7 @@ func NewProject(p *Project) error {
return errors.New("project type is not valid") return errors.New("project type is not valid")
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
@ -167,7 +167,7 @@ func NewProject(p *Project) error {
// GetProjectByID returns the projects in a repository // GetProjectByID returns the projects in a repository
func GetProjectByID(id int64) (*Project, error) { func GetProjectByID(id int64) (*Project, error) {
return getProjectByID(db.DefaultContext().Engine(), id) return getProjectByID(db.GetEngine(db.DefaultContext), id)
} }
func getProjectByID(e db.Engine, id int64) (*Project, error) { func getProjectByID(e db.Engine, id int64) (*Project, error) {
@ -185,7 +185,7 @@ func getProjectByID(e db.Engine, id int64) (*Project, error) {
// UpdateProject updates project properties // UpdateProject updates project properties
func UpdateProject(p *Project) error { func UpdateProject(p *Project) error {
return updateProject(db.DefaultContext().Engine(), p) return updateProject(db.GetEngine(db.DefaultContext), p)
} }
func updateProject(e db.Engine, p *Project) error { func updateProject(e db.Engine, p *Project) error {
@ -220,7 +220,7 @@ func updateRepositoryProjectCount(e db.Engine, repoID int64) error {
// ChangeProjectStatusByRepoIDAndID toggles a project between opened and closed // ChangeProjectStatusByRepoIDAndID toggles a project between opened and closed
func ChangeProjectStatusByRepoIDAndID(repoID, projectID int64, isClosed bool) error { func ChangeProjectStatusByRepoIDAndID(repoID, projectID int64, isClosed bool) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -244,7 +244,7 @@ func ChangeProjectStatusByRepoIDAndID(repoID, projectID int64, isClosed bool) er
// ChangeProjectStatus toggle a project between opened and closed // ChangeProjectStatus toggle a project between opened and closed
func ChangeProjectStatus(p *Project, isClosed bool) error { func ChangeProjectStatus(p *Project, isClosed bool) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -273,7 +273,7 @@ func changeProjectStatus(e db.Engine, p *Project, isClosed bool) error {
// DeleteProjectByID deletes a project from a repository. // DeleteProjectByID deletes a project from a repository.
func DeleteProjectByID(id int64) error { func DeleteProjectByID(id int64) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err

View File

@ -100,13 +100,13 @@ func createBoardsForProjectsType(sess *xorm.Session, project *Project) error {
// NewProjectBoard adds a new project board to a given project // NewProjectBoard adds a new project board to a given project
func NewProjectBoard(board *ProjectBoard) error { func NewProjectBoard(board *ProjectBoard) error {
_, err := db.DefaultContext().Engine().Insert(board) _, err := db.GetEngine(db.DefaultContext).Insert(board)
return err return err
} }
// DeleteProjectBoardByID removes all issues references to the project board. // DeleteProjectBoardByID removes all issues references to the project board.
func DeleteProjectBoardByID(boardID int64) error { func DeleteProjectBoardByID(boardID int64) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -146,7 +146,7 @@ func deleteProjectBoardByProjectID(e db.Engine, projectID int64) error {
// GetProjectBoard fetches the current board of a project // GetProjectBoard fetches the current board of a project
func GetProjectBoard(boardID int64) (*ProjectBoard, error) { func GetProjectBoard(boardID int64) (*ProjectBoard, error) {
return getProjectBoard(db.DefaultContext().Engine(), boardID) return getProjectBoard(db.GetEngine(db.DefaultContext), boardID)
} }
func getProjectBoard(e db.Engine, boardID int64) (*ProjectBoard, error) { func getProjectBoard(e db.Engine, boardID int64) (*ProjectBoard, error) {
@ -164,7 +164,7 @@ func getProjectBoard(e db.Engine, boardID int64) (*ProjectBoard, error) {
// UpdateProjectBoard updates a project board // UpdateProjectBoard updates a project board
func UpdateProjectBoard(board *ProjectBoard) error { func UpdateProjectBoard(board *ProjectBoard) error {
return updateProjectBoard(db.DefaultContext().Engine(), board) return updateProjectBoard(db.GetEngine(db.DefaultContext), board)
} }
func updateProjectBoard(e db.Engine, board *ProjectBoard) error { func updateProjectBoard(e db.Engine, board *ProjectBoard) error {
@ -186,7 +186,7 @@ func updateProjectBoard(e db.Engine, board *ProjectBoard) error {
// GetProjectBoards fetches all boards related to a project // GetProjectBoards fetches all boards related to a project
// if no default board set, first board is a temporary "Uncategorized" board // if no default board set, first board is a temporary "Uncategorized" board
func GetProjectBoards(projectID int64) (ProjectBoardList, error) { func GetProjectBoards(projectID int64) (ProjectBoardList, error) {
return getProjectBoards(db.DefaultContext().Engine(), projectID) return getProjectBoards(db.GetEngine(db.DefaultContext), projectID)
} }
func getProjectBoards(e db.Engine, projectID int64) ([]*ProjectBoard, error) { func getProjectBoards(e db.Engine, projectID int64) ([]*ProjectBoard, error) {
@ -226,7 +226,7 @@ func getDefaultBoard(e db.Engine, projectID int64) (*ProjectBoard, error) {
// SetDefaultBoard represents a board for issues not assigned to one // SetDefaultBoard represents a board for issues not assigned to one
// if boardID is 0 unset default // if boardID is 0 unset default
func SetDefaultBoard(projectID, boardID int64) error { func SetDefaultBoard(projectID, boardID int64) error {
_, err := db.DefaultContext().Engine().Where(builder.Eq{ _, err := db.GetEngine(db.DefaultContext).Where(builder.Eq{
"project_id": projectID, "project_id": projectID,
"`default`": true, "`default`": true,
}).Cols("`default`").Update(&ProjectBoard{Default: false}) }).Cols("`default`").Update(&ProjectBoard{Default: false})
@ -235,7 +235,7 @@ func SetDefaultBoard(projectID, boardID int64) error {
} }
if boardID > 0 { if boardID > 0 {
_, err = db.DefaultContext().Engine().ID(boardID).Where(builder.Eq{"project_id": projectID}). _, err = db.GetEngine(db.DefaultContext).ID(boardID).Where(builder.Eq{"project_id": projectID}).
Cols("`default`").Update(&ProjectBoard{Default: true}) Cols("`default`").Update(&ProjectBoard{Default: true})
} }
@ -293,7 +293,7 @@ func (bs ProjectBoardList) LoadIssues() (IssueList, error) {
// UpdateProjectBoardSorting update project board sorting // UpdateProjectBoardSorting update project board sorting
func UpdateProjectBoardSorting(bs ProjectBoardList) error { func UpdateProjectBoardSorting(bs ProjectBoardList) error {
for i := range bs { for i := range bs {
_, err := db.DefaultContext().Engine().ID(bs[i].ID).Cols( _, err := db.GetEngine(db.DefaultContext).ID(bs[i].ID).Cols(
"sorting", "sorting",
).Update(bs[i]) ).Update(bs[i])
if err != nil { if err != nil {

View File

@ -39,7 +39,7 @@ func deleteProjectIssuesByProjectID(e db.Engine, projectID int64) error {
// LoadProject load the project the issue was assigned to // LoadProject load the project the issue was assigned to
func (i *Issue) LoadProject() (err error) { func (i *Issue) LoadProject() (err error) {
return i.loadProject(db.DefaultContext().Engine()) return i.loadProject(db.GetEngine(db.DefaultContext))
} }
func (i *Issue) loadProject(e db.Engine) (err error) { func (i *Issue) loadProject(e db.Engine) (err error) {
@ -58,7 +58,7 @@ func (i *Issue) loadProject(e db.Engine) (err error) {
// ProjectID return project id if issue was assigned to one // ProjectID return project id if issue was assigned to one
func (i *Issue) ProjectID() int64 { func (i *Issue) ProjectID() int64 {
return i.projectID(db.DefaultContext().Engine()) return i.projectID(db.GetEngine(db.DefaultContext))
} }
func (i *Issue) projectID(e db.Engine) int64 { func (i *Issue) projectID(e db.Engine) int64 {
@ -72,7 +72,7 @@ func (i *Issue) projectID(e db.Engine) int64 {
// ProjectBoardID return project board id if issue was assigned to one // ProjectBoardID return project board id if issue was assigned to one
func (i *Issue) ProjectBoardID() int64 { func (i *Issue) ProjectBoardID() int64 {
return i.projectBoardID(db.DefaultContext().Engine()) return i.projectBoardID(db.GetEngine(db.DefaultContext))
} }
func (i *Issue) projectBoardID(e db.Engine) int64 { func (i *Issue) projectBoardID(e db.Engine) int64 {
@ -93,7 +93,7 @@ func (i *Issue) projectBoardID(e db.Engine) int64 {
// NumIssues return counter of all issues assigned to a project // NumIssues return counter of all issues assigned to a project
func (p *Project) NumIssues() int { func (p *Project) NumIssues() int {
c, err := db.DefaultContext().Engine().Table("project_issue"). c, err := db.GetEngine(db.DefaultContext).Table("project_issue").
Where("project_id=?", p.ID). Where("project_id=?", p.ID).
GroupBy("issue_id"). GroupBy("issue_id").
Cols("issue_id"). Cols("issue_id").
@ -106,7 +106,7 @@ func (p *Project) NumIssues() int {
// NumClosedIssues return counter of closed issues assigned to a project // NumClosedIssues return counter of closed issues assigned to a project
func (p *Project) NumClosedIssues() int { func (p *Project) NumClosedIssues() int {
c, err := db.DefaultContext().Engine().Table("project_issue"). c, err := db.GetEngine(db.DefaultContext).Table("project_issue").
Join("INNER", "issue", "project_issue.issue_id=issue.id"). Join("INNER", "issue", "project_issue.issue_id=issue.id").
Where("project_issue.project_id=? AND issue.is_closed=?", p.ID, true). Where("project_issue.project_id=? AND issue.is_closed=?", p.ID, true).
Cols("issue_id"). Cols("issue_id").
@ -119,7 +119,7 @@ func (p *Project) NumClosedIssues() int {
// NumOpenIssues return counter of open issues assigned to a project // NumOpenIssues return counter of open issues assigned to a project
func (p *Project) NumOpenIssues() int { func (p *Project) NumOpenIssues() int {
c, err := db.DefaultContext().Engine().Table("project_issue"). c, err := db.GetEngine(db.DefaultContext).Table("project_issue").
Join("INNER", "issue", "project_issue.issue_id=issue.id"). Join("INNER", "issue", "project_issue.issue_id=issue.id").
Where("project_issue.project_id=? AND issue.is_closed=?", p.ID, false).Count("issue.id") Where("project_issue.project_id=? AND issue.is_closed=?", p.ID, false).Count("issue.id")
if err != nil { if err != nil {
@ -130,7 +130,7 @@ func (p *Project) NumOpenIssues() int {
// ChangeProjectAssign changes the project associated with an issue // ChangeProjectAssign changes the project associated with an issue
func ChangeProjectAssign(issue *Issue, doer *User, newProjectID int64) error { func ChangeProjectAssign(issue *Issue, doer *User, newProjectID int64) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -183,7 +183,7 @@ func addUpdateIssueProject(e *xorm.Session, issue *Issue, doer *User, newProject
// MoveIssueAcrossProjectBoards move a card from one board to another // MoveIssueAcrossProjectBoards move a card from one board to another
func MoveIssueAcrossProjectBoards(issue *Issue, board *ProjectBoard) error { func MoveIssueAcrossProjectBoards(issue *Issue, board *ProjectBoard) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err

View File

@ -35,19 +35,19 @@ func init() {
// InsertProtectedTag inserts a protected tag to database // InsertProtectedTag inserts a protected tag to database
func InsertProtectedTag(pt *ProtectedTag) error { func InsertProtectedTag(pt *ProtectedTag) error {
_, err := db.DefaultContext().Engine().Insert(pt) _, err := db.GetEngine(db.DefaultContext).Insert(pt)
return err return err
} }
// UpdateProtectedTag updates the protected tag // UpdateProtectedTag updates the protected tag
func UpdateProtectedTag(pt *ProtectedTag) error { func UpdateProtectedTag(pt *ProtectedTag) error {
_, err := db.DefaultContext().Engine().ID(pt.ID).AllCols().Update(pt) _, err := db.GetEngine(db.DefaultContext).ID(pt.ID).AllCols().Update(pt)
return err return err
} }
// DeleteProtectedTag deletes a protected tag by ID // DeleteProtectedTag deletes a protected tag by ID
func DeleteProtectedTag(pt *ProtectedTag) error { func DeleteProtectedTag(pt *ProtectedTag) error {
_, err := db.DefaultContext().Engine().ID(pt.ID).Delete(&ProtectedTag{}) _, err := db.GetEngine(db.DefaultContext).ID(pt.ID).Delete(&ProtectedTag{})
return err return err
} }
@ -86,13 +86,13 @@ func (pt *ProtectedTag) IsUserAllowed(userID int64) (bool, error) {
// GetProtectedTags gets all protected tags of the repository // GetProtectedTags gets all protected tags of the repository
func (repo *Repository) GetProtectedTags() ([]*ProtectedTag, error) { func (repo *Repository) GetProtectedTags() ([]*ProtectedTag, error) {
tags := make([]*ProtectedTag, 0) tags := make([]*ProtectedTag, 0)
return tags, db.DefaultContext().Engine().Find(&tags, &ProtectedTag{RepoID: repo.ID}) return tags, db.GetEngine(db.DefaultContext).Find(&tags, &ProtectedTag{RepoID: repo.ID})
} }
// GetProtectedTagByID gets the protected tag with the specific id // GetProtectedTagByID gets the protected tag with the specific id
func GetProtectedTagByID(id int64) (*ProtectedTag, error) { func GetProtectedTagByID(id int64) (*ProtectedTag, error) {
tag := new(ProtectedTag) tag := new(ProtectedTag)
has, err := db.DefaultContext().Engine().ID(id).Get(tag) has, err := db.GetEngine(db.DefaultContext).ID(id).Get(tag)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -122,7 +122,7 @@ func (pr *PullRequest) loadAttributes(e db.Engine) (err error) {
// LoadAttributes loads pull request attributes from database // LoadAttributes loads pull request attributes from database
func (pr *PullRequest) LoadAttributes() error { func (pr *PullRequest) LoadAttributes() error {
return pr.loadAttributes(db.DefaultContext().Engine()) return pr.loadAttributes(db.GetEngine(db.DefaultContext))
} }
func (pr *PullRequest) loadHeadRepo(e db.Engine) (err error) { func (pr *PullRequest) loadHeadRepo(e db.Engine) (err error) {
@ -148,12 +148,12 @@ func (pr *PullRequest) loadHeadRepo(e db.Engine) (err error) {
// LoadHeadRepo loads the head repository // LoadHeadRepo loads the head repository
func (pr *PullRequest) LoadHeadRepo() error { func (pr *PullRequest) LoadHeadRepo() error {
return pr.loadHeadRepo(db.DefaultContext().Engine()) return pr.loadHeadRepo(db.GetEngine(db.DefaultContext))
} }
// LoadBaseRepo loads the target repository // LoadBaseRepo loads the target repository
func (pr *PullRequest) LoadBaseRepo() error { func (pr *PullRequest) LoadBaseRepo() error {
return pr.loadBaseRepo(db.DefaultContext().Engine()) return pr.loadBaseRepo(db.GetEngine(db.DefaultContext))
} }
func (pr *PullRequest) loadBaseRepo(e db.Engine) (err error) { func (pr *PullRequest) loadBaseRepo(e db.Engine) (err error) {
@ -180,7 +180,7 @@ func (pr *PullRequest) loadBaseRepo(e db.Engine) (err error) {
// LoadIssue loads issue information from database // LoadIssue loads issue information from database
func (pr *PullRequest) LoadIssue() (err error) { func (pr *PullRequest) LoadIssue() (err error) {
return pr.loadIssue(db.DefaultContext().Engine()) return pr.loadIssue(db.GetEngine(db.DefaultContext))
} }
func (pr *PullRequest) loadIssue(e db.Engine) (err error) { func (pr *PullRequest) loadIssue(e db.Engine) (err error) {
@ -197,7 +197,7 @@ func (pr *PullRequest) loadIssue(e db.Engine) (err error) {
// LoadProtectedBranch loads the protected branch of the base branch // LoadProtectedBranch loads the protected branch of the base branch
func (pr *PullRequest) LoadProtectedBranch() (err error) { func (pr *PullRequest) LoadProtectedBranch() (err error) {
return pr.loadProtectedBranch(db.DefaultContext().Engine()) return pr.loadProtectedBranch(db.GetEngine(db.DefaultContext))
} }
func (pr *PullRequest) loadProtectedBranch(e db.Engine) (err error) { func (pr *PullRequest) loadProtectedBranch(e db.Engine) (err error) {
@ -257,7 +257,7 @@ type ReviewCount struct {
// GetApprovalCounts returns the approval counts by type // GetApprovalCounts returns the approval counts by type
// FIXME: Only returns official counts due to double counting of non-official counts // FIXME: Only returns official counts due to double counting of non-official counts
func (pr *PullRequest) GetApprovalCounts() ([]*ReviewCount, error) { func (pr *PullRequest) GetApprovalCounts() ([]*ReviewCount, error) {
return pr.getApprovalCounts(db.DefaultContext().Engine()) return pr.getApprovalCounts(db.GetEngine(db.DefaultContext))
} }
func (pr *PullRequest) getApprovalCounts(e db.Engine) ([]*ReviewCount, error) { func (pr *PullRequest) getApprovalCounts(e db.Engine) ([]*ReviewCount, error) {
@ -284,7 +284,7 @@ func (pr *PullRequest) getReviewedByLines(writer io.Writer) error {
return nil return nil
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -393,7 +393,7 @@ func (pr *PullRequest) SetMerged() (bool, error) {
pr.HasMerged = true pr.HasMerged = true
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return false, err return false, err
@ -455,7 +455,7 @@ func NewPullRequest(repo *Repository, issue *Issue, labelIDs []int64, uuids []st
issue.Index = idx issue.Index = idx
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -492,7 +492,7 @@ func NewPullRequest(repo *Repository, issue *Issue, labelIDs []int64, uuids []st
// by given head/base and repo/branch. // by given head/base and repo/branch.
func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string, flow PullRequestFlow) (*PullRequest, error) { func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string, flow PullRequestFlow) (*PullRequest, error) {
pr := new(PullRequest) pr := new(PullRequest)
has, err := db.DefaultContext().Engine(). has, err := db.GetEngine(db.DefaultContext).
Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND flow = ? AND issue.is_closed=?", Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND flow = ? AND issue.is_closed=?",
headRepoID, headBranch, baseRepoID, baseBranch, false, flow, false). headRepoID, headBranch, baseRepoID, baseBranch, false, flow, false).
Join("INNER", "issue", "issue.id=pull_request.issue_id"). Join("INNER", "issue", "issue.id=pull_request.issue_id").
@ -510,7 +510,7 @@ func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch
// by given head information (repo and branch). // by given head information (repo and branch).
func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest, error) { func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest, error) {
pr := new(PullRequest) pr := new(PullRequest)
has, err := db.DefaultContext().Engine(). has, err := db.GetEngine(db.DefaultContext).
Where("head_repo_id = ? AND head_branch = ? AND flow = ?", repoID, branch, PullRequestFlowGithub). Where("head_repo_id = ? AND head_branch = ? AND flow = ?", repoID, branch, PullRequestFlowGithub).
OrderBy("id DESC"). OrderBy("id DESC").
Get(pr) Get(pr)
@ -527,7 +527,7 @@ func GetPullRequestByIndex(repoID, index int64) (*PullRequest, error) {
Index: index, Index: index,
} }
has, err := db.DefaultContext().Engine().Get(pr) has, err := db.GetEngine(db.DefaultContext).Get(pr)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -557,13 +557,13 @@ func getPullRequestByID(e db.Engine, id int64) (*PullRequest, error) {
// GetPullRequestByID returns a pull request by given ID. // GetPullRequestByID returns a pull request by given ID.
func GetPullRequestByID(id int64) (*PullRequest, error) { func GetPullRequestByID(id int64) (*PullRequest, error) {
return getPullRequestByID(db.DefaultContext().Engine(), id) return getPullRequestByID(db.GetEngine(db.DefaultContext), id)
} }
// GetPullRequestByIssueIDWithNoAttributes returns pull request with no attributes loaded by given issue ID. // GetPullRequestByIssueIDWithNoAttributes returns pull request with no attributes loaded by given issue ID.
func GetPullRequestByIssueIDWithNoAttributes(issueID int64) (*PullRequest, error) { func GetPullRequestByIssueIDWithNoAttributes(issueID int64) (*PullRequest, error) {
var pr PullRequest var pr PullRequest
has, err := db.DefaultContext().Engine().Where("issue_id = ?", issueID).Get(&pr) has, err := db.GetEngine(db.DefaultContext).Where("issue_id = ?", issueID).Get(&pr)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -591,7 +591,7 @@ func getPullRequestByIssueID(e db.Engine, issueID int64) (*PullRequest, error) {
func GetAllUnmergedAgitPullRequestByPoster(uid int64) ([]*PullRequest, error) { func GetAllUnmergedAgitPullRequestByPoster(uid int64) ([]*PullRequest, error) {
pulls := make([]*PullRequest, 0, 10) pulls := make([]*PullRequest, 0, 10)
err := db.DefaultContext().Engine(). err := db.GetEngine(db.DefaultContext).
Where("has_merged=? AND flow = ? AND issue.is_closed=? AND issue.poster_id=?", Where("has_merged=? AND flow = ? AND issue.is_closed=? AND issue.poster_id=?",
false, PullRequestFlowAGit, false, uid). false, PullRequestFlowAGit, false, uid).
Join("INNER", "issue", "issue.id=pull_request.issue_id"). Join("INNER", "issue", "issue.id=pull_request.issue_id").
@ -602,24 +602,24 @@ func GetAllUnmergedAgitPullRequestByPoster(uid int64) ([]*PullRequest, error) {
// GetPullRequestByIssueID returns pull request by given issue ID. // GetPullRequestByIssueID returns pull request by given issue ID.
func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) { func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
return getPullRequestByIssueID(db.DefaultContext().Engine(), issueID) return getPullRequestByIssueID(db.GetEngine(db.DefaultContext), issueID)
} }
// Update updates all fields of pull request. // Update updates all fields of pull request.
func (pr *PullRequest) Update() error { func (pr *PullRequest) Update() error {
_, err := db.DefaultContext().Engine().ID(pr.ID).AllCols().Update(pr) _, err := db.GetEngine(db.DefaultContext).ID(pr.ID).AllCols().Update(pr)
return err return err
} }
// UpdateCols updates specific fields of pull request. // UpdateCols updates specific fields of pull request.
func (pr *PullRequest) UpdateCols(cols ...string) error { func (pr *PullRequest) UpdateCols(cols ...string) error {
_, err := db.DefaultContext().Engine().ID(pr.ID).Cols(cols...).Update(pr) _, err := db.GetEngine(db.DefaultContext).ID(pr.ID).Cols(cols...).Update(pr)
return err return err
} }
// UpdateColsIfNotMerged updates specific fields of a pull request if it has not been merged // UpdateColsIfNotMerged updates specific fields of a pull request if it has not been merged
func (pr *PullRequest) UpdateColsIfNotMerged(cols ...string) error { func (pr *PullRequest) UpdateColsIfNotMerged(cols ...string) error {
_, err := db.DefaultContext().Engine().Where("id = ? AND has_merged = ?", pr.ID, false).Cols(cols...).Update(pr) _, err := db.GetEngine(db.DefaultContext).Where("id = ? AND has_merged = ?", pr.ID, false).Cols(cols...).Update(pr)
return err return err
} }
@ -665,7 +665,7 @@ func (pr *PullRequest) GetWorkInProgressPrefix() string {
// UpdateCommitDivergence update Divergence of a pull request // UpdateCommitDivergence update Divergence of a pull request
func (pr *PullRequest) UpdateCommitDivergence(ahead, behind int) error { func (pr *PullRequest) UpdateCommitDivergence(ahead, behind int) error {
return pr.updateCommitDivergence(db.DefaultContext().Engine(), ahead, behind) return pr.updateCommitDivergence(db.GetEngine(db.DefaultContext), ahead, behind)
} }
func (pr *PullRequest) updateCommitDivergence(e db.Engine, ahead, behind int) error { func (pr *PullRequest) updateCommitDivergence(e db.Engine, ahead, behind int) error {

View File

@ -25,7 +25,7 @@ type PullRequestsOptions struct {
} }
func listPullRequestStatement(baseRepoID int64, opts *PullRequestsOptions) (*xorm.Session, error) { func listPullRequestStatement(baseRepoID int64, opts *PullRequestsOptions) (*xorm.Session, error) {
sess := db.DefaultContext().Engine().Where("pull_request.base_repo_id=?", baseRepoID) sess := db.GetEngine(db.DefaultContext).Where("pull_request.base_repo_id=?", baseRepoID)
sess.Join("INNER", "issue", "pull_request.issue_id = issue.id") sess.Join("INNER", "issue", "pull_request.issue_id = issue.id")
switch opts.State { switch opts.State {
@ -51,7 +51,7 @@ func listPullRequestStatement(baseRepoID int64, opts *PullRequestsOptions) (*xor
// by given head information (repo and branch). // by given head information (repo and branch).
func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) { func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
prs := make([]*PullRequest, 0, 2) prs := make([]*PullRequest, 0, 2)
return prs, db.DefaultContext().Engine(). return prs, db.GetEngine(db.DefaultContext).
Where("head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ? AND flow = ?", Where("head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ? AND flow = ?",
repoID, branch, false, false, PullRequestFlowGithub). repoID, branch, false, false, PullRequestFlowGithub).
Join("INNER", "issue", "issue.id = pull_request.issue_id"). Join("INNER", "issue", "issue.id = pull_request.issue_id").
@ -62,7 +62,7 @@ func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequ
// by given base information (repo and branch). // by given base information (repo and branch).
func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) { func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
prs := make([]*PullRequest, 0, 2) prs := make([]*PullRequest, 0, 2)
return prs, db.DefaultContext().Engine(). return prs, db.GetEngine(db.DefaultContext).
Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?", Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
repoID, branch, false, false). repoID, branch, false, false).
Join("INNER", "issue", "issue.id=pull_request.issue_id"). Join("INNER", "issue", "issue.id=pull_request.issue_id").
@ -72,7 +72,7 @@ func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequ
// GetPullRequestIDsByCheckStatus returns all pull requests according the special checking status. // GetPullRequestIDsByCheckStatus returns all pull requests according the special checking status.
func GetPullRequestIDsByCheckStatus(status PullRequestStatus) ([]int64, error) { func GetPullRequestIDsByCheckStatus(status PullRequestStatus) ([]int64, error) {
prs := make([]int64, 0, 10) prs := make([]int64, 0, 10)
return prs, db.DefaultContext().Engine().Table("pull_request"). return prs, db.GetEngine(db.DefaultContext).Table("pull_request").
Where("status=?", status). Where("status=?", status).
Cols("pull_request.id"). Cols("pull_request.id").
Find(&prs) Find(&prs)
@ -144,7 +144,7 @@ func (prs PullRequestList) getIssueIDs() []int64 {
// LoadAttributes load all the prs attributes // LoadAttributes load all the prs attributes
func (prs PullRequestList) LoadAttributes() error { func (prs PullRequestList) LoadAttributes() error {
return prs.loadAttributes(db.DefaultContext().Engine()) return prs.loadAttributes(db.GetEngine(db.DefaultContext))
} }
func (prs PullRequestList) invalidateCodeComments(e db.Engine, doer *User, repo *git.Repository, branch string) error { func (prs PullRequestList) invalidateCodeComments(e db.Engine, doer *User, repo *git.Repository, branch string) error {
@ -169,5 +169,5 @@ func (prs PullRequestList) invalidateCodeComments(e db.Engine, doer *User, repo
// InvalidateCodeComments will lookup the prs for code comments which got invalidated by change // InvalidateCodeComments will lookup the prs for code comments which got invalidated by change
func (prs PullRequestList) InvalidateCodeComments(doer *User, repo *git.Repository, branch string) error { func (prs PullRequestList) InvalidateCodeComments(doer *User, repo *git.Repository, branch string) error {
return prs.invalidateCodeComments(db.DefaultContext().Engine(), doer, repo, branch) return prs.invalidateCodeComments(db.GetEngine(db.DefaultContext), doer, repo, branch)
} }

View File

@ -6,6 +6,7 @@
package models package models
import ( import (
"context"
"errors" "errors"
"fmt" "fmt"
"sort" "sort"
@ -72,7 +73,7 @@ func (r *Release) loadAttributes(e db.Engine) error {
// LoadAttributes load repo and publisher attributes for a release // LoadAttributes load repo and publisher attributes for a release
func (r *Release) LoadAttributes() error { func (r *Release) LoadAttributes() error {
return r.loadAttributes(db.DefaultContext().Engine()) return r.loadAttributes(db.GetEngine(db.DefaultContext))
} }
// APIURL the api url for a release. release must have attributes loaded // APIURL the api url for a release. release must have attributes loaded
@ -102,31 +103,31 @@ func IsReleaseExist(repoID int64, tagName string) (bool, error) {
return false, nil return false, nil
} }
return db.DefaultContext().Engine().Get(&Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)}) return db.GetEngine(db.DefaultContext).Get(&Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)})
} }
// InsertRelease inserts a release // InsertRelease inserts a release
func InsertRelease(rel *Release) error { func InsertRelease(rel *Release) error {
_, err := db.DefaultContext().Engine().Insert(rel) _, err := db.GetEngine(db.DefaultContext).Insert(rel)
return err return err
} }
// InsertReleasesContext insert releases // InsertReleasesContext insert releases
func InsertReleasesContext(ctx *db.Context, rels []*Release) error { func InsertReleasesContext(ctx context.Context, rels []*Release) error {
_, err := ctx.Engine().Insert(rels) _, err := db.GetEngine(ctx).Insert(rels)
return err return err
} }
// UpdateRelease updates all columns of a release // UpdateRelease updates all columns of a release
func UpdateRelease(ctx *db.Context, rel *Release) error { func UpdateRelease(ctx context.Context, rel *Release) error {
_, err := ctx.Engine().ID(rel.ID).AllCols().Update(rel) _, err := db.GetEngine(ctx).ID(rel.ID).AllCols().Update(rel)
return err return err
} }
// AddReleaseAttachments adds a release attachments // AddReleaseAttachments adds a release attachments
func AddReleaseAttachments(ctx *db.Context, releaseID int64, attachmentUUIDs []string) (err error) { func AddReleaseAttachments(ctx context.Context, releaseID int64, attachmentUUIDs []string) (err error) {
// Check attachments // Check attachments
attachments, err := getAttachmentsByUUIDs(ctx.Engine(), attachmentUUIDs) attachments, err := getAttachmentsByUUIDs(db.GetEngine(ctx), attachmentUUIDs)
if err != nil { if err != nil {
return fmt.Errorf("GetAttachmentsByUUIDs [uuids: %v]: %v", attachmentUUIDs, err) return fmt.Errorf("GetAttachmentsByUUIDs [uuids: %v]: %v", attachmentUUIDs, err)
} }
@ -137,7 +138,7 @@ func AddReleaseAttachments(ctx *db.Context, releaseID int64, attachmentUUIDs []s
} }
attachments[i].ReleaseID = releaseID attachments[i].ReleaseID = releaseID
// No assign value could be 0, so ignore AllCols(). // No assign value could be 0, so ignore AllCols().
if _, err = ctx.Engine().ID(attachments[i].ID).Update(attachments[i]); err != nil { if _, err = db.GetEngine(ctx).ID(attachments[i].ID).Update(attachments[i]); err != nil {
return fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err) return fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
} }
} }
@ -155,14 +156,14 @@ func GetRelease(repoID int64, tagName string) (*Release, error) {
} }
rel := &Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)} rel := &Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)}
_, err = db.DefaultContext().Engine().Get(rel) _, err = db.GetEngine(db.DefaultContext).Get(rel)
return rel, err return rel, err
} }
// GetReleaseByID returns release with given ID. // GetReleaseByID returns release with given ID.
func GetReleaseByID(id int64) (*Release, error) { func GetReleaseByID(id int64) (*Release, error) {
rel := new(Release) rel := new(Release)
has, err := db.DefaultContext().Engine(). has, err := db.GetEngine(db.DefaultContext).
ID(id). ID(id).
Get(rel) Get(rel)
if err != nil { if err != nil {
@ -208,7 +209,7 @@ func (opts *FindReleasesOptions) toConds(repoID int64) builder.Cond {
// GetReleasesByRepoID returns a list of releases of repository. // GetReleasesByRepoID returns a list of releases of repository.
func GetReleasesByRepoID(repoID int64, opts FindReleasesOptions) ([]*Release, error) { func GetReleasesByRepoID(repoID int64, opts FindReleasesOptions) ([]*Release, error) {
sess := db.DefaultContext().Engine(). sess := db.GetEngine(db.DefaultContext).
Desc("created_unix", "id"). Desc("created_unix", "id").
Where(opts.toConds(repoID)) Where(opts.toConds(repoID))
@ -222,7 +223,7 @@ func GetReleasesByRepoID(repoID int64, opts FindReleasesOptions) ([]*Release, er
// CountReleasesByRepoID returns a number of releases matching FindReleaseOptions and RepoID. // CountReleasesByRepoID returns a number of releases matching FindReleaseOptions and RepoID.
func CountReleasesByRepoID(repoID int64, opts FindReleasesOptions) (int64, error) { func CountReleasesByRepoID(repoID int64, opts FindReleasesOptions) (int64, error) {
return db.DefaultContext().Engine().Where(opts.toConds(repoID)).Count(new(Release)) return db.GetEngine(db.DefaultContext).Where(opts.toConds(repoID)).Count(new(Release))
} }
// GetLatestReleaseByRepoID returns the latest release for a repository // GetLatestReleaseByRepoID returns the latest release for a repository
@ -234,7 +235,7 @@ func GetLatestReleaseByRepoID(repoID int64) (*Release, error) {
And(builder.Eq{"is_tag": false}) And(builder.Eq{"is_tag": false})
rel := new(Release) rel := new(Release)
has, err := db.DefaultContext().Engine(). has, err := db.GetEngine(db.DefaultContext).
Desc("created_unix", "id"). Desc("created_unix", "id").
Where(cond). Where(cond).
Get(rel) Get(rel)
@ -248,8 +249,8 @@ func GetLatestReleaseByRepoID(repoID int64) (*Release, error) {
} }
// GetReleasesByRepoIDAndNames returns a list of releases of repository according repoID and tagNames. // GetReleasesByRepoIDAndNames returns a list of releases of repository according repoID and tagNames.
func GetReleasesByRepoIDAndNames(ctx *db.Context, repoID int64, tagNames []string) (rels []*Release, err error) { func GetReleasesByRepoIDAndNames(ctx context.Context, repoID int64, tagNames []string) (rels []*Release, err error) {
err = ctx.Engine(). err = db.GetEngine(ctx).
In("tag_name", tagNames). In("tag_name", tagNames).
Desc("created_unix"). Desc("created_unix").
Find(&rels, Release{RepoID: repoID}) Find(&rels, Release{RepoID: repoID})
@ -258,7 +259,7 @@ func GetReleasesByRepoIDAndNames(ctx *db.Context, repoID int64, tagNames []strin
// GetReleaseCountByRepoID returns the count of releases of repository // GetReleaseCountByRepoID returns the count of releases of repository
func GetReleaseCountByRepoID(repoID int64, opts FindReleasesOptions) (int64, error) { func GetReleaseCountByRepoID(repoID int64, opts FindReleasesOptions) (int64, error) {
return db.DefaultContext().Engine().Where(opts.toConds(repoID)).Count(&Release{}) return db.GetEngine(db.DefaultContext).Where(opts.toConds(repoID)).Count(&Release{})
} }
type releaseMetaSearch struct { type releaseMetaSearch struct {
@ -281,7 +282,7 @@ func (s releaseMetaSearch) Less(i, j int) bool {
// GetReleaseAttachments retrieves the attachments for releases // GetReleaseAttachments retrieves the attachments for releases
func GetReleaseAttachments(rels ...*Release) (err error) { func GetReleaseAttachments(rels ...*Release) (err error) {
return getReleaseAttachments(db.DefaultContext().Engine(), rels...) return getReleaseAttachments(db.GetEngine(db.DefaultContext), rels...)
} }
func getReleaseAttachments(e db.Engine, rels ...*Release) (err error) { func getReleaseAttachments(e db.Engine, rels ...*Release) (err error) {
@ -352,13 +353,13 @@ func SortReleases(rels []*Release) {
// DeleteReleaseByID deletes a release from database by given ID. // DeleteReleaseByID deletes a release from database by given ID.
func DeleteReleaseByID(id int64) error { func DeleteReleaseByID(id int64) error {
_, err := db.DefaultContext().Engine().ID(id).Delete(new(Release)) _, err := db.GetEngine(db.DefaultContext).ID(id).Delete(new(Release))
return err return err
} }
// UpdateReleasesMigrationsByType updates all migrated repositories' releases from gitServiceType to replace originalAuthorID to posterID // UpdateReleasesMigrationsByType updates all migrated repositories' releases from gitServiceType to replace originalAuthorID to posterID
func UpdateReleasesMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error { func UpdateReleasesMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error {
_, err := db.DefaultContext().Engine().Table("release"). _, err := db.GetEngine(db.DefaultContext).Table("release").
Where("repo_id IN (SELECT id FROM repository WHERE original_service_type = ?)", gitServiceType). Where("repo_id IN (SELECT id FROM repository WHERE original_service_type = ?)", gitServiceType).
And("original_author_id = ?", originalAuthorID). And("original_author_id = ?", originalAuthorID).
Update(map[string]interface{}{ Update(map[string]interface{}{

View File

@ -302,7 +302,7 @@ func (repo *Repository) AfterLoad() {
// It creates a fake object that contains error details // It creates a fake object that contains error details
// when error occurs. // when error occurs.
func (repo *Repository) MustOwner() *User { func (repo *Repository) MustOwner() *User {
return repo.mustOwner(db.DefaultContext().Engine()) return repo.mustOwner(db.GetEngine(db.DefaultContext))
} }
// FullName returns the repository full name // FullName returns the repository full name
@ -354,7 +354,7 @@ func (repo *Repository) getUnits(e db.Engine) (err error) {
// CheckUnitUser check whether user could visit the unit of this repository // CheckUnitUser check whether user could visit the unit of this repository
func (repo *Repository) CheckUnitUser(user *User, unitType UnitType) bool { func (repo *Repository) CheckUnitUser(user *User, unitType UnitType) bool {
return repo.checkUnitUser(db.DefaultContext().Engine(), user, unitType) return repo.checkUnitUser(db.GetEngine(db.DefaultContext), user, unitType)
} }
func (repo *Repository) checkUnitUser(e db.Engine, user *User, unitType UnitType) bool { func (repo *Repository) checkUnitUser(e db.Engine, user *User, unitType UnitType) bool {
@ -372,7 +372,7 @@ func (repo *Repository) checkUnitUser(e db.Engine, user *User, unitType UnitType
// UnitEnabled if this repository has the given unit enabled // UnitEnabled if this repository has the given unit enabled
func (repo *Repository) UnitEnabled(tp UnitType) bool { func (repo *Repository) UnitEnabled(tp UnitType) bool {
if err := repo.getUnits(db.DefaultContext().Engine()); err != nil { if err := repo.getUnits(db.GetEngine(db.DefaultContext)); err != nil {
log.Warn("Error loading repository (ID: %d) units: %s", repo.ID, err.Error()) log.Warn("Error loading repository (ID: %d) units: %s", repo.ID, err.Error())
} }
for _, unit := range repo.Units { for _, unit := range repo.Units {
@ -434,7 +434,7 @@ func (repo *Repository) MustGetUnit(tp UnitType) *RepoUnit {
// GetUnit returns a RepoUnit object // GetUnit returns a RepoUnit object
func (repo *Repository) GetUnit(tp UnitType) (*RepoUnit, error) { func (repo *Repository) GetUnit(tp UnitType) (*RepoUnit, error) {
return repo.getUnit(db.DefaultContext().Engine(), tp) return repo.getUnit(db.GetEngine(db.DefaultContext), tp)
} }
func (repo *Repository) getUnit(e db.Engine, tp UnitType) (*RepoUnit, error) { func (repo *Repository) getUnit(e db.Engine, tp UnitType) (*RepoUnit, error) {
@ -460,7 +460,7 @@ func (repo *Repository) getOwner(e db.Engine) (err error) {
// GetOwner returns the repository owner // GetOwner returns the repository owner
func (repo *Repository) GetOwner() error { func (repo *Repository) GetOwner() error {
return repo.getOwner(db.DefaultContext().Engine()) return repo.getOwner(db.GetEngine(db.DefaultContext))
} }
func (repo *Repository) mustOwner(e db.Engine) *User { func (repo *Repository) mustOwner(e db.Engine) *User {
@ -498,7 +498,7 @@ func (repo *Repository) ComposeMetas() map[string]string {
repo.MustOwner() repo.MustOwner()
if repo.Owner.IsOrganization() { if repo.Owner.IsOrganization() {
teams := make([]string, 0, 5) teams := make([]string, 0, 5)
_ = db.DefaultContext().Engine().Table("team_repo"). _ = db.GetEngine(db.DefaultContext).Table("team_repo").
Join("INNER", "team", "team.id = team_repo.team_id"). Join("INNER", "team", "team.id = team_repo.team_id").
Where("team_repo.repo_id = ?", repo.ID). Where("team_repo.repo_id = ?", repo.ID).
Select("team.lower_name"). Select("team.lower_name").
@ -561,7 +561,7 @@ func (repo *Repository) getAssignees(e db.Engine) (_ []*User, err error) {
// GetAssignees returns all users that have write access and can be assigned to issues // GetAssignees returns all users that have write access and can be assigned to issues
// of the repository, // of the repository,
func (repo *Repository) GetAssignees() (_ []*User, err error) { func (repo *Repository) GetAssignees() (_ []*User, err error) {
return repo.getAssignees(db.DefaultContext().Engine()) return repo.getAssignees(db.GetEngine(db.DefaultContext))
} }
func (repo *Repository) getReviewers(e db.Engine, doerID, posterID int64) ([]*User, error) { func (repo *Repository) getReviewers(e db.Engine, doerID, posterID int64) ([]*User, error) {
@ -613,7 +613,7 @@ func (repo *Repository) getReviewers(e db.Engine, doerID, posterID int64) ([]*Us
// all repo watchers and all organization members. // all repo watchers and all organization members.
// TODO: may be we should have a busy choice for users to block review request to them. // 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) { func (repo *Repository) GetReviewers(doerID, posterID int64) ([]*User, error) {
return repo.getReviewers(db.DefaultContext().Engine(), doerID, posterID) return repo.getReviewers(db.GetEngine(db.DefaultContext), doerID, posterID)
} }
// GetReviewerTeams get all teams can be requested to review // GetReviewerTeams get all teams can be requested to review
@ -659,7 +659,7 @@ func (repo *Repository) LoadPushMirrors() (err error) {
// returns an error on failure (NOTE: no error is returned for // returns an error on failure (NOTE: no error is returned for
// non-fork repositories, and BaseRepo will be left untouched) // non-fork repositories, and BaseRepo will be left untouched)
func (repo *Repository) GetBaseRepo() (err error) { func (repo *Repository) GetBaseRepo() (err error) {
return repo.getBaseRepo(db.DefaultContext().Engine()) return repo.getBaseRepo(db.GetEngine(db.DefaultContext))
} }
func (repo *Repository) getBaseRepo(e db.Engine) (err error) { func (repo *Repository) getBaseRepo(e db.Engine) (err error) {
@ -680,7 +680,7 @@ func (repo *Repository) IsGenerated() bool {
// returns an error on failure (NOTE: no error is returned for // returns an error on failure (NOTE: no error is returned for
// non-generated repositories, and TemplateRepo will be left untouched) // non-generated repositories, and TemplateRepo will be left untouched)
func (repo *Repository) GetTemplateRepo() (err error) { func (repo *Repository) GetTemplateRepo() (err error) {
return repo.getTemplateRepo(db.DefaultContext().Engine()) return repo.getTemplateRepo(db.GetEngine(db.DefaultContext))
} }
func (repo *Repository) getTemplateRepo(e db.Engine) (err error) { func (repo *Repository) getTemplateRepo(e db.Engine) (err error) {
@ -724,7 +724,7 @@ func (repo *Repository) ComposeCompareURL(oldCommitID, newCommitID string) strin
// UpdateDefaultBranch updates the default branch // UpdateDefaultBranch updates the default branch
func (repo *Repository) UpdateDefaultBranch() error { func (repo *Repository) UpdateDefaultBranch() error {
_, err := db.DefaultContext().Engine().ID(repo.ID).Cols("default_branch").Update(repo) _, err := db.GetEngine(db.DefaultContext).ID(repo.ID).Cols("default_branch").Update(repo)
return err return err
} }
@ -750,8 +750,8 @@ func (repo *Repository) updateSize(e db.Engine) error {
} }
// UpdateSize updates the repository size, calculating it using util.GetDirectorySize // UpdateSize updates the repository size, calculating it using util.GetDirectorySize
func (repo *Repository) UpdateSize(ctx *db.Context) error { func (repo *Repository) UpdateSize(ctx context.Context) error {
return repo.updateSize(ctx.Engine()) return repo.updateSize(db.GetEngine(ctx))
} }
// CanUserFork returns true if specified user can fork repository. // CanUserFork returns true if specified user can fork repository.
@ -812,12 +812,12 @@ func (repo *Repository) CanEnableEditor() bool {
// GetReaders returns all users that have explicit read access or higher to the repository. // GetReaders returns all users that have explicit read access or higher to the repository.
func (repo *Repository) GetReaders() (_ []*User, err error) { func (repo *Repository) GetReaders() (_ []*User, err error) {
return repo.getUsersWithAccessMode(db.DefaultContext().Engine(), AccessModeRead) return repo.getUsersWithAccessMode(db.GetEngine(db.DefaultContext), AccessModeRead)
} }
// GetWriters returns all users that have write access to the repository. // GetWriters returns all users that have write access to the repository.
func (repo *Repository) GetWriters() (_ []*User, err error) { func (repo *Repository) GetWriters() (_ []*User, err error) {
return repo.getUsersWithAccessMode(db.DefaultContext().Engine(), AccessModeWrite) return repo.getUsersWithAccessMode(db.GetEngine(db.DefaultContext), AccessModeWrite)
} }
// IsReader returns true if user has explicit read access or higher to the repository. // IsReader returns true if user has explicit read access or higher to the repository.
@ -825,7 +825,7 @@ func (repo *Repository) IsReader(userID int64) (bool, error) {
if repo.OwnerID == userID { if repo.OwnerID == userID {
return true, nil return true, nil
} }
return db.DefaultContext().Engine().Where("repo_id = ? AND user_id = ? AND mode >= ?", repo.ID, userID, AccessModeRead).Get(&Access{}) return db.GetEngine(db.DefaultContext).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. // getUsersWithAccessMode returns users that have at least given access mode to the repository.
@ -874,7 +874,7 @@ func (repo *Repository) DescriptionHTML() template.HTML {
// ReadBy sets repo to be visited by given user. // ReadBy sets repo to be visited by given user.
func (repo *Repository) ReadBy(userID int64) error { func (repo *Repository) ReadBy(userID int64) error {
return setRepoNotificationStatusReadIfUnread(db.DefaultContext().Engine(), userID, repo.ID) return setRepoNotificationStatusReadIfUnread(db.GetEngine(db.DefaultContext), userID, repo.ID)
} }
func isRepositoryExist(e db.Engine, u *User, repoName string) (bool, error) { func isRepositoryExist(e db.Engine, u *User, repoName string) (bool, error) {
@ -891,7 +891,7 @@ func isRepositoryExist(e db.Engine, u *User, repoName string) (bool, error) {
// IsRepositoryExist returns true if the repository with given name under user has already existed. // IsRepositoryExist returns true if the repository with given name under user has already existed.
func IsRepositoryExist(u *User, repoName string) (bool, error) { func IsRepositoryExist(u *User, repoName string) (bool, error) {
return isRepositoryExist(db.DefaultContext().Engine(), u, repoName) return isRepositoryExist(db.GetEngine(db.DefaultContext), u, repoName)
} }
// CloneLink represents different types of clone URLs of repository. // CloneLink represents different types of clone URLs of repository.
@ -953,7 +953,7 @@ func CheckCreateRepository(doer, u *User, name string, overwriteOrAdopt bool) er
return err return err
} }
has, err := isRepositoryExist(db.DefaultContext().Engine(), u, name) has, err := isRepositoryExist(db.GetEngine(db.DefaultContext), u, name)
if err != nil { if err != nil {
return fmt.Errorf("IsRepositoryExist: %v", err) return fmt.Errorf("IsRepositoryExist: %v", err)
} else if has { } else if has {
@ -1042,12 +1042,12 @@ func IsUsableRepoName(name string) error {
} }
// CreateRepository creates a repository for the user/organization. // CreateRepository creates a repository for the user/organization.
func CreateRepository(ctx *db.Context, doer, u *User, repo *Repository, overwriteOrAdopt bool) (err error) { func CreateRepository(ctx context.Context, doer, u *User, repo *Repository, overwriteOrAdopt bool) (err error) {
if err = IsUsableRepoName(repo.Name); err != nil { if err = IsUsableRepoName(repo.Name); err != nil {
return err return err
} }
has, err := isRepositoryExist(ctx.Engine(), u, repo.Name) has, err := isRepositoryExist(db.GetEngine(ctx), u, repo.Name)
if err != nil { if err != nil {
return fmt.Errorf("IsRepositoryExist: %v", err) return fmt.Errorf("IsRepositoryExist: %v", err)
} else if has { } else if has {
@ -1068,10 +1068,10 @@ func CreateRepository(ctx *db.Context, doer, u *User, repo *Repository, overwrit
} }
} }
if _, err = ctx.Engine().Insert(repo); err != nil { if _, err = db.GetEngine(ctx).Insert(repo); err != nil {
return err return err
} }
if err = deleteRepoRedirect(ctx.Engine(), u.ID, repo.Name); err != nil { if err = deleteRepoRedirect(db.GetEngine(ctx), u.ID, repo.Name); err != nil {
return err return err
} }
@ -1102,46 +1102,46 @@ func CreateRepository(ctx *db.Context, doer, u *User, repo *Repository, overwrit
} }
} }
if _, err = ctx.Engine().Insert(&units); err != nil { if _, err = db.GetEngine(ctx).Insert(&units); err != nil {
return err return err
} }
// Remember visibility preference. // Remember visibility preference.
u.LastRepoVisibility = repo.IsPrivate u.LastRepoVisibility = repo.IsPrivate
if err = updateUserCols(ctx.Engine(), u, "last_repo_visibility"); err != nil { if err = updateUserCols(db.GetEngine(ctx), u, "last_repo_visibility"); err != nil {
return fmt.Errorf("updateUser: %v", err) return fmt.Errorf("updateUser: %v", err)
} }
if _, err = ctx.Engine().Incr("num_repos").ID(u.ID).Update(new(User)); err != nil { if _, err = db.GetEngine(ctx).Incr("num_repos").ID(u.ID).Update(new(User)); err != nil {
return fmt.Errorf("increment user total_repos: %v", err) return fmt.Errorf("increment user total_repos: %v", err)
} }
u.NumRepos++ u.NumRepos++
// Give access to all members in teams with access to all repositories. // Give access to all members in teams with access to all repositories.
if u.IsOrganization() { if u.IsOrganization() {
if err := u.loadTeams(ctx.Engine()); err != nil { if err := u.loadTeams(db.GetEngine(ctx)); err != nil {
return fmt.Errorf("loadTeams: %v", err) return fmt.Errorf("loadTeams: %v", err)
} }
for _, t := range u.Teams { for _, t := range u.Teams {
if t.IncludesAllRepositories { if t.IncludesAllRepositories {
if err := t.addRepository(ctx.Engine(), repo); err != nil { if err := t.addRepository(db.GetEngine(ctx), repo); err != nil {
return fmt.Errorf("addRepository: %v", err) return fmt.Errorf("addRepository: %v", err)
} }
} }
} }
if isAdmin, err := isUserRepoAdmin(ctx.Engine(), repo, doer); err != nil { if isAdmin, err := isUserRepoAdmin(db.GetEngine(ctx), repo, doer); err != nil {
return fmt.Errorf("isUserRepoAdmin: %v", err) return fmt.Errorf("isUserRepoAdmin: %v", err)
} else if !isAdmin { } else if !isAdmin {
// Make creator repo admin if it wan't assigned automatically // Make creator repo admin if it wan't assigned automatically
if err = repo.addCollaborator(ctx.Engine(), doer); err != nil { if err = repo.addCollaborator(db.GetEngine(ctx), doer); err != nil {
return fmt.Errorf("AddCollaborator: %v", err) return fmt.Errorf("AddCollaborator: %v", err)
} }
if err = repo.changeCollaborationAccessMode(ctx.Engine(), doer.ID, AccessModeAdmin); err != nil { if err = repo.changeCollaborationAccessMode(db.GetEngine(ctx), doer.ID, AccessModeAdmin); err != nil {
return fmt.Errorf("ChangeCollaborationAccessMode: %v", err) return fmt.Errorf("ChangeCollaborationAccessMode: %v", err)
} }
} }
} else if err = repo.recalculateAccesses(ctx.Engine()); err != nil { } else if err = repo.recalculateAccesses(db.GetEngine(ctx)); err != nil {
// Organization automatically called this in addRepository method. // Organization automatically called this in addRepository method.
return fmt.Errorf("recalculateAccesses: %v", err) return fmt.Errorf("recalculateAccesses: %v", err)
} }
@ -1157,12 +1157,12 @@ func CreateRepository(ctx *db.Context, doer, u *User, repo *Repository, overwrit
} }
if setting.Service.AutoWatchNewRepos { if setting.Service.AutoWatchNewRepos {
if err = watchRepo(ctx.Engine(), doer.ID, repo.ID, true); err != nil { if err = watchRepo(db.GetEngine(ctx), doer.ID, repo.ID, true); err != nil {
return fmt.Errorf("watchRepo: %v", err) return fmt.Errorf("watchRepo: %v", err)
} }
} }
if err = copyDefaultWebhooksToRepo(ctx.Engine(), repo.ID); err != nil { if err = copyDefaultWebhooksToRepo(db.GetEngine(ctx), repo.ID); err != nil {
return fmt.Errorf("copyDefaultWebhooksToRepo: %v", err) return fmt.Errorf("copyDefaultWebhooksToRepo: %v", err)
} }
@ -1170,7 +1170,7 @@ func CreateRepository(ctx *db.Context, doer, u *User, repo *Repository, overwrit
} }
func countRepositories(userID int64, private bool) int64 { func countRepositories(userID int64, private bool) int64 {
sess := db.DefaultContext().Engine().Where("id > 0") sess := db.GetEngine(db.DefaultContext).Where("id > 0")
if userID > 0 { if userID > 0 {
sess.And("owner_id = ?", userID) sess.And("owner_id = ?", userID)
@ -1206,14 +1206,14 @@ func RepoPath(userName, repoName string) string {
} }
// IncrementRepoForkNum increment repository fork number // IncrementRepoForkNum increment repository fork number
func IncrementRepoForkNum(ctx *db.Context, repoID int64) error { func IncrementRepoForkNum(ctx context.Context, repoID int64) error {
_, err := ctx.Engine().Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", repoID) _, err := db.GetEngine(ctx).Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", repoID)
return err return err
} }
// DecrementRepoForkNum decrement repository fork number // DecrementRepoForkNum decrement repository fork number
func DecrementRepoForkNum(ctx *db.Context, repoID int64) error { func DecrementRepoForkNum(ctx context.Context, repoID int64) error {
_, err := ctx.Engine().Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repoID) _, err := db.GetEngine(ctx).Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repoID)
return err return err
} }
@ -1253,7 +1253,7 @@ func ChangeRepositoryName(doer *User, repo *Repository, newRepoName string) (err
} }
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return fmt.Errorf("sess.Begin: %v", err) return fmt.Errorf("sess.Begin: %v", err)
@ -1275,7 +1275,7 @@ func getRepositoriesByForkID(e db.Engine, forkID int64) ([]*Repository, error) {
// GetRepositoriesByForkID returns all repositories with given fork ID. // GetRepositoriesByForkID returns all repositories with given fork ID.
func GetRepositoriesByForkID(forkID int64) ([]*Repository, error) { func GetRepositoriesByForkID(forkID int64) ([]*Repository, error) {
return getRepositoriesByForkID(db.DefaultContext().Engine(), forkID) return getRepositoriesByForkID(db.GetEngine(db.DefaultContext), forkID)
} }
func updateRepository(e db.Engine, repo *Repository, visibilityChanged bool) (err error) { func updateRepository(e db.Engine, repo *Repository, visibilityChanged bool) (err error) {
@ -1353,13 +1353,13 @@ func updateRepository(e db.Engine, repo *Repository, visibilityChanged bool) (er
} }
// UpdateRepositoryCtx updates a repository with db context // UpdateRepositoryCtx updates a repository with db context
func UpdateRepositoryCtx(ctx *db.Context, repo *Repository, visibilityChanged bool) error { func UpdateRepositoryCtx(ctx context.Context, repo *Repository, visibilityChanged bool) error {
return updateRepository(ctx.Engine(), repo, visibilityChanged) return updateRepository(db.GetEngine(ctx), repo, visibilityChanged)
} }
// UpdateRepository updates a repository // UpdateRepository updates a repository
func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) { func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -1377,7 +1377,7 @@ func UpdateRepositoryOwnerNames(ownerID int64, ownerName string) error {
if ownerID == 0 { if ownerID == 0 {
return nil return nil
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -1394,13 +1394,13 @@ func UpdateRepositoryOwnerNames(ownerID int64, ownerName string) error {
// UpdateRepositoryUpdatedTime updates a repository's updated time // UpdateRepositoryUpdatedTime updates a repository's updated time
func UpdateRepositoryUpdatedTime(repoID int64, updateTime time.Time) error { func UpdateRepositoryUpdatedTime(repoID int64, updateTime time.Time) error {
_, err := db.DefaultContext().Engine().Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", updateTime.Unix(), repoID) _, err := db.GetEngine(db.DefaultContext).Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", updateTime.Unix(), repoID)
return err return err
} }
// UpdateRepositoryUnits updates a repository's units // UpdateRepositoryUnits updates a repository's units
func UpdateRepositoryUnits(repo *Repository, units []RepoUnit, deleteUnitTypes []UnitType) (err error) { func UpdateRepositoryUnits(repo *Repository, units []RepoUnit, deleteUnitTypes []UnitType) (err error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -1427,7 +1427,7 @@ func UpdateRepositoryUnits(repo *Repository, units []RepoUnit, deleteUnitTypes [
// DeleteRepository deletes a repository for a user or organization. // 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) // 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 { func DeleteRepository(doer *User, uid, repoID int64) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -1643,21 +1643,21 @@ func DeleteRepository(doer *User, uid, repoID int64) error {
// Remove repository files. // Remove repository files.
repoPath := repo.RepoPath() repoPath := repo.RepoPath()
removeAllWithNotice(db.DefaultContext().Engine(), "Delete repository files", repoPath) removeAllWithNotice(db.GetEngine(db.DefaultContext), "Delete repository files", repoPath)
// Remove wiki files // Remove wiki files
if repo.HasWiki() { if repo.HasWiki() {
removeAllWithNotice(db.DefaultContext().Engine(), "Delete repository wiki", repo.WikiPath()) removeAllWithNotice(db.GetEngine(db.DefaultContext), "Delete repository wiki", repo.WikiPath())
} }
// Remove archives // Remove archives
for i := range archivePaths { for i := range archivePaths {
removeStorageWithNotice(db.DefaultContext().Engine(), storage.RepoArchives, "Delete repo archive file", archivePaths[i]) removeStorageWithNotice(db.GetEngine(db.DefaultContext), storage.RepoArchives, "Delete repo archive file", archivePaths[i])
} }
// Remove lfs objects // Remove lfs objects
for i := range lfsPaths { for i := range lfsPaths {
removeStorageWithNotice(db.DefaultContext().Engine(), storage.LFS, "Delete orphaned LFS file", lfsPaths[i]) removeStorageWithNotice(db.GetEngine(db.DefaultContext), storage.LFS, "Delete orphaned LFS file", lfsPaths[i])
} }
// Remove issue attachment files. // Remove issue attachment files.
@ -1686,7 +1686,7 @@ func DeleteRepository(doer *User, uid, repoID int64) error {
// GetRepositoryByOwnerAndName returns the repository by given ownername and reponame. // GetRepositoryByOwnerAndName returns the repository by given ownername and reponame.
func GetRepositoryByOwnerAndName(ownerName, repoName string) (*Repository, error) { func GetRepositoryByOwnerAndName(ownerName, repoName string) (*Repository, error) {
return getRepositoryByOwnerAndName(db.DefaultContext().Engine(), ownerName, repoName) return getRepositoryByOwnerAndName(db.GetEngine(db.DefaultContext), ownerName, repoName)
} }
func getRepositoryByOwnerAndName(e db.Engine, ownerName, repoName string) (*Repository, error) { func getRepositoryByOwnerAndName(e db.Engine, ownerName, repoName string) (*Repository, error) {
@ -1710,7 +1710,7 @@ func GetRepositoryByName(ownerID int64, name string) (*Repository, error) {
OwnerID: ownerID, OwnerID: ownerID,
LowerName: strings.ToLower(name), LowerName: strings.ToLower(name),
} }
has, err := db.DefaultContext().Engine().Get(repo) has, err := db.GetEngine(db.DefaultContext).Get(repo)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -1732,18 +1732,18 @@ func getRepositoryByID(e db.Engine, id int64) (*Repository, error) {
// GetRepositoryByID returns the repository by given id if exists. // GetRepositoryByID returns the repository by given id if exists.
func GetRepositoryByID(id int64) (*Repository, error) { func GetRepositoryByID(id int64) (*Repository, error) {
return getRepositoryByID(db.DefaultContext().Engine(), id) return getRepositoryByID(db.GetEngine(db.DefaultContext), id)
} }
// GetRepositoryByIDCtx returns the repository by given id if exists. // GetRepositoryByIDCtx returns the repository by given id if exists.
func GetRepositoryByIDCtx(ctx *db.Context, id int64) (*Repository, error) { func GetRepositoryByIDCtx(ctx context.Context, id int64) (*Repository, error) {
return getRepositoryByID(ctx.Engine(), id) return getRepositoryByID(db.GetEngine(ctx), id)
} }
// GetRepositoriesMapByIDs returns the repositories by given id slice. // GetRepositoriesMapByIDs returns the repositories by given id slice.
func GetRepositoriesMapByIDs(ids []int64) (map[int64]*Repository, error) { func GetRepositoriesMapByIDs(ids []int64) (map[int64]*Repository, error) {
repos := make(map[int64]*Repository, len(ids)) repos := make(map[int64]*Repository, len(ids))
return repos, db.DefaultContext().Engine().In("id", ids).Find(&repos) return repos, db.GetEngine(db.DefaultContext).In("id", ids).Find(&repos)
} }
// GetUserRepositories returns a list of repositories of given user. // GetUserRepositories returns a list of repositories of given user.
@ -1762,7 +1762,7 @@ func GetUserRepositories(opts *SearchRepoOptions) ([]*Repository, int64, error)
cond = cond.And(builder.In("lower_name", opts.LowerNames)) cond = cond.And(builder.In("lower_name", opts.LowerNames))
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
count, err := sess.Where(cond).Count(new(Repository)) count, err := sess.Where(cond).Count(new(Repository))
@ -1778,7 +1778,7 @@ func GetUserRepositories(opts *SearchRepoOptions) ([]*Repository, int64, error)
// GetUserMirrorRepositories returns a list of mirror repositories of given user. // GetUserMirrorRepositories returns a list of mirror repositories of given user.
func GetUserMirrorRepositories(userID int64) ([]*Repository, error) { func GetUserMirrorRepositories(userID int64) ([]*Repository, error) {
repos := make([]*Repository, 0, 10) repos := make([]*Repository, 0, 10)
return repos, db.DefaultContext().Engine(). return repos, db.GetEngine(db.DefaultContext).
Where("owner_id = ?", userID). Where("owner_id = ?", userID).
And("is_mirror = ?", true). And("is_mirror = ?", true).
Find(&repos) Find(&repos)
@ -1798,17 +1798,17 @@ func getPrivateRepositoryCount(e db.Engine, u *User) (int64, error) {
// GetRepositoryCount returns the total number of repositories of user. // GetRepositoryCount returns the total number of repositories of user.
func GetRepositoryCount(u *User) (int64, error) { func GetRepositoryCount(u *User) (int64, error) {
return getRepositoryCount(db.DefaultContext().Engine(), u) return getRepositoryCount(db.GetEngine(db.DefaultContext), u)
} }
// GetPublicRepositoryCount returns the total number of public repositories of user. // GetPublicRepositoryCount returns the total number of public repositories of user.
func GetPublicRepositoryCount(u *User) (int64, error) { func GetPublicRepositoryCount(u *User) (int64, error) {
return getPublicRepositoryCount(db.DefaultContext().Engine(), u) return getPublicRepositoryCount(db.GetEngine(db.DefaultContext), u)
} }
// GetPrivateRepositoryCount returns the total number of private repositories of user. // GetPrivateRepositoryCount returns the total number of private repositories of user.
func GetPrivateRepositoryCount(u *User) (int64, error) { func GetPrivateRepositoryCount(u *User) (int64, error) {
return getPrivateRepositoryCount(db.DefaultContext().Engine(), u) return getPrivateRepositoryCount(db.GetEngine(db.DefaultContext), u)
} }
// DeleteOldRepositoryArchives deletes old repository archives. // DeleteOldRepositoryArchives deletes old repository archives.
@ -1817,7 +1817,7 @@ func DeleteOldRepositoryArchives(ctx context.Context, olderThan time.Duration) e
for { for {
var archivers []RepoArchiver var archivers []RepoArchiver
err := db.DefaultContext().Engine().Where("created_unix < ?", time.Now().Add(-olderThan).Unix()). err := db.GetEngine(db.DefaultContext).Where("created_unix < ?", time.Now().Add(-olderThan).Unix()).
Asc("created_unix"). Asc("created_unix").
Limit(100). Limit(100).
Find(&archivers) Find(&archivers)
@ -1847,7 +1847,7 @@ func deleteOldRepoArchiver(ctx context.Context, archiver *RepoArchiver) error {
if err != nil { if err != nil {
return err return err
} }
_, err = db.DefaultContext().Engine().ID(archiver.ID).Delete(delRepoArchiver) _, err = db.GetEngine(db.DefaultContext).ID(archiver.ID).Delete(delRepoArchiver)
if err != nil { if err != nil {
return err return err
} }
@ -1863,7 +1863,7 @@ type repoChecker struct {
} }
func repoStatsCheck(ctx context.Context, checker *repoChecker) { func repoStatsCheck(ctx context.Context, checker *repoChecker) {
results, err := db.DefaultContext().Engine().Query(checker.querySQL) results, err := db.GetEngine(db.DefaultContext).Query(checker.querySQL)
if err != nil { if err != nil {
log.Error("Select %s: %v", checker.desc, err) log.Error("Select %s: %v", checker.desc, err)
return return
@ -1877,7 +1877,7 @@ func repoStatsCheck(ctx context.Context, checker *repoChecker) {
default: default:
} }
log.Trace("Updating %s: %d", checker.desc, id) log.Trace("Updating %s: %d", checker.desc, id)
_, err = db.DefaultContext().Engine().Exec(checker.correctSQL, id, id) _, err = db.GetEngine(db.DefaultContext).Exec(checker.correctSQL, id, id)
if err != nil { if err != nil {
log.Error("Update %s[%d]: %v", checker.desc, id, err) log.Error("Update %s[%d]: %v", checker.desc, id, err)
} }
@ -1932,7 +1932,7 @@ func CheckRepoStats(ctx context.Context) error {
// ***** START: Repository.NumClosedIssues ***** // ***** START: Repository.NumClosedIssues *****
desc := "repository count 'num_closed_issues'" desc := "repository count 'num_closed_issues'"
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) results, err := db.GetEngine(db.DefaultContext).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 { if err != nil {
log.Error("Select %s: %v", desc, err) log.Error("Select %s: %v", desc, err)
} else { } else {
@ -1945,7 +1945,7 @@ func CheckRepoStats(ctx context.Context) error {
default: default:
} }
log.Trace("Updating %s: %d", desc, id) log.Trace("Updating %s: %d", desc, 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) _, err = db.GetEngine(db.DefaultContext).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 { if err != nil {
log.Error("Update %s[%d]: %v", desc, id, err) log.Error("Update %s[%d]: %v", desc, id, err)
} }
@ -1955,7 +1955,7 @@ func CheckRepoStats(ctx context.Context) error {
// ***** START: Repository.NumClosedPulls ***** // ***** START: Repository.NumClosedPulls *****
desc = "repository count 'num_closed_pulls'" desc = "repository count 'num_closed_pulls'"
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) results, err = db.GetEngine(db.DefaultContext).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 { if err != nil {
log.Error("Select %s: %v", desc, err) log.Error("Select %s: %v", desc, err)
} else { } else {
@ -1968,7 +1968,7 @@ func CheckRepoStats(ctx context.Context) error {
default: default:
} }
log.Trace("Updating %s: %d", desc, id) log.Trace("Updating %s: %d", desc, 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) _, err = db.GetEngine(db.DefaultContext).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 { if err != nil {
log.Error("Update %s[%d]: %v", desc, id, err) log.Error("Update %s[%d]: %v", desc, id, err)
} }
@ -1978,7 +1978,7 @@ func CheckRepoStats(ctx context.Context) error {
// FIXME: use checker when stop supporting old fork repo format. // FIXME: use checker when stop supporting old fork repo format.
// ***** START: Repository.NumForks ***** // ***** START: Repository.NumForks *****
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)") results, err = db.GetEngine(db.DefaultContext).Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)")
if err != nil { if err != nil {
log.Error("Select repository count 'num_forks': %v", err) log.Error("Select repository count 'num_forks': %v", err)
} else { } else {
@ -1998,7 +1998,7 @@ func CheckRepoStats(ctx context.Context) error {
continue continue
} }
rawResult, err := db.DefaultContext().Engine().Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID) rawResult, err := db.GetEngine(db.DefaultContext).Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID)
if err != nil { if err != nil {
log.Error("Select count of forks[%d]: %v", repo.ID, err) log.Error("Select count of forks[%d]: %v", repo.ID, err)
continue continue
@ -2018,7 +2018,7 @@ func CheckRepoStats(ctx context.Context) error {
// SetArchiveRepoState sets if a repo is archived // SetArchiveRepoState sets if a repo is archived
func (repo *Repository) SetArchiveRepoState(isArchived bool) (err error) { func (repo *Repository) SetArchiveRepoState(isArchived bool) (err error) {
repo.IsArchived = isArchived repo.IsArchived = isArchived
_, err = db.DefaultContext().Engine().Where("id = ?", repo.ID).Cols("is_archived").NoAutoTime().Update(repo) _, err = db.GetEngine(db.DefaultContext).Where("id = ?", repo.ID).Cols("is_archived").NoAutoTime().Update(repo)
return return
} }
@ -2032,23 +2032,23 @@ func (repo *Repository) SetArchiveRepoState(isArchived bool) (err error) {
// HasForkedRepo checks if given user has already forked a repository with given ID. // HasForkedRepo checks if given user has already forked a repository with given ID.
func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) { func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) {
repo := new(Repository) repo := new(Repository)
has, _ := db.DefaultContext().Engine(). has, _ := db.GetEngine(db.DefaultContext).
Where("owner_id=? AND fork_id=?", ownerID, repoID). Where("owner_id=? AND fork_id=?", ownerID, repoID).
Get(repo) Get(repo)
return repo, has return repo, has
} }
// CopyLFS copies LFS data from one repo to another // CopyLFS copies LFS data from one repo to another
func CopyLFS(ctx *db.Context, newRepo, oldRepo *Repository) error { func CopyLFS(ctx context.Context, newRepo, oldRepo *Repository) error {
var lfsObjects []*LFSMetaObject var lfsObjects []*LFSMetaObject
if err := ctx.Engine().Where("repository_id=?", oldRepo.ID).Find(&lfsObjects); err != nil { if err := db.GetEngine(ctx).Where("repository_id=?", oldRepo.ID).Find(&lfsObjects); err != nil {
return err return err
} }
for _, v := range lfsObjects { for _, v := range lfsObjects {
v.ID = 0 v.ID = 0
v.RepositoryID = newRepo.ID v.RepositoryID = newRepo.ID
if _, err := ctx.Engine().Insert(v); err != nil { if _, err := db.GetEngine(ctx).Insert(v); err != nil {
return err return err
} }
} }
@ -2060,7 +2060,7 @@ func CopyLFS(ctx *db.Context, newRepo, oldRepo *Repository) error {
func (repo *Repository) GetForks(listOptions ListOptions) ([]*Repository, error) { func (repo *Repository) GetForks(listOptions ListOptions) ([]*Repository, error) {
if listOptions.Page == 0 { if listOptions.Page == 0 {
forks := make([]*Repository, 0, repo.NumForks) forks := make([]*Repository, 0, repo.NumForks)
return forks, db.DefaultContext().Engine().Find(&forks, &Repository{ForkID: repo.ID}) return forks, db.GetEngine(db.DefaultContext).Find(&forks, &Repository{ForkID: repo.ID})
} }
sess := getPaginatedSession(&listOptions) sess := getPaginatedSession(&listOptions)
@ -2071,7 +2071,7 @@ func (repo *Repository) GetForks(listOptions ListOptions) ([]*Repository, error)
// GetUserFork return user forked repository from this repository, if not forked return nil // GetUserFork return user forked repository from this repository, if not forked return nil
func (repo *Repository) GetUserFork(userID int64) (*Repository, error) { func (repo *Repository) GetUserFork(userID int64) (*Repository, error) {
var forkedRepo Repository var forkedRepo Repository
has, err := db.DefaultContext().Engine().Where("fork_id = ?", repo.ID).And("owner_id = ?", userID).Get(&forkedRepo) has, err := db.GetEngine(db.DefaultContext).Where("fork_id = ?", repo.ID).And("owner_id = ?", userID).Get(&forkedRepo)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -2114,7 +2114,7 @@ func updateRepositoryCols(e db.Engine, repo *Repository, cols ...string) error {
// UpdateRepositoryCols updates repository's columns // UpdateRepositoryCols updates repository's columns
func UpdateRepositoryCols(repo *Repository, cols ...string) error { func UpdateRepositoryCols(repo *Repository, cols ...string) error {
return updateRepositoryCols(db.DefaultContext().Engine(), repo, cols...) return updateRepositoryCols(db.GetEngine(db.DefaultContext), repo, cols...)
} }
// GetTrustModel will get the TrustModel for the repo or the default trust model // GetTrustModel will get the TrustModel for the repo or the default trust model
@ -2132,7 +2132,7 @@ func (repo *Repository) GetTrustModel() TrustModelType {
// DoctorUserStarNum recalculate Stars number for all user // DoctorUserStarNum recalculate Stars number for all user
func DoctorUserStarNum() (err error) { func DoctorUserStarNum() (err error) {
const batchSize = 100 const batchSize = 100
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
for start := 0; ; start += batchSize { for start := 0; ; start += batchSize {
@ -2170,7 +2170,7 @@ func IterateRepository(f func(repo *Repository) error) error {
batchSize := setting.Database.IterateBufferSize batchSize := setting.Database.IterateBufferSize
for { for {
repos := make([]*Repository, 0, batchSize) repos := make([]*Repository, 0, batchSize)
if err := db.DefaultContext().Engine().Limit(batchSize, start).Find(&repos); err != nil { if err := db.GetEngine(db.DefaultContext).Limit(batchSize, start).Find(&repos); err != nil {
return err return err
} }
if len(repos) == 0 { if len(repos) == 0 {

View File

@ -246,7 +246,7 @@ func (stats *ActivityStats) FillPullRequests(repoID int64, fromTime time.Time) e
} }
func pullRequestsForActivityStatement(repoID int64, fromTime time.Time, merged bool) *xorm.Session { func pullRequestsForActivityStatement(repoID int64, fromTime time.Time, merged bool) *xorm.Session {
sess := db.DefaultContext().Engine().Where("pull_request.base_repo_id=?", repoID). sess := db.GetEngine(db.DefaultContext).Where("pull_request.base_repo_id=?", repoID).
Join("INNER", "issue", "pull_request.issue_id = issue.id") Join("INNER", "issue", "pull_request.issue_id = issue.id")
if merged { if merged {
@ -314,7 +314,7 @@ func (stats *ActivityStats) FillUnresolvedIssues(repoID int64, fromTime time.Tim
} }
func issuesForActivityStatement(repoID int64, fromTime time.Time, closed, unresolved bool) *xorm.Session { func issuesForActivityStatement(repoID int64, fromTime time.Time, closed, unresolved bool) *xorm.Session {
sess := db.DefaultContext().Engine().Where("issue.repo_id = ?", repoID). sess := db.GetEngine(db.DefaultContext).Where("issue.repo_id = ?", repoID).
And("issue.is_closed = ?", closed) And("issue.is_closed = ?", closed)
if !unresolved { if !unresolved {
@ -356,7 +356,7 @@ func (stats *ActivityStats) FillReleases(repoID int64, fromTime time.Time) error
} }
func releasesForActivityStatement(repoID int64, fromTime time.Time) *xorm.Session { func releasesForActivityStatement(repoID int64, fromTime time.Time) *xorm.Session {
return db.DefaultContext().Engine().Where("release.repo_id = ?", repoID). return db.GetEngine(db.DefaultContext).Where("release.repo_id = ?", repoID).
And("release.is_draft = ?", false). And("release.is_draft = ?", false).
And("release.created_unix >= ?", fromTime.Unix()) And("release.created_unix >= ?", fromTime.Unix())
} }

View File

@ -5,6 +5,7 @@
package models package models
import ( import (
"context"
"fmt" "fmt"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
@ -43,7 +44,7 @@ func (archiver *RepoArchiver) LoadRepo() (*Repository, error) {
} }
var repo Repository var repo Repository
has, err := db.DefaultContext().Engine().ID(archiver.RepoID).Get(&repo) has, err := db.GetEngine(db.DefaultContext).ID(archiver.RepoID).Get(&repo)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -61,9 +62,9 @@ func (archiver *RepoArchiver) RelativePath() (string, error) {
} }
// GetRepoArchiver get an archiver // GetRepoArchiver get an archiver
func GetRepoArchiver(ctx *db.Context, repoID int64, tp git.ArchiveType, commitID string) (*RepoArchiver, error) { func GetRepoArchiver(ctx context.Context, repoID int64, tp git.ArchiveType, commitID string) (*RepoArchiver, error) {
var archiver RepoArchiver var archiver RepoArchiver
has, err := ctx.Engine().Where("repo_id=?", repoID).And("`type`=?", tp).And("commit_id=?", commitID).Get(&archiver) has, err := db.GetEngine(ctx).Where("repo_id=?", repoID).And("`type`=?", tp).And("commit_id=?", commitID).Get(&archiver)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -74,19 +75,19 @@ func GetRepoArchiver(ctx *db.Context, repoID int64, tp git.ArchiveType, commitID
} }
// AddRepoArchiver adds an archiver // AddRepoArchiver adds an archiver
func AddRepoArchiver(ctx *db.Context, archiver *RepoArchiver) error { func AddRepoArchiver(ctx context.Context, archiver *RepoArchiver) error {
_, err := ctx.Engine().Insert(archiver) _, err := db.GetEngine(ctx).Insert(archiver)
return err return err
} }
// UpdateRepoArchiverStatus updates archiver's status // UpdateRepoArchiverStatus updates archiver's status
func UpdateRepoArchiverStatus(ctx *db.Context, archiver *RepoArchiver) error { func UpdateRepoArchiverStatus(ctx context.Context, archiver *RepoArchiver) error {
_, err := ctx.Engine().ID(archiver.ID).Cols("status").Update(archiver) _, err := db.GetEngine(ctx).ID(archiver.ID).Cols("status").Update(archiver)
return err return err
} }
// DeleteAllRepoArchives deletes all repo archives records // DeleteAllRepoArchives deletes all repo archives records
func DeleteAllRepoArchives() error { func DeleteAllRepoArchives() error {
_, err := db.DefaultContext().Engine().Where("1=1").Delete(new(RepoArchiver)) _, err := db.GetEngine(db.DefaultContext).Where("1=1").Delete(new(RepoArchiver))
return err return err
} }

View File

@ -57,7 +57,7 @@ func (repo *Repository) generateRandomAvatar(e db.Engine) error {
// RemoveRandomAvatars removes the randomly generated avatars that were created for repositories // RemoveRandomAvatars removes the randomly generated avatars that were created for repositories
func RemoveRandomAvatars(ctx context.Context) error { func RemoveRandomAvatars(ctx context.Context) error {
return db.DefaultContext().Engine(). return db.GetEngine(db.DefaultContext).
Where("id > 0").BufferSize(setting.Database.IterateBufferSize). Where("id > 0").BufferSize(setting.Database.IterateBufferSize).
Iterate(new(Repository), Iterate(new(Repository),
func(idx int, bean interface{}) error { func(idx int, bean interface{}) error {
@ -77,7 +77,7 @@ func RemoveRandomAvatars(ctx context.Context) error {
// RelAvatarLink returns a relative link to the repository's avatar. // RelAvatarLink returns a relative link to the repository's avatar.
func (repo *Repository) RelAvatarLink() string { func (repo *Repository) RelAvatarLink() string {
return repo.relAvatarLink(db.DefaultContext().Engine()) return repo.relAvatarLink(db.GetEngine(db.DefaultContext))
} }
func (repo *Repository) relAvatarLink(e db.Engine) string { func (repo *Repository) relAvatarLink(e db.Engine) string {
@ -101,7 +101,7 @@ func (repo *Repository) relAvatarLink(e db.Engine) string {
// AvatarLink returns a link to the repository's avatar. // AvatarLink returns a link to the repository's avatar.
func (repo *Repository) AvatarLink() string { func (repo *Repository) AvatarLink() string {
return repo.avatarLink(db.DefaultContext().Engine()) return repo.avatarLink(db.GetEngine(db.DefaultContext))
} }
// avatarLink returns user avatar absolute link. // avatarLink returns user avatar absolute link.
@ -129,7 +129,7 @@ func (repo *Repository) UploadAvatar(data []byte) error {
return nil return nil
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -172,7 +172,7 @@ func (repo *Repository) DeleteAvatar() error {
avatarPath := repo.CustomAvatarRelativePath() avatarPath := repo.CustomAvatarRelativePath()
log.Trace("DeleteAvatar[%d]: %s", repo.ID, avatarPath) log.Trace("DeleteAvatar[%d]: %s", repo.ID, avatarPath)
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err

View File

@ -51,7 +51,7 @@ func (repo *Repository) addCollaborator(e db.Engine, u *User) error {
// AddCollaborator adds new collaboration to a repository with default access mode. // AddCollaborator adds new collaboration to a repository with default access mode.
func (repo *Repository) AddCollaborator(u *User) error { func (repo *Repository) AddCollaborator(u *User) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -104,12 +104,12 @@ func (repo *Repository) getCollaborators(e db.Engine, listOptions ListOptions) (
// GetCollaborators returns the collaborators for a repository // GetCollaborators returns the collaborators for a repository
func (repo *Repository) GetCollaborators(listOptions ListOptions) ([]*Collaborator, error) { func (repo *Repository) GetCollaborators(listOptions ListOptions) ([]*Collaborator, error) {
return repo.getCollaborators(db.DefaultContext().Engine(), listOptions) return repo.getCollaborators(db.GetEngine(db.DefaultContext), listOptions)
} }
// CountCollaborators returns total number of collaborators for a repository // CountCollaborators returns total number of collaborators for a repository
func (repo *Repository) CountCollaborators() (int64, error) { func (repo *Repository) CountCollaborators() (int64, error) {
return db.DefaultContext().Engine().Where("repo_id = ? ", repo.ID).Count(&Collaboration{}) return db.GetEngine(db.DefaultContext).Where("repo_id = ? ", repo.ID).Count(&Collaboration{})
} }
func (repo *Repository) getCollaboration(e db.Engine, uid int64) (*Collaboration, error) { func (repo *Repository) getCollaboration(e db.Engine, uid int64) (*Collaboration, error) {
@ -130,7 +130,7 @@ func (repo *Repository) isCollaborator(e db.Engine, userID int64) (bool, error)
// IsCollaborator check if a user is a collaborator of a repository // IsCollaborator check if a user is a collaborator of a repository
func (repo *Repository) IsCollaborator(userID int64) (bool, error) { func (repo *Repository) IsCollaborator(userID int64) (bool, error) {
return repo.isCollaborator(db.DefaultContext().Engine(), userID) return repo.isCollaborator(db.GetEngine(db.DefaultContext), userID)
} }
func (repo *Repository) changeCollaborationAccessMode(e db.Engine, uid int64, mode AccessMode) error { func (repo *Repository) changeCollaborationAccessMode(e db.Engine, uid int64, mode AccessMode) error {
@ -169,7 +169,7 @@ func (repo *Repository) changeCollaborationAccessMode(e db.Engine, uid int64, mo
// ChangeCollaborationAccessMode sets new access mode for the collaboration. // ChangeCollaborationAccessMode sets new access mode for the collaboration.
func (repo *Repository) ChangeCollaborationAccessMode(uid int64, mode AccessMode) error { func (repo *Repository) ChangeCollaborationAccessMode(uid int64, mode AccessMode) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -189,7 +189,7 @@ func (repo *Repository) DeleteCollaboration(uid int64) (err error) {
UserID: uid, UserID: uid,
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -259,7 +259,7 @@ func (repo *Repository) getRepoTeams(e db.Engine) (teams []*Team, err error) {
// GetRepoTeams gets the list of teams that has access to the repository // GetRepoTeams gets the list of teams that has access to the repository
func (repo *Repository) GetRepoTeams() ([]*Team, error) { func (repo *Repository) GetRepoTeams() ([]*Team, error) {
return repo.getRepoTeams(db.DefaultContext().Engine()) return repo.getRepoTeams(db.GetEngine(db.DefaultContext))
} }
// IsOwnerMemberCollaborator checks if a provided user is the owner, a collaborator or a member of a team in a repository // IsOwnerMemberCollaborator checks if a provided user is the owner, a collaborator or a member of a team in a repository
@ -267,7 +267,7 @@ func (repo *Repository) IsOwnerMemberCollaborator(userID int64) (bool, error) {
if repo.OwnerID == userID { if repo.OwnerID == userID {
return true, nil return true, nil
} }
teamMember, err := db.DefaultContext().Engine().Join("INNER", "team_repo", "team_repo.team_id = team_user.team_id"). teamMember, err := db.GetEngine(db.DefaultContext).Join("INNER", "team_repo", "team_repo.team_id = team_user.team_id").
Join("INNER", "team_unit", "team_unit.team_id = team_user.team_id"). Join("INNER", "team_unit", "team_unit.team_id = team_user.team_id").
Where("team_repo.repo_id = ?", repo.ID). Where("team_repo.repo_id = ?", repo.ID).
And("team_unit.`type` = ?", UnitTypeCode). And("team_unit.`type` = ?", UnitTypeCode).
@ -279,5 +279,5 @@ func (repo *Repository) IsOwnerMemberCollaborator(userID int64) (bool, error) {
return true, nil return true, nil
} }
return db.DefaultContext().Engine().Get(&Collaboration{RepoID: repo.ID, UserID: userID}) return db.GetEngine(db.DefaultContext).Get(&Collaboration{RepoID: repo.ID, UserID: userID})
} }

View File

@ -32,7 +32,7 @@ func TestRepository_GetCollaborators(t *testing.T) {
repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository)
collaborators, err := repo.GetCollaborators(ListOptions{}) collaborators, err := repo.GetCollaborators(ListOptions{})
assert.NoError(t, err) assert.NoError(t, err)
expectedLen, err := db.DefaultContext().Engine().Count(&Collaboration{RepoID: repoID}) expectedLen, err := db.GetEngine(db.DefaultContext).Count(&Collaboration{RepoID: repoID})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, collaborators, int(expectedLen)) assert.Len(t, collaborators, int(expectedLen))
for _, collaborator := range collaborators { for _, collaborator := range collaborators {

View File

@ -7,6 +7,7 @@ package models
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"context"
"strconv" "strconv"
"strings" "strings"
@ -68,9 +69,9 @@ func (gt GiteaTemplate) Globs() []glob.Glob {
} }
// GenerateTopics generates topics from a template repository // GenerateTopics generates topics from a template repository
func GenerateTopics(ctx *db.Context, templateRepo, generateRepo *Repository) error { func GenerateTopics(ctx context.Context, templateRepo, generateRepo *Repository) error {
for _, topic := range templateRepo.Topics { for _, topic := range templateRepo.Topics {
if _, err := addTopicByNameToRepo(ctx.Engine(), generateRepo.ID, topic); err != nil { if _, err := addTopicByNameToRepo(db.GetEngine(ctx), generateRepo.ID, topic); err != nil {
return err return err
} }
} }
@ -78,7 +79,7 @@ func GenerateTopics(ctx *db.Context, templateRepo, generateRepo *Repository) err
} }
// GenerateGitHooks generates git hooks from a template repository // GenerateGitHooks generates git hooks from a template repository
func GenerateGitHooks(ctx *db.Context, templateRepo, generateRepo *Repository) error { func GenerateGitHooks(ctx context.Context, templateRepo, generateRepo *Repository) error {
generateGitRepo, err := git.OpenRepository(generateRepo.RepoPath()) generateGitRepo, err := git.OpenRepository(generateRepo.RepoPath())
if err != nil { if err != nil {
return err return err
@ -111,7 +112,7 @@ func GenerateGitHooks(ctx *db.Context, templateRepo, generateRepo *Repository) e
} }
// GenerateWebhooks generates webhooks from a template repository // GenerateWebhooks generates webhooks from a template repository
func GenerateWebhooks(ctx *db.Context, templateRepo, generateRepo *Repository) error { func GenerateWebhooks(ctx context.Context, templateRepo, generateRepo *Repository) error {
templateWebhooks, err := ListWebhooksByOpts(&ListWebhookOptions{RepoID: templateRepo.ID}) templateWebhooks, err := ListWebhooksByOpts(&ListWebhookOptions{RepoID: templateRepo.ID})
if err != nil { if err != nil {
return err return err
@ -131,7 +132,7 @@ func GenerateWebhooks(ctx *db.Context, templateRepo, generateRepo *Repository) e
Events: templateWebhook.Events, Events: templateWebhook.Events,
Meta: templateWebhook.Meta, Meta: templateWebhook.Meta,
} }
if err := createWebhook(ctx.Engine(), generateWebhook); err != nil { if err := createWebhook(db.GetEngine(ctx), generateWebhook); err != nil {
return err return err
} }
} }
@ -139,18 +140,18 @@ func GenerateWebhooks(ctx *db.Context, templateRepo, generateRepo *Repository) e
} }
// GenerateAvatar generates the avatar from a template repository // GenerateAvatar generates the avatar from a template repository
func GenerateAvatar(ctx *db.Context, templateRepo, generateRepo *Repository) error { func GenerateAvatar(ctx context.Context, templateRepo, generateRepo *Repository) error {
generateRepo.Avatar = strings.Replace(templateRepo.Avatar, strconv.FormatInt(templateRepo.ID, 10), strconv.FormatInt(generateRepo.ID, 10), 1) generateRepo.Avatar = strings.Replace(templateRepo.Avatar, strconv.FormatInt(templateRepo.ID, 10), strconv.FormatInt(generateRepo.ID, 10), 1)
if _, err := storage.Copy(storage.RepoAvatars, generateRepo.CustomAvatarRelativePath(), storage.RepoAvatars, templateRepo.CustomAvatarRelativePath()); err != nil { if _, err := storage.Copy(storage.RepoAvatars, generateRepo.CustomAvatarRelativePath(), storage.RepoAvatars, templateRepo.CustomAvatarRelativePath()); err != nil {
return err return err
} }
return updateRepositoryCols(ctx.Engine(), generateRepo, "avatar") return updateRepositoryCols(db.GetEngine(ctx), generateRepo, "avatar")
} }
// GenerateIssueLabels generates issue labels from a template repository // GenerateIssueLabels generates issue labels from a template repository
func GenerateIssueLabels(ctx *db.Context, templateRepo, generateRepo *Repository) error { func GenerateIssueLabels(ctx context.Context, templateRepo, generateRepo *Repository) error {
templateLabels, err := getLabelsByRepoID(ctx.Engine(), templateRepo.ID, "", ListOptions{}) templateLabels, err := getLabelsByRepoID(db.GetEngine(ctx), templateRepo.ID, "", ListOptions{})
if err != nil { if err != nil {
return err return err
} }
@ -162,7 +163,7 @@ func GenerateIssueLabels(ctx *db.Context, templateRepo, generateRepo *Repository
Description: templateLabel.Description, Description: templateLabel.Description,
Color: templateLabel.Color, Color: templateLabel.Color,
} }
if err := newLabel(ctx.Engine(), generateLabel); err != nil { if err := newLabel(db.GetEngine(ctx), generateLabel); err != nil {
return err return err
} }
} }

View File

@ -42,7 +42,7 @@ func GetUnindexedRepos(indexerType RepoIndexerType, maxRepoID int64, page, pageS
}).And(builder.Eq{ }).And(builder.Eq{
"repository.is_empty": false, "repository.is_empty": false,
}) })
sess := db.DefaultContext().Engine().Table("repository").Join("LEFT OUTER", "repo_indexer_status", "repository.id = repo_indexer_status.repo_id AND repo_indexer_status.indexer_type = ?", indexerType) sess := db.GetEngine(db.DefaultContext).Table("repository").Join("LEFT OUTER", "repo_indexer_status", "repository.id = repo_indexer_status.repo_id AND repo_indexer_status.indexer_type = ?", indexerType)
if maxRepoID > 0 { if maxRepoID > 0 {
cond = builder.And(cond, builder.Lte{ cond = builder.And(cond, builder.Lte{
"repository.id": maxRepoID, "repository.id": maxRepoID,
@ -91,7 +91,7 @@ func (repo *Repository) getIndexerStatus(e db.Engine, indexerType RepoIndexerTyp
// GetIndexerStatus loads repo codes indxer status // GetIndexerStatus loads repo codes indxer status
func (repo *Repository) GetIndexerStatus(indexerType RepoIndexerType) (*RepoIndexerStatus, error) { func (repo *Repository) GetIndexerStatus(indexerType RepoIndexerType) (*RepoIndexerStatus, error) {
return repo.getIndexerStatus(db.DefaultContext().Engine(), indexerType) return repo.getIndexerStatus(db.GetEngine(db.DefaultContext), indexerType)
} }
// updateIndexerStatus updates indexer status // updateIndexerStatus updates indexer status
@ -120,5 +120,5 @@ func (repo *Repository) updateIndexerStatus(e db.Engine, indexerType RepoIndexer
// UpdateIndexerStatus updates indexer status // UpdateIndexerStatus updates indexer status
func (repo *Repository) UpdateIndexerStatus(indexerType RepoIndexerType, sha string) error { func (repo *Repository) UpdateIndexerStatus(indexerType RepoIndexerType, sha string) error {
return repo.updateIndexerStatus(db.DefaultContext().Engine(), indexerType, sha) return repo.updateIndexerStatus(db.GetEngine(db.DefaultContext), indexerType, sha)
} }

View File

@ -75,12 +75,12 @@ func (repo *Repository) getLanguageStats(e db.Engine) (LanguageStatList, error)
// GetLanguageStats returns the language statistics for a repository // GetLanguageStats returns the language statistics for a repository
func (repo *Repository) GetLanguageStats() (LanguageStatList, error) { func (repo *Repository) GetLanguageStats() (LanguageStatList, error) {
return repo.getLanguageStats(db.DefaultContext().Engine()) return repo.getLanguageStats(db.GetEngine(db.DefaultContext))
} }
// GetTopLanguageStats returns the top language statistics for a repository // GetTopLanguageStats returns the top language statistics for a repository
func (repo *Repository) GetTopLanguageStats(limit int) (LanguageStatList, error) { func (repo *Repository) GetTopLanguageStats(limit int) (LanguageStatList, error) {
stats, err := repo.getLanguageStats(db.DefaultContext().Engine()) stats, err := repo.getLanguageStats(db.GetEngine(db.DefaultContext))
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -112,7 +112,7 @@ func (repo *Repository) GetTopLanguageStats(limit int) (LanguageStatList, error)
// UpdateLanguageStats updates the language statistics for repository // UpdateLanguageStats updates the language statistics for repository
func (repo *Repository) UpdateLanguageStats(commitID string, stats map[string]int64) error { func (repo *Repository) UpdateLanguageStats(commitID string, stats map[string]int64) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
} }
@ -183,7 +183,7 @@ func (repo *Repository) UpdateLanguageStats(commitID string, stats map[string]in
// CopyLanguageStat Copy originalRepo language stat information to destRepo (use for forked repo) // CopyLanguageStat Copy originalRepo language stat information to destRepo (use for forked repo)
func CopyLanguageStat(originalRepo, destRepo *Repository) error { func CopyLanguageStat(originalRepo, destRepo *Repository) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err

View File

@ -90,7 +90,7 @@ func (repos RepositoryList) loadAttributes(e db.Engine) error {
// LoadAttributes loads the attributes for the given RepositoryList // LoadAttributes loads the attributes for the given RepositoryList
func (repos RepositoryList) LoadAttributes() error { func (repos RepositoryList) LoadAttributes() error {
return repos.loadAttributes(db.DefaultContext().Engine()) return repos.loadAttributes(db.GetEngine(db.DefaultContext))
} }
// MirrorRepositoryList contains the mirror repositories // MirrorRepositoryList contains the mirror repositories
@ -130,7 +130,7 @@ func (repos MirrorRepositoryList) loadAttributes(e db.Engine) error {
// LoadAttributes loads the attributes for the given MirrorRepositoryList // LoadAttributes loads the attributes for the given MirrorRepositoryList
func (repos MirrorRepositoryList) LoadAttributes() error { func (repos MirrorRepositoryList) LoadAttributes() error {
return repos.loadAttributes(db.DefaultContext().Engine()) return repos.loadAttributes(db.GetEngine(db.DefaultContext))
} }
// SearchRepoOptions holds the search options // SearchRepoOptions holds the search options
@ -410,7 +410,7 @@ func searchRepositoryByCondition(opts *SearchRepoOptions, cond builder.Cond) (*x
opts.OrderBy = SearchOrderBy(fmt.Sprintf("CASE WHEN owner_id = %d THEN 0 ELSE owner_id END, %s", opts.PriorityOwnerID, opts.OrderBy)) opts.OrderBy = SearchOrderBy(fmt.Sprintf("CASE WHEN owner_id = %d THEN 0 ELSE owner_id END, %s", opts.PriorityOwnerID, opts.OrderBy))
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
var count int64 var count int64
if opts.PageSize > 0 { if opts.PageSize > 0 {
@ -520,7 +520,7 @@ func AccessibleRepoIDsQuery(user *User) *builder.Builder {
// FindUserAccessibleRepoIDs find all accessible repositories' ID by user's id // FindUserAccessibleRepoIDs find all accessible repositories' ID by user's id
func FindUserAccessibleRepoIDs(user *User) ([]int64, error) { func FindUserAccessibleRepoIDs(user *User) ([]int64, error) {
repoIDs := make([]int64, 0, 10) repoIDs := make([]int64, 0, 10)
if err := db.DefaultContext().Engine(). if err := db.GetEngine(db.DefaultContext).
Table("repository"). Table("repository").
Cols("id"). Cols("id").
Where(accessibleRepositoryCondition(user)). Where(accessibleRepositoryCondition(user)).

View File

@ -95,7 +95,7 @@ func getMirrorByRepoID(e db.Engine, repoID int64) (*Mirror, error) {
// GetMirrorByRepoID returns mirror information of a repository. // GetMirrorByRepoID returns mirror information of a repository.
func GetMirrorByRepoID(repoID int64) (*Mirror, error) { func GetMirrorByRepoID(repoID int64) (*Mirror, error) {
return getMirrorByRepoID(db.DefaultContext().Engine(), repoID) return getMirrorByRepoID(db.GetEngine(db.DefaultContext), repoID)
} }
func updateMirror(e db.Engine, m *Mirror) error { func updateMirror(e db.Engine, m *Mirror) error {
@ -105,18 +105,18 @@ func updateMirror(e db.Engine, m *Mirror) error {
// UpdateMirror updates the mirror // UpdateMirror updates the mirror
func UpdateMirror(m *Mirror) error { func UpdateMirror(m *Mirror) error {
return updateMirror(db.DefaultContext().Engine(), m) return updateMirror(db.GetEngine(db.DefaultContext), m)
} }
// DeleteMirrorByRepoID deletes a mirror by repoID // DeleteMirrorByRepoID deletes a mirror by repoID
func DeleteMirrorByRepoID(repoID int64) error { func DeleteMirrorByRepoID(repoID int64) error {
_, err := db.DefaultContext().Engine().Delete(&Mirror{RepoID: repoID}) _, err := db.GetEngine(db.DefaultContext).Delete(&Mirror{RepoID: repoID})
return err return err
} }
// MirrorsIterate iterates all mirror repositories. // MirrorsIterate iterates all mirror repositories.
func MirrorsIterate(f func(idx int, bean interface{}) error) error { func MirrorsIterate(f func(idx int, bean interface{}) error) error {
return db.DefaultContext().Engine(). return db.GetEngine(db.DefaultContext).
Where("next_update_unix<=?", time.Now().Unix()). Where("next_update_unix<=?", time.Now().Unix()).
And("next_update_unix!=0"). And("next_update_unix!=0").
Iterate(new(Mirror), f) Iterate(new(Mirror), f)
@ -124,6 +124,6 @@ func MirrorsIterate(f func(idx int, bean interface{}) error) error {
// InsertMirror inserts a mirror to database // InsertMirror inserts a mirror to database
func InsertMirror(mirror *Mirror) error { func InsertMirror(mirror *Mirror) error {
_, err := db.DefaultContext().Engine().Insert(mirror) _, err := db.GetEngine(db.DefaultContext).Insert(mirror)
return err return err
} }

View File

@ -140,7 +140,7 @@ func (p *Permission) ColorFormat(s fmt.State) {
// GetUserRepoPermission returns the user permissions to the repository // GetUserRepoPermission returns the user permissions to the repository
func GetUserRepoPermission(repo *Repository, user *User) (Permission, error) { func GetUserRepoPermission(repo *Repository, user *User) (Permission, error) {
return getUserRepoPermission(db.DefaultContext().Engine(), repo, user) return getUserRepoPermission(db.GetEngine(db.DefaultContext), repo, user)
} }
func getUserRepoPermission(e db.Engine, repo *Repository, user *User) (perm Permission, err error) { func getUserRepoPermission(e db.Engine, repo *Repository, user *User) (perm Permission, err error) {
@ -278,7 +278,7 @@ func IsUserRealRepoAdmin(repo *Repository, user *User) (bool, error) {
return true, nil return true, nil
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := repo.getOwner(sess); err != nil { if err := repo.getOwner(sess); err != nil {
@ -295,7 +295,7 @@ func IsUserRealRepoAdmin(repo *Repository, user *User) (bool, error) {
// IsUserRepoAdmin return true if user has admin right of a repo // IsUserRepoAdmin return true if user has admin right of a repo
func IsUserRepoAdmin(repo *Repository, user *User) (bool, error) { func IsUserRepoAdmin(repo *Repository, user *User) (bool, error) {
return isUserRepoAdmin(db.DefaultContext().Engine(), repo, user) return isUserRepoAdmin(db.GetEngine(db.DefaultContext), repo, user)
} }
func isUserRepoAdmin(e db.Engine, repo *Repository, user *User) (bool, error) { func isUserRepoAdmin(e db.Engine, repo *Repository, user *User) (bool, error) {
@ -330,13 +330,13 @@ func isUserRepoAdmin(e db.Engine, repo *Repository, user *User) (bool, error) {
// AccessLevel returns the Access a user has to a repository. Will return NoneAccess if the // AccessLevel returns the Access a user has to a repository. Will return NoneAccess if the
// user does not have access. // user does not have access.
func AccessLevel(user *User, repo *Repository) (AccessMode, error) { func AccessLevel(user *User, repo *Repository) (AccessMode, error) {
return accessLevelUnit(db.DefaultContext().Engine(), user, repo, UnitTypeCode) return accessLevelUnit(db.GetEngine(db.DefaultContext), user, repo, UnitTypeCode)
} }
// AccessLevelUnit returns the Access a user has to a repository's. Will return NoneAccess if the // AccessLevelUnit returns the Access a user has to a repository's. Will return NoneAccess if the
// user does not have access. // user does not have access.
func AccessLevelUnit(user *User, repo *Repository, unitType UnitType) (AccessMode, error) { func AccessLevelUnit(user *User, repo *Repository, unitType UnitType) (AccessMode, error) {
return accessLevelUnit(db.DefaultContext().Engine(), user, repo, unitType) return accessLevelUnit(db.GetEngine(db.DefaultContext), user, repo, unitType)
} }
func accessLevelUnit(e db.Engine, user *User, repo *Repository, unitType UnitType) (AccessMode, error) { func accessLevelUnit(e db.Engine, user *User, repo *Repository, unitType UnitType) (AccessMode, error) {
@ -354,14 +354,14 @@ func hasAccessUnit(e db.Engine, user *User, repo *Repository, unitType UnitType,
// HasAccessUnit returns true if user has testMode to the unit of the repository // HasAccessUnit returns true if user has testMode to the unit of the repository
func HasAccessUnit(user *User, repo *Repository, unitType UnitType, testMode AccessMode) (bool, error) { func HasAccessUnit(user *User, repo *Repository, unitType UnitType, testMode AccessMode) (bool, error) {
return hasAccessUnit(db.DefaultContext().Engine(), user, repo, unitType, testMode) return hasAccessUnit(db.GetEngine(db.DefaultContext), user, repo, unitType, testMode)
} }
// CanBeAssigned return true if user can be assigned to issue or pull requests in repo // CanBeAssigned return true if user can be assigned to issue or pull requests in repo
// Currently any write access (code, issues or pr's) is assignable, to match assignee list in user interface. // Currently any write access (code, issues or pr's) is assignable, to match assignee list in user interface.
// FIXME: user could send PullRequest also could be assigned??? // FIXME: user could send PullRequest also could be assigned???
func CanBeAssigned(user *User, repo *Repository, isPull bool) (bool, error) { func CanBeAssigned(user *User, repo *Repository, isPull bool) (bool, error) {
return canBeAssigned(db.DefaultContext().Engine(), user, repo, isPull) return canBeAssigned(db.GetEngine(db.DefaultContext), user, repo, isPull)
} }
func canBeAssigned(e db.Engine, user *User, repo *Repository, _ bool) (bool, error) { func canBeAssigned(e db.Engine, user *User, repo *Repository, _ bool) (bool, error) {
@ -393,7 +393,7 @@ func hasAccess(e db.Engine, userID int64, repo *Repository) (bool, error) {
// HasAccess returns true if user has access to repo // HasAccess returns true if user has access to repo
func HasAccess(userID int64, repo *Repository) (bool, error) { func HasAccess(userID int64, repo *Repository) (bool, error) {
return hasAccess(db.DefaultContext().Engine(), userID, repo) return hasAccess(db.GetEngine(db.DefaultContext), userID, repo)
} }
// FilterOutRepoIdsWithoutUnitAccess filter out repos where user has no access to repositories // FilterOutRepoIdsWithoutUnitAccess filter out repos where user has no access to repositories

View File

@ -16,7 +16,7 @@ func TestRepoPermissionPublicNonOrgRepo(t *testing.T) {
// public non-organization repo // public non-organization repo
repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository)
assert.NoError(t, repo.getUnits(db.DefaultContext().Engine())) assert.NoError(t, repo.getUnits(db.GetEngine(db.DefaultContext)))
// plain user // plain user
user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
@ -69,7 +69,7 @@ func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) {
// private non-organization repo // private non-organization repo
repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository)
assert.NoError(t, repo.getUnits(db.DefaultContext().Engine())) assert.NoError(t, repo.getUnits(db.GetEngine(db.DefaultContext)))
// plain user // plain user
user := db.AssertExistsAndLoadBean(t, &User{ID: 4}).(*User) user := db.AssertExistsAndLoadBean(t, &User{ID: 4}).(*User)
@ -121,7 +121,7 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) {
// public organization repo // public organization repo
repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 32}).(*Repository) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 32}).(*Repository)
assert.NoError(t, repo.getUnits(db.DefaultContext().Engine())) assert.NoError(t, repo.getUnits(db.GetEngine(db.DefaultContext)))
// plain user // plain user
user := db.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) user := db.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User)
@ -183,7 +183,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) {
// private organization repo // private organization repo
repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 24}).(*Repository) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 24}).(*Repository)
assert.NoError(t, repo.getUnits(db.DefaultContext().Engine())) assert.NoError(t, repo.getUnits(db.GetEngine(db.DefaultContext)))
// plain user // plain user
user := db.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) user := db.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User)

View File

@ -62,32 +62,32 @@ func (m *PushMirror) GetRemoteName() string {
// InsertPushMirror inserts a push-mirror to database // InsertPushMirror inserts a push-mirror to database
func InsertPushMirror(m *PushMirror) error { func InsertPushMirror(m *PushMirror) error {
_, err := db.DefaultContext().Engine().Insert(m) _, err := db.GetEngine(db.DefaultContext).Insert(m)
return err return err
} }
// UpdatePushMirror updates the push-mirror // UpdatePushMirror updates the push-mirror
func UpdatePushMirror(m *PushMirror) error { func UpdatePushMirror(m *PushMirror) error {
_, err := db.DefaultContext().Engine().ID(m.ID).AllCols().Update(m) _, err := db.GetEngine(db.DefaultContext).ID(m.ID).AllCols().Update(m)
return err return err
} }
// DeletePushMirrorByID deletes a push-mirrors by ID // DeletePushMirrorByID deletes a push-mirrors by ID
func DeletePushMirrorByID(ID int64) error { func DeletePushMirrorByID(ID int64) error {
_, err := db.DefaultContext().Engine().ID(ID).Delete(&PushMirror{}) _, err := db.GetEngine(db.DefaultContext).ID(ID).Delete(&PushMirror{})
return err return err
} }
// DeletePushMirrorsByRepoID deletes all push-mirrors by repoID // DeletePushMirrorsByRepoID deletes all push-mirrors by repoID
func DeletePushMirrorsByRepoID(repoID int64) error { func DeletePushMirrorsByRepoID(repoID int64) error {
_, err := db.DefaultContext().Engine().Delete(&PushMirror{RepoID: repoID}) _, err := db.GetEngine(db.DefaultContext).Delete(&PushMirror{RepoID: repoID})
return err return err
} }
// GetPushMirrorByID returns push-mirror information. // GetPushMirrorByID returns push-mirror information.
func GetPushMirrorByID(ID int64) (*PushMirror, error) { func GetPushMirrorByID(ID int64) (*PushMirror, error) {
m := &PushMirror{} m := &PushMirror{}
has, err := db.DefaultContext().Engine().ID(ID).Get(m) has, err := db.GetEngine(db.DefaultContext).ID(ID).Get(m)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -99,12 +99,12 @@ func GetPushMirrorByID(ID int64) (*PushMirror, error) {
// GetPushMirrorsByRepoID returns push-mirror information of a repository. // GetPushMirrorsByRepoID returns push-mirror information of a repository.
func GetPushMirrorsByRepoID(repoID int64) ([]*PushMirror, error) { func GetPushMirrorsByRepoID(repoID int64) ([]*PushMirror, error) {
mirrors := make([]*PushMirror, 0, 10) mirrors := make([]*PushMirror, 0, 10)
return mirrors, db.DefaultContext().Engine().Where("repo_id=?", repoID).Find(&mirrors) return mirrors, db.GetEngine(db.DefaultContext).Where("repo_id=?", repoID).Find(&mirrors)
} }
// PushMirrorsIterate iterates all push-mirror repositories. // PushMirrorsIterate iterates all push-mirror repositories.
func PushMirrorsIterate(f func(idx int, bean interface{}) error) error { func PushMirrorsIterate(f func(idx int, bean interface{}) error) error {
return db.DefaultContext().Engine(). return db.GetEngine(db.DefaultContext).
Where("last_update + (`interval` / ?) <= ?", time.Second, time.Now().Unix()). Where("last_update + (`interval` / ?) <= ?", time.Second, time.Now().Unix()).
And("`interval` != 0"). And("`interval` != 0").
Iterate(new(PushMirror), f) Iterate(new(PushMirror), f)

View File

@ -26,7 +26,7 @@ func init() {
func LookupRepoRedirect(ownerID int64, repoName string) (int64, error) { func LookupRepoRedirect(ownerID int64, repoName string) (int64, error) {
repoName = strings.ToLower(repoName) repoName = strings.ToLower(repoName)
redirect := &RepoRedirect{OwnerID: ownerID, LowerName: repoName} redirect := &RepoRedirect{OwnerID: ownerID, LowerName: repoName}
if has, err := db.DefaultContext().Engine().Get(redirect); err != nil { if has, err := db.GetEngine(db.DefaultContext).Get(redirect); err != nil {
return 0, err return 0, err
} else if !has { } else if !has {
return 0, ErrRepoRedirectNotExist{OwnerID: ownerID, RepoName: repoName} return 0, ErrRepoRedirectNotExist{OwnerID: ownerID, RepoName: repoName}

View File

@ -27,7 +27,7 @@ func TestNewRepoRedirect(t *testing.T) {
assert.NoError(t, db.PrepareTestDatabase()) assert.NoError(t, db.PrepareTestDatabase())
repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
assert.NoError(t, newRepoRedirect(db.DefaultContext().Engine(), repo.OwnerID, repo.ID, repo.Name, "newreponame")) assert.NoError(t, newRepoRedirect(db.GetEngine(db.DefaultContext), repo.OwnerID, repo.ID, repo.Name, "newreponame"))
db.AssertExistsAndLoadBean(t, &RepoRedirect{ db.AssertExistsAndLoadBean(t, &RepoRedirect{
OwnerID: repo.OwnerID, OwnerID: repo.OwnerID,
@ -46,7 +46,7 @@ func TestNewRepoRedirect2(t *testing.T) {
assert.NoError(t, db.PrepareTestDatabase()) assert.NoError(t, db.PrepareTestDatabase())
repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
assert.NoError(t, newRepoRedirect(db.DefaultContext().Engine(), repo.OwnerID, repo.ID, repo.Name, "oldrepo1")) assert.NoError(t, newRepoRedirect(db.GetEngine(db.DefaultContext), repo.OwnerID, repo.ID, repo.Name, "oldrepo1"))
db.AssertExistsAndLoadBean(t, &RepoRedirect{ db.AssertExistsAndLoadBean(t, &RepoRedirect{
OwnerID: repo.OwnerID, OwnerID: repo.OwnerID,
@ -65,7 +65,7 @@ func TestNewRepoRedirect3(t *testing.T) {
assert.NoError(t, db.PrepareTestDatabase()) assert.NoError(t, db.PrepareTestDatabase())
repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository)
assert.NoError(t, newRepoRedirect(db.DefaultContext().Engine(), repo.OwnerID, repo.ID, repo.Name, "newreponame")) assert.NoError(t, newRepoRedirect(db.GetEngine(db.DefaultContext), repo.OwnerID, repo.ID, repo.Name, "newreponame"))
db.AssertExistsAndLoadBean(t, &RepoRedirect{ db.AssertExistsAndLoadBean(t, &RepoRedirect{
OwnerID: repo.OwnerID, OwnerID: repo.OwnerID,

View File

@ -109,7 +109,7 @@ func TestUpdateRepositoryVisibilityChanged(t *testing.T) {
// Check visibility of action has become private // Check visibility of action has become private
act := Action{} act := Action{}
_, err = db.DefaultContext().Engine().ID(3).Get(&act) _, err = db.GetEngine(db.DefaultContext).ID(3).Get(&act)
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, act.IsPrivate) assert.True(t, act.IsPrivate)

View File

@ -98,7 +98,7 @@ func (r *RepoTransfer) CanUserAcceptTransfer(u *User) bool {
func GetPendingRepositoryTransfer(repo *Repository) (*RepoTransfer, error) { func GetPendingRepositoryTransfer(repo *Repository) (*RepoTransfer, error) {
transfer := new(RepoTransfer) transfer := new(RepoTransfer)
has, err := db.DefaultContext().Engine().Where("repo_id = ? ", repo.ID).Get(transfer) has, err := db.GetEngine(db.DefaultContext).Where("repo_id = ? ", repo.ID).Get(transfer)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -118,7 +118,7 @@ func deleteRepositoryTransfer(e db.Engine, repoID int64) error {
// CancelRepositoryTransfer marks the repository as ready and remove pending transfer entry, // CancelRepositoryTransfer marks the repository as ready and remove pending transfer entry,
// thus cancel the transfer process. // thus cancel the transfer process.
func CancelRepositoryTransfer(repo *Repository) error { func CancelRepositoryTransfer(repo *Repository) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -150,7 +150,7 @@ func TestRepositoryReadyForTransfer(status RepositoryStatus) error {
// CreatePendingRepositoryTransfer transfer a repo from one owner to a new one. // CreatePendingRepositoryTransfer transfer a repo from one owner to a new one.
// it marks the repository transfer as "pending" // it marks the repository transfer as "pending"
func CreatePendingRepositoryTransfer(doer, newOwner *User, repoID int64, teams []*Team) error { func CreatePendingRepositoryTransfer(doer, newOwner *User, repoID int64, teams []*Team) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -232,7 +232,7 @@ func TransferOwnership(doer *User, newOwnerName string, repo *Repository) (err e
} }
}() }()
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return fmt.Errorf("sess.Begin: %v", err) return fmt.Errorf("sess.Begin: %v", err)

View File

@ -60,7 +60,7 @@ func isWatchMode(mode RepoWatchMode) bool {
// IsWatching checks if user has watched given repository. // IsWatching checks if user has watched given repository.
func IsWatching(userID, repoID int64) bool { func IsWatching(userID, repoID int64) bool {
watch, err := getWatch(db.DefaultContext().Engine(), userID, repoID) watch, err := getWatch(db.GetEngine(db.DefaultContext), userID, repoID)
return err == nil && isWatchMode(watch.Mode) return err == nil && isWatchMode(watch.Mode)
} }
@ -107,10 +107,10 @@ func watchRepoMode(e db.Engine, watch Watch, mode RepoWatchMode) (err error) {
// WatchRepoMode watch repository in specific mode. // WatchRepoMode watch repository in specific mode.
func WatchRepoMode(userID, repoID int64, mode RepoWatchMode) (err error) { func WatchRepoMode(userID, repoID int64, mode RepoWatchMode) (err error) {
var watch Watch var watch Watch
if watch, err = getWatch(db.DefaultContext().Engine(), userID, repoID); err != nil { if watch, err = getWatch(db.GetEngine(db.DefaultContext), userID, repoID); err != nil {
return err return err
} }
return watchRepoMode(db.DefaultContext().Engine(), watch, mode) return watchRepoMode(db.GetEngine(db.DefaultContext), watch, mode)
} }
func watchRepo(e db.Engine, userID, repoID int64, doWatch bool) (err error) { func watchRepo(e db.Engine, userID, repoID int64, doWatch bool) (err error) {
@ -130,7 +130,7 @@ func watchRepo(e db.Engine, userID, repoID int64, doWatch bool) (err error) {
// WatchRepo watch or unwatch repository. // WatchRepo watch or unwatch repository.
func WatchRepo(userID, repoID int64, watch bool) (err error) { func WatchRepo(userID, repoID int64, watch bool) (err error) {
return watchRepo(db.DefaultContext().Engine(), userID, repoID, watch) return watchRepo(db.GetEngine(db.DefaultContext), userID, repoID, watch)
} }
func getWatchers(e db.Engine, repoID int64) ([]*Watch, error) { func getWatchers(e db.Engine, repoID int64) ([]*Watch, error) {
@ -145,14 +145,14 @@ func getWatchers(e db.Engine, repoID int64) ([]*Watch, error) {
// GetWatchers returns all watchers of given repository. // GetWatchers returns all watchers of given repository.
func GetWatchers(repoID int64) ([]*Watch, error) { func GetWatchers(repoID int64) ([]*Watch, error) {
return getWatchers(db.DefaultContext().Engine(), repoID) return getWatchers(db.GetEngine(db.DefaultContext), repoID)
} }
// GetRepoWatchersIDs returns IDs of watchers for a given repo ID // GetRepoWatchersIDs returns IDs of watchers for a given repo ID
// but avoids joining with `user` for performance reasons // but avoids joining with `user` for performance reasons
// User permissions must be verified elsewhere if required // User permissions must be verified elsewhere if required
func GetRepoWatchersIDs(repoID int64) ([]int64, error) { func GetRepoWatchersIDs(repoID int64) ([]int64, error) {
return getRepoWatchersIDs(db.DefaultContext().Engine(), repoID) return getRepoWatchersIDs(db.GetEngine(db.DefaultContext), repoID)
} }
func getRepoWatchersIDs(e db.Engine, repoID int64) ([]int64, error) { func getRepoWatchersIDs(e db.Engine, repoID int64) ([]int64, error) {
@ -166,7 +166,7 @@ func getRepoWatchersIDs(e db.Engine, repoID int64) ([]int64, error) {
// GetWatchers returns range of users watching given repository. // GetWatchers returns range of users watching given repository.
func (repo *Repository) GetWatchers(opts ListOptions) ([]*User, error) { func (repo *Repository) GetWatchers(opts ListOptions) ([]*User, error) {
sess := db.DefaultContext().Engine().Where("watch.repo_id=?", repo.ID). sess := db.GetEngine(db.DefaultContext).Where("watch.repo_id=?", repo.ID).
Join("LEFT", "watch", "`user`.id=`watch`.user_id"). Join("LEFT", "watch", "`user`.id=`watch`.user_id").
And("`watch`.mode<>?", RepoWatchModeDont) And("`watch`.mode<>?", RepoWatchModeDont)
if opts.Page > 0 { if opts.Page > 0 {
@ -284,12 +284,12 @@ func notifyWatchers(e db.Engine, actions ...*Action) error {
// NotifyWatchers creates batch of actions for every watcher. // NotifyWatchers creates batch of actions for every watcher.
func NotifyWatchers(actions ...*Action) error { func NotifyWatchers(actions ...*Action) error {
return notifyWatchers(db.DefaultContext().Engine(), actions...) return notifyWatchers(db.GetEngine(db.DefaultContext), actions...)
} }
// NotifyWatchersActions creates batch of actions for every watcher. // NotifyWatchersActions creates batch of actions for every watcher.
func NotifyWatchersActions(acts []*Action) error { func NotifyWatchersActions(acts []*Action) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -318,5 +318,5 @@ func watchIfAuto(e db.Engine, userID, repoID int64, isWrite bool) error {
// WatchIfAuto subscribes to repo if AutoWatchOnChanges is set // WatchIfAuto subscribes to repo if AutoWatchOnChanges is set
func WatchIfAuto(userID, repoID int64, isWrite bool) error { func WatchIfAuto(userID, repoID int64, isWrite bool) error {
return watchIfAuto(db.DefaultContext().Engine(), userID, repoID, isWrite) return watchIfAuto(db.GetEngine(db.DefaultContext), userID, repoID, isWrite)
} }

View File

@ -95,7 +95,7 @@ func (r *Review) loadCodeComments(e db.Engine) (err error) {
// LoadCodeComments loads CodeComments // LoadCodeComments loads CodeComments
func (r *Review) LoadCodeComments() error { func (r *Review) LoadCodeComments() error {
return r.loadCodeComments(db.DefaultContext().Engine()) return r.loadCodeComments(db.GetEngine(db.DefaultContext))
} }
func (r *Review) loadIssue(e db.Engine) (err error) { func (r *Review) loadIssue(e db.Engine) (err error) {
@ -125,12 +125,12 @@ func (r *Review) loadReviewerTeam(e db.Engine) (err error) {
// LoadReviewer loads reviewer // LoadReviewer loads reviewer
func (r *Review) LoadReviewer() error { func (r *Review) LoadReviewer() error {
return r.loadReviewer(db.DefaultContext().Engine()) return r.loadReviewer(db.GetEngine(db.DefaultContext))
} }
// LoadReviewerTeam loads reviewer team // LoadReviewerTeam loads reviewer team
func (r *Review) LoadReviewerTeam() error { func (r *Review) LoadReviewerTeam() error {
return r.loadReviewerTeam(db.DefaultContext().Engine()) return r.loadReviewerTeam(db.GetEngine(db.DefaultContext))
} }
func (r *Review) loadAttributes(e db.Engine) (err error) { func (r *Review) loadAttributes(e db.Engine) (err error) {
@ -151,7 +151,7 @@ func (r *Review) loadAttributes(e db.Engine) (err error) {
// LoadAttributes loads all attributes except CodeComments // LoadAttributes loads all attributes except CodeComments
func (r *Review) LoadAttributes() error { func (r *Review) LoadAttributes() error {
return r.loadAttributes(db.DefaultContext().Engine()) return r.loadAttributes(db.GetEngine(db.DefaultContext))
} }
func getReviewByID(e db.Engine, id int64) (*Review, error) { func getReviewByID(e db.Engine, id int64) (*Review, error) {
@ -167,7 +167,7 @@ func getReviewByID(e db.Engine, id int64) (*Review, error) {
// GetReviewByID returns the review by the given ID // GetReviewByID returns the review by the given ID
func GetReviewByID(id int64) (*Review, error) { func GetReviewByID(id int64) (*Review, error) {
return getReviewByID(db.DefaultContext().Engine(), id) return getReviewByID(db.GetEngine(db.DefaultContext), id)
} }
// FindReviewOptions represent possible filters to find reviews // FindReviewOptions represent possible filters to find reviews
@ -210,12 +210,12 @@ func findReviews(e db.Engine, opts FindReviewOptions) ([]*Review, error) {
// FindReviews returns reviews passing FindReviewOptions // FindReviews returns reviews passing FindReviewOptions
func FindReviews(opts FindReviewOptions) ([]*Review, error) { func FindReviews(opts FindReviewOptions) ([]*Review, error) {
return findReviews(db.DefaultContext().Engine(), opts) return findReviews(db.GetEngine(db.DefaultContext), opts)
} }
// CountReviews returns count of reviews passing FindReviewOptions // CountReviews returns count of reviews passing FindReviewOptions
func CountReviews(opts FindReviewOptions) (int64, error) { func CountReviews(opts FindReviewOptions) (int64, error) {
return db.DefaultContext().Engine().Where(opts.toCond()).Count(&Review{}) return db.GetEngine(db.DefaultContext).Where(opts.toCond()).Count(&Review{})
} }
// CreateReviewOptions represent the options to create a review. Type, Issue and Reviewer are required. // CreateReviewOptions represent the options to create a review. Type, Issue and Reviewer are required.
@ -232,7 +232,7 @@ type CreateReviewOptions struct {
// IsOfficialReviewer check if at least one of the provided reviewers can make official reviews in issue (counts towards required approvals) // IsOfficialReviewer check if at least one of the provided reviewers can make official reviews in issue (counts towards required approvals)
func IsOfficialReviewer(issue *Issue, reviewers ...*User) (bool, error) { func IsOfficialReviewer(issue *Issue, reviewers ...*User) (bool, error) {
return isOfficialReviewer(db.DefaultContext().Engine(), issue, reviewers...) return isOfficialReviewer(db.GetEngine(db.DefaultContext), issue, reviewers...)
} }
func isOfficialReviewer(e db.Engine, issue *Issue, reviewers ...*User) (bool, error) { func isOfficialReviewer(e db.Engine, issue *Issue, reviewers ...*User) (bool, error) {
@ -259,7 +259,7 @@ func isOfficialReviewer(e db.Engine, issue *Issue, reviewers ...*User) (bool, er
// IsOfficialReviewerTeam check if reviewer in this team can make official reviews in issue (counts towards required approvals) // IsOfficialReviewerTeam check if reviewer in this team can make official reviews in issue (counts towards required approvals)
func IsOfficialReviewerTeam(issue *Issue, team *Team) (bool, error) { func IsOfficialReviewerTeam(issue *Issue, team *Team) (bool, error) {
return isOfficialReviewerTeam(db.DefaultContext().Engine(), issue, team) return isOfficialReviewerTeam(db.GetEngine(db.DefaultContext), issue, team)
} }
func isOfficialReviewerTeam(e db.Engine, issue *Issue, team *Team) (bool, error) { func isOfficialReviewerTeam(e db.Engine, issue *Issue, team *Team) (bool, error) {
@ -310,7 +310,7 @@ func createReview(e db.Engine, opts CreateReviewOptions) (*Review, error) {
// CreateReview creates a new review based on opts // CreateReview creates a new review based on opts
func CreateReview(opts CreateReviewOptions) (*Review, error) { func CreateReview(opts CreateReviewOptions) (*Review, error) {
return createReview(db.DefaultContext().Engine(), opts) return createReview(db.GetEngine(db.DefaultContext), opts)
} }
func getCurrentReview(e db.Engine, reviewer *User, issue *Issue) (*Review, error) { func getCurrentReview(e db.Engine, reviewer *User, issue *Issue) (*Review, error) {
@ -335,12 +335,12 @@ func getCurrentReview(e db.Engine, reviewer *User, issue *Issue) (*Review, error
// ReviewExists returns whether a review exists for a particular line of code in the PR // ReviewExists returns whether a review exists for a particular line of code in the PR
func ReviewExists(issue *Issue, treePath string, line int64) (bool, error) { func ReviewExists(issue *Issue, treePath string, line int64) (bool, error) {
return db.DefaultContext().Engine().Cols("id").Exist(&Comment{IssueID: issue.ID, TreePath: treePath, Line: line, Type: CommentTypeCode}) return db.GetEngine(db.DefaultContext).Cols("id").Exist(&Comment{IssueID: issue.ID, TreePath: treePath, Line: line, Type: CommentTypeCode})
} }
// GetCurrentReview returns the current pending review of reviewer for given issue // GetCurrentReview returns the current pending review of reviewer for given issue
func GetCurrentReview(reviewer *User, issue *Issue) (*Review, error) { func GetCurrentReview(reviewer *User, issue *Issue) (*Review, error) {
return getCurrentReview(db.DefaultContext().Engine(), reviewer, issue) return getCurrentReview(db.GetEngine(db.DefaultContext), reviewer, issue)
} }
// ContentEmptyErr represents an content empty error // ContentEmptyErr represents an content empty error
@ -358,7 +358,7 @@ func IsContentEmptyErr(err error) bool {
// SubmitReview creates a review out of the existing pending review or creates a new one if no pending review exist // SubmitReview creates a review out of the existing pending review or creates a new one if no pending review exist
func SubmitReview(doer *User, issue *Issue, reviewType ReviewType, content, commitID string, stale bool, attachmentUUIDs []string) (*Review, *Comment, error) { func SubmitReview(doer *User, issue *Issue, reviewType ReviewType, content, commitID string, stale bool, attachmentUUIDs []string) (*Review, *Comment, error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return nil, nil, err return nil, nil, err
@ -470,7 +470,7 @@ func SubmitReview(doer *User, issue *Issue, reviewType ReviewType, content, comm
func GetReviewersByIssueID(issueID int64) ([]*Review, error) { func GetReviewersByIssueID(issueID int64) ([]*Review, error) {
reviews := make([]*Review, 0, 10) reviews := make([]*Review, 0, 10)
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return nil, err return nil, err
@ -502,7 +502,7 @@ func GetReviewersFromOriginalAuthorsByIssueID(issueID int64) ([]*Review, error)
reviews := make([]*Review, 0, 10) reviews := make([]*Review, 0, 10)
// Get latest review of each reviewer, sorted in order they were made // Get latest review of each reviewer, sorted in order they were made
if err := db.DefaultContext().Engine().SQL("SELECT * FROM review WHERE id IN (SELECT max(id) as id FROM review WHERE issue_id = ? AND reviewer_team_id = 0 AND type in (?, ?, ?) AND original_author_id <> 0 GROUP BY issue_id, original_author_id) ORDER BY review.updated_unix ASC", if err := db.GetEngine(db.DefaultContext).SQL("SELECT * FROM review WHERE id IN (SELECT max(id) as id FROM review WHERE issue_id = ? AND reviewer_team_id = 0 AND type in (?, ?, ?) AND original_author_id <> 0 GROUP BY issue_id, original_author_id) ORDER BY review.updated_unix ASC",
issueID, ReviewTypeApprove, ReviewTypeReject, ReviewTypeRequest). issueID, ReviewTypeApprove, ReviewTypeReject, ReviewTypeRequest).
Find(&reviews); err != nil { Find(&reviews); err != nil {
return nil, err return nil, err
@ -513,7 +513,7 @@ func GetReviewersFromOriginalAuthorsByIssueID(issueID int64) ([]*Review, error)
// GetReviewByIssueIDAndUserID get the latest review of reviewer for a pull request // GetReviewByIssueIDAndUserID get the latest review of reviewer for a pull request
func GetReviewByIssueIDAndUserID(issueID, userID int64) (*Review, error) { func GetReviewByIssueIDAndUserID(issueID, userID int64) (*Review, error) {
return getReviewByIssueIDAndUserID(db.DefaultContext().Engine(), issueID, userID) return getReviewByIssueIDAndUserID(db.GetEngine(db.DefaultContext), issueID, userID)
} }
func getReviewByIssueIDAndUserID(e db.Engine, issueID, userID int64) (*Review, error) { func getReviewByIssueIDAndUserID(e db.Engine, issueID, userID int64) (*Review, error) {
@ -535,7 +535,7 @@ func getReviewByIssueIDAndUserID(e db.Engine, issueID, userID int64) (*Review, e
// GetTeamReviewerByIssueIDAndTeamID get the latest review requst of reviewer team for a pull request // GetTeamReviewerByIssueIDAndTeamID get the latest review requst of reviewer team for a pull request
func GetTeamReviewerByIssueIDAndTeamID(issueID, teamID int64) (review *Review, err error) { func GetTeamReviewerByIssueIDAndTeamID(issueID, teamID int64) (review *Review, err error) {
return getTeamReviewerByIssueIDAndTeamID(db.DefaultContext().Engine(), issueID, teamID) return getTeamReviewerByIssueIDAndTeamID(db.GetEngine(db.DefaultContext), issueID, teamID)
} }
func getTeamReviewerByIssueIDAndTeamID(e db.Engine, issueID, teamID int64) (review *Review, err error) { func getTeamReviewerByIssueIDAndTeamID(e db.Engine, issueID, teamID int64) (review *Review, err error) {
@ -557,14 +557,14 @@ func getTeamReviewerByIssueIDAndTeamID(e db.Engine, issueID, teamID int64) (revi
// MarkReviewsAsStale marks existing reviews as stale // MarkReviewsAsStale marks existing reviews as stale
func MarkReviewsAsStale(issueID int64) (err error) { func MarkReviewsAsStale(issueID int64) (err error) {
_, err = db.DefaultContext().Engine().Exec("UPDATE `review` SET stale=? WHERE issue_id=?", true, issueID) _, err = db.GetEngine(db.DefaultContext).Exec("UPDATE `review` SET stale=? WHERE issue_id=?", true, issueID)
return return
} }
// MarkReviewsAsNotStale marks existing reviews as not stale for a giving commit SHA // MarkReviewsAsNotStale marks existing reviews as not stale for a giving commit SHA
func MarkReviewsAsNotStale(issueID int64, commitID string) (err error) { func MarkReviewsAsNotStale(issueID int64, commitID string) (err error) {
_, err = db.DefaultContext().Engine().Exec("UPDATE `review` SET stale=? WHERE issue_id=? AND commit_id=?", false, issueID, commitID) _, err = db.GetEngine(db.DefaultContext).Exec("UPDATE `review` SET stale=? WHERE issue_id=? AND commit_id=?", false, issueID, commitID)
return return
} }
@ -581,14 +581,14 @@ func DismissReview(review *Review, isDismiss bool) (err error) {
return ErrReviewNotExist{} return ErrReviewNotExist{}
} }
_, err = db.DefaultContext().Engine().ID(review.ID).Cols("dismissed").Update(review) _, err = db.GetEngine(db.DefaultContext).ID(review.ID).Cols("dismissed").Update(review)
return return
} }
// InsertReviews inserts review and review comments // InsertReviews inserts review and review comments
func InsertReviews(reviews []*Review) error { func InsertReviews(reviews []*Review) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
@ -630,7 +630,7 @@ func InsertReviews(reviews []*Review) error {
// AddReviewRequest add a review request from one reviewer // AddReviewRequest add a review request from one reviewer
func AddReviewRequest(issue *Issue, reviewer, doer *User) (*Comment, error) { func AddReviewRequest(issue *Issue, reviewer, doer *User) (*Comment, error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return nil, err return nil, err
@ -684,7 +684,7 @@ func AddReviewRequest(issue *Issue, reviewer, doer *User) (*Comment, error) {
// RemoveReviewRequest remove a review request from one reviewer // RemoveReviewRequest remove a review request from one reviewer
func RemoveReviewRequest(issue *Issue, reviewer, doer *User) (*Comment, error) { func RemoveReviewRequest(issue *Issue, reviewer, doer *User) (*Comment, error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return nil, err return nil, err
@ -737,7 +737,7 @@ func RemoveReviewRequest(issue *Issue, reviewer, doer *User) (*Comment, error) {
// AddTeamReviewRequest add a review request from one team // AddTeamReviewRequest add a review request from one team
func AddTeamReviewRequest(issue *Issue, reviewer *Team, doer *User) (*Comment, error) { func AddTeamReviewRequest(issue *Issue, reviewer *Team, doer *User) (*Comment, error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return nil, err return nil, err
@ -796,7 +796,7 @@ func AddTeamReviewRequest(issue *Issue, reviewer *Team, doer *User) (*Comment, e
// RemoveTeamReviewRequest remove a review request from one team // RemoveTeamReviewRequest remove a review request from one team
func RemoveTeamReviewRequest(issue *Issue, reviewer *Team, doer *User) (*Comment, error) { func RemoveTeamReviewRequest(issue *Issue, reviewer *Team, doer *User) (*Comment, error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return nil, err return nil, err
@ -864,7 +864,7 @@ func MarkConversation(comment *Comment, doer *User, isResolve bool) (err error)
return nil return nil
} }
if _, err = db.DefaultContext().Engine().Exec("UPDATE `comment` SET resolve_doer_id=? WHERE id=?", doer.ID, comment.ID); err != nil { if _, err = db.GetEngine(db.DefaultContext).Exec("UPDATE `comment` SET resolve_doer_id=? WHERE id=?", doer.ID, comment.ID); err != nil {
return err return err
} }
} else { } else {
@ -872,7 +872,7 @@ func MarkConversation(comment *Comment, doer *User, isResolve bool) (err error)
return nil return nil
} }
if _, err = db.DefaultContext().Engine().Exec("UPDATE `comment` SET resolve_doer_id=? WHERE id=?", 0, comment.ID); err != nil { if _, err = db.GetEngine(db.DefaultContext).Exec("UPDATE `comment` SET resolve_doer_id=? WHERE id=?", 0, comment.ID); err != nil {
return err return err
} }
} }
@ -914,7 +914,7 @@ func CanMarkConversation(issue *Issue, doer *User) (permResult bool, err error)
// DeleteReview delete a review and it's code comments // DeleteReview delete a review and it's code comments
func DeleteReview(r *Review) error { func DeleteReview(r *Review) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
@ -968,7 +968,7 @@ func (r *Review) GetCodeCommentsCount() int {
conds = conds.And(builder.Eq{"invalidated": false}) conds = conds.And(builder.Eq{"invalidated": false})
} }
count, err := db.DefaultContext().Engine().Where(conds).Count(new(Comment)) count, err := db.GetEngine(db.DefaultContext).Where(conds).Count(new(Comment))
if err != nil { if err != nil {
return 0 return 0
} }
@ -983,7 +983,7 @@ func (r *Review) HTMLURL() string {
ReviewID: r.ID, ReviewID: r.ID,
} }
comment := new(Comment) comment := new(Comment)
has, err := db.DefaultContext().Engine().Where(opts.toConds()).Get(comment) has, err := db.GetEngine(db.DefaultContext).Where(opts.toConds()).Get(comment)
if err != nil || !has { if err != nil || !has {
return "" return ""
} }

View File

@ -24,7 +24,7 @@ func init() {
// UpdateSession updates the session with provided id // UpdateSession updates the session with provided id
func UpdateSession(key string, data []byte) error { func UpdateSession(key string, data []byte) error {
_, err := db.DefaultContext().Engine().ID(key).Update(&Session{ _, err := db.GetEngine(db.DefaultContext).ID(key).Update(&Session{
Data: data, Data: data,
Expiry: timeutil.TimeStampNow(), Expiry: timeutil.TimeStampNow(),
}) })
@ -36,7 +36,7 @@ func ReadSession(key string) (*Session, error) {
session := Session{ session := Session{
Key: key, Key: key,
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return nil, err return nil, err
@ -60,12 +60,12 @@ func ExistSession(key string) (bool, error) {
session := Session{ session := Session{
Key: key, Key: key,
} }
return db.DefaultContext().Engine().Get(&session) return db.GetEngine(db.DefaultContext).Get(&session)
} }
// DestroySession destroys a session // DestroySession destroys a session
func DestroySession(key string) error { func DestroySession(key string) error {
_, err := db.DefaultContext().Engine().Delete(&Session{ _, err := db.GetEngine(db.DefaultContext).Delete(&Session{
Key: key, Key: key,
}) })
return err return err
@ -73,7 +73,7 @@ func DestroySession(key string) error {
// RegenerateSession regenerates a session from the old id // RegenerateSession regenerates a session from the old id
func RegenerateSession(oldKey, newKey string) (*Session, error) { func RegenerateSession(oldKey, newKey string) (*Session, error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return nil, err return nil, err
@ -117,11 +117,11 @@ func RegenerateSession(oldKey, newKey string) (*Session, error) {
// CountSessions returns the number of sessions // CountSessions returns the number of sessions
func CountSessions() (int64, error) { func CountSessions() (int64, error) {
return db.DefaultContext().Engine().Count(&Session{}) return db.GetEngine(db.DefaultContext).Count(&Session{})
} }
// CleanupSessions cleans up expired sessions // CleanupSessions cleans up expired sessions
func CleanupSessions(maxLifetime int64) error { func CleanupSessions(maxLifetime int64) error {
_, err := db.DefaultContext().Engine().Where("expiry <= ?", timeutil.TimeStampNow().Add(-maxLifetime)).Delete(&Session{}) _, err := db.GetEngine(db.DefaultContext).Where("expiry <= ?", timeutil.TimeStampNow().Add(-maxLifetime)).Delete(&Session{})
return err return err
} }

View File

@ -95,7 +95,7 @@ func AddPublicKey(ownerID int64, name, content string, loginSourceID int64) (*Pu
return nil, err return nil, err
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return nil, err return nil, err
@ -134,7 +134,7 @@ func AddPublicKey(ownerID int64, name, content string, loginSourceID int64) (*Pu
// GetPublicKeyByID returns public key by given ID. // GetPublicKeyByID returns public key by given ID.
func GetPublicKeyByID(keyID int64) (*PublicKey, error) { func GetPublicKeyByID(keyID int64) (*PublicKey, error) {
key := new(PublicKey) key := new(PublicKey)
has, err := db.DefaultContext().Engine(). has, err := db.GetEngine(db.DefaultContext).
ID(keyID). ID(keyID).
Get(key) Get(key)
if err != nil { if err != nil {
@ -161,7 +161,7 @@ func searchPublicKeyByContentWithEngine(e db.Engine, content string) (*PublicKey
// SearchPublicKeyByContent searches content as prefix (leak e-mail part) // SearchPublicKeyByContent searches content as prefix (leak e-mail part)
// and returns public key found. // and returns public key found.
func SearchPublicKeyByContent(content string) (*PublicKey, error) { func SearchPublicKeyByContent(content string) (*PublicKey, error) {
return searchPublicKeyByContentWithEngine(db.DefaultContext().Engine(), content) return searchPublicKeyByContentWithEngine(db.GetEngine(db.DefaultContext), content)
} }
func searchPublicKeyByContentExactWithEngine(e db.Engine, content string) (*PublicKey, error) { func searchPublicKeyByContentExactWithEngine(e db.Engine, content string) (*PublicKey, error) {
@ -180,7 +180,7 @@ func searchPublicKeyByContentExactWithEngine(e db.Engine, content string) (*Publ
// SearchPublicKeyByContentExact searches content // SearchPublicKeyByContentExact searches content
// and returns public key found. // and returns public key found.
func SearchPublicKeyByContentExact(content string) (*PublicKey, error) { func SearchPublicKeyByContentExact(content string) (*PublicKey, error) {
return searchPublicKeyByContentExactWithEngine(db.DefaultContext().Engine(), content) return searchPublicKeyByContentExactWithEngine(db.GetEngine(db.DefaultContext), content)
} }
// SearchPublicKey returns a list of public keys matching the provided arguments. // SearchPublicKey returns a list of public keys matching the provided arguments.
@ -193,12 +193,12 @@ func SearchPublicKey(uid int64, fingerprint string) ([]*PublicKey, error) {
if fingerprint != "" { if fingerprint != "" {
cond = cond.And(builder.Eq{"fingerprint": fingerprint}) cond = cond.And(builder.Eq{"fingerprint": fingerprint})
} }
return keys, db.DefaultContext().Engine().Where(cond).Find(&keys) return keys, db.GetEngine(db.DefaultContext).Where(cond).Find(&keys)
} }
// ListPublicKeys returns a list of public keys belongs to given user. // ListPublicKeys returns a list of public keys belongs to given user.
func ListPublicKeys(uid int64, listOptions ListOptions) ([]*PublicKey, error) { func ListPublicKeys(uid int64, listOptions ListOptions) ([]*PublicKey, error) {
sess := db.DefaultContext().Engine().Where("owner_id = ? AND type != ?", uid, KeyTypePrincipal) sess := db.GetEngine(db.DefaultContext).Where("owner_id = ? AND type != ?", uid, KeyTypePrincipal)
if listOptions.Page != 0 { if listOptions.Page != 0 {
sess = setSessionPagination(sess, &listOptions) sess = setSessionPagination(sess, &listOptions)
@ -212,14 +212,14 @@ func ListPublicKeys(uid int64, listOptions ListOptions) ([]*PublicKey, error) {
// CountPublicKeys count public keys a user has // CountPublicKeys count public keys a user has
func CountPublicKeys(userID int64) (int64, error) { func CountPublicKeys(userID int64) (int64, error) {
sess := db.DefaultContext().Engine().Where("owner_id = ? AND type != ?", userID, KeyTypePrincipal) sess := db.GetEngine(db.DefaultContext).Where("owner_id = ? AND type != ?", userID, KeyTypePrincipal)
return sess.Count(&PublicKey{}) return sess.Count(&PublicKey{})
} }
// ListPublicKeysBySource returns a list of synchronized public keys for a given user and login source. // ListPublicKeysBySource returns a list of synchronized public keys for a given user and login source.
func ListPublicKeysBySource(uid, loginSourceID int64) ([]*PublicKey, error) { func ListPublicKeysBySource(uid, loginSourceID int64) ([]*PublicKey, error) {
keys := make([]*PublicKey, 0, 5) keys := make([]*PublicKey, 0, 5)
return keys, db.DefaultContext().Engine(). return keys, db.GetEngine(db.DefaultContext).
Where("owner_id = ? AND login_source_id = ?", uid, loginSourceID). Where("owner_id = ? AND login_source_id = ?", uid, loginSourceID).
Find(&keys) Find(&keys)
} }
@ -228,13 +228,13 @@ func ListPublicKeysBySource(uid, loginSourceID int64) ([]*PublicKey, error) {
func UpdatePublicKeyUpdated(id int64) error { func UpdatePublicKeyUpdated(id int64) error {
// Check if key exists before update as affected rows count is unreliable // Check if key exists before update as affected rows count is unreliable
// and will return 0 affected rows if two updates are made at the same time // and will return 0 affected rows if two updates are made at the same time
if cnt, err := db.DefaultContext().Engine().ID(id).Count(&PublicKey{}); err != nil { if cnt, err := db.GetEngine(db.DefaultContext).ID(id).Count(&PublicKey{}); err != nil {
return err return err
} else if cnt != 1 { } else if cnt != 1 {
return ErrKeyNotExist{id} return ErrKeyNotExist{id}
} }
_, err := db.DefaultContext().Engine().ID(id).Cols("updated_unix").Update(&PublicKey{ _, err := db.GetEngine(db.DefaultContext).ID(id).Cols("updated_unix").Update(&PublicKey{
UpdatedUnix: timeutil.TimeStampNow(), UpdatedUnix: timeutil.TimeStampNow(),
}) })
if err != nil { if err != nil {
@ -333,7 +333,7 @@ func DeletePublicKey(doer *User, id int64) (err error) {
return ErrKeyAccessDenied{doer.ID, key.ID, "public"} return ErrKeyAccessDenied{doer.ID, key.ID, "public"}
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -358,7 +358,7 @@ func DeletePublicKey(doer *User, id int64) (err error) {
// deleteKeysMarkedForDeletion returns true if ssh keys needs update // deleteKeysMarkedForDeletion returns true if ssh keys needs update
func deleteKeysMarkedForDeletion(keys []string) (bool, error) { func deleteKeysMarkedForDeletion(keys []string) (bool, error) {
// Start session // Start session
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return false, err return false, err

View File

@ -115,10 +115,10 @@ func appendAuthorizedKeysToFile(keys ...*PublicKey) error {
} }
// RewriteAllPublicKeys removes any authorized key and rewrite all keys from database again. // RewriteAllPublicKeys removes any authorized key and rewrite all keys from database again.
// Note: db.DefaultContext().Engine().Iterate does not get latest data after insert/delete, so we have to call this function // Note: db.GetEngine(db.DefaultContext).Iterate does not get latest data after insert/delete, so we have to call this function
// outside any session scope independently. // outside any session scope independently.
func RewriteAllPublicKeys() error { func RewriteAllPublicKeys() error {
return rewriteAllPublicKeys(db.DefaultContext().Engine()) return rewriteAllPublicKeys(db.GetEngine(db.DefaultContext))
} }
func rewriteAllPublicKeys(e db.Engine) error { func rewriteAllPublicKeys(e db.Engine) error {
@ -179,7 +179,7 @@ func rewriteAllPublicKeys(e db.Engine) error {
// RegeneratePublicKeys regenerates the authorized_keys file // RegeneratePublicKeys regenerates the authorized_keys file
func RegeneratePublicKeys(t io.StringWriter) error { func RegeneratePublicKeys(t io.StringWriter) error {
return regeneratePublicKeys(db.DefaultContext().Engine(), t) return regeneratePublicKeys(db.GetEngine(db.DefaultContext), t)
} }
func regeneratePublicKeys(e db.Engine, t io.StringWriter) error { func regeneratePublicKeys(e db.Engine, t io.StringWriter) error {

View File

@ -40,10 +40,10 @@ import (
const authorizedPrincipalsFile = "authorized_principals" const authorizedPrincipalsFile = "authorized_principals"
// RewriteAllPrincipalKeys removes any authorized principal and rewrite all keys from database again. // RewriteAllPrincipalKeys removes any authorized principal and rewrite all keys from database again.
// Note: db.DefaultContext().Engine().Iterate does not get latest data after insert/delete, so we have to call this function // Note: db.GetEngine(db.DefaultContext).Iterate does not get latest data after insert/delete, so we have to call this function
// outside any session scope independently. // outside any session scope independently.
func RewriteAllPrincipalKeys() error { func RewriteAllPrincipalKeys() error {
return rewriteAllPrincipalKeys(db.DefaultContext().Engine()) return rewriteAllPrincipalKeys(db.GetEngine(db.DefaultContext))
} }
func rewriteAllPrincipalKeys(e db.Engine) error { func rewriteAllPrincipalKeys(e db.Engine) error {
@ -102,7 +102,7 @@ func rewriteAllPrincipalKeys(e db.Engine) error {
// RegeneratePrincipalKeys regenerates the authorized_principals file // RegeneratePrincipalKeys regenerates the authorized_principals file
func RegeneratePrincipalKeys(t io.StringWriter) error { func RegeneratePrincipalKeys(t io.StringWriter) error {
return regeneratePrincipalKeys(db.DefaultContext().Engine(), t) return regeneratePrincipalKeys(db.GetEngine(db.DefaultContext), t)
} }
func regeneratePrincipalKeys(e db.Engine, t io.StringWriter) error { func regeneratePrincipalKeys(e db.Engine, t io.StringWriter) error {

View File

@ -107,7 +107,7 @@ func addDeployKey(e *xorm.Session, keyID, repoID int64, name, fingerprint string
// HasDeployKey returns true if public key is a deploy key of given repository. // HasDeployKey returns true if public key is a deploy key of given repository.
func HasDeployKey(keyID, repoID int64) bool { func HasDeployKey(keyID, repoID int64) bool {
has, _ := db.DefaultContext().Engine(). has, _ := db.GetEngine(db.DefaultContext).
Where("key_id = ? AND repo_id = ?", keyID, repoID). Where("key_id = ? AND repo_id = ?", keyID, repoID).
Get(new(DeployKey)) Get(new(DeployKey))
return has return has
@ -125,7 +125,7 @@ func AddDeployKey(repoID int64, name, content string, readOnly bool) (*DeployKey
accessMode = AccessModeWrite accessMode = AccessModeWrite
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return nil, err return nil, err
@ -164,7 +164,7 @@ func AddDeployKey(repoID int64, name, content string, readOnly bool) (*DeployKey
// GetDeployKeyByID returns deploy key by given ID. // GetDeployKeyByID returns deploy key by given ID.
func GetDeployKeyByID(id int64) (*DeployKey, error) { func GetDeployKeyByID(id int64) (*DeployKey, error) {
return getDeployKeyByID(db.DefaultContext().Engine(), id) return getDeployKeyByID(db.GetEngine(db.DefaultContext), id)
} }
func getDeployKeyByID(e db.Engine, id int64) (*DeployKey, error) { func getDeployKeyByID(e db.Engine, id int64) (*DeployKey, error) {
@ -180,7 +180,7 @@ func getDeployKeyByID(e db.Engine, id int64) (*DeployKey, error) {
// GetDeployKeyByRepo returns deploy key by given public key ID and repository ID. // GetDeployKeyByRepo returns deploy key by given public key ID and repository ID.
func GetDeployKeyByRepo(keyID, repoID int64) (*DeployKey, error) { func GetDeployKeyByRepo(keyID, repoID int64) (*DeployKey, error) {
return getDeployKeyByRepo(db.DefaultContext().Engine(), keyID, repoID) return getDeployKeyByRepo(db.GetEngine(db.DefaultContext), keyID, repoID)
} }
func getDeployKeyByRepo(e db.Engine, keyID, repoID int64) (*DeployKey, error) { func getDeployKeyByRepo(e db.Engine, keyID, repoID int64) (*DeployKey, error) {
@ -199,19 +199,19 @@ func getDeployKeyByRepo(e db.Engine, keyID, repoID int64) (*DeployKey, error) {
// UpdateDeployKeyCols updates deploy key information in the specified columns. // UpdateDeployKeyCols updates deploy key information in the specified columns.
func UpdateDeployKeyCols(key *DeployKey, cols ...string) error { func UpdateDeployKeyCols(key *DeployKey, cols ...string) error {
_, err := db.DefaultContext().Engine().ID(key.ID).Cols(cols...).Update(key) _, err := db.GetEngine(db.DefaultContext).ID(key.ID).Cols(cols...).Update(key)
return err return err
} }
// UpdateDeployKey updates deploy key information. // UpdateDeployKey updates deploy key information.
func UpdateDeployKey(key *DeployKey) error { func UpdateDeployKey(key *DeployKey) error {
_, err := db.DefaultContext().Engine().ID(key.ID).AllCols().Update(key) _, err := db.GetEngine(db.DefaultContext).ID(key.ID).AllCols().Update(key)
return err return err
} }
// DeleteDeployKey deletes deploy key from its repository authorized_keys file if needed. // DeleteDeployKey deletes deploy key from its repository authorized_keys file if needed.
func DeleteDeployKey(doer *User, id int64) error { func DeleteDeployKey(doer *User, id int64) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -293,7 +293,7 @@ func (opt ListDeployKeysOptions) toCond() builder.Cond {
// ListDeployKeys returns a list of deploy keys matching the provided arguments. // ListDeployKeys returns a list of deploy keys matching the provided arguments.
func ListDeployKeys(opts *ListDeployKeysOptions) ([]*DeployKey, error) { func ListDeployKeys(opts *ListDeployKeysOptions) ([]*DeployKey, error) {
return listDeployKeys(db.DefaultContext().Engine(), opts) return listDeployKeys(db.GetEngine(db.DefaultContext), opts)
} }
func listDeployKeys(e db.Engine, opts *ListDeployKeysOptions) ([]*DeployKey, error) { func listDeployKeys(e db.Engine, opts *ListDeployKeysOptions) ([]*DeployKey, error) {
@ -312,5 +312,5 @@ func listDeployKeys(e db.Engine, opts *ListDeployKeysOptions) ([]*DeployKey, err
// CountDeployKeys returns count deploy keys matching the provided arguments. // CountDeployKeys returns count deploy keys matching the provided arguments.
func CountDeployKeys(opts *ListDeployKeysOptions) (int64, error) { func CountDeployKeys(opts *ListDeployKeysOptions) (int64, error) {
return db.DefaultContext().Engine().Where(opts.toCond()).Count(&DeployKey{}) return db.GetEngine(db.DefaultContext).Where(opts.toCond()).Count(&DeployKey{})
} }

View File

@ -24,7 +24,7 @@ import (
// AddPrincipalKey adds new principal to database and authorized_principals file. // AddPrincipalKey adds new principal to database and authorized_principals file.
func AddPrincipalKey(ownerID int64, content string, loginSourceID int64) (*PublicKey, error) { func AddPrincipalKey(ownerID int64, content string, loginSourceID int64) (*PublicKey, error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return nil, err return nil, err
@ -113,7 +113,7 @@ func CheckPrincipalKeyString(user *User, content string) (_ string, err error) {
// ListPrincipalKeys returns a list of principals belongs to given user. // ListPrincipalKeys returns a list of principals belongs to given user.
func ListPrincipalKeys(uid int64, listOptions ListOptions) ([]*PublicKey, error) { func ListPrincipalKeys(uid int64, listOptions ListOptions) ([]*PublicKey, error) {
sess := db.DefaultContext().Engine().Where("owner_id = ? AND type = ?", uid, KeyTypePrincipal) sess := db.GetEngine(db.DefaultContext).Where("owner_id = ? AND type = ?", uid, KeyTypePrincipal)
if listOptions.Page != 0 { if listOptions.Page != 0 {
sess = setSessionPagination(sess, &listOptions) sess = setSessionPagination(sess, &listOptions)

View File

@ -23,7 +23,7 @@ func init() {
// StarRepo or unstar repository. // StarRepo or unstar repository.
func StarRepo(userID, repoID int64, star bool) error { func StarRepo(userID, repoID int64, star bool) error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
@ -65,7 +65,7 @@ func StarRepo(userID, repoID int64, star bool) error {
// IsStaring checks if user has starred given repository. // IsStaring checks if user has starred given repository.
func IsStaring(userID, repoID int64) bool { func IsStaring(userID, repoID int64) bool {
return isStaring(db.DefaultContext().Engine(), userID, repoID) return isStaring(db.GetEngine(db.DefaultContext), userID, repoID)
} }
func isStaring(e db.Engine, userID, repoID int64) bool { func isStaring(e db.Engine, userID, repoID int64) bool {
@ -75,7 +75,7 @@ func isStaring(e db.Engine, userID, repoID int64) bool {
// GetStargazers returns the users that starred the repo. // GetStargazers returns the users that starred the repo.
func (repo *Repository) GetStargazers(opts ListOptions) ([]*User, error) { func (repo *Repository) GetStargazers(opts ListOptions) ([]*User, error) {
sess := db.DefaultContext().Engine().Where("star.repo_id = ?", repo.ID). sess := db.GetEngine(db.DefaultContext).Where("star.repo_id = ?", repo.ID).
Join("LEFT", "star", "`user`.id = star.uid") Join("LEFT", "star", "`user`.id = star.uid")
if opts.Page > 0 { if opts.Page > 0 {
sess = setSessionPagination(sess, &opts) sess = setSessionPagination(sess, &opts)
@ -93,7 +93,7 @@ func (u *User) GetStarredRepos(private bool, page, pageSize int, orderBy string)
if len(orderBy) == 0 { if len(orderBy) == 0 {
orderBy = "updated_unix DESC" orderBy = "updated_unix DESC"
} }
sess := db.DefaultContext().Engine(). sess := db.GetEngine(db.DefaultContext).
Join("INNER", "star", "star.repo_id = repository.id"). Join("INNER", "star", "star.repo_id = repository.id").
Where("star.uid = ?", u.ID). Where("star.uid = ?", u.ID).
OrderBy(orderBy) OrderBy(orderBy)
@ -113,7 +113,7 @@ func (u *User) GetStarredRepos(private bool, page, pageSize int, orderBy string)
return return
} }
if err = repos.loadAttributes(db.DefaultContext().Engine()); err != nil { if err = repos.loadAttributes(db.GetEngine(db.DefaultContext)); err != nil {
return return
} }
@ -122,7 +122,7 @@ func (u *User) GetStarredRepos(private bool, page, pageSize int, orderBy string)
// GetStarredRepoCount returns the numbers of repo the user starred. // GetStarredRepoCount returns the numbers of repo the user starred.
func (u *User) GetStarredRepoCount(private bool) (int64, error) { func (u *User) GetStarredRepoCount(private bool) (int64, error) {
sess := db.DefaultContext().Engine(). sess := db.GetEngine(db.DefaultContext).
Join("INNER", "star", "star.repo_id = repository.id"). Join("INNER", "star", "star.repo_id = repository.id").
Where("star.uid = ?", u.ID) Where("star.uid = ?", u.ID)

View File

@ -23,12 +23,12 @@ type Statistic struct {
func GetStatistic() (stats Statistic) { func GetStatistic() (stats Statistic) {
stats.Counter.User = CountUsers() stats.Counter.User = CountUsers()
stats.Counter.Org = CountOrganizations() stats.Counter.Org = CountOrganizations()
stats.Counter.PublicKey, _ = db.DefaultContext().Engine().Count(new(PublicKey)) stats.Counter.PublicKey, _ = db.GetEngine(db.DefaultContext).Count(new(PublicKey))
stats.Counter.Repo = CountRepositories(true) stats.Counter.Repo = CountRepositories(true)
stats.Counter.Watch, _ = db.DefaultContext().Engine().Count(new(Watch)) stats.Counter.Watch, _ = db.GetEngine(db.DefaultContext).Count(new(Watch))
stats.Counter.Star, _ = db.DefaultContext().Engine().Count(new(Star)) stats.Counter.Star, _ = db.GetEngine(db.DefaultContext).Count(new(Star))
stats.Counter.Action, _ = db.DefaultContext().Engine().Count(new(Action)) stats.Counter.Action, _ = db.GetEngine(db.DefaultContext).Count(new(Action))
stats.Counter.Access, _ = db.DefaultContext().Engine().Count(new(Access)) stats.Counter.Access, _ = db.GetEngine(db.DefaultContext).Count(new(Access))
type IssueCount struct { type IssueCount struct {
Count int64 Count int64
@ -36,7 +36,7 @@ func GetStatistic() (stats Statistic) {
} }
issueCounts := []IssueCount{} issueCounts := []IssueCount{}
_ = db.DefaultContext().Engine().Select("COUNT(*) AS count, is_closed").Table("issue").GroupBy("is_closed").Find(&issueCounts) _ = db.GetEngine(db.DefaultContext).Select("COUNT(*) AS count, is_closed").Table("issue").GroupBy("is_closed").Find(&issueCounts)
for _, c := range issueCounts { for _, c := range issueCounts {
if c.IsClosed { if c.IsClosed {
stats.Counter.IssueClosed = c.Count stats.Counter.IssueClosed = c.Count
@ -47,17 +47,17 @@ func GetStatistic() (stats Statistic) {
stats.Counter.Issue = stats.Counter.IssueClosed + stats.Counter.IssueOpen stats.Counter.Issue = stats.Counter.IssueClosed + stats.Counter.IssueOpen
stats.Counter.Comment, _ = db.DefaultContext().Engine().Count(new(Comment)) stats.Counter.Comment, _ = db.GetEngine(db.DefaultContext).Count(new(Comment))
stats.Counter.Oauth = 0 stats.Counter.Oauth = 0
stats.Counter.Follow, _ = db.DefaultContext().Engine().Count(new(Follow)) stats.Counter.Follow, _ = db.GetEngine(db.DefaultContext).Count(new(Follow))
stats.Counter.Mirror, _ = db.DefaultContext().Engine().Count(new(Mirror)) stats.Counter.Mirror, _ = db.GetEngine(db.DefaultContext).Count(new(Mirror))
stats.Counter.Release, _ = db.DefaultContext().Engine().Count(new(Release)) stats.Counter.Release, _ = db.GetEngine(db.DefaultContext).Count(new(Release))
stats.Counter.LoginSource = CountLoginSources() stats.Counter.LoginSource = CountLoginSources()
stats.Counter.Webhook, _ = db.DefaultContext().Engine().Count(new(Webhook)) stats.Counter.Webhook, _ = db.GetEngine(db.DefaultContext).Count(new(Webhook))
stats.Counter.Milestone, _ = db.DefaultContext().Engine().Count(new(Milestone)) stats.Counter.Milestone, _ = db.GetEngine(db.DefaultContext).Count(new(Milestone))
stats.Counter.Label, _ = db.DefaultContext().Engine().Count(new(Label)) stats.Counter.Label, _ = db.GetEngine(db.DefaultContext).Count(new(Label))
stats.Counter.HookTask, _ = db.DefaultContext().Engine().Count(new(HookTask)) stats.Counter.HookTask, _ = db.GetEngine(db.DefaultContext).Count(new(HookTask))
stats.Counter.Team, _ = db.DefaultContext().Engine().Count(new(Team)) stats.Counter.Team, _ = db.GetEngine(db.DefaultContext).Count(new(Team))
stats.Counter.Attachment, _ = db.DefaultContext().Engine().Count(new(Attachment)) stats.Counter.Attachment, _ = db.GetEngine(db.DefaultContext).Count(new(Attachment))
return return
} }

View File

@ -49,7 +49,7 @@ type TranslatableMessage struct {
// LoadRepo loads repository of the task // LoadRepo loads repository of the task
func (task *Task) LoadRepo() error { func (task *Task) LoadRepo() error {
return task.loadRepo(db.DefaultContext().Engine()) return task.loadRepo(db.GetEngine(db.DefaultContext))
} }
func (task *Task) loadRepo(e db.Engine) error { func (task *Task) loadRepo(e db.Engine) error {
@ -76,7 +76,7 @@ func (task *Task) LoadDoer() error {
} }
var doer User var doer User
has, err := db.DefaultContext().Engine().ID(task.DoerID).Get(&doer) has, err := db.GetEngine(db.DefaultContext).ID(task.DoerID).Get(&doer)
if err != nil { if err != nil {
return err return err
} else if !has { } else if !has {
@ -96,7 +96,7 @@ func (task *Task) LoadOwner() error {
} }
var owner User var owner User
has, err := db.DefaultContext().Engine().ID(task.OwnerID).Get(&owner) has, err := db.GetEngine(db.DefaultContext).ID(task.OwnerID).Get(&owner)
if err != nil { if err != nil {
return err return err
} else if !has { } else if !has {
@ -111,7 +111,7 @@ func (task *Task) LoadOwner() error {
// UpdateCols updates some columns // UpdateCols updates some columns
func (task *Task) UpdateCols(cols ...string) error { func (task *Task) UpdateCols(cols ...string) error {
_, err := db.DefaultContext().Engine().ID(task.ID).Cols(cols...).Update(task) _, err := db.GetEngine(db.DefaultContext).ID(task.ID).Cols(cols...).Update(task)
return err return err
} }
@ -170,7 +170,7 @@ func GetMigratingTask(repoID int64) (*Task, error) {
RepoID: repoID, RepoID: repoID,
Type: structs.TaskTypeMigrateRepo, Type: structs.TaskTypeMigrateRepo,
} }
has, err := db.DefaultContext().Engine().Get(&task) has, err := db.GetEngine(db.DefaultContext).Get(&task)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -186,7 +186,7 @@ func GetMigratingTaskByID(id, doerID int64) (*Task, *migration.MigrateOptions, e
DoerID: doerID, DoerID: doerID,
Type: structs.TaskTypeMigrateRepo, Type: structs.TaskTypeMigrateRepo,
} }
has, err := db.DefaultContext().Engine().Get(&task) has, err := db.GetEngine(db.DefaultContext).Get(&task)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} else if !has { } else if !has {
@ -217,13 +217,13 @@ func (opts FindTaskOptions) ToConds() builder.Cond {
// FindTasks find all tasks // FindTasks find all tasks
func FindTasks(opts FindTaskOptions) ([]*Task, error) { func FindTasks(opts FindTaskOptions) ([]*Task, error) {
tasks := make([]*Task, 0, 10) tasks := make([]*Task, 0, 10)
err := db.DefaultContext().Engine().Where(opts.ToConds()).Find(&tasks) err := db.GetEngine(db.DefaultContext).Where(opts.ToConds()).Find(&tasks)
return tasks, err return tasks, err
} }
// CreateTask creates a task on database // CreateTask creates a task on database
func CreateTask(task *Task) error { func CreateTask(task *Task) error {
return createTask(db.DefaultContext().Engine(), task) return createTask(db.GetEngine(db.DefaultContext), task)
} }
func createTask(e db.Engine, task *Task) error { func createTask(e db.Engine, task *Task) error {
@ -253,7 +253,7 @@ func FinishMigrateTask(task *Task) error {
} }
task.PayloadContent = string(confBytes) task.PayloadContent = string(confBytes)
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err

View File

@ -69,7 +69,7 @@ func NewAccessToken(t *AccessToken) error {
t.Token = base.EncodeSha1(gouuid.New().String()) t.Token = base.EncodeSha1(gouuid.New().String())
t.TokenHash = hashToken(t.Token, t.TokenSalt) t.TokenHash = hashToken(t.Token, t.TokenSalt)
t.TokenLastEight = t.Token[len(t.Token)-8:] t.TokenLastEight = t.Token[len(t.Token)-8:]
_, err = db.DefaultContext().Engine().Insert(t) _, err = db.GetEngine(db.DefaultContext).Insert(t)
return err return err
} }
@ -110,7 +110,7 @@ func GetAccessTokenBySHA(token string) (*AccessToken, error) {
TokenLastEight: lastEight, TokenLastEight: lastEight,
} }
// Re-get the token from the db in case it has been deleted in the intervening period // Re-get the token from the db in case it has been deleted in the intervening period
has, err := db.DefaultContext().Engine().ID(id).Get(token) has, err := db.GetEngine(db.DefaultContext).ID(id).Get(token)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -121,7 +121,7 @@ func GetAccessTokenBySHA(token string) (*AccessToken, error) {
} }
var tokens []AccessToken var tokens []AccessToken
err := db.DefaultContext().Engine().Table(&AccessToken{}).Where("token_last_eight = ?", lastEight).Find(&tokens) err := db.GetEngine(db.DefaultContext).Table(&AccessToken{}).Where("token_last_eight = ?", lastEight).Find(&tokens)
if err != nil { if err != nil {
return nil, err return nil, err
} else if len(tokens) == 0 { } else if len(tokens) == 0 {
@ -142,7 +142,7 @@ func GetAccessTokenBySHA(token string) (*AccessToken, error) {
// AccessTokenByNameExists checks if a token name has been used already by a user. // AccessTokenByNameExists checks if a token name has been used already by a user.
func AccessTokenByNameExists(token *AccessToken) (bool, error) { func AccessTokenByNameExists(token *AccessToken) (bool, error) {
return db.DefaultContext().Engine().Table("access_token").Where("name = ?", token.Name).And("uid = ?", token.UID).Exist() return db.GetEngine(db.DefaultContext).Table("access_token").Where("name = ?", token.Name).And("uid = ?", token.UID).Exist()
} }
// ListAccessTokensOptions contain filter options // ListAccessTokensOptions contain filter options
@ -154,7 +154,7 @@ type ListAccessTokensOptions struct {
// ListAccessTokens returns a list of access tokens belongs to given user. // ListAccessTokens returns a list of access tokens belongs to given user.
func ListAccessTokens(opts ListAccessTokensOptions) ([]*AccessToken, error) { func ListAccessTokens(opts ListAccessTokensOptions) ([]*AccessToken, error) {
sess := db.DefaultContext().Engine().Where("uid=?", opts.UserID) sess := db.GetEngine(db.DefaultContext).Where("uid=?", opts.UserID)
if len(opts.Name) != 0 { if len(opts.Name) != 0 {
sess = sess.Where("name=?", opts.Name) sess = sess.Where("name=?", opts.Name)
@ -175,13 +175,13 @@ func ListAccessTokens(opts ListAccessTokensOptions) ([]*AccessToken, error) {
// UpdateAccessToken updates information of access token. // UpdateAccessToken updates information of access token.
func UpdateAccessToken(t *AccessToken) error { func UpdateAccessToken(t *AccessToken) error {
_, err := db.DefaultContext().Engine().ID(t.ID).AllCols().Update(t) _, err := db.GetEngine(db.DefaultContext).ID(t.ID).AllCols().Update(t)
return err return err
} }
// CountAccessTokens count access tokens belongs to given user by options // CountAccessTokens count access tokens belongs to given user by options
func CountAccessTokens(opts ListAccessTokensOptions) (int64, error) { func CountAccessTokens(opts ListAccessTokensOptions) (int64, error) {
sess := db.DefaultContext().Engine().Where("uid=?", opts.UserID) sess := db.GetEngine(db.DefaultContext).Where("uid=?", opts.UserID)
if len(opts.Name) != 0 { if len(opts.Name) != 0 {
sess = sess.Where("name=?", opts.Name) sess = sess.Where("name=?", opts.Name)
} }
@ -190,7 +190,7 @@ func CountAccessTokens(opts ListAccessTokensOptions) (int64, error) {
// DeleteAccessTokenByID deletes access token by given ID. // DeleteAccessTokenByID deletes access token by given ID.
func DeleteAccessTokenByID(id, userID int64) error { func DeleteAccessTokenByID(id, userID int64) error {
cnt, err := db.DefaultContext().Engine().ID(id).Delete(&AccessToken{ cnt, err := db.GetEngine(db.DefaultContext).ID(id).Delete(&AccessToken{
UID: userID, UID: userID,
}) })
if err != nil { if err != nil {

View File

@ -88,7 +88,7 @@ func SanitizeAndValidateTopics(topics []string) (validTopics, invalidTopics []st
// GetTopicByName retrieves topic by name // GetTopicByName retrieves topic by name
func GetTopicByName(name string) (*Topic, error) { func GetTopicByName(name string) (*Topic, error) {
var topic Topic var topic Topic
if has, err := db.DefaultContext().Engine().Where("name = ?", name).Get(&topic); err != nil { if has, err := db.GetEngine(db.DefaultContext).Where("name = ?", name).Get(&topic); err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
return nil, ErrTopicNotExist{name} return nil, ErrTopicNotExist{name}
@ -184,7 +184,7 @@ func (opts *FindTopicOptions) toConds() builder.Cond {
// FindTopics retrieves the topics via FindTopicOptions // FindTopics retrieves the topics via FindTopicOptions
func FindTopics(opts *FindTopicOptions) ([]*Topic, int64, error) { func FindTopics(opts *FindTopicOptions) ([]*Topic, int64, error) {
sess := db.DefaultContext().Engine().Select("topic.*").Where(opts.toConds()) sess := db.GetEngine(db.DefaultContext).Select("topic.*").Where(opts.toConds())
if opts.RepoID > 0 { if opts.RepoID > 0 {
sess.Join("INNER", "repo_topic", "repo_topic.topic_id = topic.id") sess.Join("INNER", "repo_topic", "repo_topic.topic_id = topic.id")
} }
@ -198,7 +198,7 @@ func FindTopics(opts *FindTopicOptions) ([]*Topic, int64, error) {
// CountTopics counts the number of topics matching the FindTopicOptions // CountTopics counts the number of topics matching the FindTopicOptions
func CountTopics(opts *FindTopicOptions) (int64, error) { func CountTopics(opts *FindTopicOptions) (int64, error) {
sess := db.DefaultContext().Engine().Where(opts.toConds()) sess := db.GetEngine(db.DefaultContext).Where(opts.toConds())
if opts.RepoID > 0 { if opts.RepoID > 0 {
sess.Join("INNER", "repo_topic", "repo_topic.topic_id = topic.id") sess.Join("INNER", "repo_topic", "repo_topic.topic_id = topic.id")
} }
@ -207,7 +207,7 @@ func CountTopics(opts *FindTopicOptions) (int64, error) {
// GetRepoTopicByName retrieves topic from name for a repo if it exist // GetRepoTopicByName retrieves topic from name for a repo if it exist
func GetRepoTopicByName(repoID int64, topicName string) (*Topic, error) { func GetRepoTopicByName(repoID int64, topicName string) (*Topic, error) {
return getRepoTopicByName(db.DefaultContext().Engine(), repoID, topicName) return getRepoTopicByName(db.GetEngine(db.DefaultContext), repoID, topicName)
} }
func getRepoTopicByName(e db.Engine, repoID int64, topicName string) (*Topic, error) { func getRepoTopicByName(e db.Engine, repoID int64, topicName string) (*Topic, error) {
@ -225,7 +225,7 @@ func getRepoTopicByName(e db.Engine, repoID int64, topicName string) (*Topic, er
// AddTopic adds a topic name to a repository (if it does not already have it) // AddTopic adds a topic name to a repository (if it does not already have it)
func AddTopic(repoID int64, topicName string) (*Topic, error) { func AddTopic(repoID int64, topicName string) (*Topic, error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return nil, err return nil, err
@ -272,7 +272,7 @@ func DeleteTopic(repoID int64, topicName string) (*Topic, error) {
return nil, nil return nil, nil
} }
err = removeTopicFromRepo(db.DefaultContext().Engine(), repoID, topic) err = removeTopicFromRepo(db.GetEngine(db.DefaultContext), repoID, topic)
return topic, err return topic, err
} }
@ -286,7 +286,7 @@ func SaveTopics(repoID int64, topicNames ...string) error {
return err return err
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {

View File

@ -93,13 +93,13 @@ func (t *TwoFactor) ValidateTOTP(passcode string) (bool, error) {
// NewTwoFactor creates a new two-factor authentication token. // NewTwoFactor creates a new two-factor authentication token.
func NewTwoFactor(t *TwoFactor) error { func NewTwoFactor(t *TwoFactor) error {
_, err := db.DefaultContext().Engine().Insert(t) _, err := db.GetEngine(db.DefaultContext).Insert(t)
return err return err
} }
// UpdateTwoFactor updates a two-factor authentication token. // UpdateTwoFactor updates a two-factor authentication token.
func UpdateTwoFactor(t *TwoFactor) error { func UpdateTwoFactor(t *TwoFactor) error {
_, err := db.DefaultContext().Engine().ID(t.ID).AllCols().Update(t) _, err := db.GetEngine(db.DefaultContext).ID(t.ID).AllCols().Update(t)
return err return err
} }
@ -107,7 +107,7 @@ func UpdateTwoFactor(t *TwoFactor) error {
// the user, if any. // the user, if any.
func GetTwoFactorByUID(uid int64) (*TwoFactor, error) { func GetTwoFactorByUID(uid int64) (*TwoFactor, error) {
twofa := &TwoFactor{} twofa := &TwoFactor{}
has, err := db.DefaultContext().Engine().Where("uid=?", uid).Get(twofa) has, err := db.GetEngine(db.DefaultContext).Where("uid=?", uid).Get(twofa)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -118,7 +118,7 @@ func GetTwoFactorByUID(uid int64) (*TwoFactor, error) {
// DeleteTwoFactorByID deletes two-factor authentication token by given ID. // DeleteTwoFactorByID deletes two-factor authentication token by given ID.
func DeleteTwoFactorByID(id, userID int64) error { func DeleteTwoFactorByID(id, userID int64) error {
cnt, err := db.DefaultContext().Engine().ID(id).Delete(&TwoFactor{ cnt, err := db.GetEngine(db.DefaultContext).ID(id).Delete(&TwoFactor{
UID: userID, UID: userID,
}) })
if err != nil { if err != nil {

View File

@ -45,7 +45,7 @@ func (reg *U2FRegistration) updateCounter(e db.Engine) error {
// UpdateCounter will update the database value of counter // UpdateCounter will update the database value of counter
func (reg *U2FRegistration) UpdateCounter() error { func (reg *U2FRegistration) UpdateCounter() error {
return reg.updateCounter(db.DefaultContext().Engine()) return reg.updateCounter(db.GetEngine(db.DefaultContext))
} }
// U2FRegistrationList is a list of *U2FRegistration // U2FRegistrationList is a list of *U2FRegistration
@ -73,7 +73,7 @@ func getU2FRegistrationsByUID(e db.Engine, uid int64) (U2FRegistrationList, erro
// GetU2FRegistrationByID returns U2F registration by id // GetU2FRegistrationByID returns U2F registration by id
func GetU2FRegistrationByID(id int64) (*U2FRegistration, error) { func GetU2FRegistrationByID(id int64) (*U2FRegistration, error) {
return getU2FRegistrationByID(db.DefaultContext().Engine(), id) return getU2FRegistrationByID(db.GetEngine(db.DefaultContext), id)
} }
func getU2FRegistrationByID(e db.Engine, id int64) (*U2FRegistration, error) { func getU2FRegistrationByID(e db.Engine, id int64) (*U2FRegistration, error) {
@ -88,7 +88,7 @@ func getU2FRegistrationByID(e db.Engine, id int64) (*U2FRegistration, error) {
// GetU2FRegistrationsByUID returns all U2F registrations of the given user // GetU2FRegistrationsByUID returns all U2F registrations of the given user
func GetU2FRegistrationsByUID(uid int64) (U2FRegistrationList, error) { func GetU2FRegistrationsByUID(uid int64) (U2FRegistrationList, error) {
return getU2FRegistrationsByUID(db.DefaultContext().Engine(), uid) return getU2FRegistrationsByUID(db.GetEngine(db.DefaultContext), uid)
} }
func createRegistration(e db.Engine, user *User, name string, reg *u2f.Registration) (*U2FRegistration, error) { func createRegistration(e db.Engine, user *User, name string, reg *u2f.Registration) (*U2FRegistration, error) {
@ -111,12 +111,12 @@ func createRegistration(e db.Engine, user *User, name string, reg *u2f.Registrat
// CreateRegistration will create a new U2FRegistration from the given Registration // CreateRegistration will create a new U2FRegistration from the given Registration
func CreateRegistration(user *User, name string, reg *u2f.Registration) (*U2FRegistration, error) { func CreateRegistration(user *User, name string, reg *u2f.Registration) (*U2FRegistration, error) {
return createRegistration(db.DefaultContext().Engine(), user, name, reg) return createRegistration(db.GetEngine(db.DefaultContext), user, name, reg)
} }
// DeleteRegistration will delete U2FRegistration // DeleteRegistration will delete U2FRegistration
func DeleteRegistration(reg *U2FRegistration) error { func DeleteRegistration(reg *U2FRegistration) error {
return deleteRegistration(db.DefaultContext().Engine(), reg) return deleteRegistration(db.GetEngine(db.DefaultContext), reg)
} }
func deleteRegistration(e db.Engine, reg *U2FRegistration) error { func deleteRegistration(e db.Engine, reg *U2FRegistration) error {

View File

@ -5,6 +5,7 @@
package models package models
import ( import (
"context"
"fmt" "fmt"
"strings" "strings"
@ -12,8 +13,8 @@ import (
) )
// PushUpdateDeleteTagsContext updates a number of delete tags with context // PushUpdateDeleteTagsContext updates a number of delete tags with context
func PushUpdateDeleteTagsContext(ctx *db.Context, repo *Repository, tags []string) error { func PushUpdateDeleteTagsContext(ctx context.Context, repo *Repository, tags []string) error {
return pushUpdateDeleteTags(ctx.Engine(), repo, tags) return pushUpdateDeleteTags(db.GetEngine(ctx), repo, tags)
} }
func pushUpdateDeleteTags(e db.Engine, repo *Repository, tags []string) error { func pushUpdateDeleteTags(e db.Engine, repo *Repository, tags []string) error {
@ -55,14 +56,14 @@ func PushUpdateDeleteTag(repo *Repository, tagName string) error {
return fmt.Errorf("GetRelease: %v", err) return fmt.Errorf("GetRelease: %v", err)
} }
if rel.IsTag { if rel.IsTag {
if _, err = db.DefaultContext().Engine().ID(rel.ID).Delete(new(Release)); err != nil { if _, err = db.GetEngine(db.DefaultContext).ID(rel.ID).Delete(new(Release)); err != nil {
return fmt.Errorf("Delete: %v", err) return fmt.Errorf("Delete: %v", err)
} }
} else { } else {
rel.IsDraft = true rel.IsDraft = true
rel.NumCommits = 0 rel.NumCommits = 0
rel.Sha1 = "" rel.Sha1 = ""
if _, err = db.DefaultContext().Engine().ID(rel.ID).AllCols().Update(rel); err != nil { if _, err = db.GetEngine(db.DefaultContext).ID(rel.ID).AllCols().Update(rel); err != nil {
return fmt.Errorf("Update: %v", err) return fmt.Errorf("Update: %v", err)
} }
} }
@ -79,7 +80,7 @@ func SaveOrUpdateTag(repo *Repository, newRel *Release) error {
if rel == nil { if rel == nil {
rel = newRel rel = newRel
if _, err = db.DefaultContext().Engine().Insert(rel); err != nil { if _, err = db.GetEngine(db.DefaultContext).Insert(rel); err != nil {
return fmt.Errorf("InsertOne: %v", err) return fmt.Errorf("InsertOne: %v", err)
} }
} else { } else {
@ -90,7 +91,7 @@ func SaveOrUpdateTag(repo *Repository, newRel *Release) error {
if rel.IsTag && newRel.PublisherID > 0 { if rel.IsTag && newRel.PublisherID > 0 {
rel.PublisherID = newRel.PublisherID rel.PublisherID = newRel.PublisherID
} }
if _, err = db.DefaultContext().Engine().ID(rel.ID).AllCols().Update(rel); err != nil { if _, err = db.GetEngine(db.DefaultContext).ID(rel.ID).AllCols().Update(rel); err != nil {
return fmt.Errorf("Update: %v", err) return fmt.Errorf("Update: %v", err)
} }
} }

View File

@ -73,7 +73,7 @@ func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err err
return nil, fmt.Errorf("Copy: %v", err) return nil, fmt.Errorf("Copy: %v", err)
} }
if _, err := db.DefaultContext().Engine().Insert(upload); err != nil { if _, err := db.GetEngine(db.DefaultContext).Insert(upload); err != nil {
return nil, err return nil, err
} }
@ -83,7 +83,7 @@ func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err err
// GetUploadByUUID returns the Upload by UUID // GetUploadByUUID returns the Upload by UUID
func GetUploadByUUID(uuid string) (*Upload, error) { func GetUploadByUUID(uuid string) (*Upload, error) {
upload := &Upload{} upload := &Upload{}
has, err := db.DefaultContext().Engine().Where("uuid=?", uuid).Get(upload) has, err := db.GetEngine(db.DefaultContext).Where("uuid=?", uuid).Get(upload)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -100,7 +100,7 @@ func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) {
// Silently drop invalid uuids. // Silently drop invalid uuids.
uploads := make([]*Upload, 0, len(uuids)) uploads := make([]*Upload, 0, len(uuids))
return uploads, db.DefaultContext().Engine().In("uuid", uuids).Find(&uploads) return uploads, db.GetEngine(db.DefaultContext).In("uuid", uuids).Find(&uploads)
} }
// DeleteUploads deletes multiple uploads // DeleteUploads deletes multiple uploads
@ -109,7 +109,7 @@ func DeleteUploads(uploads ...*Upload) (err error) {
return nil return nil
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err

View File

@ -236,7 +236,7 @@ func (u *User) GetEmail() string {
// GetAllUsers returns a slice of all individual users found in DB. // GetAllUsers returns a slice of all individual users found in DB.
func GetAllUsers() ([]*User, error) { func GetAllUsers() ([]*User, error) {
users := make([]*User, 0) users := make([]*User, 0)
return users, db.DefaultContext().Engine().OrderBy("id").Where("type = ?", UserTypeIndividual).Find(&users) return users, db.GetEngine(db.DefaultContext).OrderBy("id").Where("type = ?", UserTypeIndividual).Find(&users)
} }
// IsLocal returns true if user login type is LoginPlain. // IsLocal returns true if user login type is LoginPlain.
@ -332,7 +332,7 @@ func (u *User) GenerateEmailActivateCode(email string) string {
// GetFollowers returns range of user's followers. // GetFollowers returns range of user's followers.
func (u *User) GetFollowers(listOptions ListOptions) ([]*User, error) { func (u *User) GetFollowers(listOptions ListOptions) ([]*User, error) {
sess := db.DefaultContext().Engine(). sess := db.GetEngine(db.DefaultContext).
Where("follow.follow_id=?", u.ID). Where("follow.follow_id=?", u.ID).
Join("LEFT", "follow", "`user`.id=follow.user_id") Join("LEFT", "follow", "`user`.id=follow.user_id")
@ -354,7 +354,7 @@ func (u *User) IsFollowing(followID int64) bool {
// GetFollowing returns range of user's following. // GetFollowing returns range of user's following.
func (u *User) GetFollowing(listOptions ListOptions) ([]*User, error) { func (u *User) GetFollowing(listOptions ListOptions) ([]*User, error) {
sess := db.DefaultContext().Engine(). sess := db.GetEngine(db.DefaultContext).
Where("follow.user_id=?", u.ID). Where("follow.user_id=?", u.ID).
Join("LEFT", "follow", "`user`.id=follow.follow_id") Join("LEFT", "follow", "`user`.id=follow.follow_id")
@ -437,7 +437,7 @@ func (u *User) IsPasswordSet() bool {
// IsVisibleToUser check if viewer is able to see user profile // IsVisibleToUser check if viewer is able to see user profile
func (u *User) IsVisibleToUser(viewer *User) bool { func (u *User) IsVisibleToUser(viewer *User) bool {
return u.isVisibleToUser(db.DefaultContext().Engine(), viewer) return u.isVisibleToUser(db.GetEngine(db.DefaultContext), viewer)
} }
func (u *User) isVisibleToUser(e db.Engine, viewer *User) bool { func (u *User) isVisibleToUser(e db.Engine, viewer *User) bool {
@ -465,7 +465,7 @@ func (u *User) isVisibleToUser(e db.Engine, viewer *User) bool {
} }
// Now we need to check if they in some organization together // Now we need to check if they in some organization together
count, err := db.DefaultContext().Engine().Table("team_user"). count, err := db.GetEngine(db.DefaultContext).Table("team_user").
Where( Where(
builder.And( builder.And(
builder.Eq{"uid": viewer.ID}, builder.Eq{"uid": viewer.ID},
@ -508,7 +508,7 @@ func (u *User) IsUserOrgOwner(orgID int64) bool {
// HasMemberWithUserID returns true if user with userID is part of the u organisation. // HasMemberWithUserID returns true if user with userID is part of the u organisation.
func (u *User) HasMemberWithUserID(userID int64) bool { func (u *User) HasMemberWithUserID(userID int64) bool {
return u.hasMemberWithUserID(db.DefaultContext().Engine(), userID) return u.hasMemberWithUserID(db.GetEngine(db.DefaultContext), userID)
} }
func (u *User) hasMemberWithUserID(e db.Engine, userID int64) bool { func (u *User) hasMemberWithUserID(e db.Engine, userID int64) bool {
@ -538,7 +538,7 @@ func (u *User) getOrganizationCount(e db.Engine) (int64, error) {
// GetOrganizationCount returns count of membership of organization of user. // GetOrganizationCount returns count of membership of organization of user.
func (u *User) GetOrganizationCount() (int64, error) { func (u *User) GetOrganizationCount() (int64, error) {
return u.getOrganizationCount(db.DefaultContext().Engine()) return u.getOrganizationCount(db.GetEngine(db.DefaultContext))
} }
// GetRepositories returns repositories that user owns, including private repositories. // GetRepositories returns repositories that user owns, including private repositories.
@ -552,7 +552,7 @@ func (u *User) GetRepositories(listOpts ListOptions, names ...string) (err error
func (u *User) GetRepositoryIDs(units ...UnitType) ([]int64, error) { func (u *User) GetRepositoryIDs(units ...UnitType) ([]int64, error) {
var ids []int64 var ids []int64
sess := db.DefaultContext().Engine().Table("repository").Cols("repository.id") sess := db.GetEngine(db.DefaultContext).Table("repository").Cols("repository.id")
if len(units) > 0 { if len(units) > 0 {
sess = sess.Join("INNER", "repo_unit", "repository.id = repo_unit.repo_id") sess = sess.Join("INNER", "repo_unit", "repository.id = repo_unit.repo_id")
@ -567,7 +567,7 @@ func (u *User) GetRepositoryIDs(units ...UnitType) ([]int64, error) {
func (u *User) GetActiveRepositoryIDs(units ...UnitType) ([]int64, error) { func (u *User) GetActiveRepositoryIDs(units ...UnitType) ([]int64, error) {
var ids []int64 var ids []int64
sess := db.DefaultContext().Engine().Table("repository").Cols("repository.id") sess := db.GetEngine(db.DefaultContext).Table("repository").Cols("repository.id")
if len(units) > 0 { if len(units) > 0 {
sess = sess.Join("INNER", "repo_unit", "repository.id = repo_unit.repo_id") sess = sess.Join("INNER", "repo_unit", "repository.id = repo_unit.repo_id")
@ -584,7 +584,7 @@ func (u *User) GetActiveRepositoryIDs(units ...UnitType) ([]int64, error) {
func (u *User) GetOrgRepositoryIDs(units ...UnitType) ([]int64, error) { func (u *User) GetOrgRepositoryIDs(units ...UnitType) ([]int64, error) {
var ids []int64 var ids []int64
if err := db.DefaultContext().Engine().Table("repository"). if err := db.GetEngine(db.DefaultContext).Table("repository").
Cols("repository.id"). Cols("repository.id").
Join("INNER", "team_user", "repository.owner_id = team_user.org_id"). Join("INNER", "team_user", "repository.owner_id = team_user.org_id").
Join("INNER", "team_repo", "(? != ? and repository.is_private != ?) OR (team_user.team_id = team_repo.team_id AND repository.id = team_repo.repo_id)", true, u.IsRestricted, true). Join("INNER", "team_repo", "(? != ? and repository.is_private != ?) OR (team_user.team_id = team_repo.team_id AND repository.id = team_repo.repo_id)", true, u.IsRestricted, true).
@ -605,7 +605,7 @@ func (u *User) GetOrgRepositoryIDs(units ...UnitType) ([]int64, error) {
func (u *User) GetActiveOrgRepositoryIDs(units ...UnitType) ([]int64, error) { func (u *User) GetActiveOrgRepositoryIDs(units ...UnitType) ([]int64, error) {
var ids []int64 var ids []int64
if err := db.DefaultContext().Engine().Table("repository"). if err := db.GetEngine(db.DefaultContext).Table("repository").
Cols("repository.id"). Cols("repository.id").
Join("INNER", "team_user", "repository.owner_id = team_user.org_id"). Join("INNER", "team_user", "repository.owner_id = team_user.org_id").
Join("INNER", "team_repo", "(? != ? and repository.is_private != ?) OR (team_user.team_id = team_repo.team_id AND repository.id = team_repo.repo_id)", true, u.IsRestricted, true). Join("INNER", "team_repo", "(? != ? and repository.is_private != ?) OR (team_user.team_id = team_repo.team_id AND repository.id = team_repo.repo_id)", true, u.IsRestricted, true).
@ -743,7 +743,7 @@ func isUserExist(e db.Engine, uid int64, name string) (bool, error) {
// If uid is presented, then check will rule out that one, // If uid is presented, then check will rule out that one,
// it is used when update a user name in settings page. // it is used when update a user name in settings page.
func IsUserExist(uid int64, name string) (bool, error) { func IsUserExist(uid int64, name string) (bool, error) {
return isUserExist(db.DefaultContext().Engine(), uid, name) return isUserExist(db.GetEngine(db.DefaultContext), uid, name)
} }
// GetUserSalt returns a random user salt token. // GetUserSalt returns a random user salt token.
@ -879,7 +879,7 @@ func CreateUser(u *User, overwriteDefault ...*CreateUserOverwriteOptions) (err e
u.Visibility = overwriteDefault[0].Visibility u.Visibility = overwriteDefault[0].Visibility
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -949,7 +949,7 @@ func countUsers(e db.Engine) int64 {
// CountUsers returns number of users. // CountUsers returns number of users.
func CountUsers() int64 { func CountUsers() int64 {
return countUsers(db.DefaultContext().Engine()) return countUsers(db.GetEngine(db.DefaultContext))
} }
// get user by verify code // get user by verify code
@ -997,7 +997,7 @@ func VerifyActiveEmailCode(code, email string) *EmailAddress {
if base.VerifyTimeLimitCode(data, minutes, prefix) { if base.VerifyTimeLimitCode(data, minutes, prefix) {
emailAddress := &EmailAddress{UID: user.ID, Email: email} emailAddress := &EmailAddress{UID: user.ID, Email: email}
if has, _ := db.DefaultContext().Engine().Get(emailAddress); has { if has, _ := db.GetEngine(db.DefaultContext).Get(emailAddress); has {
return emailAddress return emailAddress
} }
} }
@ -1012,7 +1012,7 @@ func ChangeUserName(u *User, newUserName string) (err error) {
return err return err
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -1086,12 +1086,12 @@ func updateUser(e db.Engine, u *User) error {
// UpdateUser updates user's information. // UpdateUser updates user's information.
func UpdateUser(u *User) error { func UpdateUser(u *User) error {
return updateUser(db.DefaultContext().Engine(), u) return updateUser(db.GetEngine(db.DefaultContext), u)
} }
// UpdateUserCols update user according special columns // UpdateUserCols update user according special columns
func UpdateUserCols(u *User, cols ...string) error { func UpdateUserCols(u *User, cols ...string) error {
return updateUserCols(db.DefaultContext().Engine(), u, cols...) return updateUserCols(db.GetEngine(db.DefaultContext), u, cols...)
} }
func updateUserCols(e db.Engine, u *User, cols ...string) error { func updateUserCols(e db.Engine, u *User, cols ...string) error {
@ -1105,7 +1105,7 @@ func updateUserCols(e db.Engine, u *User, cols ...string) error {
// UpdateUserSetting updates user's settings. // UpdateUserSetting updates user's settings.
func UpdateUserSetting(u *User) (err error) { func UpdateUserSetting(u *User) (err error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -1311,7 +1311,7 @@ func DeleteUser(u *User) (err error) {
return fmt.Errorf("%s is an organization not a user", u.Name) return fmt.Errorf("%s is an organization not a user", u.Name)
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -1329,13 +1329,13 @@ func DeleteUser(u *User) (err error) {
func DeleteInactiveUsers(ctx context.Context, olderThan time.Duration) (err error) { func DeleteInactiveUsers(ctx context.Context, olderThan time.Duration) (err error) {
users := make([]*User, 0, 10) users := make([]*User, 0, 10)
if olderThan > 0 { if olderThan > 0 {
if err = db.DefaultContext().Engine(). if err = db.GetEngine(db.DefaultContext).
Where("is_active = ? and created_unix < ?", false, time.Now().Add(-olderThan).Unix()). Where("is_active = ? and created_unix < ?", false, time.Now().Add(-olderThan).Unix()).
Find(&users); err != nil { Find(&users); err != nil {
return fmt.Errorf("get all inactive users: %v", err) return fmt.Errorf("get all inactive users: %v", err)
} }
} else { } else {
if err = db.DefaultContext().Engine(). if err = db.GetEngine(db.DefaultContext).
Where("is_active = ?", false). Where("is_active = ?", false).
Find(&users); err != nil { Find(&users); err != nil {
return fmt.Errorf("get all inactive users: %v", err) return fmt.Errorf("get all inactive users: %v", err)
@ -1357,7 +1357,7 @@ func DeleteInactiveUsers(ctx context.Context, olderThan time.Duration) (err erro
} }
} }
_, err = db.DefaultContext().Engine(). _, err = db.GetEngine(db.DefaultContext).
Where("is_activated = ?", false). Where("is_activated = ?", false).
Delete(new(EmailAddress)) Delete(new(EmailAddress))
return err return err
@ -1381,12 +1381,12 @@ func getUserByID(e db.Engine, id int64) (*User, error) {
// GetUserByID returns the user object by given ID if exists. // GetUserByID returns the user object by given ID if exists.
func GetUserByID(id int64) (*User, error) { func GetUserByID(id int64) (*User, error) {
return getUserByID(db.DefaultContext().Engine(), id) return getUserByID(db.GetEngine(db.DefaultContext), id)
} }
// GetUserByName returns user by given name. // GetUserByName returns user by given name.
func GetUserByName(name string) (*User, error) { func GetUserByName(name string) (*User, error) {
return getUserByName(db.DefaultContext().Engine(), name) return getUserByName(db.GetEngine(db.DefaultContext), name)
} }
func getUserByName(e db.Engine, name string) (*User, error) { func getUserByName(e db.Engine, name string) (*User, error) {
@ -1406,7 +1406,7 @@ func getUserByName(e db.Engine, name string) (*User, error) {
// GetUserEmailsByNames returns a list of e-mails corresponds to names of users // GetUserEmailsByNames returns a list of e-mails corresponds to names of users
// that have their email notifications set to enabled or onmention. // that have their email notifications set to enabled or onmention.
func GetUserEmailsByNames(names []string) []string { func GetUserEmailsByNames(names []string) []string {
return getUserEmailsByNames(db.DefaultContext().Engine(), names) return getUserEmailsByNames(db.GetEngine(db.DefaultContext), names)
} }
func getUserEmailsByNames(e db.Engine, names []string) []string { func getUserEmailsByNames(e db.Engine, names []string) []string {
@ -1431,7 +1431,7 @@ func GetMaileableUsersByIDs(ids []int64, isMention bool) ([]*User, error) {
ous := make([]*User, 0, len(ids)) ous := make([]*User, 0, len(ids))
if isMention { if isMention {
return ous, db.DefaultContext().Engine().In("id", ids). return ous, db.GetEngine(db.DefaultContext).In("id", ids).
Where("`type` = ?", UserTypeIndividual). Where("`type` = ?", UserTypeIndividual).
And("`prohibit_login` = ?", false). And("`prohibit_login` = ?", false).
And("`is_active` = ?", true). And("`is_active` = ?", true).
@ -1439,7 +1439,7 @@ func GetMaileableUsersByIDs(ids []int64, isMention bool) ([]*User, error) {
Find(&ous) Find(&ous)
} }
return ous, db.DefaultContext().Engine().In("id", ids). return ous, db.GetEngine(db.DefaultContext).In("id", ids).
Where("`type` = ?", UserTypeIndividual). Where("`type` = ?", UserTypeIndividual).
And("`prohibit_login` = ?", false). And("`prohibit_login` = ?", false).
And("`is_active` = ?", true). And("`is_active` = ?", true).
@ -1450,7 +1450,7 @@ func GetMaileableUsersByIDs(ids []int64, isMention bool) ([]*User, error) {
// GetUserNamesByIDs returns usernames for all resolved users from a list of Ids. // GetUserNamesByIDs returns usernames for all resolved users from a list of Ids.
func GetUserNamesByIDs(ids []int64) ([]string, error) { func GetUserNamesByIDs(ids []int64) ([]string, error) {
unames := make([]string, 0, len(ids)) unames := make([]string, 0, len(ids))
err := db.DefaultContext().Engine().In("id", ids). err := db.GetEngine(db.DefaultContext).In("id", ids).
Table("user"). Table("user").
Asc("name"). Asc("name").
Cols("name"). Cols("name").
@ -1464,7 +1464,7 @@ func GetUsersByIDs(ids []int64) (UserList, error) {
if len(ids) == 0 { if len(ids) == 0 {
return ous, nil return ous, nil
} }
err := db.DefaultContext().Engine().In("id", ids). err := db.GetEngine(db.DefaultContext).In("id", ids).
Asc("name"). Asc("name").
Find(&ous) Find(&ous)
return ous, err return ous, err
@ -1490,7 +1490,7 @@ func GetUserIDsByNames(names []string, ignoreNonExistent bool) ([]int64, error)
// GetUsersBySource returns a list of Users for a login source // GetUsersBySource returns a list of Users for a login source
func GetUsersBySource(s *LoginSource) ([]*User, error) { func GetUsersBySource(s *LoginSource) ([]*User, error) {
var users []*User var users []*User
err := db.DefaultContext().Engine().Where("login_type = ? AND login_source = ?", s.Type, s.ID).Find(&users) err := db.GetEngine(db.DefaultContext).Where("login_type = ? AND login_source = ?", s.Type, s.ID).Find(&users)
return users, err return users, err
} }
@ -1539,11 +1539,11 @@ func ValidateCommitsWithEmails(oldCommits []*git.Commit) []*UserCommit {
// GetUserByEmail returns the user object by given e-mail if exists. // GetUserByEmail returns the user object by given e-mail if exists.
func GetUserByEmail(email string) (*User, error) { func GetUserByEmail(email string) (*User, error) {
return GetUserByEmailContext(db.DefaultContext(), email) return GetUserByEmailContext(db.DefaultContext, email)
} }
// GetUserByEmailContext returns the user object by given e-mail if exists with db context // GetUserByEmailContext returns the user object by given e-mail if exists with db context
func GetUserByEmailContext(ctx *db.Context, email string) (*User, error) { func GetUserByEmailContext(ctx context.Context, email string) (*User, error) {
if len(email) == 0 { if len(email) == 0 {
return nil, ErrUserNotExist{0, email, 0} return nil, ErrUserNotExist{0, email, 0}
} }
@ -1551,7 +1551,7 @@ func GetUserByEmailContext(ctx *db.Context, email string) (*User, error) {
email = strings.ToLower(email) email = strings.ToLower(email)
// First try to find the user by primary email // First try to find the user by primary email
user := &User{Email: email} user := &User{Email: email}
has, err := ctx.Engine().Get(user) has, err := db.GetEngine(ctx).Get(user)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -1561,19 +1561,19 @@ func GetUserByEmailContext(ctx *db.Context, email string) (*User, error) {
// Otherwise, check in alternative list for activated email addresses // Otherwise, check in alternative list for activated email addresses
emailAddress := &EmailAddress{Email: email, IsActivated: true} emailAddress := &EmailAddress{Email: email, IsActivated: true}
has, err = ctx.Engine().Get(emailAddress) has, err = db.GetEngine(ctx).Get(emailAddress)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if has { if has {
return getUserByID(ctx.Engine(), emailAddress.UID) return getUserByID(db.GetEngine(ctx), emailAddress.UID)
} }
// Finally, if email address is the protected email address: // Finally, if email address is the protected email address:
if strings.HasSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress)) { if strings.HasSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress)) {
username := strings.TrimSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress)) username := strings.TrimSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress))
user := &User{} user := &User{}
has, err := ctx.Engine().Where("lower_name=?", username).Get(user) has, err := db.GetEngine(ctx).Where("lower_name=?", username).Get(user)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -1587,7 +1587,7 @@ func GetUserByEmailContext(ctx *db.Context, email string) (*User, error) {
// GetUser checks if a user already exists // GetUser checks if a user already exists
func GetUser(user *User) (bool, error) { func GetUser(user *User) (bool, error) {
return db.DefaultContext().Engine().Get(user) return db.GetEngine(db.DefaultContext).Get(user)
} }
// SearchUserOptions contains the options for searching // SearchUserOptions contains the options for searching
@ -1664,7 +1664,7 @@ func (opts *SearchUserOptions) toConds() builder.Cond {
// it returns results in given range and number of total results. // it returns results in given range and number of total results.
func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) { func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
cond := opts.toConds() cond := opts.toConds()
count, err := db.DefaultContext().Engine().Where(cond).Count(new(User)) count, err := db.GetEngine(db.DefaultContext).Where(cond).Count(new(User))
if err != nil { if err != nil {
return nil, 0, fmt.Errorf("Count: %v", err) return nil, 0, fmt.Errorf("Count: %v", err)
} }
@ -1673,7 +1673,7 @@ func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
opts.OrderBy = SearchOrderByAlphabetically opts.OrderBy = SearchOrderByAlphabetically
} }
sess := db.DefaultContext().Engine().Where(cond).OrderBy(opts.OrderBy.String()) sess := db.GetEngine(db.DefaultContext).Where(cond).OrderBy(opts.OrderBy.String())
if opts.Page != 0 { if opts.Page != 0 {
sess = setSessionPagination(sess, opts) sess = setSessionPagination(sess, opts)
} }
@ -1684,7 +1684,7 @@ func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
// GetStarredRepos returns the repos starred by a particular user // GetStarredRepos returns the repos starred by a particular user
func GetStarredRepos(userID int64, private bool, listOptions ListOptions) ([]*Repository, error) { func GetStarredRepos(userID int64, private bool, listOptions ListOptions) ([]*Repository, error) {
sess := db.DefaultContext().Engine().Where("star.uid=?", userID). sess := db.GetEngine(db.DefaultContext).Where("star.uid=?", userID).
Join("LEFT", "star", "`repository`.id=`star`.repo_id") Join("LEFT", "star", "`repository`.id=`star`.repo_id")
if !private { if !private {
sess = sess.And("is_private=?", false) sess = sess.And("is_private=?", false)
@ -1703,7 +1703,7 @@ func GetStarredRepos(userID int64, private bool, listOptions ListOptions) ([]*Re
// GetWatchedRepos returns the repos watched by a particular user // GetWatchedRepos returns the repos watched by a particular user
func GetWatchedRepos(userID int64, private bool, listOptions ListOptions) ([]*Repository, int64, error) { func GetWatchedRepos(userID int64, private bool, listOptions ListOptions) ([]*Repository, int64, error) {
sess := db.DefaultContext().Engine().Where("watch.user_id=?", userID). sess := db.GetEngine(db.DefaultContext).Where("watch.user_id=?", userID).
And("`watch`.mode<>?", RepoWatchModeDont). And("`watch`.mode<>?", RepoWatchModeDont).
Join("LEFT", "watch", "`repository`.id=`watch`.repo_id") Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
if !private { if !private {
@ -1729,7 +1729,7 @@ func IterateUser(f func(user *User) error) error {
batchSize := setting.Database.IterateBufferSize batchSize := setting.Database.IterateBufferSize
for { for {
users := make([]*User, 0, batchSize) users := make([]*User, 0, batchSize)
if err := db.DefaultContext().Engine().Limit(batchSize, start).Find(&users); err != nil { if err := db.GetEngine(db.DefaultContext).Limit(batchSize, start).Find(&users); err != nil {
return err return err
} }
if len(users) == 0 { if len(users) == 0 {

View File

@ -26,7 +26,7 @@ func (u *User) CustomAvatarRelativePath() string {
// GenerateRandomAvatar generates a random avatar for user. // GenerateRandomAvatar generates a random avatar for user.
func (u *User) GenerateRandomAvatar() error { func (u *User) GenerateRandomAvatar() error {
return u.generateRandomAvatar(db.DefaultContext().Engine()) return u.generateRandomAvatar(db.GetEngine(db.DefaultContext))
} }
func (u *User) generateRandomAvatar(e db.Engine) error { func (u *User) generateRandomAvatar(e db.Engine) error {
@ -125,7 +125,7 @@ func (u *User) UploadAvatar(data []byte) error {
return err return err
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -165,7 +165,7 @@ func (u *User) DeleteAvatar() error {
u.UseCustomAvatar = false u.UseCustomAvatar = false
u.Avatar = "" u.Avatar = ""
if _, err := db.DefaultContext().Engine().ID(u.ID).Cols("avatar, use_custom_avatar").Update(u); err != nil { if _, err := db.GetEngine(db.DefaultContext).ID(u.ID).Cols("avatar, use_custom_avatar").Update(u); err != nil {
return fmt.Errorf("UpdateUser: %v", err) return fmt.Errorf("UpdateUser: %v", err)
} }
return nil return nil

View File

@ -23,7 +23,7 @@ func init() {
// IsFollowing returns true if user is following followID. // IsFollowing returns true if user is following followID.
func IsFollowing(userID, followID int64) bool { func IsFollowing(userID, followID int64) bool {
has, _ := db.DefaultContext().Engine().Get(&Follow{UserID: userID, FollowID: followID}) has, _ := db.GetEngine(db.DefaultContext).Get(&Follow{UserID: userID, FollowID: followID})
return has return has
} }
@ -33,7 +33,7 @@ func FollowUser(userID, followID int64) (err error) {
return nil return nil
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -59,7 +59,7 @@ func UnfollowUser(userID, followID int64) (err error) {
return nil return nil
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err

View File

@ -59,7 +59,7 @@ func getUserHeatmapData(user *User, team *Team, doer *User) ([]*UserHeatmapData,
return nil, err return nil, err
} }
return hdata, db.DefaultContext().Engine(). return hdata, db.GetEngine(db.DefaultContext).
Select(groupBy+" AS timestamp, count(user_id) as contributions"). Select(groupBy+" AS timestamp, count(user_id) as contributions").
Table("action"). Table("action").
Where(cond). Where(cond).

View File

@ -58,7 +58,7 @@ func ValidateEmail(email string) error {
// GetEmailAddresses returns all email addresses belongs to given user. // GetEmailAddresses returns all email addresses belongs to given user.
func GetEmailAddresses(uid int64) ([]*EmailAddress, error) { func GetEmailAddresses(uid int64) ([]*EmailAddress, error) {
emails := make([]*EmailAddress, 0, 5) emails := make([]*EmailAddress, 0, 5)
if err := db.DefaultContext().Engine(). if err := db.GetEngine(db.DefaultContext).
Where("uid=?", uid). Where("uid=?", uid).
Asc("id"). Asc("id").
Find(&emails); err != nil { Find(&emails); err != nil {
@ -71,7 +71,7 @@ func GetEmailAddresses(uid int64) ([]*EmailAddress, error) {
func GetEmailAddressByID(uid, id int64) (*EmailAddress, error) { func GetEmailAddressByID(uid, id int64) (*EmailAddress, error) {
// User ID is required for security reasons // User ID is required for security reasons
email := &EmailAddress{UID: uid} email := &EmailAddress{UID: uid}
if has, err := db.DefaultContext().Engine().ID(id).Get(email); err != nil { if has, err := db.GetEngine(db.DefaultContext).ID(id).Get(email); err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
return nil, nil return nil, nil
@ -114,7 +114,7 @@ func isEmailUsed(e db.Engine, email string) (bool, error) {
// IsEmailUsed returns true if the email has been used. // IsEmailUsed returns true if the email has been used.
func IsEmailUsed(email string) (bool, error) { func IsEmailUsed(email string) (bool, error) {
return isEmailUsed(db.DefaultContext().Engine(), email) return isEmailUsed(db.GetEngine(db.DefaultContext), email)
} }
func addEmailAddress(e db.Engine, email *EmailAddress) error { func addEmailAddress(e db.Engine, email *EmailAddress) error {
@ -136,7 +136,7 @@ func addEmailAddress(e db.Engine, email *EmailAddress) error {
// AddEmailAddress adds an email address to given user. // AddEmailAddress adds an email address to given user.
func AddEmailAddress(email *EmailAddress) error { func AddEmailAddress(email *EmailAddress) error {
return addEmailAddress(db.DefaultContext().Engine(), email) return addEmailAddress(db.GetEngine(db.DefaultContext), email)
} }
// AddEmailAddresses adds an email address to given user. // AddEmailAddresses adds an email address to given user.
@ -159,7 +159,7 @@ func AddEmailAddresses(emails []*EmailAddress) error {
} }
} }
if _, err := db.DefaultContext().Engine().Insert(emails); err != nil { if _, err := db.GetEngine(db.DefaultContext).Insert(emails); err != nil {
return fmt.Errorf("Insert: %v", err) return fmt.Errorf("Insert: %v", err)
} }
@ -168,7 +168,7 @@ func AddEmailAddresses(emails []*EmailAddress) error {
// Activate activates the email address to given user. // Activate activates the email address to given user.
func (email *EmailAddress) Activate() error { func (email *EmailAddress) Activate() error {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
@ -206,12 +206,12 @@ func DeleteEmailAddress(email *EmailAddress) (err error) {
UID: email.UID, UID: email.UID,
} }
if email.ID > 0 { if email.ID > 0 {
deleted, err = db.DefaultContext().Engine().ID(email.ID).Delete(&address) deleted, err = db.GetEngine(db.DefaultContext).ID(email.ID).Delete(&address)
} else { } else {
if email.Email != "" && email.LowerEmail == "" { if email.Email != "" && email.LowerEmail == "" {
email.LowerEmail = strings.ToLower(email.Email) email.LowerEmail = strings.ToLower(email.Email)
} }
deleted, err = db.DefaultContext().Engine(). deleted, err = db.GetEngine(db.DefaultContext).
Where("lower_email=?", email.LowerEmail). Where("lower_email=?", email.LowerEmail).
Delete(&address) Delete(&address)
} }
@ -237,7 +237,7 @@ func DeleteEmailAddresses(emails []*EmailAddress) (err error) {
// MakeEmailPrimary sets primary email address of given user. // MakeEmailPrimary sets primary email address of given user.
func MakeEmailPrimary(email *EmailAddress) error { func MakeEmailPrimary(email *EmailAddress) error {
has, err := db.DefaultContext().Engine().Get(email) has, err := db.GetEngine(db.DefaultContext).Get(email)
if err != nil { if err != nil {
return err return err
} else if !has { } else if !has {
@ -249,14 +249,14 @@ func MakeEmailPrimary(email *EmailAddress) error {
} }
user := &User{} user := &User{}
has, err = db.DefaultContext().Engine().ID(email.UID).Get(user) has, err = db.GetEngine(db.DefaultContext).ID(email.UID).Get(user)
if err != nil { if err != nil {
return err return err
} else if !has { } else if !has {
return ErrUserNotExist{email.UID, "", 0} return ErrUserNotExist{email.UID, "", 0}
} }
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err
@ -346,7 +346,7 @@ func SearchEmails(opts *SearchEmailOptions) ([]*SearchEmailResult, int64, error)
cond = cond.And(builder.Eq{"email_address.is_activated": false}) cond = cond.And(builder.Eq{"email_address.is_activated": false})
} }
count, err := db.DefaultContext().Engine().Join("INNER", "`user`", "`user`.ID = email_address.uid"). count, err := db.GetEngine(db.DefaultContext).Join("INNER", "`user`", "`user`.ID = email_address.uid").
Where(cond).Count(new(EmailAddress)) Where(cond).Count(new(EmailAddress))
if err != nil { if err != nil {
return nil, 0, fmt.Errorf("Count: %v", err) return nil, 0, fmt.Errorf("Count: %v", err)
@ -360,7 +360,7 @@ func SearchEmails(opts *SearchEmailOptions) ([]*SearchEmailResult, int64, error)
opts.setDefaultValues() opts.setDefaultValues()
emails := make([]*SearchEmailResult, 0, opts.PageSize) emails := make([]*SearchEmailResult, 0, opts.PageSize)
err = db.DefaultContext().Engine().Table("email_address"). err = db.GetEngine(db.DefaultContext).Table("email_address").
Select("email_address.*, `user`.name, `user`.full_name"). Select("email_address.*, `user`.name, `user`.full_name").
Join("INNER", "`user`", "`user`.ID = email_address.uid"). Join("INNER", "`user`", "`user`.ID = email_address.uid").
Where(cond). Where(cond).
@ -374,7 +374,7 @@ func SearchEmails(opts *SearchEmailOptions) ([]*SearchEmailResult, int64, error)
// ActivateUserEmail will change the activated state of an email address, // ActivateUserEmail will change the activated state of an email address,
// either primary or secondary (all in the email_address table) // either primary or secondary (all in the email_address table)
func ActivateUserEmail(userID int64, email string, activate bool) (err error) { func ActivateUserEmail(userID int64, email string, activate bool) (err error) {
sess := db.DefaultContext().NewSession() sess := db.NewSession(db.DefaultContext)
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {
return err return err

Some files were not shown because too many files have changed in this diff Show More