Fix SQL query for MySQL/Postgres on user profile (#424)

This commit is contained in:
Thomas Miceli
2025-02-03 23:29:34 +01:00
committed by GitHub
parent c14380f4de
commit 87ae60ce4c
2 changed files with 7 additions and 12 deletions

View File

@ -168,13 +168,6 @@ func GetAllGistsFromSearch(currentUserId uint, query string, offset int, sort st
}
func gistsFromUserStatement(fromUserId uint, currentUserId uint) *gorm.DB {
return db.
Where("((gists.private = 0) or (gists.private > 0 and gists.user_id = ?))", currentUserId).
Where("users.id = ?", fromUserId).
Joins("join users on gists.user_id = users.id")
}
func gistsFromUserStatementWithPreloads(fromUserId uint, currentUserId uint) *gorm.DB {
return db.Preload("User").Preload("Forked.User").Preload("Topics").
Where("((gists.private = 0) or (gists.private > 0 and gists.user_id = ?))", currentUserId).
Where("users.id = ?", fromUserId).
@ -185,7 +178,7 @@ func GetAllGistsFromUser(fromUserId uint, currentUserId uint, title string, lang
var gists []*Gist
var count int64
baseQuery := gistsFromUserStatementWithPreloads(fromUserId, currentUserId).Model(&Gist{})
baseQuery := gistsFromUserStatement(fromUserId, currentUserId).Model(&Gist{})
if title != "" {
baseQuery = baseQuery.Where("gists.title like ?", "%"+title+"%")
@ -220,7 +213,7 @@ func GetAllGistsFromUser(fromUserId uint, currentUserId uint, title string, lang
func CountAllGistsFromUser(fromUserId uint, currentUserId uint) (int64, error) {
var count int64
err := gistsFromUserStatementWithPreloads(fromUserId, currentUserId).Model(&Gist{}).Count(&count).Error
err := gistsFromUserStatement(fromUserId, currentUserId).Model(&Gist{}).Count(&count).Error
return count, err
}

View File

@ -14,13 +14,15 @@ func GetGistLanguagesForUser(fromUserId, currentUserId uint) ([]struct {
Count int64
}
err := gistsFromUserStatement(fromUserId, currentUserId).Model(&GistLanguage{}).
err := db.Model(&GistLanguage{}).
Select("language, count(*) as count").
Joins("JOIN gists ON gists.id = gist_languages.gist_id").
Where("gists.user_id = ?", fromUserId).
Joins("JOIN users ON gists.user_id = users.id").
Where("((gists.private = 0) or (gists.private > 0 and gists.user_id = ?))", currentUserId).
Where("users.id = ?", fromUserId).
Group("language").
Order("count DESC").
Limit(15). // Added limit of 15
Limit(15).
Find(&results).Error
return results, err